repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
asm-products/really-good-email-processor
config.js
288
module.exports = function (app) { // url app.set('url', process.env.URL || 'http://localhost'); // port app.set('port', process.env.PORT || 3000); // destination api url app.set('destination_url', process.env.DESTINATION_URL || 'http://localhost:3000/test'); };
bsd-2-clause
scifio/scifio
src/main/java/io/scif/services/TranslatorService.java
3488
/* * #%L * SCIFIO library for reading and converting scientific file formats. * %% * Copyright (C) 2011 - 2021 SCIFIO developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package io.scif.services; import io.scif.Metadata; import io.scif.SCIFIOService; import io.scif.Translator; import org.scijava.plugin.SingletonService; /** * Collection of methods for creating and using appropriate Translators to * convert between Metadata types. * * @see io.scif.Translator * @author Mark Hiner */ public interface TranslatorService extends SCIFIOService, SingletonService<Translator> { /** * Returns a translator capable of translating from the source Metadata to the * dest Metadata type, or null if no such Translator exists. * * @param source - Metadata to read from * @param dest - Metadata to populate * @param exact - true if a translator that exactly matches these Metadata is * desired * @return Translator whose translate method will accept these Metadata * instances */ Translator findTranslator(Metadata source, Metadata dest, boolean exact); /** * Returns a translator capable of translating from the source Metadata to the * dest Metadata type, or null if no such Translator exists. * * @param source - Metadata to read from * @param dest - Metadata to populate * @param exact - true if a translator that exactly matches these Metadata is * desired * @return Translator whose translate method will accept these Metadata * instances */ Translator findTranslator(Class<? extends Metadata> source, Class<? extends Metadata> dest, boolean exact); /** * Convenience method to immediately translate from the source Metadata to the * dest Metadata type, assuming an appropriate Translator is found. * <p> * Useful if you don't need a handle on the Translator itself. * </p> * * @param source - Metadata to read from * @param dest - Metadata to populate * @param exact - true if a translator that exactly matches these Metadata is * desired * @return true if translation was successful, and false otherwise. */ boolean translate(Metadata source, Metadata dest, boolean exact); }
bsd-2-clause
mvbattista/homebrew-core
Formula/baresip.rb
1507
class Baresip < Formula desc "Modular SIP useragent" homepage "http://www.creytiv.com/baresip.html" url "http://www.creytiv.com/pub/baresip-0.5.4.tar.gz" sha256 "710c16d209f8e5b7fd63433d27dd0ce2e651967a720ce5447162c268ec0e1c8a" bottle do sha256 "d97728c4347d3bd5a75cdbd1b2b43aabcfd18c26dd9a0552b87d76b0f745c002" => :sierra sha256 "19d6ba3cf7beb0163444c4634904751b43865af7a3a307e21b51227800217aa3" => :el_capitan sha256 "5c13318f2683da5ded44c6d89094a1d94a9b17ab0944dc37cb4955749b641d35" => :yosemite end depends_on "librem" depends_on "libre" def install # baresip doesn't like the 10.11 SDK when on Yosemite if MacOS::Xcode.installed? && MacOS::Xcode.version.to_i >= 7 ENV.delete("SDKROOT") ENV.delete("HOMEBREW_SDKROOT") if MacOS::Xcode.without_clt? end libre = Formula["libre"] system "make", "install", "PREFIX=#{prefix}", "LIBRE_MK=#{libre.opt_share}/re/re.mk", "LIBRE_INC=#{libre.opt_include}/re", "LIBRE_SO=#{libre.opt_lib}", "MOD_AUTODETECT=", "USE_AVCAPTURE=1", "USE_COREAUDIO=1", "USE_G711=1", "USE_OPENGL=1", "USE_STDIO=1", "USE_UUID=1" end test do system "#{bin}/baresip", "-f", "#{ENV["HOME"]}/.baresip", "-t" end end
bsd-2-clause
mvbattista/homebrew-core
Formula/pcl.rb
2359
class Pcl < Formula desc "Library for 2D/3D image and point cloud processing" homepage "http://www.pointclouds.org/" url "https://github.com/PointCloudLibrary/pcl/archive/pcl-1.8.1.tar.gz" sha256 "5a102a2fbe2ba77c775bf92c4a5d2e3d8170be53a68c3a76cfc72434ff7b9783" head "https://github.com/PointCloudLibrary/pcl.git" bottle do sha256 "46229b4eb3d168ecaff4f83dcfff95642a05d0ff989ab89adb63ba0397c4a909" => :sierra sha256 "176fb1d15c2dfbb323eb29d28929624bcf342a09dcb848f610af652e89ba5ec2" => :el_capitan sha256 "bd0b24e10b74ba20d63c09af7a1292d70d8c9ff8f7ffae98fabf4591993c09d4" => :yosemite end depends_on "cmake" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "cminpack" depends_on "eigen" depends_on "flann" depends_on "glew" depends_on "libusb" depends_on "qhull" depends_on "vtk" depends_on "homebrew/science/openni" => :optional depends_on "homebrew/science/openni2" => :optional def install args = std_cmake_args + %w[ -DBUILD_SHARED_LIBS:BOOL=ON -DBUILD_apps=AUTO_OFF -DBUILD_apps_3d_rec_framework=AUTO_OFF -DBUILD_apps_cloud_composer=AUTO_OFF -DBUILD_apps_in_hand_scanner=AUTO_OFF -DBUILD_apps_optronic_viewer=AUTO_OFF -DBUILD_apps_point_cloud_editor=AUTO_OFF -DBUILD_examples:BOOL=ON -DBUILD_global_tests:BOOL=OFF -DBUILD_outofcore:BOOL=AUTO_OFF -DBUILD_people:BOOL=AUTO_OFF -DBUILD_simulation:BOOL=AUTO_OFF -DWITH_CUDA:BOOL=OFF -DWITH_DOCS:BOOL=OFF -DWITH_QT:BOOL=FALSE -DWITH_TUTORIALS:BOOL=OFF ] if build.head? args << "-DBUILD_apps_modeler=AUTO_OFF" else args << "-DBUILD_apps_modeler:BOOL=OFF" end if build.with? "openni" args << "-DOPENNI_INCLUDE_DIR=#{Formula["openni"].opt_include}/ni" else args << "-DCMAKE_DISABLE_FIND_PACKAGE_OpenNI:BOOL=TRUE" end if build.with? "openni2" ENV.append "OPENNI2_INCLUDE", "#{Formula["openni2"].opt_include}/ni2" ENV.append "OPENNI2_LIB", "#{Formula["openni2"].opt_lib}/ni2" args << "-DBUILD_OPENNI2:BOOL=ON" end mkdir "build" do system "cmake", "..", *args system "make", "install" prefix.install Dir["#{bin}/*.app"] end end test do assert_match "tiff files", shell_output("#{bin}/pcl_tiff2pcd -h", 255) end end
bsd-2-clause
PetterS/easy-IP
examples/parking.cpp
8241
// Petter Strandmark 2013 // petter.strandmark@gmail.com #include <iostream> #include <stdexcept> #include <vector> using std::vector; using std::size_t; #include <easy-ip.h> // // This class adds connectivity constraints to the IP class. // It does so in two different ways, but they both result in // problems that are quite difficult to solve. // class MyIP : public IP { public: // The first way is based on following the perimeter around the // area and counting left and right turns. void add_connected_constraint_perimeter(const vector<vector<BooleanVariable>>& grid) { auto m = grid.size(); if (m == 0) return; auto n = grid[0].size(); // Pad grid with zeroes to be able to add constraints everywhere. vector<vector<BooleanVariable>> padded_grid; for (int i = 0; i < m + 2; ++i) { padded_grid.push_back(vector<BooleanVariable>()); for (int j = 0; j < n + 2; ++j) { if (i == 0 || i == m + 1 || j == 0 || j == n + 1) { auto zero_var = add_boolean(); set_bounds(0, zero_var, 0); padded_grid.back().push_back(zero_var); } else { padded_grid.back().push_back(grid[i-1][j-1]); } } } Sum turn_sum; auto add_triple_constraints = [&] (const BooleanVariable& x1, const BooleanVariable& x2, const BooleanVariable& y) { auto v1 = add_boolean(); // v1 <=> y && !x1 && !x2. // <= add_constraint( y + (1-x1) + (1-x2) <= 2 + v1 ); // => add_constraint( implication(v1, !x1) ); add_constraint( implication(v1, !x2) ); add_constraint( implication(v1, y) ); turn_sum += v1; auto v2 = add_boolean(); // v2 <=> !y && x1 && x2. // <= add_constraint( (1-y) + x1 + x2 <= 2 + v2 ); // => add_constraint( implication(v2, x1) ); add_constraint( implication(v2, x2) ); add_constraint( implication(v2, !y) ); turn_sum -= v2; }; for (size_t i = 0; i < m + 1; ++i) { for (size_t j = 0; j < n + 1; ++j) { // X // YX { auto& x1 = padded_grid[i][j]; auto& x2 = padded_grid[i+1][j+1]; auto& y = padded_grid[i][j+1]; add_triple_constraints(x1, x2, y); } // XY // X { auto& x1 = padded_grid[i][j]; auto& x2 = padded_grid[i+1][j+1]; auto& y = padded_grid[i+1][j]; add_triple_constraints(x1, x2, y); } // YX // X { auto& x1 = padded_grid[i+1][j]; auto& x2 = padded_grid[i][j+1]; auto& y = padded_grid[i][j]; add_triple_constraints(x1, x2, y); } // X // XY { auto& x1 = padded_grid[i+1][j]; auto& x2 = padded_grid[i][j+1]; auto& y = padded_grid[i+1][j+1]; add_triple_constraints(x1, x2, y); } } } add_constraint(4, turn_sum, 4); // Forbid the two configurations // // 01 10 // 10 and 01 // // This is not completely correct, but the code // above can not handle them. for (int i = 0; i < m + 1; ++i) { for (int j = 0; j < n + 1; ++j) { add_constraint(padded_grid[i][i] + (1 - padded_grid[i+1][j]) + (1 - padded_grid[i][j+1]) + padded_grid[i+1][j+1] <= 3); add_constraint((1 - padded_grid[i][i]) + padded_grid[i+1][j] + padded_grid[i][j+1] + (1 - padded_grid[i+1][j+1]) <= 3); } } } // The second way is based on adding flow to one square and // requiring it to dissipate through the grid. void add_connected_constraint_flow(const vector<vector<BooleanVariable>>& grid, int start_i, int start_j) { auto m = grid.size(); if (m == 0) return; auto n = grid[0].size(); auto num_elements = double(m * n); vector<vector<Sum>> node_balance(m, vector<Sum>(n, 0.0)); Sum number_of_active_nodes = 0; for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < n; ++j) { number_of_active_nodes += grid[i][j]; if (i < m - 1) { auto fij = add_variable(Real); node_balance[i][j] += fij; node_balance[i+1][j] -= fij; add_constraint( fij >= 0 ); add_constraint( fij <= num_elements*grid[i][j] ); add_constraint( fij <= num_elements*grid[i+1][j] ); } if (i > 0) { auto fij = add_variable(Real); node_balance[i][j] += fij; node_balance[i-1][j] -= fij; add_constraint( fij >= 0 ); add_constraint( fij <= num_elements*grid[i][j] ); add_constraint( fij <= num_elements*grid[i-1][j] ); } if (j < n - 1) { auto fij = add_variable(Real); node_balance[i][j] += fij; node_balance[i][j+1] -= fij; add_constraint( fij >= 0 ); add_constraint( fij <= num_elements*grid[i][j] ); add_constraint( fij <= num_elements*grid[i][j+1] ); } if (j > 0) { auto fij = add_variable(Real); node_balance[i][j] += fij; node_balance[i][j-1] -= fij; add_constraint( fij >= 0 ); add_constraint( fij <= num_elements*grid[i][j] ); add_constraint( fij <= num_elements*grid[i][j-1] ); } } } auto total_flow = add_variable(Real); set_bounds(0, total_flow, num_elements); add_constraint(total_flow == number_of_active_nodes); node_balance[start_i][start_j] += total_flow; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { auto f_it = add_variable(Real); set_bounds(0, f_it, 1); node_balance[i][j] -= f_it; add_constraint(node_balance[i][j] == 0); } } } }; int main_program() { using namespace std; int n = 6; MyIP ip; // Parking spots. We want to maximize the number of these. auto P = ip.add_boolean_grid(n, n, -1.0); // Transporation to parking spots. auto T = ip.add_boolean_grid(n, n); int starti = 0; int startj = 1; // Entrance to the parking lot. ip.add_constraint( T[starti][startj] ); // Border // Sum border = 0; // for (int i = 1; i < n-1; ++i) { // border += T[0][i]; // border += T[n-1][i]; // border += T[i][0]; // border += T[i][n-1]; // } // // There has to be an entrance. // ip.add_constraint(border >= 1); // T[0][0] == 1 //. P P P P P //. . . . . . //. P P P P P //. P P P P P //. . . . . . //P P P P P P // 21 // T[0][1] == 1 //P . P P P P //P . . . . . //P . P P P P //P . P P P P //P . . . . . // P P P P P // 22 // T[0][2] == 1 //P . . . . P //P . P P . P //P . P P . P //P . P P . P //P . P P . P //P . P P . P // 22 // T[0][1] == 1 // P . P P P P P P . P // P . P . . . . . . P // P . P P P P P P . P // P . P P P P P . P // P . P P . . . . . P // P . P P . P . P . P // P . P P . P P P . P // P . P P . P P P P P // . . . . . . . . . . // P P P P P P P P P P // 61 // We can not have both parking and transportation. for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { // Not allowing both to be zero seems to give a slightly // stronger formulation. ip.add_constraint(P[i][j] + T[i][j] == 1); } } // Every parking lot needs to be adjacent to a transport square. for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { Sum neighborhood; if (i > 0) { neighborhood += T[i-1][j]; } if (i < n - 1) { neighborhood += T[i+1][j]; } if (j > 0) { neighborhood += T[i][j-1]; } if (j < n - 1) { neighborhood += T[i][j+1]; } ip.add_constraint( P[i][j] <= neighborhood ); ip.add_constraint( T[i][j] <= neighborhood + P[i][j] ); } } // The hardest part: the transport squares need to be // connected to each other. ip.add_connected_constraint_perimeter(T); //ip.add_connected_constraint_flow(T, starti, startj); auto print_solution = [&] () { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { auto p = ip.get_solution(P[i][j]); auto t = ip.get_solution(T[i][j]); if (p && t) { // Infeasible. cout << '#'; } else if (!p && !t) { cout << ' '; } else if (p) { cout << 'P'; } else { cout << '.'; } cout << ' '; } cout << endl; } cout << endl; }; //ip.set_external_solver(IP::MOSEK); ip.set_external_solver(IP::Minisat); attest(ip.solve()); do { print_solution(); } while (ip.next_solution()); return 0; } int main() { try { return main_program(); } catch (std::exception& err) { std::cerr << "ERROR: " << err.what() << std::endl; } }
bsd-2-clause
swax/DeOps
Core/Services/Voice/RecordAudio.cs
11763
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Threading; namespace DeOps.Services.Voice { public class RecordAudio : IDisposable { VoiceService Voices; IntPtr WaveHandle; WinMM.WaveFormat Format; WinMM.WaveDelegate CallbackHandler; AutoResetEvent RecordEvent = new AutoResetEvent(false); bool HighQuality = true; public int FrameSize; int SampleRate; int BufferSize; int NextBuffer; const int BufferCount = 5; // 1/10 of a second in buffers, 20ms each RecordBuffer[] Buffers = new RecordBuffer[BufferCount]; Speex.SpeexBits EncodeBits; IntPtr SpeexEncoder; int SpeexMode; byte[] EncodedBytes; IntPtr PreProcessor; //public IntPtr EchoState; public RecordAudio(VoiceService voices) { Voices = voices; CallbackHandler = new WinMM.WaveDelegate(WaveCallback); // if 20ms, at high quality (16khz) is 320 samples at 2 bytes each if (HighQuality) { SampleRate = 16000; BufferSize = 320 * 2; SpeexMode = Speex.SPEEX_MODEID_WB; } else { SampleRate = 8000; BufferSize = 160 * 2; SpeexMode = Speex.SPEEX_MODEID_NB; } //LastBuffer = new byte[BufferSize]; try { InitSpeexEncoder(); Format = new WinMM.WaveFormat(SampleRate, 16, 1); WinMM.ErrorCheck(WinMM.waveInOpen(out WaveHandle, Voices.RecordingDevice, Format, CallbackHandler, 0, WinMM.CALLBACK_FUNCTION)); for (int i = 0; i < BufferCount; i++) Buffers[i] = new RecordBuffer(i, WaveHandle, BufferSize); WinMM.ErrorCheck(WinMM.waveInStart(WaveHandle)); } catch (Exception ex) { Dispose(); Voices.Core.Network.UpdateLog("Voice", "Error starting recording: " + ex.Message); } } private void InitSpeexEncoder() { // init Speex.speex_bits_init(ref EncodeBits); // get narrow band mode IntPtr modePtr = Speex.speex_lib_get_mode(SpeexMode); SpeexEncoder = Speex.speex_encoder_init(modePtr); //int zeroNoError = 0; int tmp = 0; // no variable bit rate Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_VBR, ref tmp); tmp = 4; // ok quality Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_QUALITY, ref tmp); tmp = 1; // uses a little more cpu for better processing Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_COMPLEXITY, ref tmp); tmp = 1; // voice activated, deadspace is not encoded Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_VAD, ref tmp); tmp = 1; // dead space no transmission Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_DTX, ref tmp); Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_GET_FRAME_SIZE, ref FrameSize); Debug.Assert(FrameSize == BufferSize / 2); if (FrameSize != BufferSize / 2) throw new Exception("Frame size " + FrameSize + " did agree with buffer " + BufferSize); /* Turn this off if you want to measure SNR (on by default) */ tmp = 1; Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_HIGHPASS, ref tmp); // pre-processor PreProcessor = Speex.speex_preprocess_state_init(FrameSize, SampleRate); tmp = 1; Speex.speex_preprocess_ctl(PreProcessor, Speex.SPEEX_PREPROCESS_SET_DENOISE, ref tmp); // echo cancelation //EchoState = Speex.speex_echo_state_init(FrameSize, FrameSize * 3); // 100ms tail length suggested //Speex.speex_preprocess_ctl(PreProcessor, Speex.SPEEX_PREPROCESS_SET_ECHO_STATE, EchoState); EncodedBytes = new byte[BufferSize]; } int AddedBuffers; public void WaveCallback(IntPtr hdrvr, int uMsg, int dwUser, ref WinMM.WaveHdr wavhdr, int dwParam2) { if (uMsg == WinMM.MM_WIM_DATA) { // use dwUser parameter of header to keep buffers in sync? // doesnt seem like buffers are getting out of sync at all AddedBuffers--; Voices.AudioEvent.Set(); } } public void ProcessBuffers() { try { while (AddedBuffers < BufferCount) { RecordBuffer buffer = Buffers[NextBuffer]; if (buffer.Added) EncodeAudio(buffer); /*if (!EncodeAudio(buffer) && LastBufferSet) { // no data sent - send last buffer so that audio doesnt snap, but fades out // reverse - so waves match up byte[] frame = new byte[2]; int backpos = 0; for (int i = 0; i < FrameSize / 2; i++) { backpos = LastBuffer.Length - 2 - i * 2; Buffer.BlockCopy(LastBuffer, i * 2, frame, 0, 2); // front to temp Buffer.BlockCopy(LastBuffer, backpos, LastBuffer, i * 2, 2); // back to front Buffer.BlockCopy(frame, 0, LastBuffer, backpos, 2); // temp to back } // fade so no sharp end to the sound for (int i = 0; i < FrameSize; i++) { short value = BitConverter.ToInt16(LastBuffer, i * 2); value = (short) (value * (FrameSize - i) / FrameSize); BitConverter.GetBytes(value).CopyTo(LastBuffer, i * 2); } LastBuffer.CopyTo(buffer.Data, 0); int tmp = 0; Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_VAD, ref tmp); Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_DTX, ref tmp); //EncodeAudio(buffer); tmp = 1; Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_VAD, ref tmp); Speex.speex_encoder_ctl(SpeexEncoder, Speex.SPEEX_SET_DTX, ref tmp); LastBufferSet = false; }*/ WinMM.ErrorCheck(WinMM.waveInAddBuffer(WaveHandle, ref buffer.Header, Marshal.SizeOf(buffer.Header))); buffer.Added = true; NextBuffer++; if (NextBuffer >= BufferCount) NextBuffer = 0; AddedBuffers++; } } catch (Exception ex) { Debug.Assert(false); Voices.Core.RunInCoreAsync(() => { Voices.Core.Network.UpdateLog("Voice", "Error in record thread: " + ex.Message); Dispose(); }); } } //byte[] LastBuffer; //bool LastBufferSet; //byte[] EchoBuff; private bool EncodeAudio(RecordBuffer buffer) { // done in a seperate function to avoid buffer from being re-assigned while delegate is being processed short maxVolume = 0; for (int i = 0; i < BufferSize / 2; i++) { short val = BitConverter.ToInt16(buffer.Data, i * 2); if (val > maxVolume) maxVolume = val; } // pre-process Speex.speex_preprocess_run(PreProcessor, buffer.Data); // echo cancel //if (EchoBuff == null) EchoBuff = new byte[BufferSize]; //Speex.speex_echo_capture(EchoState, buffer.Data, EchoBuff); //EchoBuff.CopyTo(buffer.Data, 0); // encode Speex.speex_bits_reset(ref EncodeBits); int success = Speex.speex_encode_int(SpeexEncoder, buffer.DataPtr, ref EncodeBits); if (success == 0) // dtx returns 0 if no data return false; int written = Speex.speex_bits_write(ref EncodeBits, EncodedBytes, EncodedBytes.Length); // filler is 10b high quality, 6b low quality, dont write filler only good audio if (written > 10) { //buffer.Data.CopyTo(LastBuffer, 0); //LastBufferSet = true; byte[] safeBuffer = Utilities.ExtractBytes(EncodedBytes, 0, written); // pass frame size because recorder could be null by the time event gets there Voices.Core.RunInCoreAsync(() => Voices.Recorder_AudioData(safeBuffer, maxVolume, FrameSize)); return true; } return false; } public void Dispose() { try { WinMM.ErrorCheck(WinMM.waveInReset(WaveHandle)); // free buffers foreach (RecordBuffer buffer in Buffers) buffer.Dispose(); Buffers = null; // free speex Speex.speex_bits_destroy(ref EncodeBits); Speex.speex_encoder_destroy(SpeexEncoder); Speex.speex_preprocess_state_destroy(PreProcessor); //Speex.speex_echo_state_destroy(EchoState); WinMM.ErrorCheck(WinMM.waveInClose(WaveHandle)); } catch (Exception ex) { Voices.Core.Network.UpdateLog("Voice", "Error Disposing: " + ex.Message); } Voices.Recorder = null; } } public class RecordBuffer : IDisposable { IntPtr WaveHandle; public WinMM.WaveHdr Header; GCHandle HeaderHandle; public byte[] Data; GCHandle DataHandle; public IntPtr DataPtr; public bool Added; public RecordBuffer(int index, IntPtr handle, int size) { WaveHandle = handle; HeaderHandle = GCHandle.Alloc(Header, GCHandleType.Pinned); Data = new byte[size]; DataHandle = GCHandle.Alloc(Data, GCHandleType.Pinned); DataPtr = DataHandle.AddrOfPinnedObject(); //Header.dwUser = new IntPtr(index); //(IntPtr)GCHandle.Alloc(this); Header.lpData = DataHandle.AddrOfPinnedObject(); Header.dwBufferLength = size; WinMM.ErrorCheck(WinMM.waveInPrepareHeader(WaveHandle, ref Header, Marshal.SizeOf(Header))); } public void Dispose() { if (HeaderHandle.IsAllocated) { WinMM.ErrorCheck(WinMM.waveInUnprepareHeader(WaveHandle, ref Header, Marshal.SizeOf(Header))); HeaderHandle.Free(); } if (DataHandle.IsAllocated) DataHandle.Free(); } } }
bsd-2-clause
lhm/homebrew
Library/Formula/mpich2.rb
1696
require 'formula' # This should really be named Mpich now, but homebrew cannot currently handle # formula renames, see homebrew issue #14374. class Mpich2 < Formula homepage 'http://www.mpich.org/' url 'http://www.mpich.org/static/downloads/3.1.1/mpich-3.1.1.tar.gz' mirror 'http://fossies.org/linux/misc/mpich-3.1.1.tar.gz' sha1 '528d225a67d16843ffd963e4e1ec93d7053cab57' head do url 'git://git.mpich.org/mpich.git' depends_on 'autoconf' => :build depends_on 'automake' => :build depends_on 'libtool' => :build end option 'disable-fortran', "Do not attempt to build Fortran bindings" option 'disable-shared', "Do not build shared libraries" depends_on :fortran unless build.include? 'disable-fortran' conflicts_with 'open-mpi', :because => 'both install mpi__ compiler wrappers' def install if build.head? # ensure that the consistent set of autotools built by homebrew is used to # build MPICH, otherwise very bizarre build errors can occur ENV['MPICH_AUTOTOOLS_DIR'] = HOMEBREW_PREFIX+'bin' system "./autogen.sh" end args = [ "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--mandir=#{man}" ] if build.include? 'disable-fortran' args << "--disable-f77" << "--disable-fc" end # MPICH configure up to version 3.0.4 defaults to "--disable-shared" if build.include? 'disable-shared' args << "--disable-shared" end system "./configure", *args system "make" system "make install" end test do # a better test would be to build and run a small MPI program system "#{bin}/mpicc", "-show" end end
bsd-2-clause
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/prototype/every/15.4.4.16-3-19.js
1191
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.every es5id: 15.4.4.16-3-19 description: > Array.prototype.every - value of 'length' is an Object which has an own toString method ---*/ function callbackfn1(val, idx, obj) { return val > 10; } function callbackfn2(val, idx, obj) { return val > 11; } var toStringAccessed = false; var obj = { 0: 12, 1: 11, 2: 9, length: { toString: function() { toStringAccessed = true; return '2'; } } }; // objects inherit the default valueOf() method from Object // that simply returns itself. Since the default valueOf() method // does not return a primitive value, ES next tries to convert the object // to a number by calling its toString() method and converting the // resulting string to a number. assert(Array.prototype.every.call(obj, callbackfn1), 'Array.prototype.every.call(obj, callbackfn1) !== true'); assert.sameValue(Array.prototype.every.call(obj, callbackfn2), false, 'Array.prototype.every.call(obj, callbackfn2)'); assert(toStringAccessed, 'toStringAccessed !== true');
bsd-2-clause
Linuxbrew/homebrew-core
Formula/flamegraph.rb
3310
class Flamegraph < Formula desc "Stack trace visualizer" homepage "https://github.com/brendangregg/FlameGraph" url "https://github.com/brendangregg/FlameGraph/archive/v1.0.tar.gz" sha256 "c5ba824228a4f7781336477015cb3b2d8178ffd86bccd5f51864ed52a5ad6675" license "CDDL-1.0" revision 1 head "https://github.com/brendangregg/FlameGraph.git" uses_from_macos "perl" def install bin.install "flamegraph.pl", "difffolded.pl" bin.install "stackcollapse-aix.pl", "stackcollapse-elfutils.pl", "stackcollapse-gdb.pl", "stackcollapse-go.pl", "stackcollapse-instruments.pl", "stackcollapse-jstack.pl", "stackcollapse-ljp.awk", "stackcollapse-perf-sched.awk", "stackcollapse-perf.pl", "stackcollapse-pmc.pl", "stackcollapse-recursive.pl", "stackcollapse-sample.awk", "stackcollapse-stap.pl", "stackcollapse-vsprof.pl", "stackcollapse-vtune.pl", "stackcollapse.pl" bin.install "files.pl", "pkgsplit-perf.pl", "range-perf.pl" if build.head? bin.install "stackcollapse-bpftrace.pl", "stackcollapse-java-exceptions.pl", "stackcollapse-xdebug.php" end end test do (testpath/"perf-mirageos-stacks-01.txt").write <<~EOS mir-console 23166 [000] 1333.768765: cpu-clock: 44bee3 camlLwt__return_1285 (/mnt/mirage/mirage-skeleton/console.unix2/_build/main.native) 4093d0 camlMain__fun_1418 (/mnt/mirage/mirage-skeleton/console.unix2/_build/main.native) swapper 0 [001] 1333.768770: cpu-clock: ffffffff810013aa xen_hypercall_sched_op ([kernel.kallsyms]) ffffffff8101caaf default_idle ([kernel.kallsyms]) ffffffff8101d376 arch_cpu_idle ([kernel.kallsyms]) ffffffff810bef35 cpu_startup_entry ([kernel.kallsyms]) ffffffff810101b8 cpu_bringup_and_idle ([kernel.kallsyms]) swapper 0 [002] 1333.768806: cpu-clock: ffffffff810013aa xen_hypercall_sched_op ([kernel.kallsyms]) ffffffff8101caaf default_idle ([kernel.kallsyms]) ffffffff8101d376 arch_cpu_idle ([kernel.kallsyms]) ffffffff810bef35 cpu_startup_entry ([kernel.kallsyms]) ffffffff810101b8 cpu_bringup_and_idle ([kernel.kallsyms]) swapper 0 [003] 1333.768847: cpu-clock: ffffffff810013aa xen_hypercall_sched_op ([kernel.kallsyms]) ffffffff8101caaf default_idle ([kernel.kallsyms]) ffffffff8101d376 arch_cpu_idle ([kernel.kallsyms]) ffffffff810bef35 cpu_startup_entry ([kernel.kallsyms]) ffffffff810101b8 cpu_bringup_and_idle ([kernel.kallsyms]) mir-console 23166 [000] 1333.778865: cpu-clock: 44b1d0 camlLwt__repr_rec_1132 (/mnt/mirage/mirage-skeleton/console.unix2/_build/main.native) 7f57a760d920 [unknown] ([unknown]) EOS (testpath/"perf-mirageos-stacks-01-collapsed-all.txt").write <<~EOS mir-console;camlMain__fun_1418;camlLwt__return_1285 1 swapper;cpu_bringup_and_idle;cpu_startup_entry;arch_cpu_idle;default_idle;xen_hypercall_sched_op 3 EOS output = shell_output "#{bin}/stackcollapse-perf.pl #{testpath}/perf-mirageos-stacks-01.txt" assert_match File.read("#{testpath}/perf-mirageos-stacks-01-collapsed-all.txt"), output system "#{bin}/flamegraph.pl", "#{testpath}/perf-mirageos-stacks-01-collapsed-all.txt" end end
bsd-2-clause
khades/servbot
ircClient/ircClient.go
3684
package ircClient import ( "fmt" "log" "time" "github.com/khades/servbot/models" "github.com/khades/servbot/repos" "gopkg.in/irc.v2" ) // IrcClient struct defines object that will send messages to a twitch server type IrcClient struct { Client *irc.Client Bounces map[string]time.Time Ready bool ModChannelIndex int MessageQueue []string MessagesSent int } // PushMessage adds message to array of messages to prevent global bans for bot func (ircClient *IrcClient) PushMessage(message string) { log.Println("Pushing message: ", message) if ircClient.MessagesSent > 3 { ircClient.MessageQueue = append(ircClient.MessageQueue, message) log.Println("Messages in queue :", len(ircClient.MessageQueue)) } else { ircClient.Client.Write(message) ircClient.MessagesSent = ircClient.MessagesSent + 1 } } // SendMessages gets slice of messages to send periodically, sends them and updates list of messages func (ircClient *IrcClient) SendMessages(interval int) { ircClient.MessagesSent = 0 queueSliceSize := 3 arrayLen := len(ircClient.MessageQueue) if arrayLen == 0 { return } log.Println("Array length is:", arrayLen) if arrayLen < queueSliceSize { queueSliceSize = arrayLen } ircClient.MessagesSent = queueSliceSize messagesToSend := ircClient.MessageQueue[:queueSliceSize] log.Println("Messages to send:", len(messagesToSend)) for _, message := range messagesToSend { ircClient.Client.Write(message) } ircClient.MessageQueue = ircClient.MessageQueue[queueSliceSize:] if len(ircClient.MessageQueue) > 0 { log.Println("Messaged Delayed:", len(ircClient.MessageQueue)) } } // SendDebounced prevents from sending data too frequent in public chat sending it to a PM func (ircClient *IrcClient) SendDebounced(message models.OutgoingDebouncedMessage) { key := fmt.Sprintf("%s-%s", message.Message.Channel, message.Command) if ircClient.Bounces == nil { ircClient.Bounces = make(map[string]time.Time) } bounce, found := ircClient.Bounces[key] if found && int(time.Now().Sub(bounce).Seconds()) < 15 { ircClient.SendPrivate(&message.Message) } else { ircClient.Bounces[key] = time.Now() ircClient.SendPublic(&models.OutgoingMessage{ Channel: message.Message.Channel, Body: message.Message.Body, User: message.RedirectTo}) } } // SendRaw is wrapper to Write func (ircClient *IrcClient) SendRaw(message string) { if ircClient.Ready { ircClient.PushMessage(message) } } // SendPublic writes data to a specified chat func (ircClient *IrcClient) SendPublic(message *models.OutgoingMessage) { if ircClient.Ready { messageString := "" if message.User != "" { messageString = fmt.Sprintf("PRIVMSG #%s :@%s %s", message.Channel, message.User, message.Body) } else { messageString = fmt.Sprintf("PRIVMSG #%s :%s", message.Channel, message.Body) } ircClient.PushMessage(messageString) } } // SendPrivate writes data in private to a user func (ircClient *IrcClient) SendPrivate(message *models.OutgoingMessage) { if ircClient.Ready && message.User != "" { messageString := fmt.Sprintf("PRIVMSG #jtv :/w %s Channel %s: %s", message.User, message.Channel, message.Body) ircClient.PushMessage(messageString) } } // SendModsCommand runs mod command func (ircClient *IrcClient) SendModsCommand() { channelName := repos.Config.Channels[ircClient.ModChannelIndex] if channelName != "" { ircClient.SendPublic(&models.OutgoingMessage{Channel: channelName, Body: "/mods"}) } ircClient.ModChannelIndex++ if ircClient.ModChannelIndex == len(repos.Config.Channels) || ircClient.ModChannelIndex > len(repos.Config.Channels) { ircClient.ModChannelIndex = 0 } }
bsd-2-clause
cedwardsmedia/homebrew-cask
Casks/bit-slicer.rb
546
cask 'bit-slicer' do version '1.7.6' sha256 '03e9125481bd4c6459e379b3b0df69a2eecbde80f7cb11d9be8dfc9c0f8d3a58' # bitbucket.org is the official download host per the vendor homepage url "https://bitbucket.org/zorgiepoo/bit-slicer/downloads/Bit%20Slicer%20#{version}.zip" appcast 'https://zgcoder.net/bitslicer/update/appcast.xml', :sha256 => '3012f7d3d8b49f6d595d62e07f87525c0a225a59d44576ba46f0c67518fdf019' name 'Bit Slicer' homepage 'https://github.com/zorgiepoo/bit-slicer/' license :bsd app 'Bit Slicer.app' end
bsd-2-clause
nordicdyno/cfbackup
cfbackup/__main__.py
180
#!/usr/bin/env python """The main entry point. Invoke as `cfbackup' or `python -m cfbackup'. """ import sys from .core import main if __name__ == '__main__': sys.exit(main())
bsd-2-clause
Fedict/dcattools
scrapers/src/main/java/be/fedict/dcat/scrapers/statbel/HtmlStatbelPubs.java
9495
/* * Copyright (c) 2017, FPS BOSA DG DT * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package be.fedict.dcat.scrapers.statbel; import be.fedict.dcat.scrapers.Page; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.vocab.MDR_LANG; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.swing.text.html.HTML.Attribute; import javax.swing.text.html.HTML.Tag; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.DCAT; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.repository.RepositoryException; /** * Statbel "publications" scraper. * * @see https://statbel.fgov.be/ * @author Bart Hanssens */ public class HtmlStatbelPubs extends HtmlStatbel { public final static String LINK_THEME = "nav.block--menu--themes-doormat ul.nav h3 a"; public final static String NAV_SUBTHEME = "nav.block--menu--themes-doormat ul.nav"; public final static String LINK_SUBTHEME = "h3 a"; public final static String LINK_SUBSUBTHEME = "ul.menu li a"; public final static String LI = "ul > li"; public final static String DIV_DOCUMENT = "div.field--name-field-document-description"; public final static String DIV_SUMMARY = "div.field--name-body"; public final static String DIV_FILES = "div.field--name-field-document a"; public final static String LI_THEMES = "ol.breadcrumb li a"; /** * Scrape URLs from subthemes * * @param u link to subtheme * @return list of URLs * @throws IOException */ private List<URL> scrapeSubList(String u) throws IOException { List<URL> urls = new ArrayList<>(); String subtheme = makeRequest(makeAbsURL(u)); Elements nav = Jsoup.parse(subtheme).select(NAV_SUBTHEME); if (nav == null || nav.isEmpty()) { logger.warn("No subtheme element found"); return urls; } Elements lis = nav.select(LI); if (lis == null || lis.isEmpty()) { logger.warn("No subtheme links found"); return urls; } for (Element li: lis) { // Check if there is a third level of themes Elements subs = li.select(LINK_SUBSUBTHEME); if (subs != null && !subs.isEmpty()) { logger.debug("Subsubtheme elements {} for {}", subs.size(), u); for (Element sub : subs) { String href = sub.attr(Attribute.HREF.toString()); urls.add(makeAbsURL(href)); } } else { // Not the case, so only the title points to a dataset logger.info("No subsubtheme elements for {}", u); Element link = li.select(LINK_SUBTHEME).first(); if (link != null) { String href = link.attr(Attribute.HREF.toString()); urls.add(makeAbsURL(href)); } else { logger.warn("No subthemes nor subsubthemes found {}", u); } } } return urls; } /** * Get the list of all the downloads (DCAT Dataset). * * @return List of URLs * @throws IOException */ @Override protected List<URL> scrapeDatasetList() throws IOException { List<URL> urls = new ArrayList<>(); URL base = getBase(); String front = makeRequest(base); // Get all the main themes Elements themes = Jsoup.parse(front).select(LINK_THEME); if (themes != null) { for (Element theme : themes) { String href = theme.attr(Attribute.HREF.toString()); urls.addAll(scrapeSubList(href)); sleep(); } } else { logger.error("No themes {} found", LINK_THEME); } return urls; } /** * Generate DCAT Distribution. * * @param store RDF store * @param dataset dataset URI * @param access access URL * @param link link element * @param lang language code * @throws MalformedURLException * @throws RepositoryException */ private void generateDist(Storage store, IRI dataset, URL access, Element link, String lang) throws MalformedURLException, RepositoryException { String href = link.attr(Attribute.HREF.toString()); URL download = makeAbsURL(href); // important for EDP: does not like different datasets pointing to same distribution String id = makeHashId(dataset.toString()) + "/" + makeHashId(download.toString()); IRI dist = store.getURI(makeDistURL(id).toString() + "/" + lang); logger.debug("Generating distribution {}", dist.toString()); store.add(dataset, DCAT.HAS_DISTRIBUTION, dist); store.add(dist, RDF.TYPE, DCAT.DISTRIBUTION); store.add(dist, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang)); store.add(dist, DCTERMS.TITLE, link.ownText(), lang); store.add(dist, DCAT.ACCESS_URL, access); store.add(dist, DCAT.DOWNLOAD_URL, download); store.add(dist, DCAT.MEDIA_TYPE, getFileExt(href)); } /** * Generate DCAT Dataset. * * @param store RDF store * @param id * @param page * @throws MalformedURLException * @throws RepositoryException */ @Override public void generateDataset(Storage store, String id, Map<String, Page> page) throws MalformedURLException, RepositoryException { IRI dataset = store.getURI(makeDatasetURL(id).toString()); logger.info("Generating dataset {}", dataset.toString()); store.add(dataset, RDF.TYPE, DCAT.DATASET); store.add(dataset, DCTERMS.IDENTIFIER, id); for (String lang : getAllLangs()) { Page p = page.get(lang); if (p == null) { logger.warn("Page {} not available in {}", dataset.toString(), lang); continue; } String html = p.getContent(); Element doc = Jsoup.parse(html).body(); if (doc == null) { logger.warn("No body element"); continue; } Element h = doc.getElementsByTag(Tag.H1.toString()).first(); if (h == null) { logger.warn("No H1 element"); continue; } String title = h.text(); // by default, also use the title as description String desc = title; Element divmain = doc.select(DIV_DOCUMENT).first(); if (divmain != null) { desc = divmain.text(); } else { divmain = doc.select(DIV_SUMMARY).first(); if (divmain != null) { desc = divmain.text(); } else { logger.warn("No description found"); logger.warn(title); } } store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang)); store.add(dataset, DCTERMS.TITLE, title, lang); store.add(dataset, DCTERMS.DESCRIPTION, desc, lang); Elements themes = doc.select(LI_THEMES); if (themes != null && themes.size() > 2) { //ignore Home > Themes themes.remove(0); themes.remove(0); for (Element theme : themes) { store.add(dataset, DCAT.KEYWORD, theme.text().trim(), lang); } } else { logger.warn("No themes found {}", LI_THEMES); } Elements links = doc.select(DIV_FILES); if (links != null) { for (Element link : links) { generateDist(store, dataset, p.getUrl(), link, lang); } } else { logger.warn("No downloads found {}", DIV_FILES); } } } /** * HTML parser for Statbel publications * * @param prop * @throws IOException */ public HtmlStatbelPubs(Properties prop) throws IOException { super(prop); setName("statbelpubs"); } }
bsd-2-clause
reitermarkus/brew
Library/Homebrew/test/dev-cmd/bump_spec.rb
784
# typed: false # frozen_string_literal: true require "cmd/shared_examples/args_parse" describe "brew bump" do describe "Homebrew.bump_args" do it_behaves_like "parseable arguments" end describe "formula", :integration_test do it "returns data for single valid specified formula" do install_test_formula "testball" expect { brew "bump", "testball" } .to output.to_stdout .and not_to_output.to_stderr .and be_a_success end it "returns data for multiple valid specified formula" do install_test_formula "testball" install_test_formula "testball2" expect { brew "bump", "testball", "testball2" } .to output.to_stdout .and not_to_output.to_stderr .and be_a_success end end end
bsd-2-clause
DaveKriewall/Rearranger
test/testData/com/wrq/rearranger/GetPrefixReturnsResult.java
682
public class GetterDefinitionTest { /** name: correct prefix; body: returns */ public int getX() { return field + 1; } /** name: correct prefix; body: returns field */ public int getZ() { return field; } /** name: matches field; body: returns */ public int getField() { return field + 1; } /** name: matches field; body: returns field */ public int getField2() { return field2; } int dummyField; int field; int field2; /** name: correct prefix; body: immaterial */ public int getY() { dummyField++; return dummyField; } int dummyField2; }
bsd-2-clause
KenanSulayman/mollie-api-node
examples/6-list-available-methods.js
1467
// Generated by CoffeeScript 1.6.3 /* Example 6 - How to get the currently activated payment methods. */ (function() { var Mollie, example, _; Mollie = require("../lib/mollie"); _ = require("underscore"); example = (function() { function example(request, response) { /* Initialize the Mollie API library with your API key. See: https://www.mollie.nl/beheer/account/profielen/ */ var mollie; mollie = new Mollie.API.Client; mollie.setApiKey("test_b93kfaAsnngIAT3NysojhYvKEJ5YbP"); /* Get the all payments for this API key ordered by newest. */ mollie.methods.all(function(methods) { var method, _i, _len; if (methods.error) { console.error(methods.error); return response.end(); } response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); for (_i = 0, _len = methods.length; _i < _len; _i++) { method = methods[_i]; response.write("<div style='line-height:40px; vertical-align:top'>"); response.write("<img src='" + (_.escape(method.image.normal)) + "'>"); response.write("" + (_.escape(method.description)) + " (" + (_.escape(method.id)) + ")</div>"); } return response.end(); }); } return example; })(); module.exports = example; }).call(this); /* //@ sourceMappingURL=6-list-available-methods.map */
bsd-2-clause
mechaphish/colorguard
colorguard/harvester/__init__.py
33
from .harvester import Harvester
bsd-2-clause
bmatsuo/dispatch
examples/doc.go
476
/* * Filename: doc.go * Author: Bryan Matsuo <bmatsuo@soe.ucsc.edu> * Created: Tue Jul 5 22:13:49 PDT 2011 * Description: * Usage: gotest */ /* Examples using the dispatch package. Install the examples with the command cd $GOROOT/src/pkg/github.com/bmatsuo/dispatch && gomake exinstall && cd - Uninstall the examples with the command cd $GOROOT/src/pkg/github.com/bmatsuo/dispatch && gomake exnuke && cd - */ package documentation
bsd-2-clause
PopCap/GameIdea
Engine/Source/Editor/PropertyEditor/Private/SDetailsViewBase.cpp
39373
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "PropertyEditorPrivatePCH.h" #include "SDetailsViewBase.h" #include "AssetSelection.h" #include "PropertyNode.h" #include "ItemPropertyNode.h" #include "CategoryPropertyNode.h" #include "ObjectPropertyNode.h" #include "ScopedTransaction.h" #include "AssetThumbnail.h" #include "SDetailNameArea.h" #include "IPropertyUtilities.h" #include "PropertyEditorHelpers.h" #include "PropertyEditor.h" #include "PropertyDetailsUtilities.h" #include "SPropertyEditorEditInline.h" #include "ObjectEditorUtils.h" #include "SColorPicker.h" SDetailsViewBase::~SDetailsViewBase() { if (ThumbnailPool.IsValid()) { ThumbnailPool->ReleaseResources(); } } void SDetailsViewBase::OnGetChildrenForDetailTree(TSharedRef<IDetailTreeNode> InTreeNode, TArray< TSharedRef<IDetailTreeNode> >& OutChildren) { InTreeNode->GetChildren(OutChildren); } TSharedRef<ITableRow> SDetailsViewBase::OnGenerateRowForDetailTree(TSharedRef<IDetailTreeNode> InTreeNode, const TSharedRef<STableViewBase>& OwnerTable) { return InTreeNode->GenerateNodeWidget(OwnerTable, ColumnSizeData, PropertyUtilities.ToSharedRef()); } void SDetailsViewBase::SetRootExpansionStates(const bool bExpand, const bool bRecurse) { for (auto Iter = RootTreeNodes.CreateIterator(); Iter; ++Iter) { SetNodeExpansionState(*Iter, bExpand, bRecurse); } } void SDetailsViewBase::SetNodeExpansionState(TSharedRef<IDetailTreeNode> InTreeNode, bool bIsItemExpanded, bool bRecursive) { TArray< TSharedRef<IDetailTreeNode> > Children; InTreeNode->GetChildren(Children); if (Children.Num()) { RequestItemExpanded(InTreeNode, bIsItemExpanded); InTreeNode->OnItemExpansionChanged(bIsItemExpanded); if (bRecursive) { for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex) { TSharedRef<IDetailTreeNode> Child = Children[ChildIndex]; SetNodeExpansionState(Child, bIsItemExpanded, bRecursive); } } } } void SDetailsViewBase::SetNodeExpansionStateRecursive(TSharedRef<IDetailTreeNode> InTreeNode, bool bIsItemExpanded) { SetNodeExpansionState(InTreeNode, bIsItemExpanded, true); } void SDetailsViewBase::OnItemExpansionChanged(TSharedRef<IDetailTreeNode> InTreeNode, bool bIsItemExpanded) { SetNodeExpansionState(InTreeNode, bIsItemExpanded, false); } FReply SDetailsViewBase::OnLockButtonClicked() { bIsLocked = !bIsLocked; return FReply::Handled(); } void SDetailsViewBase::HideFilterArea(bool bHide) { DetailsViewArgs.bAllowSearch = !bHide; } static void GetPropertiesInOrderDisplayedRecursive(const TArray< TSharedRef<IDetailTreeNode> >& TreeNodes, TArray< FPropertyPath > &OutLeaves) { for (auto& TreeNode : TreeNodes) { if (TreeNode->IsLeaf()) { FPropertyPath Path = TreeNode->GetPropertyPath(); // Some leaf nodes are not associated with properties, specifically the collision presets. // @todo doc: investigate what we can do about this, result is that for these fields // we can't highlight hte property in the diff tool. if( Path.GetNumProperties() != 0 ) { OutLeaves.Push(Path); } } else { TArray< TSharedRef<IDetailTreeNode> > Children; TreeNode->GetChildren(Children); GetPropertiesInOrderDisplayedRecursive(Children, OutLeaves); } } } TArray< FPropertyPath > SDetailsViewBase::GetPropertiesInOrderDisplayed() const { TArray< FPropertyPath > Ret; GetPropertiesInOrderDisplayedRecursive(RootTreeNodes, Ret); return Ret; } static TSharedPtr< IDetailTreeNode > FindTreeNodeFromPropertyRecursive( const TArray< TSharedRef<IDetailTreeNode> >& Nodes, const FPropertyPath& Property ) { for (auto& TreeNode : Nodes) { if (TreeNode->IsLeaf()) { FPropertyPath tmp = TreeNode->GetPropertyPath(); if( Property == tmp ) { return TreeNode; } } else { TArray< TSharedRef<IDetailTreeNode> > Children; TreeNode->GetChildren(Children); auto Result = FindTreeNodeFromPropertyRecursive(Children, Property); if( Result.IsValid() ) { return Result; } } } return TSharedPtr< IDetailTreeNode >(); } void SDetailsViewBase::HighlightProperty(const FPropertyPath& Property) { auto PrevHighlightedNodePtr = CurrentlyHighlightedNode.Pin(); if (PrevHighlightedNodePtr.IsValid()) { PrevHighlightedNodePtr->SetIsHighlighted(false); } auto NextNodePtr = FindTreeNodeFromPropertyRecursive( RootTreeNodes, Property ); if (NextNodePtr.IsValid()) { NextNodePtr->SetIsHighlighted(true); auto ParentCategory = NextNodePtr->GetParentCategory(); if (ParentCategory.IsValid()) { DetailTree->SetItemExpansion(ParentCategory.ToSharedRef(), true); } DetailTree->RequestScrollIntoView(NextNodePtr.ToSharedRef()); } CurrentlyHighlightedNode = NextNodePtr; } void SDetailsViewBase::ShowAllAdvancedProperties() { CurrentFilter.bShowAllAdvanced = true; } void SDetailsViewBase::SetOnDisplayedPropertiesChanged(FOnDisplayedPropertiesChanged InOnDisplayedPropertiesChangedDelegate) { OnDisplayedPropertiesChangedDelegate = InOnDisplayedPropertiesChangedDelegate; } EVisibility SDetailsViewBase::GetTreeVisibility() const { return DetailLayout.IsValid() && DetailLayout->HasDetails() ? EVisibility::Visible : EVisibility::Collapsed; } /** Returns the image used for the icon on the filter button */ const FSlateBrush* SDetailsViewBase::OnGetFilterButtonImageResource() const { if (bHasActiveFilter) { return FEditorStyle::GetBrush(TEXT("PropertyWindow.FilterCancel")); } else { return FEditorStyle::GetBrush(TEXT("PropertyWindow.FilterSearch")); } } void SDetailsViewBase::EnqueueDeferredAction(FSimpleDelegate& DeferredAction) { DeferredActions.Add(DeferredAction); } /** * Creates the color picker window for this property view. * * @param Node The slate property node to edit. * @param bUseAlpha Whether or not alpha is supported */ void SDetailsViewBase::CreateColorPickerWindow(const TSharedRef< FPropertyEditor >& PropertyEditor, bool bUseAlpha) { const TSharedRef< FPropertyNode > PinnedColorPropertyNode = PropertyEditor->GetPropertyNode(); ColorPropertyNode = PinnedColorPropertyNode; UProperty* Property = PinnedColorPropertyNode->GetProperty(); check(Property); FReadAddressList ReadAddresses; PinnedColorPropertyNode->GetReadAddress(false, ReadAddresses, false); TArray<FLinearColor*> LinearColor; TArray<FColor*> DWORDColor; for (int32 ColorIndex = 0; ColorIndex < ReadAddresses.Num(); ++ColorIndex) { const uint8* Addr = ReadAddresses.GetAddress(ColorIndex); if (Addr) { if (Cast<UStructProperty>(Property)->Struct->GetFName() == NAME_Color) { DWORDColor.Add((FColor*)Addr); } else { check(Cast<UStructProperty>(Property)->Struct->GetFName() == NAME_LinearColor); LinearColor.Add((FLinearColor*)Addr); } } } bHasOpenColorPicker = true; FColorPickerArgs PickerArgs; PickerArgs.ParentWidget = AsShared(); PickerArgs.bUseAlpha = bUseAlpha; PickerArgs.DisplayGamma = TAttribute<float>::Create(TAttribute<float>::FGetter::CreateUObject(GEngine, &UEngine::GetDisplayGamma)); PickerArgs.ColorArray = &DWORDColor; PickerArgs.LinearColorArray = &LinearColor; PickerArgs.OnColorCommitted = FOnLinearColorValueChanged::CreateSP(this, &SDetailsViewBase::SetColorPropertyFromColorPicker); PickerArgs.OnColorPickerWindowClosed = FOnWindowClosed::CreateSP(this, &SDetailsViewBase::OnColorPickerWindowClosed); OpenColorPicker(PickerArgs); } void SDetailsViewBase::SetColorPropertyFromColorPicker(FLinearColor NewColor) { const TSharedPtr< FPropertyNode > PinnedColorPropertyNode = ColorPropertyNode.Pin(); if (ensure(PinnedColorPropertyNode.IsValid())) { UProperty* Property = PinnedColorPropertyNode->GetProperty(); check(Property); FObjectPropertyNode* ObjectNode = PinnedColorPropertyNode->FindObjectItemParent(); if (ObjectNode && ObjectNode->GetNumObjects()) { FScopedTransaction Transaction(NSLOCTEXT("UnrealEd", "SetColorProperty", "Set Color Property")); PinnedColorPropertyNode->NotifyPreChange(Property, GetNotifyHook()); FPropertyChangedEvent ChangeEvent(Property, EPropertyChangeType::ValueSet); PinnedColorPropertyNode->NotifyPostChange(ChangeEvent, GetNotifyHook()); } } } void SDetailsViewBase::OnColorPickerWindowClosed(const TSharedRef<SWindow>& Window) { const TSharedPtr< FPropertyNode > PinnedColorPropertyNode = ColorPropertyNode.Pin(); if (ensure(PinnedColorPropertyNode.IsValid())) { UProperty* Property = PinnedColorPropertyNode->GetProperty(); if (Property && PropertyUtilities.IsValid()) { FPropertyChangedEvent ChangeEvent(Property, EPropertyChangeType::ArrayAdd); PinnedColorPropertyNode->FixPropertiesInEvent(ChangeEvent); PropertyUtilities->NotifyFinishedChangingProperties(ChangeEvent); } } // A color picker window is no longer open bHasOpenColorPicker = false; ColorPropertyNode.Reset(); } void SDetailsViewBase::SetIsPropertyVisibleDelegate(FIsPropertyVisible InIsPropertyVisible) { IsPropertyVisibleDelegate = InIsPropertyVisible; } void SDetailsViewBase::SetIsPropertyReadOnlyDelegate(FIsPropertyReadOnly InIsPropertyReadOnly) { IsPropertyReadOnlyDelegate = InIsPropertyReadOnly; } void SDetailsViewBase::SetIsPropertyEditingEnabledDelegate(FIsPropertyEditingEnabled IsPropertyEditingEnabled) { IsPropertyEditingEnabledDelegate = IsPropertyEditingEnabled; } bool SDetailsViewBase::IsPropertyEditingEnabled() const { // If the delegate is not bound assume property editing is enabled, otherwise ask the delegate return !IsPropertyEditingEnabledDelegate.IsBound() || IsPropertyEditingEnabledDelegate.Execute(); } void SDetailsViewBase::SetKeyframeHandler( TSharedPtr<class IDetailKeyframeHandler> InKeyframeHandler ) { KeyframeHandler = InKeyframeHandler; } TSharedPtr<IDetailKeyframeHandler> SDetailsViewBase::GetKeyframeHandler() { return KeyframeHandler; } void SDetailsViewBase::SetExtensionHandler(TSharedPtr<class IDetailPropertyExtensionHandler> InExtensionHandler) { ExtensionHandler = InExtensionHandler; } TSharedPtr<IDetailPropertyExtensionHandler> SDetailsViewBase::GetExtensionHandler() { return ExtensionHandler; } void SDetailsViewBase::SetGenericLayoutDetailsDelegate(FOnGetDetailCustomizationInstance OnGetGenericDetails) { GenericLayoutDelegate = OnGetGenericDetails; } TSharedPtr<FAssetThumbnailPool> SDetailsViewBase::GetThumbnailPool() const { if (!ThumbnailPool.IsValid()) { // Create a thumbnail pool for the view if it doesnt exist. This does not use resources of no thumbnails are used ThumbnailPool = MakeShareable(new FAssetThumbnailPool(50, TAttribute<bool>::Create(TAttribute<bool>::FGetter::CreateSP(this, &SDetailsView::IsHovered)))); } return ThumbnailPool; } void SDetailsViewBase::NotifyFinishedChangingProperties(const FPropertyChangedEvent& PropertyChangedEvent) { OnFinishedChangingPropertiesDelegate.Broadcast(PropertyChangedEvent); } void SDetailsViewBase::RequestItemExpanded(TSharedRef<IDetailTreeNode> TreeNode, bool bExpand) { // Don't change expansion state if its already in that state if (DetailTree->IsItemExpanded(TreeNode) != bExpand) { FilteredNodesRequestingExpansionState.Add(TreeNode, bExpand); } } void SDetailsViewBase::RefreshTree() { if (OnDisplayedPropertiesChangedDelegate.IsBound()) { OnDisplayedPropertiesChangedDelegate.Execute(); } DetailTree->RequestTreeRefresh(); } void SDetailsViewBase::SaveCustomExpansionState(const FString& NodePath, bool bIsExpanded) { if (bIsExpanded) { ExpandedDetailNodes.Add(NodePath); } else { ExpandedDetailNodes.Remove(NodePath); } } bool SDetailsViewBase::GetCustomSavedExpansionState(const FString& NodePath) const { return ExpandedDetailNodes.Contains(NodePath); } bool SDetailsViewBase::IsPropertyVisible( const FPropertyAndParent& PropertyAndParent ) const { return IsPropertyVisibleDelegate.IsBound() ? IsPropertyVisibleDelegate.Execute(PropertyAndParent) : true; } bool SDetailsViewBase::IsPropertyReadOnly( const FPropertyAndParent& PropertyAndParent ) const { return IsPropertyReadOnlyDelegate.IsBound() ? IsPropertyReadOnlyDelegate.Execute(PropertyAndParent) : false; } TSharedPtr<IPropertyUtilities> SDetailsViewBase::GetPropertyUtilities() { return PropertyUtilities; } void SDetailsViewBase::OnShowOnlyModifiedClicked() { CurrentFilter.bShowOnlyModifiedProperties = !CurrentFilter.bShowOnlyModifiedProperties; UpdateFilteredDetails(); } void SDetailsViewBase::OnShowAllAdvancedClicked() { CurrentFilter.bShowAllAdvanced = !CurrentFilter.bShowAllAdvanced; UpdateFilteredDetails(); } void SDetailsViewBase::OnShowOnlyDifferingClicked() { CurrentFilter.bShowOnlyDiffering = !CurrentFilter.bShowOnlyDiffering; UpdateFilteredDetails(); } void SDetailsViewBase::OnShowAllChildrenIfCategoryMatchesClicked() { CurrentFilter.bShowAllChildrenIfCategoryMatches = !CurrentFilter.bShowAllChildrenIfCategoryMatches; UpdateFilteredDetails(); } /** Called when the filter text changes. This filters specific property nodes out of view */ void SDetailsViewBase::OnFilterTextChanged(const FText& InFilterText) { FString InFilterString = InFilterText.ToString(); InFilterString.Trim().TrimTrailing(); // Was the filter just cleared bool bFilterCleared = InFilterString.Len() == 0 && CurrentFilter.FilterStrings.Num() > 0; FilterView(InFilterString); } TSharedPtr<SWidget> SDetailsViewBase::GetNameAreaWidget() { return DetailsViewArgs.bCustomNameAreaLocation ? NameArea : nullptr; } TSharedPtr<SWidget> SDetailsViewBase::GetFilterAreaWidget() { return DetailsViewArgs.bCustomFilterAreaLocation ? FilterRow : nullptr; } TSharedPtr<class FUICommandList> SDetailsViewBase::GetHostCommandList() const { return DetailsViewArgs.HostCommandList; } /** * Hides or shows properties based on the passed in filter text * * @param InFilterText The filter text */ void SDetailsViewBase::FilterView(const FString& InFilterText) { TArray<FString> CurrentFilterStrings; FString ParseString = InFilterText; // Remove whitespace from the front and back of the string ParseString.Trim(); ParseString.TrimTrailing(); ParseString.ParseIntoArray(CurrentFilterStrings, TEXT(" "), true); bHasActiveFilter = CurrentFilterStrings.Num() > 0; CurrentFilter.FilterStrings = CurrentFilterStrings; UpdateFilteredDetails(); } void SDetailsViewBase::QueryLayoutForClass(FDetailLayoutBuilderImpl& CustomDetailLayout, UStruct* Class) { CustomDetailLayout.SetCurrentCustomizationClass(CastChecked<UClass>(Class), NAME_None); FPropertyEditorModule& ParentPlugin = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); FCustomDetailLayoutNameMap& GlobalCustomLayoutNameMap = ParentPlugin.ClassNameToDetailLayoutNameMap; // Check the instanced map first FDetailLayoutCallback* Callback = InstancedClassToDetailLayoutMap.Find(TWeakObjectPtr<UStruct>(Class)); if (!Callback) { // callback wasn't found in the per instance map, try the global instances instead Callback = GlobalCustomLayoutNameMap.Find(Class->GetFName()); } if (Callback && Callback->DetailLayoutDelegate.IsBound()) { // Create a new instance of the custom detail layout for the current class TSharedRef<IDetailCustomization> CustomizationInstance = Callback->DetailLayoutDelegate.Execute(); // Ask for details immediately CustomizationInstance->CustomizeDetails(CustomDetailLayout); // Save the instance from destruction until we refresh CustomizationClassInstances.Add(CustomizationInstance); } } void SDetailsViewBase::QueryCustomDetailLayout(FDetailLayoutBuilderImpl& CustomDetailLayout) { FPropertyEditorModule& ParentPlugin = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); // Get the registered classes that customize details FCustomDetailLayoutNameMap& GlobalCustomLayoutNameMap = ParentPlugin.ClassNameToDetailLayoutNameMap; UStruct* BaseStruct = GetBaseStruct(); // All the current customization instances need to be deleted when it is safe CustomizationClassInstancesPendingDelete = CustomizationClassInstances; CustomizationClassInstances.Empty(); //Ask for generic details not specific to an object being viewed if (GenericLayoutDelegate.IsBound()) { // Create a new instance of the custom detail layout for the current class TSharedRef<IDetailCustomization> CustomizationInstance = GenericLayoutDelegate.Execute(); // Ask for details immediately CustomizationInstance->CustomizeDetails(CustomDetailLayout); // Save the instance from destruction until we refresh CustomizationClassInstances.Add(CustomizationInstance); } // Sort them by query order. @todo not good enough struct FCompareFDetailLayoutCallback { FORCEINLINE bool operator()(const FDetailLayoutCallback& A, const FDetailLayoutCallback& B) const { return A.Order < B.Order; } }; TMap< TWeakObjectPtr<UStruct>, FDetailLayoutCallback*> FinalCallbackMap; for (auto ClassIt = ClassesWithProperties.CreateConstIterator(); ClassIt; ++ClassIt) { // Check the instanced map first FDetailLayoutCallback* Callback = InstancedClassToDetailLayoutMap.Find(*ClassIt); if (!Callback) { // callback wasn't found in the per instance map, try the global instances instead Callback = GlobalCustomLayoutNameMap.Find((*ClassIt)->GetFName()); } if (Callback) { FinalCallbackMap.Add(*ClassIt, Callback); } } FinalCallbackMap.ValueSort(FCompareFDetailLayoutCallback()); TSet<UStruct*> QueriedClasses; if (FinalCallbackMap.Num() > 0) { // Ask each class that we have properties for to customize its layout for (auto LayoutIt(FinalCallbackMap.CreateConstIterator()); LayoutIt; ++LayoutIt) { const TWeakObjectPtr<UStruct> WeakClass = LayoutIt.Key(); if (WeakClass.IsValid()) { UStruct* Class = WeakClass.Get(); FClassInstanceToPropertyMap& InstancedPropertyMap = ClassToPropertyMap.FindChecked(Class->GetFName()); for (FClassInstanceToPropertyMap::TIterator InstanceIt(InstancedPropertyMap); InstanceIt; ++InstanceIt) { FName Key = InstanceIt.Key(); CustomDetailLayout.SetCurrentCustomizationClass(CastChecked<UClass>(Class), Key); const FOnGetDetailCustomizationInstance& DetailDelegate = LayoutIt.Value()->DetailLayoutDelegate; if (DetailDelegate.IsBound()) { QueriedClasses.Add(Class); // Create a new instance of the custom detail layout for the current class TSharedRef<IDetailCustomization> CustomizationInstance = DetailDelegate.Execute(); // Ask for details immediately CustomizationInstance->CustomizeDetails(CustomDetailLayout); // Save the instance from destruction until we refresh CustomizationClassInstances.Add(CustomizationInstance); } } } } } // Ensure that the base class and its parents are always queried TSet<UStruct*> ParentClassesToQuery; if (BaseStruct && !QueriedClasses.Contains(BaseStruct)) { ParentClassesToQuery.Add(BaseStruct); ClassesWithProperties.Add(BaseStruct); } // Find base classes of queried classes that were not queried and add them to the query list // this supports cases where a parent class has no properties but still wants to add customization for (auto QueriedClassIt = ClassesWithProperties.CreateConstIterator(); QueriedClassIt; ++QueriedClassIt) { UStruct* ParentStruct = (*QueriedClassIt)->GetSuperStruct(); while (ParentStruct && ParentStruct->IsA(UClass::StaticClass()) && !QueriedClasses.Contains(ParentStruct) && !ClassesWithProperties.Contains(ParentStruct)) { ParentClassesToQuery.Add(ParentStruct); ParentStruct = ParentStruct->GetSuperStruct(); } } // Query extra base classes for (auto ParentIt = ParentClassesToQuery.CreateConstIterator(); ParentIt; ++ParentIt) { if (Cast<UClass>(*ParentIt)) { QueryLayoutForClass(CustomDetailLayout, *ParentIt); } } } EVisibility SDetailsViewBase::GetFilterBoxVisibility() const { // Visible if we allow search and we have anything to search otherwise collapsed so it doesn't take up room return (DetailsViewArgs.bAllowSearch && IsConnected()) ? EVisibility::Visible : EVisibility::Collapsed; } bool SDetailsViewBase::SupportsKeyboardFocus() const { return DetailsViewArgs.bSearchInitialKeyFocus && SearchBox->SupportsKeyboardFocus() && GetFilterBoxVisibility() == EVisibility::Visible; } FReply SDetailsViewBase::OnFocusReceived(const FGeometry& MyGeometry, const FFocusEvent& InFocusEvent) { FReply Reply = FReply::Handled(); if (InFocusEvent.GetCause() != EFocusCause::Cleared) { Reply.SetUserFocus(SearchBox.ToSharedRef(), InFocusEvent.GetCause()); } return Reply; } /** Ticks the property view. This function performs a data consistency check */ void SDetailsViewBase::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) { for (int32 i = 0; i < CustomizationClassInstancesPendingDelete.Num(); ++i) { ensure(CustomizationClassInstancesPendingDelete[i].IsUnique()); } if (RootNodePendingKill.IsValid()) { RootNodePendingKill->Disconnect(); RootNodePendingKill.Reset(); } // Empty all the customization instances that need to be deleted CustomizationClassInstancesPendingDelete.Empty(); auto RootPropertyNode = GetRootNode(); check(RootPropertyNode.IsValid()); // Purge any objects that are marked pending kill from the object list if (auto ObjectRoot = RootPropertyNode->AsObjectNode()) { ObjectRoot->PurgeKilledObjects(); } if (DeferredActions.Num() > 0) { // Any deferred actions are likely to cause the node tree to be at least partially rebuilt // Save the expansion state of existing nodes so we can expand them later SaveExpandedItems( RootPropertyNode.ToSharedRef() ); // Execute any deferred actions for (int32 ActionIndex = 0; ActionIndex < DeferredActions.Num(); ++ActionIndex) { DeferredActions[ActionIndex].ExecuteIfBound(); } DeferredActions.Empty(); } if( RootPropertyNode == RootNodePendingKill ) { // Reaquire the root property node. It may have been changed by the deferred actions if something like a blueprint editor forcefully resets a details panel during a posteditchange RootPropertyNode = GetRootNode(); RestoreExpandedItems( RootPropertyNode.ToSharedRef() ); } bool bValidateExternalNodes = true; FPropertyNode::DataValidationResult Result = RootPropertyNode->EnsureDataIsValid(); if (Result == FPropertyNode::PropertiesChanged || Result == FPropertyNode::EditInlineNewValueChanged) { RestoreExpandedItems( RootPropertyNode.ToSharedRef() ); UpdatePropertyMap(); UpdateFilteredDetails(); } else if (Result == FPropertyNode::ArraySizeChanged) { RestoreExpandedItems( RootPropertyNode.ToSharedRef() ); UpdateFilteredDetails(); } else if (Result == FPropertyNode::ObjectInvalid) { ForceRefresh(); // All objects are being reset, no need to validate external nodes bValidateExternalNodes = false; } if (bValidateExternalNodes) { for (int32 NodeIndex = 0; NodeIndex < ExternalRootPropertyNodes.Num(); ++NodeIndex) { TSharedPtr<FPropertyNode> PropertyNode = ExternalRootPropertyNodes[NodeIndex].Pin(); if (PropertyNode.IsValid()) { Result = PropertyNode->EnsureDataIsValid(); if (Result == FPropertyNode::PropertiesChanged || Result == FPropertyNode::EditInlineNewValueChanged) { RestoreExpandedItems(PropertyNode.ToSharedRef()); UpdatePropertyMap(); UpdateFilteredDetails(); // Note this will invalidate all the external root nodes so there is no need to continue ExternalRootPropertyNodes.Empty(); break; } else if (Result == FPropertyNode::ArraySizeChanged) { RestoreExpandedItems(PropertyNode.ToSharedRef()); UpdateFilteredDetails(); } } else { // Remove the current node if it is no longer valid ExternalRootPropertyNodes.RemoveAt(NodeIndex); --NodeIndex; } } } if (DetailLayout.IsValid()) { DetailLayout->Tick(InDeltaTime); } if (!ColorPropertyNode.IsValid() && bHasOpenColorPicker) { // Destroy the color picker window if the color property node has become invalid DestroyColorPicker(); bHasOpenColorPicker = false; } if (FilteredNodesRequestingExpansionState.Num() > 0) { // change expansion state on the nodes that request it for (TMap<TSharedRef<IDetailTreeNode>, bool >::TConstIterator It(FilteredNodesRequestingExpansionState); It; ++It) { DetailTree->SetItemExpansion(It.Key(), It.Value()); } FilteredNodesRequestingExpansionState.Empty(); } } /** * Recursively gets expanded items for a node * * @param InPropertyNode The node to get expanded items from * @param OutExpandedItems List of expanded items that were found */ void GetExpandedItems(TSharedPtr<FPropertyNode> InPropertyNode, TArray<FString>& OutExpandedItems) { if (InPropertyNode->HasNodeFlags(EPropertyNodeFlags::Expanded)) { const bool bWithArrayIndex = true; FString Path; Path.Empty(128); InPropertyNode->GetQualifiedName(Path, bWithArrayIndex); OutExpandedItems.Add(Path); } for (int32 ChildIndex = 0; ChildIndex < InPropertyNode->GetNumChildNodes(); ++ChildIndex) { GetExpandedItems(InPropertyNode->GetChildNode(ChildIndex), OutExpandedItems); } } /** * Recursively sets expanded items for a node * * @param InNode The node to set expanded items on * @param OutExpandedItems List of expanded items to set */ void SetExpandedItems(TSharedPtr<FPropertyNode> InPropertyNode, const TArray<FString>& InExpandedItems) { if (InExpandedItems.Num() > 0) { const bool bWithArrayIndex = true; FString Path; Path.Empty(128); InPropertyNode->GetQualifiedName(Path, bWithArrayIndex); for (int32 ItemIndex = 0; ItemIndex < InExpandedItems.Num(); ++ItemIndex) { if (InExpandedItems[ItemIndex] == Path) { InPropertyNode->SetNodeFlags(EPropertyNodeFlags::Expanded, true); break; } } for (int32 NodeIndex = 0; NodeIndex < InPropertyNode->GetNumChildNodes(); ++NodeIndex) { SetExpandedItems(InPropertyNode->GetChildNode(NodeIndex), InExpandedItems); } } } void SDetailsViewBase::SaveExpandedItems( TSharedRef<FPropertyNode> StartNode ) { UStruct* BestBaseStruct = StartNode->FindComplexParent()->GetBaseStructure(); TArray<FString> ExpandedPropertyItems; GetExpandedItems(StartNode, ExpandedPropertyItems); // Handle spaces in expanded node names by wrapping them in quotes for( FString& String : ExpandedPropertyItems ) { String.InsertAt(0, '"'); String.AppendChar('"'); } TArray<FString> ExpandedCustomItems = ExpandedDetailNodes.Array(); // Expanded custom items may have spaces but SetSingleLineArray doesnt support spaces (treats it as another element in the array) // Append a '|' after each element instead FString ExpandedCustomItemsString; for (auto It = ExpandedDetailNodes.CreateConstIterator(); It; ++It) { ExpandedCustomItemsString += *It; ExpandedCustomItemsString += TEXT(","); } //while a valid class, and we're either the same as the base class (for multiple actors being selected and base class is AActor) OR we're not down to AActor yet) for (UStruct* Struct = BestBaseStruct; Struct && ((BestBaseStruct == Struct) || (Struct != AActor::StaticClass())); Struct = Struct->GetSuperStruct()) { if (StartNode->GetNumChildNodes() > 0) { bool bShouldSave = ExpandedPropertyItems.Num() > 0; if (!bShouldSave) { TArray<FString> DummyExpandedPropertyItems; GConfig->GetSingleLineArray(TEXT("DetailPropertyExpansion"), *Struct->GetName(), DummyExpandedPropertyItems, GEditorPerProjectIni); bShouldSave = DummyExpandedPropertyItems.Num() > 0; } if (bShouldSave) { GConfig->SetSingleLineArray(TEXT("DetailPropertyExpansion"), *Struct->GetName(), ExpandedPropertyItems, GEditorPerProjectIni); } } } if (DetailLayout.IsValid() && BestBaseStruct) { bool bShouldSave = !ExpandedCustomItemsString.IsEmpty(); if (!bShouldSave) { FString DummyExpandedCustomItemsString; GConfig->GetString(TEXT("DetailCustomWidgetExpansion"), *BestBaseStruct->GetName(), DummyExpandedCustomItemsString, GEditorPerProjectIni); bShouldSave = !DummyExpandedCustomItemsString.IsEmpty(); } if (bShouldSave) { GConfig->SetString(TEXT("DetailCustomWidgetExpansion"), *BestBaseStruct->GetName(), *ExpandedCustomItemsString, GEditorPerProjectIni); } } } void SDetailsViewBase::RestoreExpandedItems(TSharedRef<FPropertyNode> InitialStartNode) { TSharedPtr<FPropertyNode> StartNode = InitialStartNode; ExpandedDetailNodes.Empty(); TArray<FString> ExpandedPropertyItems; FString ExpandedCustomItems; UStruct* BestBaseStruct = StartNode->FindComplexParent()->GetBaseStructure(); //while a valid class, and we're either the same as the base class (for multiple actors being selected and base class is AActor) OR we're not down to AActor yet) for (UStruct* Struct = BestBaseStruct; Struct && ((BestBaseStruct == Struct) || (Struct != AActor::StaticClass())); Struct = Struct->GetSuperStruct()) { GConfig->GetSingleLineArray(TEXT("DetailPropertyExpansion"), *Struct->GetName(), ExpandedPropertyItems, GEditorPerProjectIni); SetExpandedItems(StartNode, ExpandedPropertyItems); } if (BestBaseStruct) { GConfig->GetString(TEXT("DetailCustomWidgetExpansion"), *BestBaseStruct->GetName(), ExpandedCustomItems, GEditorPerProjectIni); TArray<FString> ExpandedCustomItemsArray; ExpandedCustomItems.ParseIntoArray(ExpandedCustomItemsArray, TEXT(","), true); ExpandedDetailNodes.Append(ExpandedCustomItemsArray); } } void SDetailsViewBase::UpdateFilteredDetails() { auto RootPropertyNode = GetRootNode(); if (RootPropertyNode.IsValid()) { RootPropertyNode->FilterNodes(CurrentFilter.FilterStrings); RootPropertyNode->ProcessSeenFlags(true); for (int32 NodeIndex = 0; NodeIndex < ExternalRootPropertyNodes.Num(); ++NodeIndex) { TSharedPtr<FPropertyNode> PropertyNode = ExternalRootPropertyNodes[NodeIndex].Pin(); if (PropertyNode.IsValid()) { PropertyNode->FilterNodes(CurrentFilter.FilterStrings); PropertyNode->ProcessSeenFlags(true); } } if (DetailLayout.IsValid()) { DetailLayout->FilterDetailLayout(CurrentFilter); } RootTreeNodes = DetailLayout->GetRootTreeNodes(); } RefreshTree(); } /** * Determines whether or not a property should be visible in the default generated detail layout * * @param PropertyNode The property node to check * @param ParentNode The parent property node to check * @return true if the property should be visible */ static bool IsVisibleStandaloneProperty(const FPropertyNode& PropertyNode, const FPropertyNode& ParentNode) { const UProperty* Property = PropertyNode.GetProperty(); const UArrayProperty* ParentArrayProperty = Cast<const UArrayProperty>(ParentNode.GetProperty()); bool bIsVisibleStandalone = false; if (Property) { if (Property->IsA(UObjectPropertyBase::StaticClass())) { // Do not add this child node to the current map if its a single object property in a category (serves no purpose for UI) bIsVisibleStandalone = !ParentArrayProperty && (PropertyNode.GetNumChildNodes() == 0 || PropertyNode.GetNumChildNodes() > 1); } else if (Property->IsA(UArrayProperty::StaticClass()) || (Property->ArrayDim > 1 && PropertyNode.GetArrayIndex() == INDEX_NONE)) { // Base array properties are always visible bIsVisibleStandalone = true; } else { bIsVisibleStandalone = true; } } return bIsVisibleStandalone; } void SDetailsViewBase::UpdatePropertyMapRecursive(FPropertyNode& InNode, FDetailLayoutBuilderImpl& InDetailLayout, FName CurCategory, FComplexPropertyNode* CurObjectNode) { UProperty* ParentProperty = InNode.GetProperty(); UStructProperty* ParentStructProp = Cast<UStructProperty>(ParentProperty); for (int32 ChildIndex = 0; ChildIndex < InNode.GetNumChildNodes(); ++ChildIndex) { TSharedPtr<FPropertyNode> ChildNodePtr = InNode.GetChildNode(ChildIndex); FPropertyNode& ChildNode = *ChildNodePtr; UProperty* Property = ChildNode.GetProperty(); { FObjectPropertyNode* ObjNode = ChildNode.AsObjectNode(); FCategoryPropertyNode* CategoryNode = ChildNode.AsCategoryNode(); if (ObjNode) { // Currently object property nodes do not provide any useful information other than being a container for its children. We do not draw anything for them. // When we encounter object property nodes, add their children instead of adding them to the tree. UpdatePropertyMapRecursive(ChildNode, InDetailLayout, CurCategory, ObjNode); } else if (CategoryNode) { // For category nodes, we just set the current category and recurse through the children UpdatePropertyMapRecursive(ChildNode, InDetailLayout, CategoryNode->GetCategoryName(), CurObjectNode); } else { // Whether or not the property can be visible in the default detail layout bool bVisibleByDefault = IsVisibleStandaloneProperty(ChildNode, InNode); // Whether or not the property is a struct UStructProperty* StructProperty = Cast<UStructProperty>(Property); bool bIsStruct = StructProperty != NULL; static FName ShowOnlyInners("ShowOnlyInnerProperties"); bool bIsChildOfCustomizedStruct = false; bool bIsCustomizedStruct = false; const UStruct* Struct = StructProperty ? StructProperty->Struct : NULL; const UStruct* ParentStruct = ParentStructProp ? ParentStructProp->Struct : NULL; if (Struct || ParentStruct) { FPropertyEditorModule& ParentPlugin = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); if (Struct) { bIsCustomizedStruct = ParentPlugin.IsCustomizedStruct(Struct, SharedThis( this ) ); } if (ParentStruct) { bIsChildOfCustomizedStruct = ParentPlugin.IsCustomizedStruct(ParentStruct, SharedThis( this ) ); } } // Whether or not to push out struct properties to their own categories or show them inside an expandable struct bool bPushOutStructProps = bIsStruct && !bIsCustomizedStruct && !ParentStructProp && Property->HasMetaData(ShowOnlyInners); // Is the property edit inline new const bool bIsEditInlineNew = SPropertyEditorEditInline::Supports(&ChildNode, ChildNode.GetArrayIndex()); // Is this a property of an array bool bIsChildOfArray = PropertyEditorHelpers::IsChildOfArray(ChildNode); // Edit inline new properties should be visible by default bVisibleByDefault |= bIsEditInlineNew; // Children of arrays are not visible directly, bVisibleByDefault &= !bIsChildOfArray; FPropertyAndParent PropertyAndParent(*Property, ParentProperty); const bool bIsUserVisible = IsPropertyVisible(PropertyAndParent); // Inners of customized in structs should not be taken into consideration for customizing. They are not designed to be individually customized when their parent is already customized if (!bIsChildOfCustomizedStruct) { // Add any object classes with properties so we can ask them for custom property layouts later ClassesWithProperties.Add(Property->GetOwnerStruct()); } // If there is no outer object then the class is the object root and there is only one instance FName InstanceName = NAME_None; if (CurObjectNode && CurObjectNode->GetParentNode()) { InstanceName = CurObjectNode->GetParentNode()->GetProperty()->GetFName(); } else if (ParentStructProp) { InstanceName = ParentStructProp->GetFName(); } // Do not add children of customized in struct properties or arrays if (!bIsChildOfCustomizedStruct && !bIsChildOfArray) { // Get the class property map FClassInstanceToPropertyMap& ClassInstanceMap = ClassToPropertyMap.FindOrAdd(Property->GetOwnerStruct()->GetFName()); FPropertyNodeMap& PropertyNodeMap = ClassInstanceMap.FindOrAdd(InstanceName); if (!PropertyNodeMap.ParentProperty) { PropertyNodeMap.ParentProperty = CurObjectNode; } else { ensure(PropertyNodeMap.ParentProperty == CurObjectNode); } checkSlow(!PropertyNodeMap.Contains(Property->GetFName())); PropertyNodeMap.Add(Property->GetFName(), ChildNodePtr); } if (bVisibleByDefault && bIsUserVisible && !bPushOutStructProps) { FName CategoryName = CurCategory; // For properties inside a struct, add them to their own category unless they just take the name of the parent struct. // In that case push them to the parent category FName PropertyCatagoryName = FObjectEditorUtils::GetCategoryFName(Property); if (!ParentStructProp || (PropertyCatagoryName != ParentStructProp->Struct->GetFName())) { CategoryName = PropertyCatagoryName; } if (IsPropertyReadOnly(PropertyAndParent)) { ChildNode.SetNodeFlags(EPropertyNodeFlags::IsReadOnly, true); } // Add a property to the default category FDetailCategoryImpl& CategoryImpl = InDetailLayout.DefaultCategory(CategoryName); CategoryImpl.AddPropertyNode(ChildNodePtr.ToSharedRef(), InstanceName); } bool bRecurseIntoChildren = !bIsChildOfCustomizedStruct // Don't recurse into built in struct children, we already know what they are and how to display them && !bIsCustomizedStruct // Don't recurse into customized structs && !bIsChildOfArray // Do not recurse into arrays, the children are drawn by the array property parent && !bIsEditInlineNew // Edit inline new children are not supported for customization yet && bIsUserVisible // Properties must be allowed to be visible by a user if they are not then their children are not visible either && (!bIsStruct || bPushOutStructProps); // Only recurse into struct properties if they are going to be displayed as standalone properties in categories instead of inside an expandable area inside a category if (bRecurseIntoChildren) { // Built in struct properties or children of arras UpdatePropertyMapRecursive(ChildNode, InDetailLayout, CurCategory, CurObjectNode); } } } } } void SDetailsViewBase::UpdatePropertyMap() { // Reset everything ClassToPropertyMap.Empty(); ClassesWithProperties.Empty(); // We need to be able to create a new detail layout and properly clean up the old one in the process check(!DetailLayout.IsValid() || DetailLayout.IsUnique()); RootTreeNodes.Empty(); DetailLayout = MakeShareable(new FDetailLayoutBuilderImpl(ClassToPropertyMap, PropertyUtilities.ToSharedRef(), SharedThis(this))); auto RootPropertyNode = GetRootNode(); check(RootPropertyNode.IsValid()); // Currently object property nodes do not provide any useful information other than being a container for its children. We do not draw anything for them. // When we encounter object property nodes, add their children instead of adding them to the tree. UpdatePropertyMapRecursive(*RootPropertyNode, *DetailLayout, NAME_None, RootPropertyNode.Get()); CustomUpdatePropertyMap(); // Ask for custom detail layouts, unless disabled. One reason for disabling custom layouts is that the custom layouts // inhibit our ability to find a single property's tree node. This is problematic for the diff and merge tools, that need // to display and highlight each changed property for the user. We could whitelist 'good' customizations here if // we can make them work with the diff/merge tools. if( !bDisableCustomDetailLayouts ) { QueryCustomDetailLayout(*DetailLayout); } DetailLayout->GenerateDetailLayout(); }
bsd-2-clause
tanghaibao/jcvi
jcvi/utils/console.py
355
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # console.py # utils # # Created by Haibao Tang on 01/09/21 # Copyright © 2021 Haibao Tang. All rights reserved. # """ We create a singleton console instance at the module level or as an attribute of your top-level object. """ from rich.console import Console console = Console() printf = console.print
bsd-2-clause
vividos/RemotePhotoTool
src/RemotePhotoTool/AboutDlg.cpp
1410
// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2014 Michael Fink // /// \file RemotePhotoTool\AboutDlg.cpp About dialog for remote photo tool // // includes #include "stdafx.h" #include "resource.h" #include "AboutDlg.hpp" #include "Instance.hpp" #include "../version.h" #include "Lua.hpp" void AboutDlg::SetVersionText() { DlgResize_Init(true, true); CWindow scVersion = GetDlgItem(IDC_STATIC_ABOUT_VERSION); CString cszVersion; scVersion.GetWindowText(cszVersion); CString cszAppVersion; cszAppVersion.Format(_T("")); cszVersion.Replace(_T("%VERSION%"), CString(VERSIONINFO_FILEVERSION_DISPLAYSTRING)); cszVersion.Replace(_T("%COPYRIGHT%"), CString(VERSIONINFO_COPYRIGHT)); scVersion.SetWindowText(cszVersion); } void AboutDlg::SetAboutInfo() { CWindow scInfo = GetDlgItem(IDC_STATIC_ABOUT_INFO); CString cszInfo; scInfo.GetWindowText(cszInfo); cszInfo += Instance::Get().Version(); cszInfo += _T("Lua version: "); cszInfo += Lua::State::GetVersion(); scInfo.SetWindowText(cszInfo); } LRESULT AboutDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CenterWindow(GetParent()); SetVersionText(); SetAboutInfo(); return TRUE; } LRESULT AboutDlg::OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { EndDialog(wID); return 0; }
bsd-2-clause
cblecker/homebrew-cask
Casks/thunderbird.rb
2682
cask 'thunderbird' do version '60.7.2' language 'cs' do sha256 '1a08ba2673eae88b28bf4fd5111c4af14a29cef31cac7ba91510662100aa7777' 'cs' end language 'de' do sha256 'c90f9b4bc44207b4769d440b1e309e23e7db5b37217713e07cdf73fc3e9531da' 'de' end language 'en-GB' do sha256 '4bc8ee7232a30c9941ca08df3842f109106646cca6c79ab6c4d410b669da770e' 'en-GB' end language 'en', default: true do sha256 '66d937ee3db5d06d7982046e24f9340d60612889c15ef98b224726824376f910' 'en-US' end language 'fr' do sha256 '1482e6c764f5857f23610b274ada54626a98fbb7a747623440d4028abe801085' 'fr' end language 'gl' do sha256 'cc8b175c69d7e0c17795bcf259f8a04f5ca4dbda19a2ac9460fd85490ac4c6a4' 'gl' end language 'it' do sha256 '5e5ddc846a6152139147f064e62a2ca4f5a15f9810e3d717533062d881a0c3af' 'it' end language 'ja' do sha256 'e09a928b4da3712cdb211ba86f8fef2df4d7904a13bc2e518208a13fe7b6dff0' 'ja-JP-mac' end language 'nl' do sha256 'a0b7f70c76306f674e08fbc487a0609d841fcce19e28d4df37325713e387962f' 'nl' end language 'pl' do sha256 '4e77c5017535a0ad61c208753f13b0443cfa0cc7179a0c188c2ff2277188427d' 'pl' end language 'pt' do sha256 '96ee4cabfaf55a860ce1cfde64a2862ca2f6f224ce868d106afcf6da5760b8b2' 'pt-PT' end language 'pt-BR' do sha256 '5732ccdc1cdb8a73cfbe230f2827d26e3e191980817dddd796e44ec5ad15cac3' 'pt-BR' end language 'ru' do sha256 '7ae77e285eccac3a05d126aa3b03c85f3b0f09a1eedfb12c823fb3b9c7666420' 'ru' end language 'uk' do sha256 'dbd509d572e35c32b47f852ba5d380cd048deb577c0c954537dd11e7ad787c9c' 'uk' end language 'zh-TW' do sha256 '74746c1b732ff0a5bed72ad66470920a3c7a1c8c6df282e96e59c15f3c239386' 'zh-TW' end language 'zh' do sha256 'fd73b93ee416cfe8b1e33557be018b7b9a8fed267aff11ca688001b467c2b00c' 'zh-CN' end url "https://ftp.mozilla.org/pub/thunderbird/releases/#{version}/mac/#{language}/Thunderbird%20#{version}.dmg" appcast 'https://www.thunderbird.net/en-US/thunderbird/releases/' name 'Mozilla Thunderbird' homepage 'https://www.mozilla.org/thunderbird/' auto_updates true conflicts_with cask: 'thunderbird-beta' app 'Thunderbird.app' zap trash: [ '~/Library/Thunderbird', '~/Library/Caches/Thunderbird', '~/Library/Saved Application State/org.mozilla.thunderbird.savedState', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.thunderbird.sfl*', '~/Library/Preferences/org.mozilla.thunderbird.plist', ] end
bsd-2-clause
vicchi/maps-api-demos
ovi-polylines.js
1361
var map; function initialize() { map = new ovi.mapsapi.map.Display( document.getElementById("map"), { 'zoomLevel': 12, 'center': [37.78,-122.395033836365], components: [ new ovi.mapsapi.map.component.Behavior(), new ovi.mapsapi.map.component.ZoomBar() ] }); poly(map); } function poly(mapobj) { // create a polygon object var myPoly = new ovi.mapsapi.map.Polygon([ new ovi.mapsapi.geo.Coordinate(37.7945928242851,-122.395033836365), new ovi.mapsapi.geo.Coordinate(37.7938467508748,-122.393960952759), new ovi.mapsapi.geo.Coordinate(37.7945928242851,-122.39275932312), new ovi.mapsapi.geo.Coordinate(37.789505810689,-122.387609481812), new ovi.mapsapi.geo.Coordinate(37.7782792282611,-122.387351989746), new ovi.mapsapi.geo.Coordinate(37.7768545853105,-122.390570640564), new ovi.mapsapi.geo.Coordinate(37.7690524823224,-122.397179603577), new ovi.mapsapi.geo.Coordinate(37.7668813159428,-122.394347190857), new ovi.mapsapi.geo.Coordinate(37.7658635597592,-122.407650947571), new ovi.mapsapi.geo.Coordinate(37.7689167862912,-122.408037185669), new ovi.mapsapi.geo.Coordinate(37.7765493011063,-122.417650222778), new ovi.mapsapi.geo.Coordinate(37.7945928242851,-122.395033836365) ], { pen:{strokeColor: "#000", lineWidth: 1}, brush:{color: "#2C2A"} }); mapobj.objects.add(myPoly); }
bsd-2-clause
golems/HuboCan
HuboCan/test/InfoTypes_test.cpp
2205
/* * Copyright (c) 2015, Georgia Tech Research Corporation * All rights reserved. * * Author(s): Michael X. Grey <greyxmike@gmail.com> * * Humanoid Robotics Lab * * Directed by Prof. Mike Stilman <mstilman@cc.gatech.edu> * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "HuboCan/InfoTypes.hpp" using namespace HuboCan; error_result_t make_an_error() { return ARRAY_MISMATCH; } int main(int , char* []) { error_result_t okay; std::cout << okay << std::endl; error_result_t result(READ_ONLY); result.result = READ_ONLY; std::cout << result << " (" << result.result << ")" << std::endl; std::cout << READ_ONLY << std::endl; std::cout << make_an_error() << std::endl; result |= make_an_error(); std::cout << result << std::endl; return 0; }
bsd-2-clause
pcloudcom/pfs-gui
pCloud/registerwindow.cpp
3491
#include "registerwindow.h" #include "ui_registerwindow.h" #include "binapi.h" #include "pcloudapp.h" #include "common.h" RegisterWindow::RegisterWindow(PCloudApp *a, QWidget *parent) : QMainWindow(parent), ui(new Ui::RegisterWindow) { app=a; setWindowIcon(QIcon(WINDOW_ICON)); ui->setupUi(this); connect(ui->registerButton, SIGNAL(clicked()), this, SLOT(doRegister())); // connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(hide())); connect(ui->email, SIGNAL(returnPressed()), this, SLOT(focusPass())); connect(ui->password, SIGNAL(returnPressed()), this, SLOT(focusConfirm())); connect(ui->confirmpassword, SIGNAL(returnPressed()), this, SLOT(focusTOS())); // connect(ui->accepttos, SIGNAL(returnPressed()), this, SLOT(doRegister())); connect(ui->loginButton, SIGNAL(clicked()), app, SLOT(showLogin())); } RegisterWindow::~RegisterWindow() { delete ui; } void RegisterWindow::closeEvent(QCloseEvent *event){ hide(); event->ignore(); } void RegisterWindow::setError(const char *err){ ui->error->setText(err); } void RegisterWindow::focusPass(){ ui->password->setFocus(); } void RegisterWindow::focusConfirm(){ ui->confirmpassword->setFocus(); } void RegisterWindow::focusTOS(){ ui->accepttos->setFocus(); } void RegisterWindow::doRegister(){ if (!ui->accepttos->checkState()){ setError("Registration only possible upon acceptance of terms."); return; } if (ui->password->text().length()<6){ setError("Password too short - minimum 6 characters."); return; } if (ui->password->text()!=ui->confirmpassword->text()){ setError("Password confirmation does not match."); return; } QByteArray email=ui->email->text().toUtf8(); QByteArray password=ui->password->text().toUtf8(); apisock *conn; binresult *res, *result; QByteArray err; quint64 type=0; #if defined(Q_OS_WIN) type=5; #elif defined(Q_OS_LINUX) type=7; #elif defined(Q_OS_MAC) type=6; #endif if (!(conn=app->getAPISock())){ setError("Connection to server failed."); return; } res=send_command(conn, "register", P_STR("termsaccepted", "yes"), P_LSTR("mail", email.constData(), email.size()), P_LSTR("password", password.constData(), password.size()), P_NUM("os", type)); result=find_res(res, "result"); if (!result){ setError("Connection to server failed."); free(res); api_close(conn); return; } if (result->num!=0){ setError(find_res(res, "error")->str); free(res); api_close(conn); return; } res=send_command(conn, "userinfo", P_LSTR("username", email.constData(), email.size()), P_LSTR("password", password.constData(), password.size()), P_BOOL("getauth", 1)); api_close(conn); result=find_res(res, "result"); if (!result){ setError("Connection to server failed."); free(res); return; } if (result->num!=0){ setError(find_res(res, "error")->str); free(res); return; } if (!app->userLogged(res, err, false)) setError(err); else{ setError(""); ui->password->clear(); ui->confirmpassword->clear(); hide(); app->openCloudDir(); } free(res); }
bsd-2-clause
ggobbe/vivre-uo
Scripts/Vivre/Items/Dismounter.cs
2660
using System; using Server; using Server.Mobiles; namespace Server.Items { public class Dismounter : Item { private bool m_Active; private Direction m_Direction; [CommandProperty( AccessLevel.GameMaster )] public bool Active { get { return m_Active; } set { m_Active = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public Direction Facing { get { return m_Direction; } set { m_Direction = value; InvalidateProperties(); } } [Constructable] public Dismounter() : this( Direction.Down, true ) { } [Constructable] public Dismounter( Direction dir ) : this( dir, true ) { } [Constructable] public Dismounter( Direction dir, bool active ) : base( 0x1B7A ) { Movable = false; Visible = false; Name = "Dismounter"; m_Active = active; m_Direction = dir; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( this.Name ); if ( m_Active ) list.Add( 1060742 ); // active else list.Add( 1060743 ); // inactive list.Add( (m_Direction == Direction.Mask) ? "Up" : ((Direction)m_Direction).ToString() ); } public override void OnSingleClick( Mobile from ) { base.OnSingleClick( from ); if ( m_Active ) { LabelTo( from, "Facing " + ((m_Direction == Direction.Mask) ? "Up" : ((Direction)m_Direction).ToString()) ); } else { LabelTo( from, "(inactive)" ); } } public override bool OnMoveOver( Mobile m ) { if ( m_Active ) { if (m.Player && m.Mounted && m.AccessLevel < AccessLevel.GameMaster) { IMount mount = (IMount)m.Mount; mount.Rider = null; if (mount is BaseMount) { ((BaseMount)mount).Direction = m_Direction; // Scriptiz : ajout pour éviter les abus de certains joueurs. ((BaseMount)mount).ControlOrder = OrderType.Stay; } } } return true; } public Dismounter( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( m_Active ); writer.Write( (int)m_Direction ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_Active = reader.ReadBool(); m_Direction = (Direction)reader.ReadInt(); break; } } } } }
bsd-2-clause
EpicLegion/WebRavaged
WebRavaged/application/games/dashboard/blackops.php
56520
<?php defined('SYSPATH') or die('No direct script access.'); /** * Dashboard implementation for Call of Duty: Black Ops * * Copyright (c) 2010, EpicLegion * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @author EpicLegion, Maximusya * @package rcon * @subpackage controller * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ class Controller_Dashboard extends Controller_Dashboard_Core { /** * Current action * * @var string */ protected $action = ''; /** * Ajax refresh for player list */ public function action_ajaxindex() { // Ajax? if(!Request::$is_ajax) { exit; } // Only logged in users $this->do_force_login(); // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Init vars $first_team = array(); $second_team = array(); $spectators = array(); // Get server info $server_info = $commands->get_server_info(); $server_info += array('ip' => $this->current_server['ip'], 'port' => $this->current_server['port']); $server_info['colored_hostname'] = Blackops_Rcon_Constants::colorize($server_info['sv_hostname']); $server_info['playlist_name'] = Blackops_Rcon_Constants::$playlists[$server_info['playlist']]; $server_info['map_name'] = Blackops_Rcon_Constants::$maps[$server_info['map']]; $server_info['gametype_name'] = Blackops_Rcon_Constants::$gametypes[$server_info['g_gametype']]; $server_info['gametype_abbrev'] = Blackops_Rcon_Constants::$gametypes_abbrev[$server_info['g_gametype']]; // Cache $this->session->set('last_server_info', $server_info); // Iterate players foreach($server_info['players'] as $player) { // Get correct IP if($pos = strpos($player['address'], ':')) { $player['ip'] = substr($player['address'], 0, $pos); } else { $player['ip'] = $player['address']; } // Democlient? if($player['name'] == 'democlient' AND Config::get('general.hide_democlient', TRUE)) { continue; } // Add to correct team if($player['team'] == 1) { $first_team[] = $player; } elseif($player['team'] == 2) { $second_team[] = $player; } else { $spectators[] = $player; } } // Players count $server_info['count_players'] = count($server_info['players']); // Democlient is not a player if(isset($server_info['players'][0]) && $server_info['players'][0]['team'] == 3 && $server_info['players'][0]['name'] == 'democlient') { $server_info['count_players']--; } } catch(Exception $e) { // Transmit error echo json_encode(array('error' => __($e->getMessage()), 'content' => '')); exit; } // View $view = new View('blackops/ajax'); // Server info $view->server_info = $server_info; $view->permissions = $this->current_server['permissions']; $view->first_team = $first_team; $view->second_team = $second_team; $view->spectators = $spectators; // Transmit content echo json_encode(array('error' => 'None', 'content' => $view->render())); exit; } /** * Ban player * * @param string $id */ public function action_ban($id) { // ID is numeric if(!ctype_digit($id)) { echo json_encode(array('error' => 'Invalid parameter', 'content' => '')); exit; } // Reason required? if (Config::get('general.kick_reason_required', FALSE) AND empty($_POST['reason'])) { echo json_encode(array('error' => 'Reason required', 'content' => '')); exit; } // Cast $id = (int) $id; // Ajax? if(!Request::$is_ajax) { exit; } // Only logged in users $this->do_force_login(); // Can ban if(!$this->check_permissions(SERVER_BAN, FALSE)) { echo json_encode(array('error' => 'No permission', 'content' => '')); exit; } // Decode message if($_POST['reason']) { $reason = html_entity_decode($_POST['reason'], ENT_QUOTES, 'UTF-8'); } else { $reason = ''; } // Dropdown? if(count(Config::get('kick_reasons', array())) AND $reason) { // Check if(!in_array($reason, Config::get('kick_reasons', array()))) { echo json_encode(array('error' => 'Invalid reason', 'content' => '')); exit; } } // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Ban $commands->ban($id); // Last server info $server_info = $this->session->get('last_server_info'); // Player name not available? if(!$server_info OR !is_array($server_info) OR !isset($server_info['error']) OR $server_info['error'] != '') { // Log $this->log_action(__('Banned player with ID #:id (Reason: :reason)', array(':id' => $id, ':reason' => HTML::chars($reason)))); } else { // Server info available, find player if(isset($server_info['players'][$id])) { // Player found, log name $this->log_action(__('Banned player :name (Reason: :reason)', array( ':name' => $server_info['players'][$id]['name'], ':reason' => HTML::chars($reason) ))); } else { // Player not found, log ID $this->log_action(__('Banned player with ID #:id (Reason: :reason)', array( ':id' => (int) $id, ':reason' => HTML::chars($reason) ))); } } // No error echo json_encode(array('error' => 'None', 'content' => '')); exit; } catch(Exception $e) { // Nasty error :< echo json_encode(array('error' => $e->getMessage(), 'content' => '')); exit; } } /** * Next map in rotation */ public function action_next_map() { // Only logged in users $this->do_force_login(); // Can fast restart? $this->check_permissions(SERVER_FAST_RESTART, TRUE); // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Command $rcon->command('map_rotate'); // Done $this->notice(__('Changed to next map')); // Log $this->log_action(__('Used Change to next map command')); } catch(Exception $e) { // Error $this->notice($e->getMessage()); } // Redirect $this->request->redirect('dashboard/index'); } /** * Fast restart */ public function action_fast_restart() { // Only logged in users $this->do_force_login(); // Can fast restart? $this->check_permissions(SERVER_FAST_RESTART, TRUE); // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Command $rcon->command('fast_restart'); // Done $this->notice(__('Fast restart done')); // Log $this->log_action(__('Used fast restart command')); } catch(Exception $e) { // Error $this->notice($e->getMessage()); } // Redirect $this->request->redirect('dashboard/index'); } /** * Index page */ public function action_index() { // Action $this->action = 'index'; // Only logged in users $this->do_force_login(); // Title $this->title = __('Remote console'); try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Init vars $first_team = array(); $second_team = array(); $spectators = array(); // Get server info $server_info = $commands->get_server_info(); $server_info += array('ip' => $this->current_server['ip'], 'port' => $this->current_server['port']); $server_info['colored_hostname'] = Blackops_Rcon_Constants::colorize($server_info['sv_hostname']); $server_info['playlist_name'] = Blackops_Rcon_Constants::$playlists[$server_info['playlist']]; $server_info['map_name'] = Blackops_Rcon_Constants::$maps[$server_info['map']]; $server_info['gametype_name'] = Blackops_Rcon_Constants::$gametypes[$server_info['g_gametype']]; $server_info['gametype_abbrev'] = Blackops_Rcon_Constants::$gametypes_abbrev[$server_info['g_gametype']]; // Cache $this->session->set('last_server_info', $server_info); // Iterate players foreach($server_info['players'] as $player) { // Get correct IP if($pos = strpos($player['address'], ':')) { $player['ip'] = substr($player['address'], 0, $pos); } else { $player['ip'] = $player['address']; } // Democlient? if ($player['name'] == 'democlient' AND Config::get('general.hide_democlient', TRUE)) { continue; } // Add to correct team if($player['team'] == 1) { $first_team[] = $player; } elseif($player['team'] == 2) { $second_team[] = $player; } else { $spectators[] = $player; } } // Players count $server_info['count_players'] = count($server_info['players']); // Democlient is not a player if(isset($server_info['players'][0]) && $server_info['players'][0]['team'] == 3 && $server_info['players'][0]['name'] == 'democlient') { $server_info['count_players']--; } } catch(Exception $e) { // Default $server_info = array('map' => '', 'players' => array(), 'error' => __($e->getMessage())); } // View $this->view = new View('blackops/index'); // Server info $this->view->server_info = $server_info; $this->view->permissions = (int) $this->current_server['permissions']; $this->view->first_team = $first_team; $this->view->second_team = $second_team; $this->view->spectators = $spectators; } /** * Kick player * * @param string $id */ public function action_kick($id) { // ID is numeric if(!ctype_digit($id)) { echo json_encode(array('error' => 'Invalid parameter', 'content' => '')); exit; } // Reason required? if(Config::get('general.kick_reason_required', FALSE) AND empty($_POST['reason'])) { echo json_encode(array('error' => 'Reason required', 'content' => '')); exit; } // Cast $id = (int) $id; // Ajax? if(!Request::$is_ajax) { exit; } // Only logged in users $this->do_force_login(); // Can kick if(!$this->check_permissions(SERVER_KICK, FALSE)) { echo json_encode(array('error' => 'No permission', 'content' => '')); exit; } // Decode message if($_POST['reason']) { $reason = html_entity_decode($_POST['reason'], ENT_QUOTES, 'UTF-8'); } else { $reason = ''; } // Dropdown? if (count(Config::get('kick_reasons', array())) AND $reason) { // Check if(!in_array($reason, Config::get('kick_reasons', array()))) { echo json_encode(array('error' => 'Invalid reason', 'content' => '')); exit; } } // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Kick $commands->kick($id, FALSE, $reason); // Last server info $server_info = $this->session->get('last_server_info'); // Player name not available? if(!$server_info OR !is_array($server_info) OR !isset($server_info['error']) OR $server_info['error'] != '') { // Log $this->log_action(__('Kicked player with ID #:id (Reason: :reason)', array(':id' => $id, ':reason' => HTML::chars($reason)))); } else { // Server info available, find player if(isset($server_info['players'][$id])) { // Player found, log name $this->log_action(__('Kicked player :name (Reason: :reason)', array( ':name' => $server_info['players'][$id]['name'], ':reason' => HTML::chars($reason) ))); } else { // Player not found, log ID $this->log_action(__('Kicked player with ID #:id (Reason: :reason)', array(':id' => (int) $id, ':reason' => HTML::chars($reason)))); } } // No error echo json_encode(array('error' => 'None', 'content' => '')); exit; } catch(Exception $e) { // Nasty error :< echo json_encode(array('error' => $e->getMessage(), 'content' => '')); exit; } } /** * View player logs * * @param string $guid */ public function action_logs($guid = NULL) { // Action $this->action = 'logs'; // Only logged in users $this->do_force_login(); // Title $this->title = __('Player logs'); // Check permissions $this->check_permissions(SERVER_USER_LOG); // Ajax request means player details if(Request::$is_ajax AND $guid !== NULL AND ctype_digit($guid)) { // Find $log = Model_Player::get_details($this->current_server['id'], $guid); // Valid if(count($log)) { // Unserialize names $log['names'] = empty($log['names']) ? array() : unserialize($log['names']); // Unserialize ip's $log['ip_addresses'] = empty($log['ip_addresses']) ? array() : unserialize($log['ip_addresses']); // Make sure it's array $log['names'] = !is_array($log['names']) ? array() : $log['names']; $log['ip_addresses'] = !is_array($log['ip_addresses']) ? array() : $log['ip_addresses']; // Clean up array_map('strip_tags', $log['names']); // Return echo json_encode(array('error' => 'None', 'ip' => '<li>'.implode('</li><li>', $log['ip_addresses']).'</li>', 'names' => '<li>'.implode('</li><li>', $log['names']).'</li>')); } else { // Log not found echo json_encode(array('error' => 'Log not found')); } // Exit exit; } // Load conditions if($this->session->get('conditions_player_bo', FALSE)) { // Load $conditions = $this->session->get('conditions_player_bo'); } else { // Default $conditions = array('guid' => 0); } // Apply new conditions if(isset($_POST['guid'])) { // User if(ctype_digit($_POST['guid'])) { $conditions['guid'] = (int) $_POST['guid']; } else { $conditions['guid'] = 0; } // Save conditions $this->session->set('conditions_player_bo', $conditions); // Redirect $this->request->redirect('dashboard/logs'); } // View $this->view = new View('blackops/logs'); // Pagination $pagination = new Pagination(array( 'current_page' => array('source' => 'route', 'key' => 'id'), 'items_per_page' => 50, 'auto_hide' => TRUE, 'total_items' => Model_Player::count_logs($this->current_server['id'], $conditions) )); // Logs $this->view->logs = Model_Player::get_logs($this->current_server['id'], $pagination->offset, $conditions); $this->view->pagination = $pagination->render(); $this->view->conditions = $conditions; } /** * Map management */ public function action_maps() { // Action $this->action = 'maps'; // Only logged in users $this->do_force_login(); // Check permission $this->check_permissions(SERVER_MAPS); // Title $this->title = __('Map management'); // Get presets $presets = Config::get_presets(); // Catch errors try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Map rotation $cvar_rotation = $commands->get_cvar('sv_mapRotation'); // Excludes $cvar_excludes = $commands->get_cvar('playlist_excludeMap'); // Preset? if(!empty($_POST['preset']) AND isset($presets[$_POST['preset']])) { // Get preset $preset = $presets[$_POST['preset']]; // Apply exclude if ($preset['excludes'] !== NULL) { $commands->cvar('playlist_excludeMap', $preset['excludes'], TRUE); } // Gametype included? if(substr($preset['rotation'], 0, 8) != 'gametype') { // Split using space as delimiter $rotation2 = explode(' ', $cvar_rotation, 3); // Set as new $cvar_rotation = $preset; // Add gametype if($rotation2[0] == 'gametype' AND isset($rotation2[1])) { $cvar_rotation = 'gametype '.$rotation2[1].' '.$cvar_rotation; } } else { $cvar_rotation = $preset['rotation']; } // Send $commands->cvar('sv_mapRotation', $cvar_rotation, TRUE); // Success $this->notice(__('Preset successfully applied')); // Log $this->log_action(__('Applied map preset: :preset', array(':preset' => HTML::chars($_POST['preset'])))); // Redirect $this->request->redirect('dashboard/maps'); } // Current map $current_map = $commands->get_cvar('mapname'); } catch(Exception $e) { // Error $this->notice(__('Cannot retrieve config vars')); // Redirect $this->request->redirect('dashboard/index'); } // Maps $maps = Blackops_Rcon_Constants::$maps; // Excludes and rotation $excludes = $rotation = array(); // Get excludes foreach(explode(' ', $cvar_excludes) as $e) { // Append if valid if(isset($maps[$e])) { $excludes[$e] = $e; } } // Get rotation foreach(explode(' ', $cvar_rotation) as $r) { // Mapname? if($r != 'map' AND isset($maps[$r])) { $rotation[] = $r; } } // Add remaining maps if(count($maps) != count($rotation)) { foreach(array_keys($maps) as $k) { // Already added? if(!in_array($k, $rotation)) { $rotation[] = $k; } } } // View $this->view = new View('blackops/maps'); // Vars $this->view->presets = $presets; $this->view->rotation = $rotation; $this->view->maps = $maps; $this->view->excludes = $excludes; $this->view->current_map = $current_map; } /** * Change map * * @param string $map */ public function action_maps_change($map) { // Only logged in users $this->do_force_login(); // Check permission $this->check_permissions(SERVER_MAPS); // Catch errors try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Send command $rcon->command('map '.strip_tags($map)); // Notice $this->notice(__('Map successfully change')); // Log $this->log_action(__('Change map to: :map', array(':map' => HTML::chars($map)))); } catch(Exception $e) { // Notice $this->notice(__($e->getMessage())); } // Redirect $this->request->redirect('dashboard/maps'); } /** * Set next map * * @param string $map */ public function action_maps_next($map) { // Only logged in users $this->do_force_login(); // Check permission $this->check_permissions(SERVER_MAPS); // Maps $maps = Blackops_Rcon_Constants::$maps; // Valid map? if(!isset($maps[$map])) { throw new Exception('Invalid map'); } // Remove from exclude list unset($maps[$map]); // Catch errors try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Send command $commands->cvar('playlist_excludeMap', implode(' ', array_keys($maps)), TRUE); // Notice $this->notice(__('Map successfully set as next')); // Log $this->log_action(__('Set next map: :map', array(':map' => HTML::chars($map)))); } catch(Exception $e) { // Notice $this->notice($e->getMessage()); } // Redirect $this->request->redirect('dashboard/maps'); } /** * Update map rotation */ public function action_maps_rotation() { // Only logged in users $this->do_force_login(); // Check permission if(!$this->check_permissions(SERVER_MAPS, FALSE)) { exit(__('No permissions')); } // Ajax? if(!Request::$is_ajax) { exit; } // Valid request? if(!isset($_POST['mp']) OR !is_array($_POST['mp'])) { exit; } // Construct cvar $cvar = ''; // Iterate maps foreach($_POST['mp'] as $v) { $cvar .= 'map mp_'.$v.' '; } // Trim spaces $cvar = trim($cvar); // Catch errors try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Get current $maps = explode(' ', $commands->get_cvar('sv_mapRotation'), 3); // Add gametype if($maps[0] == 'gametype' AND isset($maps[1])) { $cvar = 'gametype '.$maps[1].' '.$cvar; } // Send $commands->cvar('sv_mapRotation', $cvar, TRUE); } catch(Exception $e) { // Error exit($e->getMessage()); } // Log $this->log_action(__('Changed map rotation')); // Done exit('Done'); } /** * Exclude / include map * * @param string $map */ public function action_maps_status($map) { // Only logged in users $this->do_force_login(); // Check permission $this->check_permissions(SERVER_MAPS); // Maps $maps = Blackops_Rcon_Constants::$maps; // Valid map? if(!isset($maps[$map])) { throw new Exception('Invalid map'); } // Catch errors try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Excludes $excludes = ''; $excluded = FALSE; // Iterate excludes foreach(explode(' ', $commands->get_cvar('playlist_excludeMap')) as $e) { // Our map? if($e == $map) { $excluded = TRUE; continue; } // Append $excludes .= $e.' '; } // Exclude/include if(!$excluded) { $excludes .= $map; } // Send command $commands->cvar('playlist_excludeMap', trim($excludes), TRUE); // Notice $this->notice(__('Map successfully included/excluded')); // Log $this->log_action(__('Included/excluded map: :map', array(':map' => HTML::chars($map)))); } catch(Exception $e) { // Notice $this->notice($e->getMessage()); } // Redirect $this->request->redirect('dashboard/maps'); } /** * Send global message or whisper */ public function action_message() { // Check request vars if(!isset($_POST['message']) OR !isset($_POST['target']) OR (!ctype_digit($_POST['target']) AND $_POST['target'] != 'all')) { echo json_encode(array('error' => 'Invalid parameter', 'content' => '')); exit; } // Ajax? if(!Request::$is_ajax) { exit; } // Only logged in users $this->do_force_login(); // Can message? $this->check_permissions(SERVER_MESSAGE); // Decode message $_POST['message'] = html_entity_decode($_POST['message'], ENT_QUOTES, 'UTF-8'); // Dropdown? if (count(Config::get('messages', array()))) { // Check if(!in_array($_POST['message'], Config::get('kick_reasons', array()))) { echo json_encode(array('error' => 'Invalid message', 'content' => '')); exit; } } // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Log action if($_POST['target'] == 'all') { // Global message $this->log_action(__('Sent global message (:msg)', array(':msg' => HTML::chars($_POST['message'])))); } else { // Last server info $server_info = $this->session->get('last_server_info'); // Server info available? if(!$server_info OR !is_array($server_info) OR !isset($server_info['error']) OR $server_info['error'] != '') { // Log $this->log_action(__('Sent private message to #:id player (:msg)', array( ':id' => (int) $_POST['target'], ':msg' => HTML::chars($_POST['message']) ))); } else { // Try finding player if(isset($server_info['players'][(int) $_POST['target']])) { // Found, log name $this->log_action(__('Sent private message to :name (:msg)', array( ':name' => $server_info['players'][(int) $_POST['target']]['name'], ':msg' => HTML::chars($_POST['message']) ))); } else { // Not found, ID $this->log_action(__('Sent private message to #:id player (:msg)', array( ':id' => (int) $_POST['target'], ':msg' => HTML::chars($_POST['message']) ))); } } } // Send message $commands->message($_POST['message'], $_POST['target']); // Success echo json_encode(array('error' => 'None', 'content' => '')); exit; } catch(Exception $e) { // Houston, We've Got a Problem echo json_encode(array('error' => $e->getMessage(), 'content' => '')); exit; } } /** * Message rotation * * @param string $id */ public function action_msgrotation($id = NULL) { // Set action $this->action = 'msgrotation'; // Only logged in users $this->do_force_login(); // Title $this->title = __('Message rotation'); // Check permissions $this->check_permissions(SERVER_MESSAGE_ROTATION); // Form submit if(isset($_POST['submit']) AND isset($_POST['message'])) { // New object $message = new Model_Message; // Set user $message->user_id = $this->user->id; // Server $message->server_id = (int) $this->current_server['id']; // Message content $message->message = Security::xss_clean($_POST['message']); // Save $message->save(); // Notice and log $this->notice(__('Message added')); $this->log_action(__('Added message to rotation')); // Redirect $this->request->redirect('dashboard/msgrotation'); } // Remove if($id !== NULL AND ctype_digit($id)) { // Find $message = new Model_Message((int) $id); // Found? if(!$message->loaded() OR $message->server_id != (int) $this->current_server['id']) { throw new Exception('Not found'); } // Change rotation if($message->current == '1') { // Get random message $random = ORM::factory('message')->where('current', '=', '0')->find(); // Found? if($random->loaded()) { // Set as current $random->current = '1'; // Save $random->save(); } // Free memory unset($random); } // Delete $message->delete(); // Notice and log $this->notice(__('Message removed')); $this->log_action(__('Removed rotation message')); // Redirect $this->request->redirect('dashboard/msgrotation'); } // View $this->view = new View('blackops/messages'); // Messages $this->view->messages = Model_Message::get_messages($this->current_server['id']); } /** * Delete playlist * * @param string $server_playlist_id */ public function action_playlist_delete($server_playlist_id) { // Valid parameter? if(!ctype_digit($server_playlist_id)) { throw new Kohana_Exception('Invalid request'); } // Only logged in users $this->do_force_login(); // Check permissions $this->check_permissions(SERVER_PLAYLIST); // Remove playlist DB::delete('servers_playlists')->where('server_playlist_id', '=', (int) $server_playlist_id) ->where('server_id', '=', (int) $this->current_server['id']) ->execute(); // Log $this->log_action(__('Removed playlist with ID #:id', array(':id' => (int) $server_playlist_id))); // Notice and redirect $this->notice(__('Custom playlist deleted')); $this->request->redirect('dashboard/playlists'); } /** * Edit playlist * * @param string $server_playlist_id */ public function action_playlist_edit($server_playlist_id) { // Set action $this->action = 'playlists'; // Validate parameter if(!ctype_digit($server_playlist_id)) { throw new Kohana_Exception('Invalid request'); } // Only logged in users $this->do_force_login(); // Check permissions $this->check_permissions(SERVER_PLAYLIST); // Retrieve playlist $playlist_info = DB::select('server_playlist_name')->from('servers_playlists') ->where('server_playlist_id', '=', (int) $server_playlist_id) ->where('server_id', '=', (int) $this->current_server['id']) ->execute(); // Is this really a correct playlist? if(!count($playlist_info)) { $this->notice(__('Invalid playlist')); $this->request->redirect('dashboard/playlists'); } // First row $playlist_info = $playlist_info->as_array(); $playlist_info = current($playlist_info); // Fill all playlists $all_playlists_res = DB::select()->from('playlists') ->where('gametype_codename', 'IN', array('tdm','dm','ctf','sd','koth','dom','sab','dem')) ->execute(); // No rows if(count($all_playlists_res) <= 0) { throw new Kohana_Exception('List of playlists not found'); } // Groups $grouped_playlists = array( 'normal' => array(), 'hardcore' => array(), 'barebones' => array() ); // Group playlists foreach($all_playlists_res as $value) { $grouped_playlists[$value['gamemode_codename']] += array($value['id'] => $value['name']); } // Process post if(isset($_POST['playlists_ids']) AND is_array($_POST['playlists_ids']) AND !empty($_POST['playlists_ids'])) { // Playlist name $playlist_name = Security::xss_clean($_POST['playlist_name']); // Unique playlists $playlists_ids = array_unique($_POST['playlists_ids']); // Playlist ID's $all_playlists_ids = array_keys($all_playlists_res->as_array('id')); // Iterate playlists foreach($playlists_ids as $playlist_id) { // Invalid playlist if(!in_array($playlist_id, $all_playlists_ids)) { // Notice and redirect $this->notice(__('Invalid default playlist specified')); $this->request->redirect('dashboard/playlists'); } } // Already exists? if(count(DB::select()->from('servers_playlists')->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_name', '=', $playlist_name) ->where('server_playlist_id', '<>', (int) $server_playlist_id)->execute())) { $this->notice(__('This playlist name already exists')); $this->request->redirect('dashboard/playlists'); } // Update playlist name if($playlist_name <> $playlist_info['server_playlist_name']) { // Update DB::update('servers_playlists')->set(array('server_playlist_name' => $playlist_name)) ->where('server_playlist_id', '=', (int) $server_playlist_id) ->where('server_id', '=', (int) $this->current_server['id']) ->execute(); } // Delete old, insert new DB::delete('custom_playlists')->where('server_playlist_id', '=', (int) $server_playlist_id) ->where('server_id', '=', (int) $this->current_server['id']) ->execute(); // Create query $insert = DB::insert('custom_playlists', array('server_playlist_id', 'server_id', 'playlist_id')); // Iterate playlists foreach($playlists_ids as $playlist_id) { // Append $insert->values(array($server_playlist_id, $this->current_server['id'], $playlist_id)); } // Insert rows $insert->execute(); // Log $this->log_action(__('Edited playlist: :name', array(':name' => HTML::chars($playlist_name)))); // Notice and redirect $this->notice(__('Playlist saved')); $this->request->redirect('dashboard/playlists'); } // Set page title $this->title = __('Playlist edit'); // Umm... yeah $playlists_in_custom_playlist = DB::select('custom_playlists.playlist_id', 'playlists.name') ->from('custom_playlists') ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_id', '=', (int) $server_playlist_id) ->join('playlists')->on('custom_playlists.playlist_id', '=', 'playlists.id') ->execute(); // Setup playlist $playlist['id'] = $server_playlist_id; $playlist['name'] = $playlist_info['server_playlist_name']; $playlist['playlists'] = $playlists_in_custom_playlist->as_array(); // View $this->view = new View('blackops/playlist_edit'); // Assign $this->view->playlist = $playlist; $this->view->grouped_playlists = $grouped_playlists; } /** * Playlists * * @param string $playlist_id_to_switch * @param string $active * @throws Kohana_Exception */ public function action_playlists($playlist_id_to_switch = NULL, $active = NULL) { // Action $this->action = 'playlists'; // Only logged in users $this->do_force_login(); // Title $this->title = __('Playlists'); // Check permissions $this->check_permissions(SERVER_PLAYLIST); // Fill all playlists $all_playlists_res = DB::select()->from('playlists') ->where('gametype_codename', 'IN', array('tdm','dm','ctf','sd','koth','dom','sab','dem')) ->execute(); // Any playlist? if(count($all_playlists_res) <= 0) { throw new Kohana_Exception('List of playlists not found'); } // ID's $all_playlists_ids = array_keys($all_playlists_res->as_array('id')); // Switch playlist activity if(ctype_digit($playlist_id_to_switch) AND ($active == 0 OR $active == 1)) { // Valid playlist? if(!in_array((int) $playlist_id_to_switch, $all_playlists_ids)) { // Redirect $this->notice(__('Invalid playlist specified')); $this->request->redirect('dashboard/playlists'); } // Update DB::update('servers_playlists')->set(array('is_active' => (int) $active)) ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_id', '=', $playlist_id_to_switch) ->execute(); // Deactivate different playlists if($active) { DB::update('servers_playlists')->set(array('is_active' => 0)) ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_id', '<>', $playlist_id_to_switch)->execute(); } // Set notice if($active) { // Notice $this->notice(__('Custom playlist activated')); // Log $this->log_action(__('Activated playlist with ID #:id', array(':id' => (int) $playlist_id_to_switch))); } else { // Notice $this->notice(__('Custom playlist deactivated')); // Log $this->log_action(__('Deactivated playlist with ID #:id', array(':id' => (int) $playlist_id_to_switch))); } // Redirect $this->request->redirect('dashboard/playlists'); } // Add new custom playlist if(isset($_POST['playlists_ids']) AND is_array($_POST['playlists_ids']) AND !empty($_POST['playlists_ids'])) { // Vars $playlist_name = $_POST['playlist_name']; $make_active = isset($_POST['make_active']); // Unique playlist ID's $playlists_ids = array_unique($_POST['playlists_ids']); // Iterate playlists foreach($playlists_ids as $playlist_id) { // Invalid playlist? if(!in_array($playlist_id, $all_playlists_ids)) { // Notice and redirect $this->notice(__('Invalid default playlist specified')); $this->request->redirect('dashboard/playlists'); } } // Already exists? if(count(DB::select()->from('servers_playlists') ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_name', '=', Security::xss_clean($playlist_name))->execute())) { // Notice and redirect $this->notice(__('This playlist name already exists')); $this->request->redirect('dashboard/playlists'); } // Add playlist $res = DB::insert('servers_playlists', array('server_id', 'server_playlist_name', 'is_active'))->values(array( (int) $this->current_server['id'], Security::xss_clean($playlist_name), $make_active ))->execute(); // Last insert ID $server_playlist_id = $res[0]; // Deactivate playlists if($make_active) { DB::update('servers_playlists')->set(array('is_active' => 0)) ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_id', '<>', $server_playlist_id)->execute(); } // Create INSERT query $insert = DB::insert('custom_playlists', array('server_playlist_id', 'server_id', 'playlist_id')); // Add playlist foreach($playlists_ids as $playlist_id) { // Add VALUES $insert->values(array($server_playlist_id, $this->current_server['id'], $playlist_id)); } // Execute INSERT query $insert->execute(); // Notice $this->notice(__('Custom playlist added')); // Log $this->log_action(__('Created new playlist: :name', array(':name' => HTML::chars($playlist_name)))); // Redirect $this->request->redirect('dashboard/playlists'); } // Fill custom playlists $playlists = array(); // Retrieve custom playlists $custom_playlists = DB::select('server_playlist_id', 'server_playlist_name', 'is_active')->from('servers_playlists') ->where('server_id', '=', (int) $this->current_server['id']) ->execute(); // Iterate custom playlists foreach ($custom_playlists as $custom_playlist) { // Uhh... nevermind $playlists_in_custom_playlist = DB::select('custom_playlists.playlist_id', 'playlists.name', 'playlists.gametype_codename', 'playlists.gamemode_codename', 'playlists.size') ->from('custom_playlists') ->where('server_id', '=', (int) $this->current_server['id']) ->where('server_playlist_id', '=', $custom_playlist['server_playlist_id']) ->join('playlists')->on('custom_playlists.playlist_id', '=', 'playlists.id') ->execute(); // Gametypes array $gametypes = array(); // Iterate foreach($playlists_in_custom_playlist as $playlist) { // Append gametype $gametypes[] = array( 'name' => $playlist['name'], 'abbrev' => Blackops_Rcon_Constants::$gametypes_abbrev[$playlist['gametype_codename']], 'mode' => $playlist['gamemode_codename'], ); } // Add playlist $playlists[] = array( 'id' => $custom_playlist['server_playlist_id'], 'name' => $custom_playlist['server_playlist_name'], 'is_active' => $custom_playlist['is_active'], 'gametypes' => $gametypes, ); } // Init array $grouped_playlists = array( 'normal'=>array(), 'hardcore'=>array(), 'barebones'=>array() ); // Iterate playlists foreach($all_playlists_res as $playlist) { // Append to correct group $grouped_playlists[$playlist['gamemode_codename']] += array($playlist['id'] => $playlist['name']); } // View $this->view = new View('blackops/playlists'); // Assign $this->view->playlists = $playlists; $this->view->grouped_playlists = $grouped_playlists; } /** * Temporary ban * * @param string $id */ public function action_tempban($id) { // ID is numeric if(!ctype_digit($id)) { echo json_encode(array('error' => 'Invalid parameter', 'content' => '')); exit; } // Reason required? if(Config::get('general.kick_reason_required', FALSE) AND empty($_POST['reason'])) { echo json_encode(array('error' => 'Reason required', 'content' => '')); exit; } // Cast $id = (int) $id; // Ajax? if(!Request::$is_ajax) { exit; } // Only logged in users $this->do_force_login(); // Can ban if(!$this->check_permissions(SERVER_TEMP_BAN, FALSE)) { echo json_encode(array('error' => 'No permission', 'content' => '')); exit; } // Decode message if($_POST['reason']) { $reason = html_entity_decode($_POST['reason'], ENT_QUOTES, 'UTF-8'); } else { $reason = ''; } // Dropdown? if(count(Config::get('kick_reasons', array())) AND $reason) { // Check if(!in_array($reason, Config::get('kick_reasons', array()))) { echo json_encode(array('error' => 'Invalid reason', 'content' => '')); exit; } } // Catch them all try { // Rcon connection $rcon = new Blackops_Rcon($this->current_server['ip'], $this->current_server['port'], $this->current_server['password']); $rcon->connect(); // Commands $commands = new Blackops_Rcon_Commands($rcon); // Temporary ban $commands->temp_ban($id); // Last server info $server_info = $this->session->get('last_server_info'); // Server info available? if(!$server_info OR !is_array($server_info) OR !isset($server_info['error']) OR $server_info['error'] != '') { // Log $this->log_action(__('Temp-banned player with ID #:id (Reason: :reason)', array(':id' => $id, ':reason' => HTML::chars($reason)))); } else { // Try finding player if(isset($server_info['players'][$id])) { // Found, log name $this->log_action(__('Temp-banned player :name (Reason: :reason)', array( ':name' => $server_info['players'][$id]['name'], ':reason' => HTML::chars($reason) ))); } else { // Not found, ID $this->log_action(__('Temp-banned player with ID #:id (Reason: :reason)', array( ':id' => (int) $id, ':reason' => HTML::chars($reason) ))); } } // Success echo json_encode(array('error' => 'None', 'content' => '')); exit; } catch(Exception $e) { // Error echo json_encode(array('error' => $e->getMessage(), 'content' => '')); exit; } } /** * Navigation bar * * @see blackops/application/classes/controller/Controller_Main::after() */ public function after() { // Assign navigation $this->view->navigation = new View('blackops/navigation'); // Action $this->view->navigation->action = $this->action; // Owned servers $this->view->navigation->owned = $this->owned; // Current server ID $this->view->navigation->current_server_id = $this->current_server['id']; // Permissions $this->view->navigation->permissions = (int) $this->current_server['permissions']; // Execute parent parent::after(); } /** * Log action * * @param string $action */ protected function log_action($action) { // Add server name? if (Config::get('general.log_servername', TRUE) AND isset($this->current_server['name'])) { $action = '('.$this->current_server['name'].') '.$action; } // Call parent parent::log_action($action); } }
bsd-2-clause
jcodec/jcodec
src/main/java/org/jcodec/codecs/vpx/vp8/data/YV12buffer.java
10007
package org.jcodec.codecs.vpx.vp8.data; import java.util.EnumSet; import org.jcodec.codecs.vpx.VP8Encoder; import org.jcodec.codecs.vpx.vp8.CommonUtils; import org.jcodec.codecs.vpx.vp8.VP8Exception; import org.jcodec.codecs.vpx.vp8.enums.MVReferenceFrame; import org.jcodec.codecs.vpx.vp8.enums.CodecError; import org.jcodec.codecs.vpx.vp8.pointerhelper.FullAccessIntArrPointer; import org.jcodec.common.model.Picture; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License. * * The class is a direct java port of libvpx's * (https://github.com/webmproject/libvpx) relevant VP8 code with significant * java oriented refactoring. * * @author The JCodec project * */ public class YV12buffer { public static final int VP8BORDERINPIXELS = 32; public int y_width; public int y_height; public int y_crop_width; public int y_crop_height; public int y_stride; public int uv_width; public int uv_height; public int uv_crop_width; public int uv_crop_height; public int uv_stride; public FullAccessIntArrPointer y_buffer; // uint8 public FullAccessIntArrPointer u_buffer; // uint8 public FullAccessIntArrPointer v_buffer; // uint8 public FullAccessIntArrPointer buffer_alloc; // uint8 public int border; int frame_size; int subsampling_x; int subsampling_y; /* unsigned */ int bit_depth; int render_width; int render_height; int corrupted; public EnumSet<MVReferenceFrame> flags; private YV12buffer() { // allows shallow copy } YV12buffer shallowCopy() { YV12buffer sh = new YV12buffer(); sh.y_width = this.y_width; sh.y_height = this.y_height; sh.y_crop_width = this.y_crop_width; sh.y_crop_height = this.y_crop_height; sh.y_stride = this.y_stride; sh.uv_width = this.uv_width; sh.uv_height = this.uv_height; sh.uv_crop_width = this.uv_crop_width; sh.uv_crop_height = this.uv_crop_height; sh.uv_stride = this.uv_stride; sh.y_buffer = this.y_buffer.shallowCopy(); sh.u_buffer = this.u_buffer.shallowCopy(); sh.v_buffer = this.v_buffer.shallowCopy(); sh.buffer_alloc = this.buffer_alloc.shallowCopy(); sh.border = this.border; sh.frame_size = this.frame_size; sh.subsampling_x = this.subsampling_x; sh.subsampling_y = this.subsampling_y; sh.bit_depth = this.bit_depth; sh.render_width = this.render_width; sh.render_height = this.render_height; sh.corrupted = this.corrupted; sh.flags = this.flags == null ? EnumSet.noneOf(MVReferenceFrame.class) : EnumSet.copyOf(this.flags); return sh; } private static void extend_plane(FullAccessIntArrPointer src, int src_stride, int width, int height, int extend_top, int extend_left, int extend_bottom, int extend_right) { /* copy the left and right most columns out */ for (int i = 0; i < height; ++i) { final int strideshift = i * src_stride; src.memset(strideshift - extend_left, src.getRel(strideshift), extend_left); src.memset(strideshift + width, src.getRel(strideshift + width - 1), extend_right); } /* * Now copy the top and bottom lines into each line of the respective borders */ final int linesize = extend_left + extend_right + width; for (int i = 0; i < extend_top; ++i) { src.memcopyin(src_stride * (i - extend_top) - extend_left, src, -extend_left, linesize); } final int bottomrowstart = src_stride * (height - 1) - extend_left; for (int i = 0; i < extend_bottom; ++i) { src.memcopyin(src_stride * (i + height) - extend_left, src, bottomrowstart, linesize); } } public void extend_frame_borders() { final int uv_border = border / 2; assert (border % 2 == 0); assert (y_height - y_crop_height < 16); assert (y_width - y_crop_width < 16); assert (y_height - y_crop_height >= 0); assert (y_width - y_crop_width >= 0); YV12buffer.extend_plane(y_buffer, y_stride, y_crop_width, y_crop_height, border, border, border + y_height - y_crop_height, border + y_width - y_crop_width); YV12buffer.extend_plane(u_buffer, uv_stride, uv_crop_width, uv_crop_height, uv_border, uv_border, uv_border + uv_height - uv_crop_height, uv_border + uv_width - uv_crop_width); YV12buffer.extend_plane(v_buffer, uv_stride, uv_crop_width, uv_crop_height, uv_border, uv_border, uv_border + uv_height - uv_crop_height, uv_border + uv_width - uv_crop_width); } private static void leftcolhelper(FullAccessIntArrPointer target, int st, int h) { for (int i = 0; i < h; ++i) { target.setRel(st * i - 1, (short) 129); } } private static void toplinehelper(FullAccessIntArrPointer target, int stride, int width) { target.memset(-1 - stride, (short) 127, width + 5); } private void vp8_setup_intra_recon_left_col() { leftcolhelper(y_buffer, y_stride, y_height); leftcolhelper(u_buffer, uv_stride, uv_height); leftcolhelper(v_buffer, uv_stride, uv_height); } private void vp8_setup_intra_recon_top_line() { toplinehelper(y_buffer, y_stride, y_width); toplinehelper(u_buffer, uv_stride, uv_width); toplinehelper(v_buffer, uv_stride, uv_width); } public void vp8_setup_intra_recon() { /* set up frame new frame for intra coded blocks */ vp8_setup_intra_recon_top_line(); vp8_setup_intra_recon_left_col(); } private static void copyBufPart(final FullAccessIntArrPointer src_ptr, final FullAccessIntArrPointer dst_ptr, int width, int height, int src_stride, int dst_stride) { CommonUtils.genericCopy(src_ptr, src_stride, dst_ptr, dst_stride, height, width); } public static void copyY(YV12buffer src_ybc, YV12buffer dst_ybc) { YV12buffer.copyBufPart(src_ybc.y_buffer, dst_ybc.y_buffer, src_ybc.y_width, src_ybc.y_height, src_ybc.y_stride, dst_ybc.y_stride); } // Copies the source image into the destination image and updates the // destination's UMV borders. // Note: The frames are assumed to be identical in size. public static void copyFrame(YV12buffer src_ybc, YV12buffer dst_ybc) { YV12buffer.copyY(src_ybc, dst_ybc); YV12buffer.copyBufPart(src_ybc.u_buffer, dst_ybc.u_buffer, src_ybc.uv_width, src_ybc.uv_height, src_ybc.uv_stride, dst_ybc.uv_stride); YV12buffer.copyBufPart(src_ybc.v_buffer, dst_ybc.v_buffer, src_ybc.uv_width, src_ybc.uv_height, src_ybc.uv_stride, dst_ybc.uv_stride); dst_ybc.extend_frame_borders(); } public YV12buffer(Picture img) { byte[][] jcodec_raw_data = img.getData(); FullAccessIntArrPointer img_data = new FullAccessIntArrPointer( jcodec_raw_data[0].length + jcodec_raw_data[1].length + jcodec_raw_data[2].length); for (byte[] planeData : jcodec_raw_data) { for (byte pix : planeData) { img_data.setAndInc((short) (pix + VP8Encoder.INT_TO_BYTE_OFFSET)); } } img_data.rewind(); final int y_w = img.getWidth(); final int y_h = img.getHeight(); final int uv_w = img.getPlaneWidth(1); final int uv_h = img.getPlaneHeight(1); y_buffer = img_data; u_buffer = img_data.shallowCopyWithPosInc(jcodec_raw_data[0].length); v_buffer = u_buffer.shallowCopyWithPosInc(jcodec_raw_data[1].length); y_crop_width = y_w; y_crop_height = y_h; y_width = y_w; y_height = y_h; uv_crop_width = uv_w; uv_crop_height = uv_h; uv_width = uv_w; uv_height = uv_h; y_stride = img.getWidth(); uv_stride = img.getPlaneWidth(1); border = 0; } public YV12buffer(int width, int height) { this(width, height, VP8BORDERINPIXELS); } public YV12buffer(int width, int height, int border) { y_width = (width + 15) & ~15; y_height = (height + 15) & ~15; y_stride = ((y_width + 2 * border) + 31) & ~31; y_crop_width = width; y_crop_height = height; /** * There is currently a bunch of code which assumes uv_stride == y_stride/2, so * enforce this here. */ uv_width = y_width >> 1; uv_height = y_height >> 1; uv_stride = y_stride >> 1; uv_crop_width = (width + 1) / 2; uv_crop_height = (height + 1) / 2; this.border = border; int yplane_size = (y_height + 2 * border) * y_stride; int uvplane_size = (uv_height + border) * uv_stride; frame_size = yplane_size + 2 * uvplane_size; /* * Only support allocating buffers that have a border that's a multiple of 32. * The border restriction is required to get 16-byte alignment of the start of * the chroma rows without introducing an arbitrary gap between planes, which * would break the semantics of things like vpx_img_set_rect(). */ if ((border & 0x1f) != 0) VP8Exception.vp8_internal_error(CodecError.UNSUP_FEATURE, "Border size (%d) is not suitable for VP8", border); buffer_alloc = new FullAccessIntArrPointer(frame_size); y_buffer = buffer_alloc.shallowCopyWithPosInc((border * y_stride) + border); u_buffer = buffer_alloc.shallowCopyWithPosInc(yplane_size + (border / 2 * uv_stride) + border / 2); v_buffer = buffer_alloc .shallowCopyWithPosInc(yplane_size + uvplane_size + (border / 2 * uv_stride) + border / 2); corrupted = 0; /* assume not currupted by errors */ } }
bsd-2-clause
tidepool-org/platform
vendor/github.com/cloudevents/sdk-go/protocol/kafka_sarama/v2/message.go
3691
package kafka_sarama import ( "bytes" "context" "strings" "github.com/cloudevents/sdk-go/v2/binding" "github.com/cloudevents/sdk-go/v2/binding/format" "github.com/cloudevents/sdk-go/v2/binding/spec" "github.com/Shopify/sarama" ) const ( prefix = "ce_" contentTypeHeader = "content-type" ) var specs = spec.WithPrefix(prefix) // Message holds a Kafka Message. // This message *can* be read several times safely type Message struct { Value []byte Headers map[string][]byte ContentType string format format.Format version spec.Version } // Check if http.Message implements binding.Message var _ binding.Message = (*Message)(nil) var _ binding.MessageMetadataReader = (*Message)(nil) // NewMessageFromConsumerMessage returns a binding.Message that holds the provided ConsumerMessage. // The returned binding.Message *can* be read several times safely // This function *doesn't* guarantee that the returned binding.Message is always a kafka_sarama.Message instance func NewMessageFromConsumerMessage(cm *sarama.ConsumerMessage) *Message { var contentType string headers := make(map[string][]byte, len(cm.Headers)) for _, r := range cm.Headers { k := strings.ToLower(string(r.Key)) if k == contentTypeHeader { contentType = string(r.Value) } headers[k] = r.Value } return NewMessage(cm.Value, contentType, headers) } // NewMessage returns a binding.Message that holds the provided kafka message components. // The returned binding.Message *can* be read several times safely // This function *doesn't* guarantee that the returned binding.Message is always a kafka_sarama.Message instance func NewMessage(value []byte, contentType string, headers map[string][]byte) *Message { if ft := format.Lookup(contentType); ft != nil { return &Message{ Value: value, ContentType: contentType, Headers: headers, format: ft, } } else if v := specs.Version(string(headers[specs.PrefixedSpecVersionName()])); v != nil { return &Message{ Value: value, ContentType: contentType, Headers: headers, version: v, } } return &Message{ Value: value, ContentType: contentType, Headers: headers, } } func (m *Message) ReadEncoding() binding.Encoding { if m.version != nil { return binding.EncodingBinary } if m.format != nil { return binding.EncodingStructured } return binding.EncodingUnknown } func (m *Message) ReadStructured(ctx context.Context, encoder binding.StructuredWriter) error { if m.format != nil { return encoder.SetStructuredEvent(ctx, m.format, bytes.NewReader(m.Value)) } return binding.ErrNotStructured } func (m *Message) ReadBinary(ctx context.Context, encoder binding.BinaryWriter) (err error) { if m.version == nil { return binding.ErrNotBinary } for k, v := range m.Headers { if strings.HasPrefix(k, prefix) { attr := m.version.Attribute(k) if attr != nil { err = encoder.SetAttribute(attr, string(v)) } else { err = encoder.SetExtension(strings.TrimPrefix(k, prefix), string(v)) } } else if k == contentTypeHeader { err = encoder.SetAttribute(m.version.AttributeFromKind(spec.DataContentType), string(v)) } if err != nil { return } } if m.Value != nil { err = encoder.SetData(bytes.NewReader(m.Value)) } return } func (m *Message) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { attr := m.version.AttributeFromKind(k) if attr != nil { return attr, string(m.Headers[attr.PrefixedName()]) } return nil, nil } func (m *Message) GetExtension(name string) interface{} { return string(m.Headers[prefix+name]) } func (m *Message) Finish(error) error { return nil }
bsd-2-clause
leonidk/apriltrack
example/opencv_demo.cc
7010
/* Copyright (C) 2013-2016, The Regents of The University of Michigan. All rights reserved. This software was developed in the APRIL Robotics Lab under the direction of Edwin Olson, ebolson@umich.edu. This software may be available under alternative licensing terms; contact the address above. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the Regents of The University of Michigan. */ #include <iostream> #include "opencv2/opencv.hpp" #include "apriltag.h" #include "tag36h11.h" #include "tag36h10.h" #include "tag36artoolkit.h" #include "tag25h9.h" #include "tag25h7.h" #include "common/getopt.h" using namespace std; using namespace cv; int main(int argc, char *argv[]) { getopt_t *getopt = getopt_create(); getopt_add_bool(getopt, 'h', "help", 0, "Show this help"); getopt_add_bool(getopt, 'd', "debug", 0, "Enable debugging output (slow)"); getopt_add_bool(getopt, 'q', "quiet", 0, "Reduce output"); getopt_add_string(getopt, 'f', "family", "tag36h11", "Tag family to use"); getopt_add_int(getopt, '\0', "border", "1", "Set tag family border size"); getopt_add_int(getopt, 't', "threads", "4", "Use this many CPU threads"); getopt_add_double(getopt, 'x', "decimate", "1.0", "Decimate input image by this factor"); getopt_add_double(getopt, 'b', "blur", "0.0", "Apply low-pass blur to input"); getopt_add_bool(getopt, '0', "refine-edges", 1, "Spend more time trying to align edges of tags"); getopt_add_bool(getopt, '1', "refine-decode", 0, "Spend more time trying to decode tags"); getopt_add_bool(getopt, '2', "refine-pose", 0, "Spend more time trying to precisely localize tags"); if (!getopt_parse(getopt, argc, argv, 1) || getopt_get_bool(getopt, "help")) { printf("Usage: %s [options]\n", argv[0]); getopt_do_usage(getopt); exit(0); } // Initialize camera VideoCapture cap(0); if (!cap.isOpened()) { cerr << "Couldn't open video capture device" << endl; return -1; } // Initialize tag detector with options apriltag_family_t *tf = NULL; const char *famname = getopt_get_string(getopt, "family"); if (!strcmp(famname, "tag36h11")) tf = tag36h11_create(); else if (!strcmp(famname, "tag36h10")) tf = tag36h10_create(); else if (!strcmp(famname, "tag36artoolkit")) tf = tag36artoolkit_create(); else if (!strcmp(famname, "tag25h9")) tf = tag25h9_create(); else if (!strcmp(famname, "tag25h7")) tf = tag25h7_create(); else { printf("Unrecognized tag family name. Use e.g. \"tag36h11\".\n"); exit(-1); } tf->black_border = getopt_get_int(getopt, "border"); apriltag_detector_t *td = apriltag_detector_create(); apriltag_detector_add_family(td, tf); td->quad_decimate = getopt_get_double(getopt, "decimate"); td->quad_sigma = getopt_get_double(getopt, "blur"); td->nthreads = getopt_get_int(getopt, "threads"); td->debug = getopt_get_bool(getopt, "debug"); td->refine_edges = getopt_get_bool(getopt, "refine-edges"); td->refine_decode = getopt_get_bool(getopt, "refine-decode"); td->refine_pose = getopt_get_bool(getopt, "refine-pose"); Mat frame, gray; while (true) { cap >> frame; cvtColor(frame, gray, COLOR_BGR2GRAY); // Make an image_u8_t header for the Mat data image_u8_t im = { .width = gray.cols, .height = gray.rows, .stride = gray.cols, .buf = gray.data }; zarray_t *detections = apriltag_detector_detect(td, &im); cout << zarray_size(detections) << " tags detected" << endl; // Draw detection outlines for (int i = 0; i < zarray_size(detections); i++) { apriltag_detection_t *det; zarray_get(detections, i, &det); line(frame, Point(det->p[0][0], det->p[0][1]), Point(det->p[1][0], det->p[1][1]), Scalar(0, 0xff, 0), 2); line(frame, Point(det->p[0][0], det->p[0][1]), Point(det->p[3][0], det->p[3][1]), Scalar(0, 0, 0xff), 2); line(frame, Point(det->p[1][0], det->p[1][1]), Point(det->p[2][0], det->p[2][1]), Scalar(0xff, 0, 0), 2); line(frame, Point(det->p[2][0], det->p[2][1]), Point(det->p[3][0], det->p[3][1]), Scalar(0xff, 0, 0), 2); stringstream ss; ss << det->id; String text = ss.str(); int fontface = FONT_HERSHEY_SCRIPT_SIMPLEX; double fontscale = 1.0; int baseline; Size textsize = getTextSize(text, fontface, fontscale, 2, &baseline); putText(frame, text, Point(det->c[0]-textsize.width/2, det->c[1]+textsize.height/2), fontface, fontscale, Scalar(0xff, 0x99, 0), 2); } zarray_destroy(detections); imshow("Tag Detections", frame); if (waitKey(30) >= 0) break; } apriltag_detector_destroy(td); if (!strcmp(famname, "tag36h11")) tag36h11_destroy(tf); else if (!strcmp(famname, "tag36h10")) tag36h10_destroy(tf); else if (!strcmp(famname, "tag36artoolkit")) tag36artoolkit_destroy(tf); else if (!strcmp(famname, "tag25h9")) tag25h9_destroy(tf); else if (!strcmp(famname, "tag25h7")) tag25h7_destroy(tf); getopt_destroy(getopt); return 0; }
bsd-2-clause
avnit/EGroovy
Library/Homebrew/cmd/untap.rb
1389
require 'cmd/tap' # for tap_args module Homebrew extend self def untap raise "Usage is `brew untap <tap-name>`" if ARGV.empty? user, repo = tap_args # we consistently downcase in tap to ensure we are not bitten by case-insensive # filesystem issues. Which is the default on mac. The problem being the # filesystem cares, but our regexps don't. So unless we resolve *every* path # we will get bitten. user.downcase! repo.downcase! tapd = HOMEBREW_LIBRARY/"Taps/#{user}/homebrew-#{repo}" raise "No such tap!" unless tapd.directory? files = [] tapd.find_formula{ |file| files << Pathname.new("#{user}/homebrew-#{repo}").join(file) } unlink_tap_formula(files) tapd.rmtree tapd.dirname.rmdir_if_possible puts "Untapped #{files.length} formula" end def unlink_tap_formula formulae untapped = 0 gitignores = (HOMEBREW_LIBRARY/"Formula/.gitignore").read.split rescue [] formulae.each do |formula| file = HOMEBREW_LIBRARY.join("Taps", formula) link = HOMEBREW_LIBRARY.join("Formula", formula.basename) if link.symlink? && (!link.exist? || link.resolved_path == file) link.delete gitignores.delete(file.basename.to_s) untapped += 1 end end HOMEBREW_REPOSITORY.join("Library/Formula/.gitignore").atomic_write(gitignores * "\n") untapped end end
bsd-2-clause
DanielArenas/mezcalaria-backend
db/migrate/20170509204708_add_access_token_usuarios.rb
119
class AddAccessTokenUsuarios < ActiveRecord::Migration def change add_column :usuarios, :idiom, :string end end
bsd-2-clause
jmcnamara/XlsxWriter
xlsxwriter/test/comparison/test_object_position05.py
862
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('object_position05.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_textbox('E9', 'This is some text', {'object_position': 2}) workbook.close() self.assertExcelEqual()
bsd-2-clause
emaphp/eMacros
src/eMacros/Scope.php
2101
<?php namespace eMacros; class Scope implements \ArrayAccess, \IteratorAggregate { /** * Symboil table * @var array */ public $symbols = []; /** * Macros list * @var array */ public $macros = []; protected static function symbol($symbol) { if ($symbol instanceof Symbol) return $symbol->symbol; elseif (is_string($symbol)) return $symbol; throw new \UnexpectedValueException(sprintf("Unexpected value of type '%s'.", is_object($symbol) ? get_class($symbol) : gettype($symbol))); } /** * Obtains a symbol from table * (non-PHPdoc) * @see ArrayAccess::offsetGet() */ public function offsetGet($symbol) { $sym = self::symbol($symbol); //is symbol defined on this scope? if (array_key_exists($sym, $this->symbols)) return $this->symbols[$sym]; else { foreach ($this->macros as $regex => $callback) { if (preg_match($regex, $sym, $matches)) return $this->symbols[$sym] = $callback->__invoke($matches); } } return; } public function offsetExists($symbol) { return true; } /** * Stores a symbol * Used when setting up a Scope/Package * Ex: $this['.'] = new Concatenation(); * (non-PHPdoc) * @see ArrayAccess::offsetSet() */ public function offsetSet($symbol, $value) { $this->symbols[Symbol::validateSymbol($symbol)] = $value; } /** * Removes a symbol from table * (non-PHPdoc) * @see ArrayAccess::offsetUnset() */ public function offsetUnset($symbol) { unset($this->symbols[$symbol]); } /** * Obtains a symbol iterator * (non-PHPdoc) * @see IteratorAggregate::getIterator() */ public function getIterator() { $symbols = []; foreach ($this->listSymbols() as $name) $symbols[$name] = $this[$name]; return new \ArrayIterator($symbols); } /** * Obtains all defined symbols * @return array */ public function listSymbols() { return array_keys($this->symbols); } /** * Adds a new macro * @param string $regex * @param \Closure $handler */ public function macro($regex, \Closure $handler) { $this->macros[$regex] = $handler; } } ?>
bsd-2-clause
guaguadev/redash
migrations/gg0001_add_ggargs_active_to_user.py
364
from redash.models import db, User from playhouse.migrate import PostgresqlMigrator, migrate if __name__ == '__main__': migrator = PostgresqlMigrator(db.database) with db.database.transaction(): migrate( migrator.add_column('users', 'active', User.active), migrator.add_column('users', 'gg_args', User.gg_args), )
bsd-2-clause
fpsw/Servo
servo/validators.py
1054
# -*- coding: utf-8 -*- import os import re import phonenumbers from gsxws.core import validate from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ def phone_validator(val): try: phonenumbers.parse(val.upper(), settings.INSTALL_COUNTRY) except phonenumbers.NumberParseException: raise ValidationError(_('%s is not a valid phone number') % val) def apple_sn_validator(val): if validate(val.upper()) not in ('serialNumber', 'alternateDeviceId',): raise ValidationError(_(u'%s is not a valid serial or IMEI number') % val) def sn_validator(val): if not re.match(r'^\w*$', val): raise ValidationError(_('Serial numbers may only contain letters and numbers')) def file_upload_validator(val): allowed = ['.pdf', '.zip', '.doc', '.jpg', '.jpeg', '.png', '.txt', '.mov', '.m4v'] ext = os.path.splitext(val.name)[1].lower() if not ext in allowed: raise ValidationError(_('Invalid file type: %s') % ext)
bsd-2-clause
mahori/brew
Library/Homebrew/test/utils/git_spec.rb
7740
# frozen_string_literal: true require "utils/git" describe Utils::Git do around do |example| described_class.clear_available_cache example.run ensure described_class.clear_available_cache end before do git = HOMEBREW_SHIMS_PATH/"scm/git" HOMEBREW_CACHE.cd do system git, "init" File.open("README.md", "w") { |f| f.write("README") } system git, "add", HOMEBREW_CACHE/"README.md" system git, "commit", "-m", "File added" @h1 = `git rev-parse HEAD` File.open("README.md", "w") { |f| f.write("# README") } system git, "add", HOMEBREW_CACHE/"README.md" system git, "commit", "-m", "written to File" @h2 = `git rev-parse HEAD` File.open("LICENSE.txt", "w") { |f| f.write("LICENCE") } system git, "add", HOMEBREW_CACHE/"LICENSE.txt" system git, "commit", "-m", "File added" @h3 = `git rev-parse HEAD` File.open("LICENSE.txt", "w") { |f| f.write("LICENSE") } system git, "add", HOMEBREW_CACHE/"LICENSE.txt" system git, "commit", "-m", "written to File" File.open("LICENSE.txt", "w") { |f| f.write("test") } system git, "add", HOMEBREW_CACHE/"LICENSE.txt" system git, "commit", "-m", "written to File" @cherry_pick_commit = `git rev-parse HEAD` system git, "reset", "--hard", "HEAD^" end end let(:file) { "README.md" } let(:file_hash1) { @h1[0..6] } let(:file_hash2) { @h2[0..6] } let(:files) { ["README.md", "LICENSE.txt"] } let(:files_hash1) { [@h3[0..6], ["LICENSE.txt"]] } let(:files_hash2) { [@h2[0..6], ["README.md"]] } let(:cherry_pick_commit) { @cherry_pick_commit[0..6] } describe "#commit_message" do it "returns the commit message" do expect(described_class.commit_message(HOMEBREW_CACHE, file_hash1)).to eq("File added") expect(described_class.commit_message(HOMEBREW_CACHE, file_hash2)).to eq("written to File") end it "errors when commit doesn't exist" do expect { described_class.commit_message(HOMEBREW_CACHE, "bad_refspec") }.to raise_error(ErrorDuringExecution, /bad revision/) end end describe "#cherry_pick!" do it "can cherry pick a commit" do expect(described_class.cherry_pick!(HOMEBREW_CACHE, cherry_pick_commit)).to be_truthy end it "aborts when cherry picking an existing hash" do expect { described_class.cherry_pick!(HOMEBREW_CACHE, file_hash1) }.to raise_error(ErrorDuringExecution, /Merge conflict in README.md/) end end describe "#last_revision_commit_of_file" do it "gives last revision commit when before_commit is nil" do expect( described_class.last_revision_commit_of_file(HOMEBREW_CACHE, file), ).to eq(file_hash1) end it "gives revision commit based on before_commit when it is not nil" do expect( described_class.last_revision_commit_of_file(HOMEBREW_CACHE, file, before_commit: file_hash2), ).to eq(file_hash2) end end describe "#file_at_commit" do it "returns file contents when file exists" do expect(described_class.file_at_commit(HOMEBREW_CACHE, file, file_hash1)).to eq("README") end it "returns empty when file doesn't exist" do expect(described_class.file_at_commit(HOMEBREW_CACHE, "foo.txt", file_hash1)).to eq("") expect(described_class.file_at_commit(HOMEBREW_CACHE, "LICENSE.txt", file_hash1)).to eq("") end end describe "#last_revision_commit_of_files" do context "when before_commit is nil" do it "gives last revision commit" do expect( described_class.last_revision_commit_of_files(HOMEBREW_CACHE, files), ).to eq(files_hash1) end end context "when before_commit is not nil" do it "gives last revision commit" do expect( described_class.last_revision_commit_of_files(HOMEBREW_CACHE, files, before_commit: file_hash2), ).to eq(files_hash2) end end end describe "#last_revision_of_file" do it "returns last revision of file" do expect( described_class.last_revision_of_file(HOMEBREW_CACHE, HOMEBREW_CACHE/file), ).to eq("README") end it "returns last revision of file based on before_commit" do expect( described_class.last_revision_of_file(HOMEBREW_CACHE, HOMEBREW_CACHE/file, before_commit: "0..3"), ).to eq("# README") end end describe "::available?" do it "returns true if git --version command succeeds" do expect(described_class).to be_available end it "returns false if git --version command does not succeed" do stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim") expect(described_class).not_to be_available end end describe "::path" do it "returns nil when git is not available" do stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim") expect(described_class.path).to eq(nil) end it "returns path of git when git is available" do expect(described_class.path).to end_with("git") end end describe "::version" do it "returns nil when git is not available" do stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim") expect(described_class.version).to eq(nil) end it "returns version of git when git is available" do expect(described_class.version).not_to be_nil end end describe "::ensure_installed!" do it "returns nil if git already available" do expect(described_class.ensure_installed!).to be_nil end context "when git is not already available" do before do stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim") end it "can't install brewed git if homebrew/core is unavailable" do allow_any_instance_of(Pathname).to receive(:directory?).and_return(false) expect { described_class.ensure_installed! }.to raise_error("Git is unavailable") end it "raises error if can't install git" do stub_const("HOMEBREW_BREW_FILE", HOMEBREW_PREFIX/"bin/brew") expect { described_class.ensure_installed! }.to raise_error("Git is unavailable") end unless ENV["HOMEBREW_TEST_GENERIC_OS"] it "installs git" do expect(described_class).to receive(:available?).and_return(false) expect(described_class).to receive(:safe_system).with(HOMEBREW_BREW_FILE, "install", "git").and_return(true) expect(described_class).to receive(:available?).and_return(true) described_class.ensure_installed! end end end end describe "::remote_exists?" do it "returns true when git is not available" do stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim") expect(described_class).to be_remote_exists("blah") end context "when git is available" do it "returns true when git remote exists", :needs_network do git = HOMEBREW_SHIMS_PATH/"scm/git" url = "https://github.com/Homebrew/homebrew.github.io" repo = HOMEBREW_CACHE/"hey" repo.mkpath repo.cd do system git, "init" system git, "remote", "add", "origin", url end expect(described_class).to be_remote_exists(url) end it "returns false when git remote does not exist" do expect(described_class).not_to be_remote_exists("blah") end end end end
bsd-2-clause
NikitaKarnauhov/lansink
src/lexer.cpp
15400
/* lexer.cpp Copyright (c) 2013, Nikita Karnauhov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "lexer.h" #include <iostream> #include <functional> #include <vector> #include <assert.h> using namespace lexer; Lexer::Lexer(std::wistream &_is) : m_is(_is), m_ctype(std::use_facet<std::ctype<wchar_t> >(_is.getloc())), m_tokenKinds{ { L",", TK::Comma }, { L";", TK::Semicolon }, { L":", TK::Colon }, { L"|", TK::Pipe }, { L"=", TK::Assignment }, { L"!", TK::Bang }, { L"$", TK::Dollar }, { L"(", TK::LParen }, { L")", TK::RParen }, { L"[", TK::LBracket }, { L"]", TK::RBracket }, { L"{", TK::LBrace }, { L"}", TK::RBrace }, { L"->", TK::Arrow }, } { } bool Lexer::_is_space(wchar_t _c) const { return m_ctype.is(std::ctype_base::space, _c); } bool Lexer::_is_digit(wchar_t _c) const { return m_ctype.is(std::ctype_base::digit, _c); } bool Lexer::_is_xdigit(wchar_t _c) const { return m_ctype.is(std::ctype_base::xdigit, _c); } bool Lexer::_is_alpha(wchar_t _c) const { return m_ctype.is(std::ctype_base::alpha, _c); } bool Lexer::_is_alnum(wchar_t _c) const { return m_ctype.is(std::ctype_base::alnum, _c); } bool Lexer::_is_raw(wchar_t _c) const { switch (_c) { case L'`': case L'~': case L'!': case L'@': case L'#': case L'%': case L'^': case L'&': case L'-': case L'+': case L'\\': case L'<': case L'>': case L'/': case L'?': case L'"': case L'.': return true; default: return false; } } std::wstring Lexer::_read_digits() { std::wstring s; wchar_t c = 0; while (m_is.get(c).good()) { if (!_is_digit(c)) { m_is.unget(); break; } s += c; } return s; } static void _append(Token &_tok, wchar_t _c, bool _bDecoded = false) { // Recognized patterns: \n, \r\n, \r. if (!_bDecoded && (_c == L'\r' || _c == L'\n')) { const wchar_t d = _tok.strData.empty() ? 0 : _tok.strData[_tok.strData.size() - 1]; if (_c == L'\r' || d != L'\r') ++_tok.nLine; _tok.nCol = 0; } else ++_tok.nCol; _tok.strData += _c; } static void _append(Token &_tok, const std::wstring &_s) { _tok.strData.reserve(_tok.strData.size() + _s.size()); for (wchar_t c : _s) _append(_tok, c); } bool Lexer::_read_whitespace(Token &_tok) { if (!m_is.good() || !_is_space(m_is.peek())) return false; _tok.kind = TK::Whitespace; _tok.strData.clear(); wchar_t c; while (m_is.get(c).good()) { if (!_is_space(c)) { m_is.unget(); break; } _append(_tok, c); } return true; } bool Lexer::_read_comment(Token &_tok) { if (!m_is.good() || (m_is.peek() != L'/' && m_is.peek() != L'#')) return false; const bool bHash = m_is.peek() == L'#'; m_is.ignore(1); if (!m_is.good()) { m_is.unget(); return false; } enum class CommentKind { Single, Multi } ck; if (bHash || m_is.peek() == L'/') ck = CommentKind::Single; else if (!bHash && m_is.peek() == L'*') ck = CommentKind::Multi; else { m_is.unget(); // Put back the initial slash. return false; } _tok.kind = TK::Comment; _append(_tok, bHash ? L'#' : L'/'); wchar_t c; if (ck == CommentKind::Single) { while (m_is.get(c).good()) { if (c == L'\n' || c == L'\r') { m_is.unget(); break; } _append(_tok, c); } } else { assert(ck == CommentKind::Multi); while (m_is.get(c).good()) { _append(_tok, c); if (c == L'*' && m_is.peek() == L'/') { _append(_tok, m_is.get()); break; } } } return true; } bool Lexer::_read_integer(Token& _tok) { if (!m_is.good() || !_is_digit(m_is.peek())) return false; wchar_t c = m_is.get(); _tok.kind = TK::Integer; _append(_tok, c); if (!m_is.good()) return true; if (c == L'0' && m_is.peek() == L'x') { m_is.ignore(1); if (_is_xdigit(m_is.peek())) { _append(_tok, L'x'); while (m_is.get(c).good()) { if (!_is_xdigit(c)) { m_is.unget(); break; } _append(_tok, c); } } else m_is.unget(); } else _append(_tok, _read_digits()); return true; } bool Lexer::_read_real(Token &_tok) { if (!m_is.good() || !(_is_digit(m_is.peek()) || m_is.peek() == L'.')) return false; wchar_t c = m_is.get(); if (c == L'.' && !_is_digit(m_is.peek())) { m_is.unget(); return false; } _tok.kind = TK::Real; _append(_tok, c); _append(_tok, _read_digits()); if (m_is.peek() == L'.') { _append(_tok, m_is.get()); _append(_tok, _read_digits()); } else if (m_is.peek() != L'e' && m_is.peek() != L'E') { m_is.clear(); for (size_t i = 0; i < _tok.strData.size(); ++i) m_is.putback(_tok.strData[_tok.strData.size() - i - 1]); return false; } if (m_is.peek() == L'e' || m_is.peek() == L'E') { c = m_is.get(); if (m_is.peek() == L'-' || m_is.peek() == L'+') { const wchar_t d = m_is.get(); if (!_is_digit(m_is.peek())) { m_is.clear(); m_is.putback(d); m_is.putback(c); return true; } _append(_tok, c); _append(_tok, d); } else if (!_is_digit(m_is.peek())) { m_is.unget(); return true; } else _append(_tok, c); _append(_tok, _read_digits()); } return true; } bool Lexer::_read_char(Token &_tok) { if (m_is.peek() != L'\\') { _append(_tok, m_is.get(), true); return true; } m_is.get(); // Back slash. auto decode = [&]() { const wchar_t d = m_is.get(); std::wstring s; // fragment ESCAPED_CHAR : '\\' ('\'' | '\"' | '\\' | '0' | 'n' | 't' | 'r'); // fragment CHAR_CODE : '\\x' HEX_DIGIT (HEX_DIGIT (HEX_DIGIT HEX_DIGIT?)?)?; switch (d) { case L'0': return L'\0'; case L'n': return L'\n'; case L't': return L'\t'; case L'r': return L'\r'; case L'x': for (int i = 0; i < 4 && _is_xdigit(m_is.peek()); ++ i) s += m_is.get(); if (s.empty()) break; return (wchar_t)wcstol(s.data(), NULL, 16); } return d; }; _append(_tok, decode(), true); return true; } bool Lexer::_read_string(Token &_tok) { if (!m_is.good() || m_is.peek() != L'"') return false; _tok.kind = TK::String; m_is.get(); // Quote. while (m_is.good() && m_is.peek() != L'"') if (!_read_char(_tok)) return false; if (m_is.peek() != L'"') return false; m_is.get(); // Quote. return true; } bool Lexer::_read_identifier(Token &_tok) { if (!m_is.good() || !(_is_alpha(m_is.peek()) || m_is.peek() == L'_' || m_is.peek() == L'-')) return false; wchar_t c = m_is.get(); _append(_tok, c); if (c == L'_' || c == L'-') { while (m_is.get(c).good()) { if (c != L'_' && c != L'-') { m_is.unget(); break; } _append(_tok, c); } if (!_is_alnum(c)) { m_is.clear(); // Order doesn't matter, it's all underscores. for (wchar_t d : _tok.strData) m_is.putback(d); return false; } } _tok.kind = TK::Identifier; while (m_is.get(c).good()) { if (!_is_alnum(c) && c != L'_' && c != L'-') { m_is.unget(); break; } _append(_tok, c); } return true; } bool Lexer::_read_raw(Token &_tok) { if (!m_is.good() || !_is_raw(m_is.peek())) return false; _tok.kind = TK::Raw; wchar_t c; while (m_is.get(c).good()) { if (!_is_raw(c)) { m_is.unget(); break; } _append(_tok, c); } #if 0 Token ident; if (!_read_identifier(ident)) { m_is.clear(); for (auto i = _tok.strData.rend(); i != _tok.strData.rbegin(); ++i) m_is.putback(*i); return false; } _append(_tok, ident.strData)); #endif return true; } bool Lexer::_read_lexeme(Token &_tok) { wchar_t c = m_is.peek(); if (!m_is.good()) return false; const wchar_t strLead[]{c, 0}; auto iTK = m_tokenKinds.lower_bound(strLead); if (iTK == m_tokenKinds.end() || iTK->first[0] != c) return false; _append(_tok, c); _tok.kind = TK::None; m_is.ignore(1); if (iTK->first.size() == 1) { _tok.kind = iTK->second; return true; } while (m_is.get(c).good()) { _append(_tok, c); iTK = m_tokenKinds.lower_bound(_tok.strData); const size_t cLen = _tok.strData.size(); if (iTK == m_tokenKinds.end() || _tok.strData.compare(0, cLen, iTK->first, 0, cLen) != 0) break; if (iTK->first.size() == _tok.strData.size()) { _tok.kind = iTK->second; break; } } if (_tok.kind == TK::None) { m_is.clear(); for (size_t i = 0; i < _tok.strData.size(); ++i) m_is.putback(_tok.strData[_tok.strData.size() - i - 1]); return false; } return true; } bool Lexer::_is_eof() const { return !m_tokens.empty() && (std::prev(m_tokens.end())->kind == TK::EndOfFile || std::prev(m_tokens.end())->kind == TK::Error); } using std::placeholders::_1; Lexer::Tokens::iterator Lexer::_read() { if (m_is.tellg() != m_pos) m_is.seekg(m_pos); if (_is_eof()) return std::prev(m_tokens.end()); if (!m_is.good()) return m_tokens.insert(Token(TK::EndOfFile, m_pos, L"", m_nLine, m_nCol)).first; // Order of reader functions below does matter. std::vector<std::function<bool(Token &)> > readers{ std::bind(&Lexer::_read_whitespace, this, _1), std::bind(&Lexer::_read_comment, this, _1), std::bind(&Lexer::_read_real, this, _1), std::bind(&Lexer::_read_integer, this, _1), std::bind(&Lexer::_read_string, this, _1), std::bind(&Lexer::_read_lexeme, this, _1), std::bind(&Lexer::_read_identifier, this, _1), std::bind(&Lexer::_read_raw, this, _1) }; for (auto reader : readers) { Token tok(TK::None, m_pos, L"", m_nLine, m_nCol); if (reader(tok)) { m_pos = m_is.tellg(); std::swap(m_nLine, tok.nLine); std::swap(m_nCol, tok.nCol); return m_tokens.insert(tok).first; } } return m_tokens.insert(Token(m_is.good() ? TK::Error : TK::EndOfFile, m_pos, L"", m_nLine, m_nCol)).first; } Lexer::iterator Lexer::begin() { return iterator(Lexer::IteratorImpl(*this, m_tokens.empty() ? _read() : m_tokens.begin())); } Lexer::iterator Lexer::end() { return iterator(Lexer::IteratorImpl(*this, m_tokens.end())); } int Lexer::define(const std::wstring &_s) { const int nTK = m_nDefinition++; m_tokenKinds[_s] = nTK; return nTK; } // IteratorImpl. Lexer::IteratorImpl::IteratorImpl(const Lexer::IteratorImpl &_other) : m_pLexer(_other.m_pLexer), m_nUpdateCount(_other.m_nUpdateCount), m_iToken(_other.m_iToken), m_pos(_other.m_pos) { } Lexer::IteratorImpl::IteratorImpl(Lexer &_lexer) : m_pLexer(&_lexer), m_nUpdateCount(_lexer.m_nUpdateCount), m_iToken(_lexer.m_tokens.begin()), m_pos(0) { } Lexer::IteratorImpl::IteratorImpl(Lexer &_lexer, Lexer::Tokens::iterator _iToken) : m_pLexer(&_lexer), m_nUpdateCount(_lexer.m_nUpdateCount), m_iToken(_iToken), m_pos(m_iToken == m_pLexer->m_tokens.end() ? std::streampos(0) : m_iToken->pos) { } void Lexer::IteratorImpl::validate() { if (m_nUpdateCount < m_pLexer->m_nUpdateCount) { if (m_iToken != m_pLexer->m_tokens.end()) { Token tok(TK::None, m_pos); m_iToken = m_pLexer->m_tokens.lower_bound(tok); if (m_iToken == m_pLexer->m_tokens.end() && !m_pLexer->m_tokens.empty()) m_iToken = std::prev(m_pLexer->m_tokens.end()); while (m_iToken == m_pLexer->m_tokens.end() || (m_iToken->kind != TK::EndOfFile && m_iToken->kind != TK::Error && m_iToken->pos + std::streampos(m_iToken->get_length()) <= m_pos)) { m_iToken = m_pLexer->_read(); if (m_iToken == m_pLexer->m_tokens.end()) break; } } m_nUpdateCount = m_pLexer->m_nUpdateCount; m_pos = m_iToken == m_pLexer->m_tokens.end() ? std::streampos(0) : m_iToken->pos; } } bool Lexer::IteratorImpl::move_next() { validate(); if (m_iToken == m_pLexer->m_tokens.end()) return false; if (m_iToken->kind == TK::EndOfFile || m_iToken->kind == TK::Error) { m_pos = 0; m_iToken = m_pLexer->m_tokens.end(); return false; } ++m_iToken; if (m_iToken == m_pLexer->m_tokens.end()) m_iToken = m_pLexer->_read(); m_pos = m_iToken == m_pLexer->m_tokens.end() ? std::streampos(0) : m_iToken->pos; return m_iToken != m_pLexer->m_tokens.end(); } bool Lexer::IteratorImpl::move_prev() { validate(); if (m_iToken == m_pLexer->m_tokens.begin()) return false; --m_iToken; m_pos = m_iToken->pos; return true; }
bsd-2-clause
sebastienros/jint
Jint.Tests.Test262/test/language/statements/generators/dstr-obj-ptrn-prop-id.js
1778
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-prop-id.case // - src/dstr-binding/default/gen-func-decl.template /*--- description: Binding as specified via property name and identifier (generator function declaration) esid: sec-generator-function-definitions-runtime-semantics-instantiatefunctionobject es6id: 14.4.12 features: [generators, destructuring-binding] flags: [generated] info: | GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody } [...] 2. Let F be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, strict). [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 8. Return InitializeReferencedBinding(lhs, v). ---*/ var callCount = 0; function* f({ x: y }) { assert.sameValue(y, 23); assert.throws(ReferenceError, function() { x; }); callCount = callCount + 1; }; f({ x: 23 }).next(); assert.sameValue(callCount, 1, 'generator function invoked exactly once');
bsd-2-clause
EIDSS/EIDSS-Legacy
EIDSS v6/eidss.main/Program.cs
7764
using System; using System.Reflection; using System.Windows.Forms; using bv.common; using bv.common.Diagnostics; using bv.common.Resources; using bv.common.Resources.TranslationTool; using bv.model.Model.Core; using bv.model.Model.Validators; using bv.winclient.Core; using bv.common.Core; using eidss.model.Resources; using eidss.model.Core; using eidss.model.Enums; using bv.winclient.Localization; using bv.model.BLToolkit; using bv.common.Configuration; using System.IO; using bv.winclient.ActionPanel; namespace eidss.main { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Config.DefaultGlobalConfigFileName = Constants.GlobalEidssConfigName; bool showMessage = true; if (!OneInstanceApp.Run(true, ref showMessage)) { if (showMessage) ErrorForm.ShowMessage("msgEIDSSRunning", "You can\'t run multiple EIDSS instances simultaneously. Other instance of EIDSS is running already"); return; } //Application.SetCompatibleTextRenderingDefault(False) var eh = new UnhandledExceptionHandler(); // Adds the event handler to the event. Application.ThreadException += eh.OnThreadException; try { DbManagerFactory.SetSqlFactory(new ConnectionCredentials().ConnectionString); EidssUserContext.Init( () => EidssSiteContext.Instance.SiteType != SiteType.CDR && WinUtils.ConfirmMessage(BvMessages.Get("msgReplicationPrompt","Start the replication to transfer data on other sites?"), BvMessages.Get("msgREplicationPromptCaption", "Confirm Replication")), () => { EidssEventLog.Instance.CheckNotificationService(); EidssEventLog.Instance.StartReplication(); } ); ClassLoader.Init("bv_common.dll", null); ClassLoader.Init("bvwin_common.dll", null); ClassLoader.Init("bv.common.dll", null); ClassLoader.Init("bv.winclient.dll", null); ClassLoader.Init("eidss*.dll", null); Localizer.MenuMessages = EidssMenu.Instance; TranslationToolHelper.TranslationsDir = Path.Combine(Application.StartupPath, TranslationToolHelper.TranslationsDirectoryName); WinClientContext.ApplicationCaption = EidssMessages.Get("EIDSS_Caption", "Electronic Integrated Disease Surveillance System"); WinClientContext.Init(); //DevExpress.Skins.SkinManager.Default.RegisterAssembly(typeof(DevExpress.UserSkins.eidssmoneyskin).Assembly); if (!string.IsNullOrEmpty(BaseSettings.SkinAssembly) && File.Exists(BaseSettings.SkinAssembly)) DevExpress.Skins.SkinManager.Default.RegisterAssembly( Assembly.LoadFrom(BaseSettings.SkinAssembly)); else DevExpress.Skins.SkinManager.Default.RegisterAssembly( typeof(DevExpress.UserSkins.eidssskin).Assembly); //DevExpress.UserSkins.BonusSkins.Register(); Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(False) DevExpress.Skins.SkinManager.EnableFormSkins(); Application.DoEvents(); Splash.ShowSplash(); //BV.common.db.Core.ConnectionManager.DefaultInstance.ConfigFilesToSave = new string[] {"EIDSS_ClientAgent.exe.config"}; //string appdir = System.IO.Path.GetDirectoryName(Application.ExecutablePath); //var defHelpName = Config.GetSetting("HelpUrl", "file:///" + appdir.Replace("\\", "/") + "/WebHelp_EIDSS_with_Search/"); var defHelpName = Config.GetSetting("HelpUrl"); WinClientContext.HelpNames.Add(Localizer.lngEn, Config.GetSetting("HelpUrl." + Localizer.lngEn, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngRu, Config.GetSetting("HelpUrl." + Localizer.lngRu, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngGe, Config.GetSetting("HelpUrl." + Localizer.lngGe, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngKz, Config.GetSetting("HelpUrl." + Localizer.lngKz, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngUzCyr, Config.GetSetting("HelpUrl." + Localizer.lngUzCyr, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngUzLat, Config.GetSetting("HelpUrl." + Localizer.lngUzLat, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngAzLat, Config.GetSetting("HelpUrl." + Localizer.lngAzLat, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngUk, Config.GetSetting("HelpUrl." + Localizer.lngUk, defHelpName)); WinClientContext.HelpNames.Add(Localizer.lngAr, Config.GetSetting("HelpUrl." + Localizer.lngAr, defHelpName)); //DevXLocalizer.ForceResourceAdding(); DevXLocalizer.Init(); WinClientContext.FieldCaptions = EidssFields.Instance; BaseFieldValidator.FieldCaptions = EidssFields.Instance; ErrorForm.Messages = EidssMessages.Instance; BaseActionPanel.Messages = EidssMessages.Instance; ErrorMessage.Messages = EidssMessages.Instance; BvLookupColumnInfo.Messages = EidssMessages.Instance; bv.common.win.BaseValidator.Messages = EidssMessages.Instance; bv.common.win.BaseForm.EventLog = EidssEventLog.Instance; bv.common.win.BaseDetailForm.cancelMode = bv.common.win.BaseDetailForm.CancelCloseMode.CallPost; //CheckHelpRegistration(); //LayoutHelper.Init(); Application.EnableVisualStyles(); //DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true; //Application.SetCompatibleTextRenderingDefault(false); ActionLocker.ShowWaitDialog = WaitDialog.ShowWaitDialog; ActionLocker.CloseWaitDialog = WaitDialog.CloseWaitDialog; Application.Idle += ApplicationOnIdle; SecurityLog.WriteToEventLogDB(null, SecurityAuditEvent.ProcessStart, true, null, null, "EIDSS is started", SecurityAuditProcessType.Eidss); Dbg.Debug("EIDSS is started with ClientID {0}", ModelUserContext.ClientID); Application.Run(new MainForm()); } catch (Exception ex) { MessageForm.Show(ex.ToString(), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); MainForm.ExitApp(true); } } private static void ApplicationOnIdle(object sender, EventArgs eventArgs) { try { if (EidssUserContext.User != null && EidssUserContext.User.IsAuthenticated) { LookupManager.ClearAndReloadOnIdle(); } } catch (Exception) { } } } }
bsd-2-clause
zergylord/MyCaffe
tools/test_net.cpp
1628
// Copyright 2014 BVLC and contributors. // // This is a simple script that allows one to quickly test a network whose // structure is specified by text format protocol buffers, and whose parameter // are loaded from a pre-trained network. // Usage: // test_net net_proto pretrained_net_proto iterations [CPU/GPU] #include <cuda_runtime.h> #include <cstring> #include <cstdlib> #include <vector> #include "caffe/caffe.hpp" using namespace caffe; // NOLINT(build/namespaces) int main(int argc, char** argv) { if (argc < 4 || argc > 5) { LOG(ERROR) << "test_net net_proto pretrained_net_proto iterations " << "[CPU/GPU]"; return 1; } cudaSetDevice(0); Caffe::set_phase(Caffe::TEST); if (argc == 5 && strcmp(argv[4], "GPU") == 0) { LOG(ERROR) << "Using GPU"; Caffe::set_mode(Caffe::GPU); } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } Net<float> caffe_test_net(argv[1]); NetParameter trained_net_param; ReadProtoFromBinaryFile(argv[2], &trained_net_param); caffe_test_net.CopyTrainedLayersFrom(trained_net_param); int total_iter = atoi(argv[3]); LOG(ERROR) << "Running " << total_iter << "Iterations."; double test_accuracy = 0; vector<Blob<float>*> dummy_blob_input_vec; for (int i = 0; i < total_iter; ++i) { const vector<Blob<float>*>& result = caffe_test_net.Forward(dummy_blob_input_vec); test_accuracy += result[0]->cpu_data()[0]; LOG(ERROR) << "Batch " << i << ", accuracy: " << result[0]->cpu_data()[0]; } test_accuracy /= total_iter; LOG(ERROR) << "Test accuracy:" << test_accuracy; return 0; }
bsd-2-clause
Krozark/SFML-book
08_Multiplayer/DataPersistence/src/SFML-Book/server/Client.cpp
1735
#include <SFML-Book/server/Client.hpp> #include <SFML-Book/common/FuncIds.hpp> #include <iostream> namespace book { Client::Client() : _team(nullptr) { } Client::~Client() { if(_team) _team->remove(this); } void Client::setTeam(Team::type_ptr team) { if(_team) _team->remove(this); _team = team; if(_team) _team->add(this); } Team::type_ptr Client::getTeam()const { return _team; } bool Client::connect() { bool res = false; sf::Packet packet; std::cout<<"Get datas"<<std::endl; if(_sockIn.receive(packet) == sf::Socket::Done) { sf::Int32 fid; packet>>fid; std::cout<<"Receive datas. Compare them to expected one"<<std::endl; if(fid == FuncIds::IdHandler) { sf::Uint32 port; packet>>port; std::cout<<"Connect to given port ("<<port<<")"<<std::endl; if(_sockOut.connect(_sockIn.getRemoteAddress(),port,sf::seconds(5)) == sf::Socket::Status::Done) { std::cout<<"All is good"<<std::endl; res = true; } else std::cout<<"Failed"<<std::endl; } else std::cout<<"Error. Fuction id is not IdHandler"<<std::endl; } else std::cout<<"Failed"<<std::endl; return res; } sf::IpAddress Client::getRemoteAddress()const { return _sockIn.getRemoteAddress(); } sf::TcpSocket& Client::getSockIn() { return _sockIn; } }
bsd-2-clause
clearlycloudy/e2r
core/interface/i_interpolate.rs
329
pub trait IInterpolate < T > : DoubleEndedIterator< Item = T > where T: Clone { fn interp_delta( & mut self, steps: i64 ) -> Option< T >; fn interp_current( & self ) -> T; fn interp_is_end( & self ) -> bool; fn interp_is_start( & self ) -> bool; fn num_steps( & self ) -> u64; fn reset( & mut self ); }
bsd-2-clause
jcodec/jcodec
src/main/java/org/jcodec/containers/mp4/demuxer/DashStreamDemuxer.java
16617
package org.jcodec.containers.mp4.demuxer; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import org.jcodec.api.JCodecException; import org.jcodec.common.Demuxer; import org.jcodec.common.DemuxerTrack; import org.jcodec.common.DemuxerTrackMeta; import org.jcodec.common.SeekableDemuxerTrack; import org.jcodec.common.TrackType; import org.jcodec.common.io.NIOUtils; import org.jcodec.common.model.Packet; import org.jcodec.containers.mp4.MP4Packet; import org.jcodec.containers.mp4.MPDModel; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * Demuxes one track out of multiple DASH fragments * * @author The JCodec project * */ public class DashStreamDemuxer implements Demuxer { private List<DashStreamDemuxerTrack> tracks; private List<SeekableDemuxerTrack> coded; private URL url; private MPDModel.MPD mpd; public static int INIT_SIZE = 3; public DashStreamDemuxer(URL url) throws IOException { this.url = url; this.tracks = new LinkedList<DashStreamDemuxer.DashStreamDemuxerTrack>(); this.coded = new LinkedList<SeekableDemuxerTrack>(); try { this.mpd = MPDModel.parse(url); if (this.mpd != null && this.mpd.periods != null && this.mpd.periods.size() > 0) { MPDModel.Period period = this.mpd.periods.get(0); for (MPDModel.AdaptationSet adaptationSet : period.adaptationSets) { DashStreamDemuxerTrack tr = new DashStreamDemuxerTrack(url, adaptationSet, period); tracks.add(tr); coded.add(new CodecMP4DemuxerTrack(tr)); } } } catch (JCodecException e) { throw new IOException(e); } } static class DashStreamDemuxerTrack implements SeekableDemuxerTrack, Closeable { private MPDModel.AdaptationSet adaptationSet; private URL url; private File initFile; private String selectedRprz; private Map<Integer, Future<DashMP4DemuxerTrack>> fragments = new HashMap<Integer, Future<DashMP4DemuxerTrack>>(); private int curFragNo; private boolean streaming; private int maxDownloadAttampts = 1024; private ExecutorService threadPool; private int globalFrame; private MPDModel.Period period; private float frameRate; private double segmentDuration; private int[] seekFrames; static int next_id = 0; int id; public DashStreamDemuxerTrack(URL url, MPDModel.AdaptationSet adaptationSet, MPDModel.Period period) throws IOException { this.url = url; this.period = period; this.adaptationSet = adaptationSet; this.threadPool = Executors.newFixedThreadPool(INIT_SIZE, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; } }); if (adaptationSet.representations.size() > 0) { MPDModel.Representation rprz = adaptationSet.representations.get(0); selectedRprz = rprz.id; frameRate = rprz.frameRate == null ? 0 : rprz.frameRate.scalar(); MPDModel.SegmentTemplate stpl = getSegmentTemplate(); segmentDuration = stpl != null ? ((double) stpl.duration) / stpl.timescale : period.duration.sec; downloadInit(); for (int i = 0; i < INIT_SIZE; i++) { scheduleFragment(i); } int numSeg = (int) (period.duration.sec / segmentDuration); int segmentFrames = (int) (segmentDuration * frameRate); seekFrames = new int[numSeg]; for (int i = 0, tmp = 0; i < numSeg; i++, tmp += segmentFrames) { seekFrames[i] = tmp + 1; } } id = next_id++; } private MPDModel.Representation getRrprz() { for (MPDModel.Representation rprz : adaptationSet.representations) { if (rprz.id.equals(selectedRprz)) return rprz; } return null; } private MPDModel.SegmentTemplate getSegmentTemplate() { MPDModel.Representation rprz = getRrprz(); return adaptationSet.segmentTemplate == null ? rprz.segmentTemplate : adaptationSet.segmentTemplate; } private static void sleepQuiet(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } private DashMP4DemuxerTrack downloadFrag(int no) throws IOException { MPDModel.Representation rprz = getRrprz(); MPDModel.SegmentTemplate stpl = getSegmentTemplate(); for (int i = 0; i < maxDownloadAttampts; i++) { try { URL urlInit = null; if (stpl != null && stpl.media != null) { Map<String, Object> vals = new HashMap<String, Object>(); vals.put("RepresentationID", selectedRprz); vals.put("Number", stpl.startNumber + no); String tmp = fillTemplate(stpl.media, vals); urlInit = new URL(url, tmp); } else if (rprz.segmentList != null && rprz.segmentList.segmentUrls.size() > no) { MPDModel.SegmentURL segmentURL = rprz.segmentList.segmentUrls.get(no); urlInit = new URL(url, segmentURL.media); } if (urlInit != null) { File tempFile = File.createTempFile("org.jcodec", fileName(urlInit.getPath())); System.out.println("Fetching fragment: " + urlInit.toExternalForm()); NIOUtils.fetchUrl(urlInit, tempFile); DashMP4DemuxerTrack demuxer = DashMP4DemuxerTrack .createFromFiles(Arrays.asList(new File[] { initFile, tempFile })); demuxer.setDurationHint(segmentDuration); return demuxer; } else if (rprz.baseURL != null) { DashMP4DemuxerTrack demuxer = DashMP4DemuxerTrack .createFromFiles(Arrays.asList(new File[] { initFile, initFile })); return demuxer; } break; } catch (FileNotFoundException e) { if (!streaming) return null; sleepQuiet(100); } } return null; } private String fillTemplate(String media, Map<String, Object> vals) { StringBuilder builder = new StringBuilder(); char[] charArray = media.toCharArray(); int varStart = 0; for (int i = 0; i < charArray.length; i++) { if ('$' == charArray[i]) { if (varStart == 0) { varStart = i + 1; } else { String var = new String(charArray, varStart, i - varStart); int formatStart = var.indexOf('%'); if (formatStart != -1) { String format = var.substring(formatStart); var = var.substring(0, formatStart); Object object = vals.get(var); if (object != null) { String val = String.format(format, object); builder.append(val); } } else { Object object = vals.get(var); if (object != null) { builder.append(String.valueOf(object)); } } varStart = 0; } } else if (varStart == 0) { builder.append(charArray[i]); } } return builder.toString(); } private String fileName(String path) { String[] split = path.split("/"); return split[split.length - 1]; } private void downloadInit() throws IOException { MPDModel.Representation rprz = getRrprz(); if (getSegmentTemplate() != null && getSegmentTemplate().initialization != null) { String tmp = getSegmentTemplate().initialization.replace("$RepresentationID$", selectedRprz); URL urlInit = new URL(url, tmp); File tempFile = File.createTempFile("org.jcodec", fileName(urlInit.getPath())); System.out.println("Fetching init: " + urlInit.toExternalForm()); NIOUtils.fetchUrl(urlInit, tempFile); initFile = tempFile; } else if (rprz.baseURL != null) { URL urlInit = new URL(url, rprz.baseURL); File tempFile = File.createTempFile("org.jcodec", fileName(urlInit.getPath())); System.out.println("Fetching init: " + urlInit.toExternalForm()); NIOUtils.fetchUrl(urlInit, tempFile); initFile = tempFile; } else if (rprz.segmentList != null && rprz.segmentList.initialization != null) { URL urlInit = new URL(url, rprz.segmentList.initialization.sourceURL); File tempFile = File.createTempFile("org.jcodec", fileName(urlInit.getPath())); System.out.println("Fetching init: " + urlInit.toExternalForm()); NIOUtils.fetchUrl(urlInit, tempFile); initFile = tempFile; } } @Override public Packet nextFrame() throws IOException { try { Future<DashMP4DemuxerTrack> curFrag = fragments.get(curFragNo); MP4Packet nextFrame = null; if (curFrag != null) { nextFrame = getCurFrag(curFrag).nextFrame(); if (nextFrame == null) { getCurFrag(curFrag).close(); fragments.put(curFragNo, null); curFragNo++; } } if (nextFrame != null) { ++globalFrame; return setPts(nextFrame); } curFrag = fragments.get(curFragNo); if (curFrag == null) { for (int i = curFragNo; i < curFragNo + INIT_SIZE; i++) scheduleFragment(curFragNo); curFrag = fragments.get(curFragNo); } if (curFrag == null) return null; ++globalFrame; return setPts(getCurFrag(curFrag).nextFrame()); } catch (ExecutionException e) { throw new RuntimeException("Execution problem", e); } } private DashMP4DemuxerTrack getCurFrag(Future<DashMP4DemuxerTrack> curFrag) throws ExecutionException { while (true) { try { return curFrag.get(); } catch (InterruptedException e) { } } } private MP4Packet setPts(MP4Packet frame) { double off = curFragNo * segmentDuration; frame.setPts((long) (frame.getPts() + off * frame.getTimescale())); frame.setMediaPts((long) (frame.getMediaPts() + off * frame.getTimescale())); frame.setFrameNo(globalFrame - 1); if (id == 5) System.out.println( String.format("[%d] PTS: %f DUR: %s", id, (float) frame.getPtsD(), (float) frame.getDurationD())); return frame; } private void scheduleFragment(final int fragNo) { if (fragments.get(fragNo) == null) { Future<DashMP4DemuxerTrack> future = threadPool.submit(new Callable<DashMP4DemuxerTrack>() { @Override public DashMP4DemuxerTrack call() throws Exception { return downloadFrag(fragNo); } }); fragments.put(fragNo, future); } } @Override public DemuxerTrackMeta getMeta() { Future<DashMP4DemuxerTrack> future = fragments.get(curFragNo); if (future == null) return null; try { DashMP4DemuxerTrack frag = getCurFrag(future); MP4DemuxerTrackMeta fragMeta = (MP4DemuxerTrackMeta) frag.getMeta(); double totalDuration = period.duration.sec; int totalFrames = (int) (period.duration.sec * frameRate); return new MP4DemuxerTrackMeta(fragMeta.getType(), fragMeta.getCodec(), totalDuration, seekFrames, totalFrames, fragMeta.getCodecPrivate(), fragMeta.getVideoCodecMeta(), fragMeta.getAudioCodecMeta(), fragMeta.getSampleEntries(), fragMeta.getCodecPrivateOpaque()); } catch (ExecutionException e) { throw new RuntimeException("Execution problem", e); } } @Override public void close() throws IOException { Set<Entry<Integer, Future<DashMP4DemuxerTrack>>> entrySet = fragments.entrySet(); for (Entry<Integer, Future<DashMP4DemuxerTrack>> entry : entrySet) { if (entry.getValue() != null) { try { getCurFrag(entry.getValue()).close(); } catch (ExecutionException e) { throw new IOException("Execution problem", e); } entry.setValue(null); } } } @Override public boolean gotoFrame(long frameNo) throws IOException { if (frameNo != 0) return false; curFragNo = 0; globalFrame = 0; for (int i = 0; i < INIT_SIZE; i++) { scheduleFragment(i); } return true; } @Override public boolean gotoSyncFrame(long frameNo) throws IOException { return false; } @Override public long getCurFrame() { return globalFrame; } @Override public void seek(double second) throws IOException { throw new RuntimeException("unimpl"); } } @Override public void close() throws IOException { for (DashStreamDemuxerTrack track : tracks) { track.close(); } } @Override public List<? extends DemuxerTrack> getTracks() { return coded; } @Override public List<? extends DemuxerTrack> getVideoTracks() { ArrayList<SeekableDemuxerTrack> result = new ArrayList<SeekableDemuxerTrack>(); for (SeekableDemuxerTrack demuxerTrack : coded) { DemuxerTrackMeta meta = demuxerTrack.getMeta(); if (meta.getType() == TrackType.VIDEO) result.add(demuxerTrack); } return result; } @Override public List<? extends DemuxerTrack> getAudioTracks() { ArrayList<SeekableDemuxerTrack> result = new ArrayList<SeekableDemuxerTrack>(); for (SeekableDemuxerTrack demuxerTrack : coded) { DemuxerTrackMeta meta = demuxerTrack.getMeta(); if (meta.getType() == TrackType.AUDIO) result.add(demuxerTrack); } return result; } }
bsd-2-clause
IvionSauce/MeidoBot
IrcCalc/Verifier.cs
6326
using System; using System.Collections.Generic; namespace Calculation { static class Verifier { public static VerifiedExpression VerifyExpression(CalcToken[] tokens, CalcEnvironment env) { int currentDepth = 0; // Depth/subexpression -> Argument counter & function metadata. // A stack based solution might be better? var funcTracking = new Dictionary<int, FunctionMetadata>(); for (int i = 0; i < tokens.Length; i++) { var token = tokens[i]; // Used as `out` argument in processing types ArgSeperator and ParenClose. // The compiler complains if we define it in both cases, which are counted as the same scope. FunctionMetadata funcMeta; switch (token.Type) { // --- Verify symbol (variables and constants) --- case TokenType.Symbol: double numVal; if (env.VarOrConst(token.Value, out numVal)) { // Resolve symbol to value. var symbol = (CalcSymbolToken)token; tokens[i] = symbol.New(numVal); break; } else { return new VerifiedExpression("Undefined symbol: " + token.Value, token.OriginIndex); } // --- Verify function symbol --- case TokenType.Function: CalcFunction func; if (env.Function(token.Value, out func)) { // Resolve function symbol to function. var funcToken = (CalcFuncToken)token; tokens[i] = funcToken.New(func); // Record that the next subexpression (delimited by parentheses) is associated // with a function. funcTracking[currentDepth + 1] = new FunctionMetadata(func, funcToken); break; } else { return new VerifiedExpression("Undefined function symbol: " + token.Value, token.OriginIndex); } // --- Keep count of arguments to functions --- case TokenType.ArgSeperator: if (funcTracking.TryGetValue(currentDepth, out funcMeta)) { // Another seperator, another function argument. // The previous stage assures that there will be an operand. funcMeta.ArgCounter++; } break; // --- Record opening and closing of parentheses --- case TokenType.ParenOpen: currentDepth++; break; case TokenType.ParenClose: // If the subexpression we're closing/leaving is associated with a function we need to // verify the function argument count. if (funcTracking.TryGetValue(currentDepth, out funcMeta)) { if (!funcMeta.CountsAreEqual) { // And this is why we kept around that metadata, so we could report the appropriate // information on encountering an discrepancy in argument count. return new VerifiedExpression( string.Format("Invalid number of arguments for {0} (got {1} expected {2})", funcMeta.FuncSymbol, funcMeta.ArgCounter, funcMeta.RequiredArgs), funcMeta.OriginIndex); } // We're leaving the current depth, we no longer need this information. funcTracking.Remove(currentDepth); } currentDepth--; break; // --- The rest is not important for this stage --- default: continue; } // switch } // for // We have successfully stepped through the expression without encountering undefined symbols or functions // and the functions were supplied the correct number of arguments. Hurray! return new VerifiedExpression(tokens); } public static bool VerifySymbol(string symbol) { // Cannot contain certain reserverd characters. Or whitespace. foreach (char c in symbol) { if (CalcToken.IsOperatorChar(c) || char.IsWhiteSpace(c)) { return false; } switch (c) { case '(': case ')': case '.': case ',': return false; } } // It also can't be empty or start with a digit. if (symbol.Length > 0 && !char.IsDigit(symbol[0])) return true; return false; } } class FunctionMetadata { public int ArgCounter; readonly CalcFunction func; readonly CalcFuncToken token; public int RequiredArgs { get { return func.ArgCount; } } public string FuncSymbol { get { return token.Value; } } public int OriginIndex { get { return token.OriginIndex; } } public bool CountsAreEqual { get { return ArgCounter == func.ArgCount; } } public FunctionMetadata(CalcFunction func, CalcFuncToken token) { ArgCounter = 1; this.func = func; this.token = token; } } }
bsd-2-clause
ibrarahmad/cstore
src/Writers/DictWriter.cpp
6188
/* Copyright (c) 2005, Regents of Massachusetts Institute of Technology, * Brandeis University, Brown University, and University of Massachusetts * Boston. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Massachusetts Institute of Technology, * Brandeis University, Brown University, or University of * Massachusetts Boston nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Writes Dict Blocks // Problems: migfer@mit.edu #include "DictWriter.h" DictWriter::DictWriter(Operator* blockSrc_, int colIndex_, unsigned int bfrSizeBits_, unsigned int fieldSize_) : Writer(blockSrc_, colIndex_) { fieldSize=fieldSize_; escapeInt=0xFFFFFFFF>>(32-fieldSize); numDistinctValues=0; blockWriter=new BasicBlockWriter(blockSrc_, colIndex_); currBlock=(BasicBlock*) blockWriter->getNextValBlock(0); if (currBlock!=NULL) { outBlock=new BitBlock(currBlock->isValueSorted()); bitWriter=new BitWriter(bfrSizeBits_); dictBlock=new BasicBlock(true, true, true); buffer=bitWriter->getBuffer(); startPosPtr=(unsigned int*) (buffer+sizeof(int)); numValsPtr=(unsigned int*) (buffer+2*sizeof(int)); } else { outBlock=NULL; bitWriter=NULL; buffer=NULL; startPosPtr=NULL; numValsPtr=NULL; } init=true; readyToOutDict=false; bfrSizeBits=bfrSizeBits_; Log::writeToLog("DictWriter", 0, "Finished constructor"); } DictWriter::~DictWriter() { if (outBlock!=NULL) delete outBlock; if (dictBlock!=NULL) delete dictBlock; if (blockWriter!=NULL) delete blockWriter; if (bitWriter!=NULL) delete bitWriter; } void DictWriter::resetWriter() { Log::writeToLog("DictWriter", 0, "Reset writer"); bitWriter->clearBuffer(); bitWriter->skipBits(8*3*sizeof(int)); *((unsigned int*) (buffer))=fieldSize; startPosPtr=(unsigned int*) (buffer+sizeof(int)); numValsPtr=(unsigned int*) (buffer+2*sizeof(int)); } // Gets the next value block from the operator Block* DictWriter::getNextValBlock(int colIndex_) { if (colIndex_==0) { return getEntries(); } else if (colIndex_==1) { return getTable(); } else return NULL; } Block* DictWriter::getTable() { if (!readyToOutDict) throw new UnexpectedException("Error, you have not asked me for the entries yet"); if (entryValueMap.size()==0) { Log::writeToLog("DictWriter", 0, "entryValueMap empty returning NULL"); return NULL; } unsigned int pos=entryValueMap.begin()->first; unsigned int val=entryValueMap.begin()->second; entryValueMap.erase(entryValueMap.begin()); dictBlock->setValue(val,pos+1); Log::writeToLog("DictWriter", 0, "Returning table block: val", val); Log::writeToLog("DictWriter", 0, "Returning table block: entry", pos); return dictBlock; } Block* DictWriter::getEntries() { if (currBlock==NULL) { readyToOutDict=true; Log::writeToLog("DictWriter", 1, "Data source dry returning NULL"); return NULL; } resetWriter(); bool writeSuccess=true; while (writeSuccess) { ValPos* pair=currBlock->getStartPair(); //assume int type for now ... fix later assert(pair->type == ValPos::INTTYPE); if (init) { *startPosPtr=pair->position; init=false; } unsigned int entry; if (valueEntryMap.count(*(int*)pair->value)==0) { if (numDistinctValues>escapeInt) { Log::writeToLog("DictWriter", 5, "Error: number of distinctValues larger than possible to encode in this fieldSize", fieldSize); throw new CodingException("Error: number of distinctValues larger than possible to encode in this fieldSize"); } valueEntryMap[*(int*)pair->value]=numDistinctValues; entryValueMap[numDistinctValues]=*(int*)pair->value; entry=numDistinctValues; Log::writeToLog("DictWriter", 1, "No entry for value", *(int*)pair->value); Log::writeToLog("DictWriter", 1, "Created entry", numDistinctValues); numDistinctValues++; } else { entry=valueEntryMap[*(int*)pair->value]; Log::writeToLog("DictWriter", 0, "Writing entry for value", *(int*)pair->value); } writeSuccess=bitWriter->writeBits(entry, fieldSize); if (writeSuccess) { *numValsPtr+=1; Log::writeToLog("DictWriter", 0, "Writing successfully entry", entry); currBlock=(BasicBlock*) blockWriter->getNextValBlock(0); Log::writeToLog("DictWriter", 0, "Got next block"); if (currBlock==NULL) { Log::writeToLog("DictWriter", 1, "Data source dry returning current buffer (in block)"); outBlock->setBuffer(buffer, bfrSizeBits); return outBlock; } } } Log::writeToLog("DictWriter", 0, "Filled current buffer, returning it (in block)"); outBlock->setBuffer(buffer, bfrSizeBits); init=true; return outBlock; } // Gets the next position block (bitstring of positions) from the operator PosBlock* DictWriter::getNextPosBlock(int colIndex_) { return NULL; }
bsd-2-clause
asmodehn/sdlut
Core/include/Core/NewLogger.hh
1809
#ifndef NEWLOGGER_HH #define NEWLOGGER_HH #include "Core/Logging/logstream.hh" //to be able to access cnull #include "Core/Logging/nullstream.hh" namespace Core { /*** * * \class NewLogger * \brief NewLogger manages the Logging outputs for the application. * */ class NewLogger : public logstream { public: NewLogger(); ~NewLogger(); ///by default outputs to std::clog //enable more Sinks bool enableFileLog(const std::string & filename); //enableSysLog(); //enableWinLog(); void disableFileLog(); //disableSysLog(); //disableWinLog(); //accessors to logstreams ( to set separatelevels for example ) logstream& getFileLog(); //logstream& getSysLog(); //logstream& getWinLog(); template<typename M> NewLogger& operator << (const M & msg); //to enable manipulators on Logger NewLogger& operator << (std::ostream& (*manip)(std::ostream&)); NewLogger& operator << (std::ios_base& (*manip)(std::ios_base&)); NewLogger& operator << (NewLogger& (*manip)(NewLogger&));//to enable specific manipulators on Logger friend NewLogger& operator<<(NewLogger &log, loglevel::Level lvl); void setFilelogLevel(loglevel::Level lvl); protected : //list of logstream. Each logstream has one output and only one logstream* ptm_filelogstream; //logstream ptm_syslogstream; //logstream ptm_winlogstream; private : //list of logstreambuf. Each logstreambuf provide a different ouput to logstream logstreambuf* pvm_filelsb; //logstreambuf pvm_syslsb; //logstreambuf pvm_winlsb; }; template<typename M> NewLogger& NewLogger::operator<< ( const M & msg) { /* if (_consoleLog) std::clog << msg; if (_fileLog) _ofstr << msg; */ return *this; } } #endif
bsd-2-clause
cloudtools/awacs
awacs/datasync.py
2229
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWSDataSync" prefix = "datasync" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CancelTaskExecution = Action("CancelTaskExecution") CreateAgent = Action("CreateAgent") CreateLocationEfs = Action("CreateLocationEfs") CreateLocationFsxWindows = Action("CreateLocationFsxWindows") CreateLocationNfs = Action("CreateLocationNfs") CreateLocationObjectStorage = Action("CreateLocationObjectStorage") CreateLocationS3 = Action("CreateLocationS3") CreateLocationSmb = Action("CreateLocationSmb") CreateTask = Action("CreateTask") DeleteAgent = Action("DeleteAgent") DeleteLocation = Action("DeleteLocation") DeleteTask = Action("DeleteTask") DescribeAgent = Action("DescribeAgent") DescribeLocationEfs = Action("DescribeLocationEfs") DescribeLocationFsxWindows = Action("DescribeLocationFsxWindows") DescribeLocationNfs = Action("DescribeLocationNfs") DescribeLocationObjectStorage = Action("DescribeLocationObjectStorage") DescribeLocationS3 = Action("DescribeLocationS3") DescribeLocationSmb = Action("DescribeLocationSmb") DescribeTask = Action("DescribeTask") DescribeTaskExecution = Action("DescribeTaskExecution") ListAgents = Action("ListAgents") ListLocations = Action("ListLocations") ListTagsForResource = Action("ListTagsForResource") ListTaskExecutions = Action("ListTaskExecutions") ListTasks = Action("ListTasks") StartTaskExecution = Action("StartTaskExecution") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateAgent = Action("UpdateAgent") UpdateLocationNfs = Action("UpdateLocationNfs") UpdateLocationObjectStorage = Action("UpdateLocationObjectStorage") UpdateLocationSmb = Action("UpdateLocationSmb") UpdateTask = Action("UpdateTask") UpdateTaskExecution = Action("UpdateTaskExecution")
bsd-2-clause
gzorin/RSXGL
extsrc/mesa/src/glsl/lower_output_reads.cpp
4597
/* * Copyright © 2012 Vincent Lejeune * Copyright © 2012 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "ir.h" #include "program/hash_table.h" /** * \file lower_output_reads.cpp * * In GLSL, shader output variables (such as varyings) can be both read and * written. However, on some hardware, reading an output register causes * trouble. * * This pass creates temporary shadow copies of every (used) shader output, * and replaces all accesses to use those instead. It also adds code to the * main() function to copy the final values to the actual shader outputs. */ class output_read_remover : public ir_hierarchical_visitor { protected: /** * A hash table mapping from the original ir_variable shader outputs * (ir_var_out mode) to the new temporaries to be used instead. */ hash_table *replacements; void *mem_ctx; public: output_read_remover(); ~output_read_remover(); virtual ir_visitor_status visit(class ir_dereference_variable *); virtual ir_visitor_status visit_leave(class ir_return *); virtual ir_visitor_status visit_leave(class ir_function_signature *); }; output_read_remover::output_read_remover() { mem_ctx = ralloc_context(NULL); replacements = hash_table_ctor(0, hash_table_pointer_hash, hash_table_pointer_compare); } output_read_remover::~output_read_remover() { hash_table_dtor(replacements); ralloc_free(mem_ctx); } ir_visitor_status output_read_remover::visit(ir_dereference_variable *ir) { if (ir->var->mode != ir_var_out) return visit_continue; ir_variable *temp = (ir_variable *) hash_table_find(replacements, ir->var); /* If we don't have an existing temporary, create one. */ if (temp == NULL) { void *var_ctx = ralloc_parent(ir->var); temp = new(var_ctx) ir_variable(ir->var->type, ir->var->name, ir_var_temporary); hash_table_insert(replacements, temp, ir->var); } /* Update the dereference to use the temporary */ ir->var = temp; return visit_continue; } /** * Create an assignment to copy a temporary value back to the actual output. */ static ir_assignment * copy(void *ctx, ir_variable *output, ir_variable *temp) { ir_dereference_variable *lhs = new(ctx) ir_dereference_variable(output); ir_dereference_variable *rhs = new(ctx) ir_dereference_variable(temp); return new(ctx) ir_assignment(lhs, rhs); } /** Insert a copy-back assignment before a "return" statement */ static void emit_return_copy(const void *key, void *data, void *closure) { ir_return *ir = (ir_return *) closure; ir->insert_before(copy(ir, (ir_variable *) key, (ir_variable *) data)); } /** Insert a copy-back assignment at the end of the main() function */ static void emit_main_copy(const void *key, void *data, void *closure) { ir_function_signature *sig = (ir_function_signature *) closure; sig->body.push_tail(copy(sig, (ir_variable *) key, (ir_variable *) data)); } ir_visitor_status output_read_remover::visit_leave(ir_return *ir) { hash_table_call_foreach(replacements, emit_return_copy, ir); return visit_continue; } ir_visitor_status output_read_remover::visit_leave(ir_function_signature *sig) { if (strcmp(sig->function_name(), "main") != 0) return visit_continue; hash_table_call_foreach(replacements, emit_main_copy, sig); return visit_continue; } void lower_output_reads(exec_list *instructions) { output_read_remover v; visit_list_elements(&v, instructions); }
bsd-2-clause
rchekaluk/check_docker
check_docker.go
7713
package main import ( "encoding/json" "errors" "flag" "io/ioutil" "net/http" "strconv" "strings" "sync" "github.com/newrelic/go_nagios" ) const ( API_VERSION = "v1.10" ) // A struct representing CLI opts that will be passed at runtime type CliOpts struct { BaseUrl string CritDataSpace int WarnDataSpace int CritMetaSpace int WarnMetaSpace int ImageId string GhostsStatus int } // Information describing the status of a Docker host type DockerInfo struct { Containers float64 Driver string DriverStatus [][]string DataSpaceUsed float64 DataSpaceTotal float64 MetaSpaceUsed float64 MetaSpaceTotal float64 ImageIsRunning bool GhostCount int } // Used internally to build lists of checks to run type checkArgs struct { tag string value string healthy bool appendErrorMessage string statusVal nagios.NagiosStatusVal } // Describes one container type Container struct { Image string Status string } // An interface to request things from the Web type HttpResponseFetcher interface { Fetch(url string) ([]byte, error) } type Fetcher struct{} // Properly format a Float64 as a string func float64String(num float64) string { return strconv.FormatFloat(num, 'f', 0, 64) } // Return a float from a Docker info string for megabytes func megabytesFloat64(value string) (float64, error) { numberStr := strings.Fields(value)[0] number, err := strconv.ParseFloat(numberStr, 64) if err != nil { return 0.00, err } return number, nil } // Look through a list of driveStatus slices and find the one that matches func findDriverStatus(key string, driverStatus [][]string) string { for _, entry := range driverStatus { if entry[0] == key { return entry[1] } } return "" } // Connect to a Docker URL and return the contents as a []byte func (Fetcher) Fetch(url string) ([]byte, error) { response, err := http.Get(url) if err != nil { return nil, err } defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err } return contents, nil } // Parses JSON and populates a DockerInfo func populateInfo(contents []byte, info *DockerInfo) error { err := json.Unmarshal(contents, info) if err != nil { return err } fields := map[string]*float64{ "Data Space Used": &info.DataSpaceUsed, "Data Space Total": &info.DataSpaceTotal, "Metadata Space Used": &info.MetaSpaceUsed, "Metadata Space Total": &info.MetaSpaceTotal, } for key, val := range fields { entry := findDriverStatus(key, info.DriverStatus) if entry != "" { *val, err = megabytesFloat64(findDriverStatus(key, info.DriverStatus)) if err != nil { return errors.New("Error parsing response from API! " + err.Error()) } } } return nil } // checkRunningContainers looks to see if a container is currently running from a given // Image Id. func checkRunningContainers(contents []byte, opts *CliOpts) (bool, int, error) { var containers []Container err := json.Unmarshal(contents, &containers) if err != nil { return false, 0, err } isRunning := false ghostCount := 0 for _, container := range containers { if strings.HasPrefix(container.Image, opts.ImageId+":") && strings.HasPrefix(container.Status, "Up") { isRunning = true } else if strings.Contains(container.Status, "Ghost") { ghostCount += 1 } } return isRunning, ghostCount, nil } // fetchInfo retrieves JSON from a Docker host and fills in a DockerInfo func fetchInfo(fetcher HttpResponseFetcher, opts CliOpts, info *DockerInfo) error { var wg sync.WaitGroup wg.Add(2) var err, err2 error var imageFound bool var ghostCount int // `info` is handled by this goroutine but not the other go func() { var infoResult []byte infoResult, err = fetcher.Fetch(opts.BaseUrl + "/" + API_VERSION + "/info") if err == nil { err = populateInfo(infoResult, info) } wg.Done() }() go func() { var containersResult []byte containersResult, err2 = fetcher.Fetch(opts.BaseUrl + "/" + API_VERSION + "/containers/json") if err2 == nil { imageFound, ghostCount, err2 = checkRunningContainers(containersResult, &opts) } wg.Done() }() wg.Wait() if err != nil { return err } if err2 != nil { return err2 } info.ImageIsRunning = imageFound info.GhostCount = ghostCount return nil } // defineChecks returns a list of checks we should run based on CLI flags func defineChecks(info *DockerInfo, opts *CliOpts) []checkArgs { checks := make([]checkArgs, 0) if info.Driver == "devicemapper" { checks = append(checks, checkArgs{"Meta Space Used", float64String(info.MetaSpaceUsed / info.MetaSpaceTotal * 100), info.MetaSpaceUsed/info.MetaSpaceTotal*100 < float64(opts.CritMetaSpace), "%", nagios.NAGIOS_CRITICAL, }, checkArgs{"Data Space Used", float64String(info.DataSpaceUsed / info.DataSpaceTotal * 100), info.DataSpaceUsed/info.DataSpaceTotal*100 < float64(opts.CritDataSpace), "%", nagios.NAGIOS_CRITICAL, }, checkArgs{"Meta Space Used", float64String(info.MetaSpaceUsed / info.MetaSpaceTotal * 100), info.MetaSpaceUsed/info.MetaSpaceTotal*100 < float64(opts.WarnMetaSpace), "%", nagios.NAGIOS_WARNING, }, checkArgs{"Data Space Used", float64String(info.DataSpaceUsed / info.DataSpaceTotal * 100), info.DataSpaceUsed/info.DataSpaceTotal*100 < float64(opts.WarnDataSpace), "%", nagios.NAGIOS_WARNING, }, checkArgs{"Ghost Containers", strconv.Itoa(info.GhostCount), info.GhostCount == 0, "", nagios.NagiosStatusVal(opts.GhostsStatus), }, ) } if opts.ImageId != "" { checks = append(checks, checkArgs{"Running Image", opts.ImageId, info.ImageIsRunning, " is not running!", nagios.NAGIOS_CRITICAL, }, ) } return checks } // Runs a set of checkes and returns an array of statuses func mapAlertStatuses(info *DockerInfo, opts *CliOpts) []*nagios.NagiosStatus { var statuses []*nagios.NagiosStatus var check = func(args checkArgs) *nagios.NagiosStatus { if !args.healthy { return &nagios.NagiosStatus{args.tag + ": " + args.value + args.appendErrorMessage, args.statusVal} } return nil } checks := defineChecks(info, opts) for _, entry := range checks { result := check(entry) if result != nil { statuses = append(statuses, check(entry)) } } return statuses } // parseCommandLine parses the flags passed on the CLI func parseCommandLine() *CliOpts { var opts CliOpts flag.StringVar(&opts.BaseUrl, "base-url", "", "The Base URL for the Docker server") flag.IntVar(&opts.WarnMetaSpace, "warn-meta-space", 100, "Warning threshold for Metadata Space") flag.IntVar(&opts.WarnDataSpace, "warn-data-space", 100, "Warning threshold for Data Space") flag.IntVar(&opts.CritMetaSpace, "crit-meta-space", 100, "Critical threshold for Metadata Space") flag.IntVar(&opts.CritDataSpace, "crit-data-space", 100, "Critical threshold for Data Space") flag.StringVar(&opts.ImageId, "image-id", "", "An image ID that must be running on the Docker server") flag.IntVar(&opts.GhostsStatus, "ghosts-status", 1, "If ghosts are present, treat as this status") flag.Parse() return &opts } func main() { opts := parseCommandLine() if opts.BaseUrl == "" { nagios.Critical(errors.New("-base-url must be supplied")) } var fetcher Fetcher var info DockerInfo err := fetchInfo(fetcher, *opts, &info) if err != nil { nagios.Critical(err) } statuses := mapAlertStatuses(&info, opts) baseStatus := nagios.NagiosStatus{float64String(info.Containers) + " containers", 0} baseStatus.Aggregate(statuses) nagios.ExitWithStatus(&baseStatus) }
bsd-2-clause
dgg/NMoneys.Web
src/Web/Properties/AssemblyInfo.cs
1358
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NMoneys.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NMoneys.Web")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("92076e3e-aff4-4068-9d9c-cb375ac5a854")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
bsd-2-clause
carlosrafaelgn/FPlayAndroid
jni/SimpleVisualizerJni.cpp
15968
// // FPlayAndroid is distributed under the FreeBSD License // // Copyright (c) 2013-2014, Carlos Rafael Gimenes das Neves // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // https://github.com/carlosrafaelgn/FPlayAndroid // #include <jni.h> #include <android/native_window_jni.h> #include <android/native_window.h> #include <android/log.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> //http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html //http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html #define MAX(A,B) (((A) > (B)) ? (A) : (B)) #include "Common.h" #include "OpenGLVisualizerJni.h" static float invBarW; static int32_t barW, barH, barBins, barWidthInPixels, recreateVoice, lerp; static uint16_t bgColor; static uint16_t* voice, *alignedVoice; void JNICALL setLerp(JNIEnv* env, jclass clazz, jboolean jlerp) { lerp = (jlerp ? 1 : 0); } void JNICALL init(JNIEnv* env, jclass clazz, int32_t jbgColor) { voice = 0; recreateVoice = 0; commonColorIndex = 0; commonColorIndexApplied = 0; const uint32_t r = ((jbgColor >> 16) & 0xff) >> 3; const uint32_t g = ((jbgColor >> 8) & 0xff) >> 2; const uint32_t b = (jbgColor & 0xff) >> 3; bgColor = (uint16_t)((r << 11) | (g << 5) | b); commonUpdateMultiplier(env, clazz, 0, 0); } void JNICALL terminate(JNIEnv* env, jclass clazz) { if (voice) { delete voice; voice = 0; } } int32_t JNICALL prepareSurface(JNIEnv* env, jclass clazz, jobject surface) { ANativeWindow* wnd = ANativeWindow_fromSurface(env, surface); if (!wnd) return -1; int32_t ret = -2; int32_t w = ANativeWindow_getWidth(wnd), h = ANativeWindow_getHeight(wnd); if (w > 0 && h > 0) { barW = w >> 8; barH = h & (~1); //make the height always an even number if (barW < 1) barW = 1; const int32_t size = barW << 8; invBarW = 1.0f / (float)barW; barBins = ((size > w) ? ((w < 256) ? (w & ~7) : 256) : 256); barWidthInPixels = barBins * barW; recreateVoice = 1; ret = ANativeWindow_setBuffersGeometry(wnd, barWidthInPixels, barH, WINDOW_FORMAT_RGB_565); } if (ret < 0) { invBarW = 1; barBins = 0; barWidthInPixels = 0; recreateVoice = 0; } ANativeWindow_release(wnd); return ret; } void JNICALL process(JNIEnv* env, jclass clazz, jbyteArray jwaveform, jobject surface, int32_t opt) { ANativeWindow* wnd = ANativeWindow_fromSurface(env, surface); if (!wnd) return; ANativeWindow_Buffer inf; if (ANativeWindow_lock(wnd, &inf, 0) < 0) { ANativeWindow_release(wnd); return; } if (inf.width != barWidthInPixels || inf.height != barH) { ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); return; } inf.stride <<= 1; //convert from pixels to uint16_t //fft format: //index 0 1 2 3 4 5 ..... n-2 n-1 // Rdc Rnyq R1 I1 R2 I2 R(n-1)/2 I(n-1)/2 uint8_t* fftI; if (!(opt & IGNORE_INPUT)) { uint8_t* const waveform = (uint8_t*)env->GetPrimitiveArrayCritical(jwaveform, 0); if (!waveform) { ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); return; } fftI = _fftI; doFft(waveform, fftI, DATA_FFT); //*** we are not drawing/analyzing the last bin (Nyquist) ;) *** fftI[1] = 0; env->ReleasePrimitiveArrayCritical(jwaveform, waveform, JNI_ABORT); } else { fftI = 0; } float* const fft = _fft; const float* const multiplier = _multiplier; float* const previousM = _previousM; float coefNew = COEF_SPEED_DEF * (float)commonUptimeDeltaMillis(&commonLastTime); if (coefNew > 1.0f) coefNew = 1.0f; const float coefOld = 1.0f - coefNew; float previous = 0; for (int32_t i = 0; i < barBins; i++) { float m; if (fftI) { //fftI[i] stores values from 0 to 255 (inclusive) const int32_t re = (uint32_t)fftI[i << 1]; const int32_t im = (uint32_t)fftI[(i << 1) + 1]; const int32_t amplSq = (re * re) + (im * im); m = ((amplSq < 8) ? 0.0f : (multiplier[i] * sqrtf((float)(amplSq)))); previousM[i] = m; } else { m = previousM[i]; } const float old = fft[i]; if (m < old) m = (coefNew * m) + (coefOld * old); fft[i] = m; if (barW == 1 || !lerp) { //m goes from 0 to 32768+ (inclusive) int32_t v = (int32_t)m; if (v > 32768) v = 32768; const uint16_t color = COLORS[commonColorIndex + (v >> 7)]; v = ((v * barH) >> 15); int32_t v2 = v; v = (barH - v) >> 1; v2 += v; uint16_t* currentBar = (uint16_t*)inf.bits; inf.bits = (void*)((uint16_t*)inf.bits + barW); int32_t y = 0; switch (barW) { case 1: for (; y < v; y++) { *currentBar = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { *currentBar = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { *currentBar = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } break; case 2: for (; y < v; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { *currentBar = color; currentBar[1] = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } break; case 3: for (; y < v; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar[2] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { *currentBar = color; currentBar[1] = color; currentBar[2] = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar[2] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } break; case 4: for (; y < v; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar[2] = bgColor; currentBar[3] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { *currentBar = color; currentBar[1] = color; currentBar[2] = color; currentBar[3] = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { *currentBar = bgColor; currentBar[1] = bgColor; currentBar[2] = bgColor; currentBar[3] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } break; default: for (; y < v; y++) { for (int32_t b = barW - 1; b >= 0; b--) currentBar[b] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { for (int32_t b = barW - 1; b >= 0; b--) currentBar[b] = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { for (int32_t b = barW - 1; b >= 0; b--) currentBar[b] = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } break; } } else { //m goes from 0 to 32768+ (inclusive) const float delta = (int32_t)(m - previous) * invBarW; for (int32_t i = 0; i < barW; i++) { previous += delta; int32_t v = (int32_t)previous; if (v < 0) v = 0; else if (v > 32768) v = 32768; const uint16_t color = COLORS[commonColorIndex + (v >> 7)]; v = ((v * barH) >> 15); int32_t v2 = v; v = (barH - v) >> 1; v2 += v; uint16_t* currentBar = (uint16_t*)inf.bits; inf.bits = (void*)((uint16_t*)inf.bits + 1); int32_t y = 0; for (; y < v; y++) { *currentBar = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < v2; y++) { *currentBar = color; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } for (; y < barH; y++) { *currentBar = bgColor; currentBar = (uint16_t*)((uint8_t*)currentBar + inf.stride); } } } } ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); } void JNICALL processVoice(JNIEnv* env, jclass clazz, jbyteArray jwaveform, jobject surface, int32_t opt) { ANativeWindow* wnd = ANativeWindow_fromSurface(env, surface); if (!wnd) return; ANativeWindow_Buffer inf; if (ANativeWindow_lock(wnd, &inf, 0) < 0) { ANativeWindow_release(wnd); return; } if (inf.width != barWidthInPixels || inf.height != barH) { ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); return; } if (recreateVoice) { if (voice) delete voice; voice = (uint16_t*)(new uint8_t[((inf.stride * inf.height) << 1) + 16]); uint8_t* al = (uint8_t*)voice; while ((((size_t)al) & 15)) al++; alignedVoice = (uint16_t*)al; recreateVoice = 0; } if (!voice) { ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); return; } inf.stride <<= 1; //convert from pixels to uint16_t int32_t v = inf.stride * (inf.height - 1); memcpy(alignedVoice, (uint8_t*)alignedVoice + inf.stride, v); uint16_t* currentBar = (uint16_t*)((uint8_t*)alignedVoice + v); float* const fft = _fft; const float* const multiplier = _multiplier; float* const previousM = _previousM; //fft format: //index 0 1 2 3 4 5 ..... n-2 n-1 // Rdc Rnyq R1 I1 R2 I2 R(n-1)/2 I(n-1)/2 uint8_t* fftI; if (!(opt & IGNORE_INPUT)) { uint8_t* const waveform = (uint8_t*)env->GetPrimitiveArrayCritical(jwaveform, 0); if (!waveform) { ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); return; } fftI = _fftI; doFft(waveform, fftI, DATA_FFT); //*** we are not drawing/analyzing the last bin (Nyquist) ;) *** fftI[1] = 0; env->ReleasePrimitiveArrayCritical(jwaveform, waveform, JNI_ABORT); } else { fftI = 0; } float previous = 0; for (int32_t i = 0; i < barBins; i++) { //fftI[i] stores values from 0 to 255 (inclusive) float m; if (fftI) { const int32_t re = (uint32_t)fftI[i << 1]; const int32_t im = (uint32_t)fftI[(i << 1) + 1]; const int32_t amplSq = (re * re) + (im * im); m = ((amplSq < 8) ? 0.0f : (multiplier[i] * sqrtf((float)(amplSq)))); previousM[i] = m; } else { m = previousM[i]; } if (barW == 1) { //m goes from 0 to 256+ (inclusive) const int32_t v = (int32_t)m; *currentBar = COLORS[commonColorIndex + ((v >= 256) ? 256 : v)]; currentBar++; } else { const float delta = (m - previous) * invBarW; for (int32_t i = 0; i < barW; i++) { previous += delta; const int32_t v = (int32_t)previous; *currentBar = COLORS[commonColorIndex + ((v >= 256) ? 256 : v)]; currentBar++; } } } memcpy(inf.bits, alignedVoice, inf.stride * inf.height); ANativeWindow_unlockAndPost(wnd); ANativeWindow_release(wnd); } #ifdef FPLAY_ARM void checkNeonMode() { #ifdef FPLAY_64_BITS //can we safely assume this??? neonMode = 1; #else //based on //http://code.google.com/p/webrtc/source/browse/trunk/src/system_wrappers/source/android/cpu-features.c?r=2195 //http://code.google.com/p/webrtc/source/browse/trunk/src/system_wrappers/source/android/cpu-features.h?r=2195 neonMode = 0; char cpuinfo[4096]; int32_t cpuinfo_len = -1; int32_t fd = open("/proc/cpuinfo", O_RDONLY); if (fd >= 0) { do { cpuinfo_len = read(fd, cpuinfo, 4096); } while (cpuinfo_len < 0 && errno == EINTR); close(fd); if (cpuinfo_len > 0) { cpuinfo[cpuinfo_len] = 0; //look for the "\nFeatures: " line for (int32_t i = cpuinfo_len - 9; i >= 0; i--) { if (memcmp(cpuinfo + i, "\nFeatures", 9) == 0) { i += 9; while (i < cpuinfo_len && (cpuinfo[i] == ' ' || cpuinfo[i] == '\t' || cpuinfo[i] == ':')) i++; cpuinfo_len -= 5; //now look for the " neon" feature while (i <= cpuinfo_len && cpuinfo[i] != '\n') { if (memcmp(cpuinfo + i, " neon", 5) == 0 || memcmp(cpuinfo + i, "\tneon", 5) == 0) { neonMode = 1; break; } i++; } break; } } } } #endif } #endif extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { #ifdef FPLAY_ARM checkNeonMode(); #endif voice = 0; recreateVoice = 0; glResetState(); commonTime = 0; commonTimeLimit = 0xffffffff; commonColorIndex = 0; commonColorIndexApplied = 0; commonCoefNew = 0.0f; rootMeanSquare = 0.0f; vuMeter = 0.0f; vuMeterUnfiltered = 0.f; vuMeterFilterState[0] = 0.0f; vuMeterFilterState[1] = 0.0f; vuMeterFilterState[2] = 0.0f; vuMeterFilterState[3] = 0.0f; beatCounter = 0; beatState = BEAT_STATE_VALLEY; beatPeakOrValley = 0; beatThreshold = BEAT_MIN_RISE_THRESHOLD; beatDeltaMillis = 0; beatSilenceDeltaMillis = 0; beatSpeedBPM = 0; beatFilteredInput = 0; JNINativeMethod methodTable[] = { {"commonSetSpeed", "(I)V", (void*)commonSetSpeed}, {"commonSetColorIndex", "(I)V", (void*)commonSetColorIndex}, {"commonUpdateMultiplier", "(ZZ)V", (void*)commonUpdateMultiplier}, {"commonProcess", "([BI)I", (void*)commonProcess}, {"setLerp", "(Z)V", (void*)setLerp}, {"init", "(I)V", (void*)init}, {"terminate", "()V", (void*)terminate}, {"prepareSurface", "(Landroid/view/Surface;)I", (void*)prepareSurface}, {"process", "([BLandroid/view/Surface;I)V", (void*)process}, {"processVoice", "([BLandroid/view/Surface;I)V", (void*)processVoice}, {"glGetOESTexture", "()I", (void*)glGetOESTexture}, {"glOnSurfaceCreated", "(IIIIII)I", (void*)glOnSurfaceCreated}, {"glOnSurfaceChanged", "(IIIIII)V", (void*)glOnSurfaceChanged}, {"glLoadBitmapFromJava", "(Landroid/graphics/Bitmap;)I", (void*)glLoadBitmapFromJava}, {"glDrawFrame", "()V", (void*)glDrawFrame}, {"glOnSensorReset", "()V", (void*)glOnSensorReset}, {"glOnSensorData", "(JI[F)V", (void*)glOnSensorData}, {"glSetImmersiveCfg", "(II)V", (void*)glSetImmersiveCfg}, {"glReleaseView", "()V", (void*)glReleaseView} }; JNIEnv* env; if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) return -1; jclass clazz = env->FindClass("br/com/carlosrafaelgn/fplay/visualizer/SimpleVisualizerJni"); if (!clazz) return -1; env->RegisterNatives(clazz, methodTable, sizeof(methodTable) / sizeof(methodTable[0])); return JNI_VERSION_1_6; } JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { if (glSoundParticle) { delete glSoundParticle; glSoundParticle = 0; } } }
bsd-2-clause
AlexeySa/rspamd
lualib/lua_util.lua
5072
--[[ Copyright (c) 2017, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- local exports = {} local lpeg = require 'lpeg' local split_grammar = {} local function rspamd_str_split(s, sep) local gr = split_grammar[sep] if not gr then local _sep = lpeg.P(sep) local elem = lpeg.C((1 - _sep)^0) local p = lpeg.Ct(elem * (_sep * elem)^0) gr = p split_grammar[sep] = gr end return gr:match(s) end exports.rspamd_str_split = rspamd_str_split local space = lpeg.S' \t\n\v\f\r' local nospace = 1 - space local ptrim = space^0 * lpeg.C((space^0 * nospace^1)^0) local match = lpeg.match exports.rspamd_str_trim = function(s) return match(ptrim, s) end -- Robert Jay Gould http://lua-users.org/wiki/SimpleRound exports.round = function(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult) / mult end exports.template = function(tmpl, keys) local var_lit = lpeg.P { lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + "_" } local var = lpeg.P { (lpeg.P("$") / "") * ((var_lit^1) / keys) } local var_braced = lpeg.P { (lpeg.P("${") / "") * ((var_lit^1) / keys) * (lpeg.P("}") / "") } local template_grammar = lpeg.Cs((var + var_braced + 1)^0) return lpeg.match(template_grammar, tmpl) end exports.remove_email_aliases = function(email_addr) local function check_gmail_user(addr) -- Remove all points local no_dots_user = string.gsub(addr.user, '%.', '') local cap, pluses = string.match(no_dots_user, '^([^%+][^%+]*)(%+.*)$') if cap then return cap, rspamd_str_split(pluses, '+'), nil elseif no_dots_user ~= addr.user then return no_dots_user,{},nil end return nil end local function check_address(addr) if addr.user then local cap, pluses = string.match(addr.user, '^([^%+][^%+]*)(%+.*)$') if cap then return cap, rspamd_str_split(pluses, '+'), nil end end return nil end local function set_addr(addr, new_user, new_domain) if new_user then addr.user = new_user end if new_domain then addr.domain = new_domain end if addr.domain then addr.addr = string.format('%s@%s', addr.user, addr.domain) else addr.addr = string.format('%s@', addr.user) end if addr.name and #addr.name > 0 then addr.raw = string.format('"%s" <%s>', addr.name, addr.addr) else addr.raw = string.format('<%s>', addr.addr) end end local function check_gmail(addr) local nu, tags, nd = check_gmail_user(addr) if nu then return nu, tags, nd end return nil end local function check_googlemail(addr) local nd = 'gmail.com' local nu, tags = check_gmail_user(addr) if nu then return nu, tags, nd end return nil, nil, nd end local specific_domains = { ['gmail.com'] = check_gmail, ['googlemail.com'] = check_googlemail, } if email_addr then if email_addr.domain and specific_domains[email_addr.domain] then local nu, tags, nd = specific_domains[email_addr.domain](email_addr) if nu or nd then set_addr(email_addr, nu, nd) return nu, tags end else local nu, tags, nd = check_address(email_addr) if nu or nd then set_addr(email_addr, nu, nd) return nu, tags end end return nil end end exports.is_rspamc_or_controller = function(task) local ua = task:get_request_header('User-Agent') or '' local pwd = task:get_request_header('Password') local is_rspamc = false if tostring(ua) == 'rspamc' or pwd then is_rspamc = true end return is_rspamc end local unpack_function = table.unpack or unpack exports.unpack = function(t) return unpack_function(t) end -- Sorted iteration: -- for k,v in spairs(t) do ... end -- -- or with custom comparison: -- for k, v in spairs(t, function(t, a, b) return t[a] < t[b] end) -- -- optional limit is also available (e.g. return top X elements) local function spairs(t, order, lim) -- collect the keys local keys = {} for k in pairs(t) do keys[#keys+1] = k end -- if order function given, sort by it by passing the table and keys a, b, -- otherwise just sort the keys if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end -- return the iterator function local i = 0 return function() i = i + 1 if not lim or i <= lim then if keys[i] then return keys[i], t[keys[i]] end end end end exports.spairs = spairs return exports
bsd-2-clause
jebreimo/Yson
src/Yson/JsonWriter/JsonWriterUtilities.hpp
627
//**************************************************************************** // Copyright © 2018 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2018-12-16. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #pragma once #include <string> #include <vector> namespace Yson { size_t findSplitPos(std::string_view s, size_t suggestedPos); size_t getCurrentLineWidth(const std::vector<char>& buffer, size_t maxLineWidth); }
bsd-2-clause
cuzzo/atom
Gruntfile.js
601
module.exports = function(grunt) { grunt.initConfig ({ sass: { dist: { files: [{ expand: true, cwd: "example/sass", src: "**/*.scss", dest: "example/css", ext: ".css" }] } }, atom: { options: { molecule_path: "example", molecular_rules_path: "example/molecular-rules.js", split_molecules_path: "example/sass/split-molecules.scss" } } }); grunt.loadNpmTasks("grunt-contrib-sass"); grunt.loadTasks("./tasks"); grunt.registerTask("dist", ["atom", "sass"]); };
bsd-2-clause
joschi/homebrew-cask
Casks/bibdesk.rb
838
cask "bibdesk" do version "1.7.9" sha256 "feb0a9556f1b748f5f78d17056c30ed0a1a4266bb02c59a35db939c1e2b349d3" url "https://downloads.sourceforge.net/bibdesk/BibDesk/BibDesk-#{version}/BibDesk-#{version}.dmg", verified: "downloads.sourceforge.net/bibdesk/" appcast "https://bibdesk.sourceforge.io/bibdesk.xml" name "BibDesk" desc "Edit and manage bibliographies" homepage "https://bibdesk.sourceforge.io/" auto_updates true app "BibDesk.app" zap trash: [ "~/Library/Application Support/BibDesk", "~/Library/Caches/com.apple.helpd/SDMHelpData/Other/English/HelpSDMIndexFile/edu.ucsd.cs.mmccrack.bibdesk.help*", "~/Library/Caches/edu.ucsd.cs.mmccrack.bibdesk", "~/Library/Cookies/edu.ucsd.cs.mmccrack.bibdesk.binarycookies", "~/Library/Preferences/edu.ucsd.cs.mmccrack.bibdesk.plist", ] end
bsd-2-clause
inviwo/inviwo
modules/fontrendering/src/util/fontutils.cpp
4775
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016-2021 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/fontrendering/util/fontutils.h> #include <modules/fontrendering/fontrenderingmodule.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/stringconversion.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/stdextensions.h> #include <inviwo/core/util/stringconversion.h> #include <algorithm> #include <tuple> #include <fmt/format.h> namespace inviwo { namespace font { std::vector<std::pair<std::string, std::string>> getAvailableFonts(const std::string& fontPath) { const std::vector<std::string> supportedExt = {"ttf", "otf", "cff", "pcf"}; const std::string path = (fontPath.empty() ? getDefaultFontPath() : fontPath); // scan for available fonts in the given path auto fonts = filesystem::getDirectoryContents(path, filesystem::ListMode::Files); // remove unsupported files util::erase_remove_if(fonts, [supportedExt](const std::string& str) { return !util::contains(supportedExt, filesystem::getFileExtension(str)); }); // sort file names case insensitive std::sort(fonts.begin(), fonts.end(), [](std::string a, std::string b) { return toLower(a) < toLower(b); }); // capitalize the first letter and each one following a space. // Also replace '-' with space for improved readability auto makeReadable = [](const std::string& str) { std::string dst(str); auto it = dst.begin(); *it = static_cast<char>(std::toupper(*it)); while (it != dst.end()) { if ((*it == '-') || (*it == ' ')) { *it = ' '; if ((it + 1) != dst.end()) { *(it + 1) = static_cast<char>(std::toupper(*(it + 1))); } } ++it; } return dst; }; std::vector<std::pair<std::string, std::string>> result; // create readable font names from file names and add full path to each file std::transform( fonts.begin(), fonts.end(), std::back_inserter(result), [path, makeReadable](const std::string& str) -> std::pair<std::string, std::string> { return {makeReadable(filesystem::getFileNameWithoutExtension(str)), path + '/' + str}; }); return result; } std::string getDefaultFontPath() { return InviwoApplication::getPtr()->getModuleByType<FontRenderingModule>()->getPath() + "/fonts"; } std::string getFont(FontType type, FullPath path) { const auto& [name, ext] = [type]() -> std::pair<std::string, std::string> { switch (type) { case FontType::Default: return {"OpenSans-Semibold", "ttf"}; case FontType::Bold: return {"OpenSans-Bold", "ttf"}; case FontType::Caption: return {"OpenSans-Semibold", "ttf"}; case FontType::Label: return {"OpenSans-Regular", "ttf"}; default: return {"OpenSans-Semibold", "ttf"}; } }(); if (path == FullPath::Yes) { return fmt::format("{}/{}.{}", getDefaultFontPath(), name, ext); } return name; } } // namespace font } // namespace inviwo
bsd-2-clause
aio-libs/aiozmq
tests/rpc_namespace_test.py
3047
import unittest import asyncio import aiozmq import aiozmq.rpc from aiozmq._test_util import find_unused_port class MyHandler(aiozmq.rpc.AttrHandler): @aiozmq.rpc.method async def func(self, arg): return arg + 1 class RootHandler(aiozmq.rpc.AttrHandler): ns = MyHandler() class RpcNamespaceTestsMixin: def close(self, service): service.close() self.loop.run_until_complete(service.wait_closed()) def make_rpc_pair(self): port = find_unused_port() async def create(): server = await aiozmq.rpc.serve_rpc( RootHandler(), bind="tcp://127.0.0.1:{}".format(port) ) client = await aiozmq.rpc.connect_rpc( connect="tcp://127.0.0.1:{}".format(port) ) return client, server self.client, self.server = self.loop.run_until_complete(create()) return self.client, self.server def test_ns_func(self): client, server = self.make_rpc_pair() async def communicate(): ret = await client.call.ns.func(1) self.assertEqual(2, ret) self.loop.run_until_complete(communicate()) def test_not_found(self): client, server = self.make_rpc_pair() async def communicate(): with self.assertRaisesRegex(aiozmq.rpc.NotFoundError, "ns1.func"): await client.call.ns1.func(1) self.loop.run_until_complete(communicate()) def test_bad_handler(self): client, server = self.make_rpc_pair() async def communicate(): with self.assertRaisesRegex(aiozmq.rpc.NotFoundError, "ns.func.foo"): await client.call.ns.func.foo(1) self.loop.run_until_complete(communicate()) def test_missing_namespace_method(self): client, server = self.make_rpc_pair() async def communicate(): with self.assertRaisesRegex(aiozmq.rpc.NotFoundError, "ns"): await client.call.ns(1) self.loop.run_until_complete(communicate()) class LoopRpcNamespaceTests(unittest.TestCase, RpcNamespaceTestsMixin): def setUp(self): self.loop = aiozmq.ZmqEventLoop() asyncio.set_event_loop(None) self.client = self.server = None def tearDown(self): if self.client is not None: self.close(self.client) if self.server is not None: self.close(self.server) self.loop.close() asyncio.set_event_loop(None) # zmq.Context.instance().term() class LooplessRpcNamespaceTests(unittest.TestCase, RpcNamespaceTestsMixin): def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) self.client = self.server = None def tearDown(self): if self.client is not None: self.close(self.client) if self.server is not None: self.close(self.server) self.loop.close() asyncio.set_event_loop(None) # zmq.Context.instance().term()
bsd-2-clause
stelfrich/imagej-ops
src/main/java/net/imagej/ops/special/hybrid/BinaryHybridCI1.java
3216
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 - 2016 Board of Regents of the University of * Wisconsin-Madison, University of Konstanz and Brian Northan. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.ops.special.hybrid; import net.imagej.ops.special.computer.BinaryComputerOp; import net.imagej.ops.special.inplace.BinaryInplace1Op; /** * A hybrid binary operation which can be used as a {@link BinaryComputerOp}, or * {@link BinaryInplace1Op}. * <p> * To populate a preallocated output object, call * {@link BinaryComputerOp#compute2}; to mutate the first input inplace, call * {@link BinaryInplace1Op#mutate1}. To do any of these things as appropriate, * call {@link #run(Object, Object, Object)}. * </p> * * @author Leon Yang * @param <I1> type of first input * @param <I2> type of second input * @param <O> type of output * @see BinaryHybridCF * @see BinaryHybridCFI */ public interface BinaryHybridCI1<I1, I2, O extends I1> extends BinaryComputerOp<I1, I2, O>, BinaryInplace1Op<I1, I2, O>, UnaryHybridCI<I1, O> { // -- UnaryInplaceOp methods -- @Override default void mutate(final O arg) { compute2(arg, in2(), arg); } // -- UnaryOp methods -- @Override default O run(final I1 input1, final I2 input2, final O output) { if (output == input1) { // run inplace mutate(output); return output; } // run as a computer compute2(input1, input2, output); return output; } // -- Runnable methods -- @Override default void run() { setOutput(run(in1(), in2(), out())); } // -- Threadable methods -- @Override default BinaryHybridCI1<I1, I2, O> getIndependentInstance() { // NB: We assume the op instance is thread-safe by default. // Individual implementations can override this assumption if they // have state (such as buffers) that cannot be shared across threads. return this; } }
bsd-2-clause
aftabahmedsajid/XenCenter-Complete-dependencies-
XenAdmin/Wizards/PatchingWizard/PatchingWizard_SelectPatchPage.cs
16620
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using XenAdmin.Controls; using XenAdmin.Controls.DataGridViewEx; using XenAdmin.Core; using XenAdmin.Network; using XenAdmin.Properties; using XenAPI; using System.ComponentModel; using System.IO; using XenAdmin.Dialogs; using System.Drawing; namespace XenAdmin.Wizards.PatchingWizard { public partial class PatchingWizard_SelectPatchPage : XenTabPage { public PatchingWizard_SelectPatchPage() { InitializeComponent(); } public override string Text { get { return Messages.PATCHINGWIZARD_SELECTPATCHPAGE_TEXT; } } public override string PageTitle { get { return Messages.PATCHINGWIZARD_SELECTPATCHPAGE_TITLE; } } public override string HelpID { get { return "SelectUpdate"; } } public override void PageLoaded(PageLoadedDirection direction) { base.PageLoaded(direction); if (direction == PageLoadedDirection.Back) { if (dataGridViewPatches.SelectedRows.Count == 0) return; // refresh selected row if the update type is Existing (i.e. the update has been uploaded) int selectedIndex = dataGridViewPatches.SelectedRows[0].Index; string updateName = dataGridViewPatches.Rows[selectedIndex].Cells[ColumnUpdate.Index].Value.ToString(); if (SelectedUpdateType == UpdateType.Existing && (updateName.EndsWith(".xsoem") || updateName.EndsWith(".xsupdate"))) { // remove selected row and add a new one dataGridViewPatches.Rows.RemoveAt(selectedIndex); var row = new PatchGridViewRow(SelectedExistingPatch); if (!dataGridViewPatches.Rows.Contains(row)) { dataGridViewPatches.Rows.Add(row); row.UpdateDetails(); } row.Selected = true; } return; } PopulatePatchesBox(); UpdateEnablement(); } public override void PageLeave(PageLoadedDirection direction, ref bool cancel) { if (direction == PageLoadedDirection.Forward) { if (dataGridViewPatches.SelectedRows.Count > 0 && dataGridViewPatches.SelectedRows[0].Cells[ColumnUpdate.Index].Value.ToString().EndsWith(".xsoem")) SelectedUpdateType = UpdateType.NewOem; else if (dataGridViewPatches.SelectedRows.Count > 0 && dataGridViewPatches.SelectedRows[0].Cells[ColumnUpdate.Index].Value.ToString().EndsWith(".xsupdate")) SelectedUpdateType = UpdateType.NewRetail; else SelectedUpdateType = UpdateType.Existing; SelectedExistingPatch = SelectedUpdateType == UpdateType.Existing ? ((PatchGridViewRow)dataGridViewPatches.SelectedRows[0]).Patch : null; if (SelectedExistingPatch != null && !SelectedExistingPatch.Connection.IsConnected) { cancel = true; PageLeaveCancelled(string.Format(Messages.UPDATES_WIZARD_CANNOT_DOWNLOAD_PATCH, SelectedExistingPatch.Connection.Name)); } else if (!string.IsNullOrEmpty(SelectedNewPatch) && !File.Exists(SelectedNewPatch)) { cancel = true; PageLeaveCancelled(string.Format(Messages.UPDATES_WIZARD_FILE_NOT_FOUND, SelectedNewPatch)); } } base.PageLeave(direction, ref cancel); } private void PageLeaveCancelled(string message) { new ThreeButtonDialog( new ThreeButtonDialog.Details(SystemIcons.Warning, message, Messages.UPDATES_WIZARD)).ShowDialog(this); ((PatchGridViewRow)dataGridViewPatches.SelectedRows[0]).UpdateDetails(); } private void PopulatePatchesBox() { dataGridViewPatches.Rows.Clear(); foreach (IXenConnection xenConnection in ConnectionsManager.XenConnectionsCopy) { foreach (Pool_patch patch in xenConnection.Cache.Pool_patches) { if (patch.size > 0) { PatchGridViewRow row = new PatchGridViewRow(patch); if (!dataGridViewPatches.Rows.Contains(row)) { dataGridViewPatches.Rows.Add(row); row.UpdateDetails(); } } } } dataGridViewPatches.Sort(ColumnUpdate, ListSortDirection.Ascending); } public override bool EnableNext() { if (dataGridViewPatches.SelectedRows.Count == 1) { DataGridViewExRow row = (DataGridViewExRow)dataGridViewPatches.SelectedRows[0]; if (row.Enabled) return true; } return false; } private void UpdateEnablement() { OnPageUpdated(); } private void BrowseButton_Click(object sender, EventArgs e) { // Showing this dialog has the (undocumented) side effect of changing the working directory // to that of the file selected. This means a handle to the directory persists, making // it undeletable until the program exits, or the working dir moves on. So, save and // restore the working dir... String oldDir = ""; try { oldDir = Directory.GetCurrentDirectory(); OpenFileDialog dlg = new OpenFileDialog(); dlg.Multiselect = false; dlg.ShowReadOnly = false; dlg.Filter = Messages.PATCHINGWIZARD_SELECTPATCHPAGE_UPDATESEXT; dlg.FilterIndex = 0; dlg.CheckFileExists = true; dlg.ShowHelp = false; dlg.Title = Messages.PATCHINGWIZARD_SELECTPATCHPAGE_CHOOSE; if (dlg.ShowDialog(this) == DialogResult.OK && dlg.CheckFileExists) { AddFile(dlg.FileName); } OnPageUpdated(); } finally { Directory.SetCurrentDirectory(oldDir); } } public void AddFile(string fileName) { if (fileName.EndsWith(".xsoem") || fileName.EndsWith(".xsupdate")) { PatchGridViewRow row = new PatchGridViewRow(fileName); int index = dataGridViewPatches.Rows.IndexOf(row); if (index < 0) { dataGridViewPatches.Rows.Insert(0, row); index = 0; } dataGridViewPatches.Rows[index].Selected = true; } else { new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, Messages.UPDATES_WIZARD_NOTVALID_EXTENSION, Messages.UPDATES)).ShowDialog(this); } } public UpdateType SelectedUpdateType { get; set; } public Pool_patch SelectedExistingPatch { get; set; } public string SelectedNewPatch { get { return SelectedUpdateType == UpdateType.NewRetail || SelectedUpdateType == UpdateType.NewOem ? ((PatchGridViewRow)dataGridViewPatches.SelectedRows[0]).PathPatch : null; } } private void dataGridViewPatches_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (e.RowIndex < 0) // The click is on a column header return; PatchGridViewRow row = (PatchGridViewRow)dataGridViewPatches.Rows[e.RowIndex]; row.toggleExpandedState(); UpdateEnablement(); } private void dataGridViewPatches_SelectionChanged(object sender, EventArgs e) { UpdateEnablement(); } private class PatchGridViewRow : DataGridViewExRow, IEquatable<PatchGridViewRow> { private readonly Pool_patch _patch; private bool expanded = false; private bool _isFile = false; private string _patchPath; private DataGridViewImageCell _imageCell; private DataGridViewTextBoxCell _nameCell; private DataGridViewTextBoxCell _descriptionCell; private DataGridViewTextBoxCell _statusCell; public PatchGridViewRow(Pool_patch patch) { if (patch == null) throw new ArgumentNullException(); _patch = patch; SetupCells(); } public PatchGridViewRow(string patchPath) { _isFile = true; _patchPath = patchPath; SetupCells(); } public Pool_patch Patch { get { return _patch; } } public string PathPatch { get { return _patchPath; } } private void SetupCells() { _imageCell = new DataGridViewExImageCell(); _nameCell = new DataGridViewTextBoxCell(); _descriptionCell = new DataGridViewTextBoxCell(); _statusCell = new DataGridViewTextBoxCell(); Cells.Add(_imageCell); Cells.Add(_nameCell); Cells.Add(_descriptionCell); Cells.Add(_statusCell); this.UpdateDetails(); } private void UpdateFileDetails(string description, string status) { _descriptionCell.Value = description; _statusCell.Value = status; } public void UpdateDetails() { _imageCell.Value = expanded ? Resources.expanded_triangle : Resources.contracted_triangle; if (_isFile) { _nameCell.Value = System.IO.Path.GetFileName(_patchPath); FileInfo fileInfo = new FileInfo(_patchPath); string description = expanded ? fileInfo.Exists ? String.Format(Messages.PATCH_EXPANDED_DESCRIPTION , _patchPath, fileInfo.CreationTime, fileInfo.LastWriteTime, fileInfo.Length / 1024 / 1024) : String.Format(Messages.PATCH_NOT_FOUND_EXPANDED_DESCRIPTION, _patchPath) : _patchPath; UpdateFileDetails(description, fileInfo.Exists ? Messages.NOT_UPLOADED : Messages.PATCH_NOT_FOUND); } else { //It works across connections _nameCell.Value = Helpers.GetName(Patch); StringBuilder appliedOn = new StringBuilder(Messages.APPLIED_ON); List<Host> hostsAppliedTo = new List<Host>(); foreach (IXenConnection xenConnection in ConnectionsManager.XenConnectionsCopy) { Pool_patch poolPatch = xenConnection.Cache.Find_By_Uuid<Pool_patch>(Patch.uuid); if (poolPatch != null) { hostsAppliedTo.AddRange(poolPatch.HostsAppliedTo()); } } if (hostsAppliedTo.Count > 0) appliedOn.Append(Helpers.GetListOfNames(hostsAppliedTo)); else { appliedOn.Append(Messages.NONE); } _descriptionCell.Value = expanded ? String.Format("{0}\n{1}", _patch.Description, appliedOn.ToString()) : _patch.Description; int totalNumberHostsRunning = 0; foreach (IXenConnection xenConnection in ConnectionsManager.XenConnectionsCopy) { foreach (Host host in xenConnection.Cache.Hosts) { totalNumberHostsRunning++; } } if (hostsAppliedTo.Count == 0) _statusCell.Value = Messages.NOT_APPLIED; else if (hostsAppliedTo.Count == totalNumberHostsRunning) { _statusCell.Value = Messages.FULLY_APPLIED; this.Enabled = false; } else { List<Host> appliedTo = Patch.HostsAppliedTo(); if (appliedTo.Count > 0 && appliedTo[0].isOEM) { _statusCell.Value = Messages.FULLY_APPLIED; this.Enabled = false; } else _statusCell.Value = Messages.PARTIALLY_APPLIED; } } } public void toggleExpandedState() { expanded = !expanded; UpdateDetails(); } public bool Equals(PatchGridViewRow other) { if (other.Patch != null && this.Patch != null && this.Patch.uuid == other.Patch.uuid) return true; if (other.PathPatch != null && this.PathPatch != null && this.PathPatch == other.PathPatch) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { if (obj is PatchGridViewRow) return this.Equals((PatchGridViewRow)obj); return false; } } } public enum UpdateType { NewRetail, NewOem, Existing } }
bsd-2-clause
tzwenn/PyOpenAirMirror
fply/rpc.py
433
import config import socket import fply.cli class FPLY(fply.cli.FPLY_repl): def __init__(self): self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.conn.connect((config.fplyServer, config.fplyServerPort)) def __del__(self): self.conn.close() def send(self, data): self.conn.sendall(data) def read(self, length): return self.conn.recv(length) def available(): return config.fplyServer is not None
bsd-2-clause
pm4j/org.pm4j
pm4j-deprecated/src/test/java/org/pm4j/deprecated/core/sample/admin/remote_sample/server/pm/SampleUserSrvPm.java
1684
package org.pm4j.deprecated.core.sample.admin.remote_sample.server.pm; import org.pm4j.core.pm.PmAttr; import org.pm4j.core.pm.PmAttrEnum; import org.pm4j.core.pm.PmAttrLong; import org.pm4j.core.pm.PmAttrString; import org.pm4j.core.pm.PmCommand; import org.pm4j.core.pm.annotation.PmBeanCfg; import org.pm4j.core.pm.annotation.PmInject; import org.pm4j.core.pm.impl.PmAttrEnumImpl; import org.pm4j.core.pm.impl.PmAttrImpl; import org.pm4j.core.pm.impl.PmAttrLongImpl; import org.pm4j.core.pm.impl.PmAttrStringImpl; import org.pm4j.core.pm.impl.PmBeanBase; import org.pm4j.core.pm.impl.PmCommandImpl; import org.pm4j.deprecated.core.sample.admin.remote_sample.server.service.AdminService; import org.pm4j.deprecated.core.sample.admin.remote_sample.server.service.Department; import org.pm4j.deprecated.core.sample.admin.remote_sample.server.service.SampleUser; import org.pm4j.deprecated.core.sample.admin.remote_sample.shared.Gender; @PmBeanCfg(beanClass=SampleUser.class) public class SampleUserSrvPm extends PmBeanBase<SampleUser> { public PmAttrLong id = new PmAttrLongImpl(this); public PmAttrString loginName = new PmAttrStringImpl(this); public PmAttrString firstName = new PmAttrStringImpl(this); public PmAttrString lastName = new PmAttrStringImpl(this); public PmAttrEnum<Gender> gender = new PmAttrEnumImpl<Gender>(this, Gender.class); public PmAttr<Department> department = new PmAttrImpl<Department>(this); public PmAttrString notes = new PmAttrStringImpl(this); public PmCommand cmdSave = new PmCommandImpl(this) { @PmInject AdminService adminService; protected void doItImpl() { adminService.saveUser(getPmBean()); } }; }
bsd-2-clause
windelbouwman/ppci-mirror
test/util/test_collections.py
786
#!/usr/bin/python import unittest from ppci.utils.collections import OrderedSet class OrderedSetTestCase(unittest.TestCase): """ Test if graph works. - Add nodes - add edges - mask and unmask nodes - combine nodes. """ def test_example(self): """ Test example from Raymond (slightly modified) """ s = OrderedSet('abracadabra') t = OrderedSet('simsalabim') self.assertSequenceEqual('abrcdsiml', list(s | t)) self.assertSequenceEqual('ab', list(s & t)) self.assertSequenceEqual('rcd', list(s - t)) def test_indexing(self): s = OrderedSet('abracadabra') self.assertEqual(s[0], 'a') self.assertEqual(s[1], 'b') s -= {'b'} self.assertEqual(s[1], 'r')
bsd-2-clause
unasuke/homebrew-fonts
Casks/font-amethysta.rb
353
cask 'font-amethysta' do version :latest sha256 :no_check # github.com/google/fonts was verified as official when first introduced to the cask url 'https://github.com/google/fonts/raw/master/ofl/amethysta/Amethysta-Regular.ttf' name 'Amethysta' homepage 'https://www.google.com/fonts/specimen/Amethysta' font 'Amethysta-Regular.ttf' end
bsd-2-clause
floatec/ProsDataBase
ProsDataBase/database/forms.py
3474
# -*- coding: UTF-8 -*- __author__ = 'My-Tien Nguyen' from models import * from django.forms import ModelForm # =============================== # ----- TABLE FORMS --------- # =============================== class CategoryForm(ModelForm): class Meta: model = Category fields = ('name', ) class ColumnForm(ModelForm): class Meta: model = Column fields = ('name', 'created', 'comment') class DatasetForm(ModelForm): class Meta: model = Dataset fields = ('created', ) class TableForm(ModelForm): class Meta: model = Table fields = ('name', 'created') # =============================== # ----- DATA FORMS -------------- # =============================== class DataForm(ModelForm): # TODO: Needed? class Meta: model = Data fields = ('created',) class DataTextForm(ModelForm): class Meta: model = DataText fields = ('created', 'content') class DataNumericForm(ModelForm): class Meta: model = DataNumeric fields = ('created', 'content') class DataDateForm(ModelForm): class Meta: model = DataDate fields = ('created', 'content') class DataSelectionForm(ModelForm): class Meta: model = DataSelection fields = ('created', 'content', 'key') class DataBoolForm(ModelForm): class Meta: model = DataBool fields = ('created', 'content') class DataTableForm(ModelForm): class Meta: model = DataTable fields = ('created',) # =============================== # ----- TYPE FORMS -------------- # =============================== class TypeForm(ModelForm): class Meta: model = Type fields = ('name', 'type') class TypeTextForm(ModelForm): class Meta: model = TypeText fields = ('length', ) class TypeNumericForm(ModelForm): class Meta: model = TypeNumeric fields = ('min', 'max') class TypeDateForm(ModelForm): class Meta: model = TypeDate fields = ('min', 'max') class SelectionValueForm(ModelForm): class Meta: model = SelectionValue fields = ('index', 'content') class TypeSelectionForm(ModelForm): class Meta: model = TypeSelection fields = ('count', ) # =============================== # ------- HISTORY TABLES -------- # =============================== class HistoryTableForm(ModelForm): class Meta: model = HistoryTable fields = ('date', 'type') class MessageTableForm(ModelForm): class Meta: model = MessageTable fields = ('content', ) class HistoryAuthForm(ModelForm): class Meta: model = HistoryAuth fields = ('date', 'type') class MessageAuthForm(ModelForm): class Meta: model = MessageAuth fields = ('content', ) # =============================== # ----- PERMISSION FORMS -------- # =============================== class DBGroupForm(ModelForm): class Meta: model = DBGroup fields = ('name', ) class MembershipForm(ModelForm): class Meta: model = Membership fields = ('isAdmin', ) class RightListForTableForm(ModelForm): class Meta: model = RightListForTable fields = ('viewLog', 'rightsAdmin', 'insert', 'delete') class RightListForColumnForm(ModelForm): class Meta: model = RightListForColumn fields = ('read', 'modify')
bsd-2-clause
fms13/cdx
docs/search/functions_4.js
176
var searchData= [ ['hamming',['hamming',['../cdx-convert-continuous-to-discrete_8cpp.html#ada194bc2ddf41e0f8f2921f88007ca90',1,'cdx-convert-continuous-to-discrete.cpp']]] ];
bsd-2-clause
Jumpscale/jumpscale6_core
apps/eve/eve_start.py
2751
from JumpScale import j import os from eve import Eve from eve.render import send_response from flask.ext.bootstrap import Bootstrap from eve_docs import eve_docs from eve_docs.config import get_cfg from generators.EveGenerator import generateDomain from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from flask import render_template from JumpScale.baselib import cmdutils # default eve settings import JumpScale.grid.osis import sys def run(port=5000, mongo_host='localhost', mongo_port=27017, pagination_limit=1000000): client = j.core.osis.getClientByInstance('main') apps = dict() for namespace in client.listNamespaces(): spec=client.getOsisSpecModel(namespace) dbname = namespace if namespace != 'system' else 'js_system' my_settings = { 'MONGO_HOST': mongo_host, 'MONGO_PORT': mongo_port , 'MONGO_DBNAME': dbname, 'DOMAIN': generateDomain(spec), 'RESOURCE_METHODS': ['GET', 'POST'], 'ITEM_METHODS': ['GET', 'PATCH', 'PUT', 'DELETE'], 'X_DOMAINS': '*', 'MONGO_QUERY_BLACKLIST': [], 'X_HEADERS': ["X-HTTP-Method-Override", 'If-Match'], 'PAGINATION_LIMIT': pagination_limit } # init application app = Eve(__name__, settings=my_settings) Bootstrap(app) @app.route('/ui') def ui(): return render_template('ui.html') # Unfortunately, eve_docs doesn't support CORS (too bad!), so we had to reimplement it ourselves @app.route('/docs/spec.json') def specs(): return send_response(None, [get_cfg()]) apps['/%s' % namespace] = app print "visit:\nhttp://localhost:%s/docs/" % port if apps: firstapp = apps.values()[0] application = DispatcherMiddleware(firstapp, apps) # let's roll run_simple('0.0.0.0', port, application, use_reloader=True) if __name__ == "__main__": parser = cmdutils.ArgumentParser() parser.add_argument("-p", '--port', help='Port', default=5000, type=int) parser.add_argument("-dh", '--mongo_host', help='Mongodb hostname', default='localhost') parser.add_argument("-dp", '--mongo_port', help='Mongodb port', default=27017, type=int) parser.add_argument("-pl", '--pagination_limit', help='pagination limit', default=1000000, type=int) opts = parser.parse_args() port = opts.port mongo_host = opts.mongo_host mongo_port = opts.mongo_port pagination_limit = opts.pagination_limit run(port=port, mongo_host=mongo_host, mongo_port=mongo_port, pagination_limit=pagination_limit)
bsd-2-clause
Drafigon/WildGraphs
src/utility/GraphFunctions.java
8615
package utility; import graph.implementation.Edge; import graph.implementation.Graph; import graph.implementation.Vertex; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; public abstract class GraphFunctions { private GraphFunctions(){}; public static Edge getHitEdge(Graph graph, Point location) { for(Edge e : graph.getEdges()) { boolean isInside = GraphFunctions.isInsideEdge(e, location); if(isInside) { return e; } } return null; } /** * Returns true if the given point * is inside the (clickable) edge shape. * An edge can be clicked around the curve point. * * @param mouse : Point * @return true/false */ public static boolean isInsideEdge(Edge edge, Point mouse) { Point curvePoint = edge.getCurvePoint(); int diffX = Math.abs(mouse.x - curvePoint.x); int diffY = Math.abs(mouse.y - curvePoint.y); int radius = 30; if(diffX < radius && diffY < radius) { return true; } return false; } public static Vertex getHitVertex(Graph graph, Point location) { for(Vertex v : graph.getVertices()) { boolean isInside = GraphFunctions.isInsideVertex(v, location); if(isInside) { return v; } } return null; } /** * Returns true if the given point * is inside the (clickable) vertex shape. * * @param mouse : Point * @return true/false */ public static boolean isInsideVertex(Vertex vertex, Point mouse) { Point location = vertex.getLocation(); int diffX = Math.abs(mouse.x - location.x); int diffY = Math.abs(mouse.y - location.y); int size = vertex.getDrawOption().getSize(); if(diffX < size * 0.6 && diffY < size * 0.6) { return true; } return false; } public static boolean hasVertexWithName(Graph graph, String name) { for(Vertex v : graph.getVertices()) { if(v.getName().equals(name)) { return true; } } return false; } /** * Moves the complete graph by the given vector. * * @param vector : Point */ public static void moveGraphBy(Graph graph, Point vector) { for(Vertex v : graph.getVertices()) { Point currentPos = v.getLocation(); int newX = currentPos.x + vector.x; int newY = currentPos.y + vector.y; v.setLocation(new Point(newX, newY)); } for(Edge e : graph.getEdges()) { Point curvePoint = e.getCurvePoint(); int newX = curvePoint.x + vector.x; int newY = curvePoint.y + vector.y; e.setCurvePoint(new Point(newX, newY)); } } public static void relaxEdge(Edge edge) { Vertex source = edge.getSource(); Vertex destination = edge.getDestination(); Point start = source.getLocation(); Point end = destination.getLocation(); Point curvePoint; // if source and destination are equal -> noose if(source == destination) { curvePoint = new Point(end.x, end.y - destination.getDrawOption().getSize() - 20); } // else line else { int deltaX = end.x - start.x; int deltaY = end.y - start.y; curvePoint = new Point(start.x + deltaX/2, start.y + deltaY/2); } edge.setCurvePoint(curvePoint); } public static boolean isTree(Graph graph) { boolean correctEdgeCount = graph.getEdges().size() == (graph.getVertices().size() - 1); // For Subgraphs which aren't connected boolean isBipartit = getBipartitParts(graph) != null; boolean noFreeVertices = true; for(Vertex v : graph.getVertices()) { if(v.getNeighbours().isEmpty()) { noFreeVertices = false; } } return correctEdgeCount && isBipartit && noFreeVertices; } public static BipartitParts getBipartitParts(Graph graph) { // init lists HashMap<Vertex, Integer> marker = new HashMap<Vertex, Integer>(); ArrayList<Vertex> temp = new ArrayList<Vertex>(); final int UNMARKED = 2; final int MARKED_A = 0; final int MARKED_B = 1; for(Vertex v : graph.getVertices()) { marker.put(v, UNMARKED); } // algorithm for(Vertex firstVertex : marker.keySet()) { if(marker.get(firstVertex) == UNMARKED) { marker.put(firstVertex, MARKED_A); temp.add(firstVertex); while(!temp.isEmpty()) { Vertex currentVertex = temp.get(0); temp.remove(0); Collection<Vertex> neighbours = currentVertex.getNeighbours().values(); for(Vertex n : neighbours) { if(marker.get(n) == UNMARKED) { int newMarker = MARKED_B - marker.get(currentVertex); marker.put(n, newMarker); temp.add(n); } else if(marker.get(n) == marker.get(currentVertex)) { return null; } } } } } BipartitParts bipartit = new BipartitParts(); for(Vertex v : marker.keySet()) { if(marker.get(v) == MARKED_A) { bipartit.partA.add(v); } if(marker.get(v) == MARKED_B) { bipartit.partB.add(v); } } return bipartit; } public static class BipartitParts { public ArrayList<Vertex> partA = new ArrayList<Vertex>(); public ArrayList<Vertex> partB = new ArrayList<Vertex>(); } public static Image getSizedGraphImage(Graph graph, int width, int height, Color background) { // create basic image BufferedImage image = getGraphImage(graph, background); final double IMAGE_WIDTH = image.getWidth(); final double IMAGE_HEIGHT = image.getHeight(); final double MAX_IMAGE_WIDTH = width; final double MAX_IMAGE_HEIGHT = height; // if necessary reduce image if(IMAGE_WIDTH > MAX_IMAGE_WIDTH || IMAGE_HEIGHT > MAX_IMAGE_HEIGHT) { // factors int littleWidth; int littleHeight; if(MAX_IMAGE_WIDTH / IMAGE_WIDTH <= MAX_IMAGE_HEIGHT / IMAGE_HEIGHT) { final double factor = IMAGE_HEIGHT / IMAGE_WIDTH; littleWidth = (int) MAX_IMAGE_WIDTH; littleHeight = (int) (MAX_IMAGE_WIDTH * factor); } else { double factor = IMAGE_WIDTH / IMAGE_HEIGHT; littleWidth = (int) (MAX_IMAGE_HEIGHT * factor); littleHeight = (int) MAX_IMAGE_HEIGHT; } // scale image Image little = image.getScaledInstance(littleWidth, littleHeight, BufferedImage.SCALE_SMOOTH); return little; } else { return image; } } public static BufferedImage getGraphImage(Graph graph, Color background) { // get borders Bounds bounds = getGraphBounds(graph); int minX = bounds.x; int minY = bounds.y; int moveBackX = 0; int moveBackY = 0; // correction: move graph in positive value range if(minX < 0) { moveGraphBy(graph, new Point(-minX,0)); moveBackX = minX; minX = 0; } if(minY < 0) { moveGraphBy(graph, new Point(0,-minY)); moveBackY = minY; minY = 0; } int maxX = minX + bounds.weight; int maxY = minY + bounds.height; // Creating image BufferedImage image = new BufferedImage(maxX, maxY, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setBackground(background); g2.clearRect(0, 0, maxX, maxY); graph.draw(g2); g2.dispose(); BufferedImage little = image.getSubimage(minX, minY, maxX - minX, maxY - minY); moveGraphBy(graph, new Point(moveBackX, moveBackY)); return little; } public static Bounds getGraphBounds(Graph graph) { int minX = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; if(graph.getVertices().isEmpty()) { return new Bounds(0,0,1,1); } else { for(Vertex v : graph.getVertices()) { Point pos = v.getLocation(); int size = v.getDrawOption().getSize(); if(pos.x - size < minX) { minX = pos.x - size; } if(pos.x + size > maxX) { maxX = pos.x + size; } if(pos.y - size < minY) { minY = pos.y - size; } if(pos.y + size > maxY) { maxY = pos.y + size; } } for(Edge e : graph.getEdges()) { Point pos = e.getCurvePoint(); int size = 50; if(pos.x - size < minX) { minX = pos.x - size; } if(pos.x + size > maxX) { maxX = pos.x + size; } if(pos.y - size < minY) { minY = pos.y - size; } if(pos.y + size > maxY) { maxY = pos.y + size; } } } int width = maxX - minX; int height = maxY - minY; Bounds bounds = new Bounds(minX, minY, width, height); return bounds; } public static class Bounds { public final int x; public final int y; public final int weight; public final int height; public Bounds(int x, int y, int weight, int height) { this.x = x; this.y = y; this.weight = weight; this.height = height; } } }
bsd-2-clause
askl56/homebrew-cask
Casks/pixel-check.rb
420
cask v1: 'pixel-check' do version '1.3' sha256 '99da44c4538463c6476be2f7d6584a4e5a9bfa175895d72e5baf1f3271316b02' url "http://macguitar.me/apps/pixelcheck/PXC#{version}.zip" name 'PiXel Check' homepage 'http://macguitar.me/apps/pixelcheck/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder app "PiXel Check #{version}/PiXel Check.app" end
bsd-2-clause
flywingsky/task-ninja
app/src-app/taskninja/android/dialogs/NewListDialog.java
1941
package taskninja.android.dialogs; import java.sql.SQLException; import taskninja.android.ActionListener; import taskninja.android.models.NinjaList; import taskninja.android.ormlite.DatabaseHelper; import android.app.Dialog; import android.content.Context; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public class NewListDialog extends Dialog implements android.view.View.OnClickListener { private ActionListener<NinjaList> mListener; private LinearLayout mLayout; private EditText mEditText; private Button mSaveButton; private Button mCancelButton; public NewListDialog(Context context, ActionListener<NinjaList> listener) { super(context); mListener = listener; setTitle("Create a New List"); mLayout = new LinearLayout(context); mLayout.setOrientation(mLayout.VERTICAL); mEditText = new EditText(context); mEditText.setHint("List Title"); mSaveButton = new Button(context); mSaveButton.setText("Save"); mSaveButton.setOnClickListener(this); mCancelButton = new Button(context); mCancelButton.setText("Cancel"); mCancelButton.setOnClickListener(this); mLayout.addView(mEditText); mLayout.addView(mCancelButton); mLayout.addView(mSaveButton); setContentView(mLayout); } @Override public void onClick(View v) { if (v.equals(mSaveButton)){ String text = mEditText.getEditableText().toString(); if (isValid(text)) { newList(text); this.dismiss(); } else { } } else if (v.equals(mCancelButton)){ this.dismiss(); } } private void newList(String text) { try { NinjaList list = new NinjaList(text); DatabaseHelper.getListDao().create(list); mListener.onAction(list); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private boolean isValid(String text) { return true; } }
bsd-2-clause
sitna/api-sitna
TC/config/browser-versions.js
350
TC.Cfg.acceptedBrowserVersions = [ { "name": "Chrome", "version": 85 }, { "name": "Edge", "version": 85 }, { "name": "Firefox", "version": 78 }, { "name": "Safari", "version": 13 }, { "name": "Mobile Safari", "version": 13 } ];
bsd-2-clause
makigumo/homebrew-core
Formula/gnupg@2.2.rb
2628
class GnupgAT22 < Formula desc "GNU Pretty Good Privacy (PGP) package" homepage "https://gnupg.org/" url "https://gnupg.org/ftp/gcrypt/gnupg/gnupg-2.2.32.tar.bz2" sha256 "b2571b35f82c63e7d278aa6a1add0d73453dc14d3f0854be490c844fca7e0614" license "GPL-3.0-or-later" livecheck do url "https://gnupg.org/ftp/gcrypt/gnupg/" regex(/href=.*?gnupg[._-]v?(2\.2(?:\.\d+)+)\.t/i) end bottle do sha256 arm64_monterey: "a4c726e2530a082a42b16537c7c842bc930869c5901b848363aa82a8e4605fc0" sha256 arm64_big_sur: "d5b237d03383aad0b7c389a1687808afe9935e0b82b3de8a57e144c42046cb25" sha256 monterey: "8b5648cefe2233296224da83f0e6a3ad3e31bd8727332c520572a9f8c42d5e72" sha256 big_sur: "97bc5ab5fbed07d57d0a5520ca821fcd7d229d515794ef549bef13d94995c8b6" sha256 catalina: "9a70625ba7a01abdbf898fa07df18eaabf7ec2737185fbe094fb629494e0916a" sha256 mojave: "2e3786d7d40b82eeee785c4a4063705110930b22d6282bbf3634ad2e3e358af7" sha256 x86_64_linux: "64ee92a2cb821ace17056b912d41ecc48cac0e8d3fbdc45742d82b3c65b546d3" end keg_only :versioned_formula depends_on "pkg-config" => :build depends_on "gettext" depends_on "gnutls" depends_on "libassuan" depends_on "libgcrypt" depends_on "libgpg-error" depends_on "libksba" depends_on "libusb" depends_on "npth" depends_on "pinentry" uses_from_macos "sqlite" => :build on_linux do depends_on "libidn" end def install system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--sbindir=#{bin}", "--sysconfdir=#{etc}", "--enable-all-tests", "--enable-symcryptrun", "--with-pinentry-pgm=#{Formula["pinentry"].opt_bin}/pinentry" system "make" system "make", "check" system "make", "install" end def post_install (var/"run").mkpath quiet_system "killall", "gpg-agent" end test do (testpath/"batch.gpg").write <<~EOS Key-Type: RSA Key-Length: 2048 Subkey-Type: RSA Subkey-Length: 2048 Name-Real: Testing Name-Email: testing@foo.bar Expire-Date: 1d %no-protection %commit EOS begin system bin/"gpg", "--batch", "--gen-key", "batch.gpg" (testpath/"test.txt").write "Hello World!" system bin/"gpg", "--detach-sign", "test.txt" system bin/"gpg", "--verify", "test.txt.sig" ensure system bin/"gpgconf", "--kill", "gpg-agent" end end end
bsd-2-clause
4honor/gingko
gko-tracker-src/src/PeerHandler.cpp
20383
#include "bbts/tracker/PeerHandler.h" #include <climits> #include <boost/format.hpp> #include <glog/logging.h> #include "bbts/encode.h" #include "bbts/KeyTypeRWLock.hpp" #include "bbts/Random.h" #include "bbts/RedisCommandCreator.h" #include "bbts/RedisManager.h" #include "bbts/StatusManager.h" #include "tracker_types.h" #include "bbts/tracker/TrackerErrorCategory.h" using std::string; using std::numeric_limits; using boost::shared_ptr; using boost::system::error_code; using boost::weak_ptr; namespace bbts { namespace tracker { PeerHandler::PeerHandler() : info_hash_expire_second_(3600) { //blank implement } void PeerHandler::ControlByInfohash(const string &infohash, int type, error_code &ec) { shared_ptr<SingleInfoHashInfo> single_info_pointer; KeyTypeRWLock<LocalInfoHashMap> lock("local_info_hash_map"); InfoHashMap::iterator info_hash_map_iterator = local_info_hash_map_->find(infohash); if (info_hash_map_iterator == local_info_hash_map_->end()) { ec.assign(errors::INFOHASH_NOT_FOUND, get_error_category()); return; } shared_ptr<SingleInfoHashInfo> &single_info = info_hash_map_iterator->second; single_info->timestamp = time(NULL); switch (type) { case STOP_DOWNLOADING: single_info->need_stop = true; break; case RESUME_DOWNLOAD: single_info->need_stop = false; break; default: ec.assign(errors::INVALID_OPERAT_TYPE, get_error_category()); break; } return; } int PeerHandler::Handle(const PeerInfo &input_peer, PeerList *peer_list_output, bool &have_seed) { int ret = UpdatePeer(input_peer); if (ret) { return ret; } if (input_peer.CheckNeedMorePeers() == true) { ret = ChoosePeers(input_peer, peer_list_output, have_seed); } return ret; } void PeerHandler::SetInfoHashMaps(const shared_ptr<InfoHashMap> &local_map, const shared_ptr<InfoHashMap> &remote_map, const shared_ptr<InfoHashQueue> &queue, uint32_t expire_second) { local_info_hash_map_ = local_map; remote_info_hash_map_ = remote_map; info_hash_queue_ = queue; info_hash_expire_second_ = expire_second; } void PeerHandler::PreHandleInfoHashInfo(const PeerInfo &input_peer, shared_ptr<SingleInfoHashInfo> &single_info) { const string &info_hash = input_peer.GetBase64InfoHash(); InfoHashMap::iterator info_hash_map_iterator = local_info_hash_map_->find(info_hash); if (info_hash_map_iterator == local_info_hash_map_->end()) { single_info.reset(new SingleInfoHashInfo()); assert(single_info); (*local_info_hash_map_)[info_hash] = single_info; }else { single_info = info_hash_map_iterator->second; single_info->timestamp = time(NULL); } } void PeerHandler::PreHandlePeerInfo(const PeerInfo &input_peer, const shared_ptr<SingleInfoHashInfo> &single_info_pointer, boost::shared_ptr<PeerInfo> &peer_info, bool *peer_is_new) { assert(peer_is_new); *peer_is_new = false; SinglePeerMap &peer_map = single_info_pointer->peer_map; SinglePeerMap::iterator single_peer_map_iterator = peer_map.find(input_peer.GetBase64PeerId()); if (single_peer_map_iterator == peer_map.end() && !input_peer.CheckToStop()) { *peer_is_new = true; peer_info.reset(new PeerInfo()); assert(peer_info); peer_map[input_peer.GetBase64PeerId()] = peer_info; } else if (single_peer_map_iterator != peer_map.end()) { if (input_peer.CheckToStop()) { if (single_peer_map_iterator->second->GetIsSetRemote()) {// delete the peers in redis if (0 == DeletePeerRemote(input_peer)) { --single_info_pointer->remote_peer_count; LOG(INFO) << "start to delete seed remote:" << input_peer.GetBase64InfoHash().c_str() << ", now: " << single_info_pointer->remote_peer_count; } } peer_map.erase(single_peer_map_iterator); ++single_info_pointer->complete_num; return; } peer_info = single_peer_map_iterator->second; } } int PeerHandler::UpdatePeer(const PeerInfo &input_peer) { shared_ptr<SingleInfoHashInfo> single_info_pointer; { // get infohash level KeyTypeRWLock<LocalInfoHashMap> lock("local_info_hash_map"); PreHandleInfoHashInfo(input_peer, single_info_pointer); } // get peer info from infohash level shared_ptr<PeerInfo> peer_info; bool peer_is_new = false; { KeyTypeRWLock<LocalInfoHashMap> lock(input_peer.GetBase64InfoHash()); PreHandlePeerInfo(input_peer, single_info_pointer, peer_info, &peer_is_new); } if (!peer_info) {// stop message return 0; } // if global need stop, return magic num to tell client stop download except seed client if (single_info_pointer->need_stop && !input_peer.IsASeed()) { return 26234; } { // we must lock vector because can't fetch this peer before it updated. KeyTypeRWLock<LocalInfoHashMap> lock(input_peer.GetBase64InfoHash() + "weak_vector"); peer_info->UpdateInfo(input_peer); if (peer_is_new) {// new peer will push to vector string idc = input_peer.GetIdc(); if (single_info_pointer->idc_to_peer_vector.find(idc) == single_info_pointer->idc_to_peer_vector.end()) { shared_ptr<SinglePeerVec> single_peer_vector(new SinglePeerVec()); single_info_pointer->idc_to_peer_vector[idc] = single_peer_vector; } shared_ptr<SinglePeerVec> single_peer_vector = single_info_pointer->idc_to_peer_vector[idc]; single_peer_vector->push_back(weak_ptr<PeerInfo>(peer_info)); if (peer_info->IsASeed()) { if (single_info_pointer->idc_to_seed_vector.find(idc) == single_info_pointer->idc_to_seed_vector.end()) { shared_ptr<SinglePeerVec> single_seed_vector(new SinglePeerVec()); single_info_pointer->idc_to_seed_vector[idc] = single_seed_vector; } shared_ptr<SinglePeerVec> single_seed_vector = single_info_pointer->idc_to_seed_vector[idc]; single_seed_vector->push_back(weak_ptr<PeerInfo>(peer_info)); } } } uint64_t probability = 1 << single_info_pointer->remote_peer_count; bool if_set_peer_remote = Random::GetRandomNumber(probability) <= 1; //printf("is_seed: %d; if_set_peer_remote: %d, is_seeding: %d\n", input_peer.IsASeed(), if_set_peer_remote, input_peer.IsSeeding()); if (peer_info->GetIsSetRemote() == true || input_peer.IsASeed() || (input_peer.IsSeeding() && if_set_peer_remote == true)) { if (0 == SetPeerRemote(input_peer)) { KeyTypeRWLock<LocalInfoHashMap> lock(input_peer.GetBase64InfoHash().c_str()); peer_info->SetIsSetRemote(true); if (peer_is_new) { ++single_info_pointer->remote_peer_count; } LOG(INFO) << "start to set seed remote:" << input_peer.GetBase64InfoHash().c_str() << ", now:" << single_info_pointer->remote_peer_count; } } return 0; } void PeerHandler::ConstructInfoHashKey(const string &base64_info_hash, string *key) { assert(key); key->append("info_hash_key_"); key->append(base64_info_hash.c_str()); } void PeerHandler::ConstructPeerKey(const string &base64_peer_id, string *key) { assert(key); key->append(base64_peer_id.c_str()); } int PeerHandler::SetPeerRemote(const PeerInfo &input_peer) { int ret = 0; string serilized_peer_info; input_peer.ConstructStringByPeerInfo(&serilized_peer_info); string encode_string; if (!Base64Encode(serilized_peer_info, &encode_string)) { LOG(INFO)<<"base64 encode serialized peer info failed"; return -1; } try { string command; string info_hash_key, peer_id_key; ConstructInfoHashKey(input_peer.GetBase64InfoHash(), &info_hash_key); ConstructPeerKey(input_peer.GetBase64PeerId(), &peer_id_key); ret = RedisCommandCreator::SetHashOneItemInfo(info_hash_key, peer_id_key, encode_string, &command); g_pRedisManager->PipelineCommand(input_peer.GetBase64InfoHash(), command); ret = ret | RedisCommandCreator::SetExpire(info_hash_key, info_hash_expire_second_, &command); g_pRedisManager->PipelineCommand(input_peer.GetBase64InfoHash(), command); } catch (std::exception &e) { LOG(WARNING) << "catch exception " << e.what(); } return ret; } int PeerHandler::DeletePeerRemote(const PeerInfo &input_peer) { string info_hash_key, peer_id_key; string command; ConstructInfoHashKey(input_peer.GetBase64InfoHash(), &info_hash_key); ConstructPeerKey(input_peer.GetBase64PeerId(), &peer_id_key); int ret = RedisCommandCreator::DeleteOneHashItem(info_hash_key.c_str(), peer_id_key.c_str(), &command); g_pRedisManager->PipelineCommand(input_peer.GetBase64InfoHash(), command); return ret; } int PeerHandler::ChoosePeers(const PeerInfo &input_peer, PeerList *peer_list_output, bool &have_seed) { assert(peer_list_output); peer_list_output->clear(); shared_ptr<SingleInfoHashInfo> info_pointer; string map_key = "local_info_hash_map"; { KeyTypeRWLock<LocalInfoHashMap> lock(map_key.c_str(), 'r'); InfoHashMap::const_iterator info_hash_map_iter = local_info_hash_map_->find(input_peer.GetBase64InfoHash()); if (info_hash_map_iter != local_info_hash_map_->end()) { info_pointer = info_hash_map_iter->second; } } { KeyTypeRWLock<LocalInfoHashMap> lock(input_peer.GetBase64InfoHash() + "weak_vector"); if (info_pointer) { VisitIdcToPeers(input_peer, info_pointer->idc_to_peer_vector, peer_list_output, have_seed, map_key, input_peer.GetWantNumber()); if (!have_seed && info_pointer->idc_to_seed_vector.size() > 0) { VisitIdcToPeers(input_peer, info_pointer->idc_to_seed_vector, peer_list_output, have_seed, map_key, 1); } } } // if fetch seed peer in local, no need to fetch seed peer from remote if (input_peer.IsASeed() || (peer_list_output->size() > 0 && have_seed)) { return 0; } // fetch remote seed peer AddNeedInfoHash(input_peer); map_key = "remote_info_hash_map"; info_pointer.reset(); { KeyTypeRWLock<RemoteInfoHashMap> lock(map_key.c_str(), 'r'); InfoHashMap::const_iterator info_hash_map_iter = remote_info_hash_map_->find(input_peer.GetBase64InfoHash()); if (info_hash_map_iter != remote_info_hash_map_->end()) { info_pointer = info_hash_map_iter->second; } } { KeyTypeRWLock<RemoteInfoHashMap> lock(input_peer.GetBase64InfoHash() + "weak_vector"); if (info_pointer) { if (peer_list_output->size() < 10) { ChoosePeersByMap(input_peer, peer_list_output, have_seed, info_pointer->peer_vec, map_key, 10 - peer_list_output->size()); } if (!have_seed && !info_pointer->peer_seed_vec.empty()) { ChoosePeersByMap(input_peer, peer_list_output, have_seed, info_pointer->peer_seed_vec, map_key, 1); } } } return 0; } int PeerHandler::VisitIdcToPeers(const PeerInfo &input_peer, IdcToSingleVector &idc_map, PeerList *peer_list_output, bool &if_seed_inserted, const string &map_key, int num_want) { assert(peer_list_output); shared_ptr<SinglePeerVec> single_peer_vector; PeerList local_output_list; int num_left = num_want; if (idc_map.find(input_peer.GetIdc()) != idc_map.end()) { single_peer_vector = idc_map[input_peer.GetIdc()]; ChoosePeersByMap(input_peer, &local_output_list, if_seed_inserted, *single_peer_vector, map_key, num_left); } num_left = num_want - local_output_list.size(); IdcToSingleVector::iterator iter = idc_map.begin(); int random_index = Random::GetRandomNumber(idc_map.size() - 1); int now_index = -1; for (; num_left > 0 && iter != idc_map.end(); iter++) { now_index++; if (random_index < now_index) { continue; } string idc = static_cast<string>(iter->first); if (idc == input_peer.GetIdc()) { continue; } single_peer_vector = iter->second; ChoosePeersByMap(input_peer, &local_output_list, if_seed_inserted, *single_peer_vector, map_key, num_left); num_left = num_want - local_output_list.size(); } PeerList::iterator vec_iter = local_output_list.begin(); for (; vec_iter != local_output_list.end(); vec_iter++) { peer_list_output->push_back(*vec_iter); } return 0; } int PeerHandler::ChoosePeersByMap(const PeerInfo &input_peer, PeerList *peer_list_output, bool &if_seed_inserted, SinglePeerVec &peer_vec, const string &map_key, int num_want) { assert(peer_list_output); int peer_vec_size = peer_vec.size(); int random_index = Random::GetRandomNumber(peer_vec_size - 1); for (int i = 0; i < peer_vec_size && num_want > 0;) { int peer_index = (i + random_index) % peer_vec_size; shared_ptr<PeerInfo> peer_info = peer_vec[peer_index].lock(); if (peer_info) { ++i; if (peer_info->Initialized() == false) { LOG(WARNING)<<"peer_info is not initialized!!!"; continue; } if (input_peer.GetBase64PeerId() == peer_info->GetBase64PeerId()) { //printf("find a peerid equal input: %s", input_peer.GetBase64PeerId().c_str()); continue; } if (if_seed_inserted == false && peer_info->IsASeed()) { if_seed_inserted = true; } peer_list_output->push_back(*peer_info); --num_want; } else { SinglePeerVec::iterator peer_it = peer_vec.begin() + peer_index; peer_vec.erase(peer_it); peer_vec_size = peer_vec.size(); } } return 0; } /* used to add need infohash to remote syncronizer */ void PeerHandler::AddNeedInfoHash(const PeerInfo &input_peer) { bool querying = false; boost::mutex::scoped_lock lock(info_hash_queue_->mutex); QueryMap::iterator query = info_hash_queue_->query_map.find(input_peer.GetBase64InfoHash()); if (query == info_hash_queue_->query_map.end()) { info_hash_queue_->query_map[input_peer.GetBase64InfoHash()] = false; g_pStatusManager->SetItemStatus("redis_to_syncronize_num", info_hash_queue_->query_map.size()); } else { querying = query->second; } if (!querying) { info_hash_queue_->have_query = true; info_hash_queue_->cond.notify_one(); } } string PeerHandler::ShowInfohashs(const string &query) { int max_infohash_num = 100; if (!query.empty()) { max_infohash_num = atoi(query.c_str()); max_infohash_num = max_infohash_num < 0 ? numeric_limits<int>::max() : max_infohash_num; } int remote_peers_num = 0; string hex_infohash; string ret = (boost::format("all infohashs: %d\n\n") % local_info_hash_map_->size()).str(); ret.append("lpn: local peers num\n" "rpn: remote peers num\n" "srn: set remote peers num\n" "s: need stop\n" "cnum: complete peers num\n\n\n" " infohash lpn rpn timestamp srn s cnum\n"); { boost::format infohash_format("%40s %6d %6d %10d %6d %1d %6d\n"); KeyTypeRWLock<LocalInfoHashMap> l_lock("local_info_hash_map", 'r'); KeyTypeRWLock<RemoteInfoHashMap> r_lock("remote_info_hash_map", 'r'); for(InfoHashMap::iterator local_it = local_info_hash_map_->begin(); max_infohash_num > 0 && local_it != local_info_hash_map_->end(); ++local_it, --max_infohash_num) { InfoHashMap::iterator remote_it = remote_info_hash_map_->find(local_it->first); remote_peers_num = remote_it != remote_info_hash_map_->end() ? remote_it->second->peer_map.size() : 0; Base64ToHex(local_it->first, &hex_infohash); boost::shared_ptr<SingleInfoHashInfo> &infohash_ptr = local_it->second; infohash_format % hex_infohash % infohash_ptr->peer_map.size() % remote_peers_num % infohash_ptr->timestamp % infohash_ptr->remote_peer_count % infohash_ptr->need_stop % infohash_ptr->complete_num; ret.append(infohash_format.str()); } } return ret; } inline static void TravelsPeerMap(const shared_ptr<SingleInfoHashInfo> &peers, int max_peers_num, const string &peers_tag, string *ret) { if (peers) { ret->append((boost::format("\ntotal %s peers num: %d\n") % peers_tag % peers->peer_map.size()).str()); ret->append(" peerid ip:port d r t uploaded downloaded left tracker\n"); boost::format peer_format("%40s %15s:%-5d %1d %1d %1d %12d %12d %12d %s\n"); for (SinglePeerMap::const_iterator it = peers->peer_map.begin() ; it != peers->peer_map.end() && max_peers_num > 0; ++it, --max_peers_num) { const shared_ptr<PeerInfo> &peer = it->second; string hex_peerid; BytesToHex(peer->GetPeerId(), &hex_peerid); peer_format % hex_peerid % peer->GetIp() % peer->GetPort() % peer->GetIsSeed() % peer->GetIsSetRemote() % peer->GetStatus() % peer->GetUploaded() % peer->GetDownloaded() % peer->GetLeft() % peer->GetTrackerId(); ret->append(peer_format.str()); } } else { ret->append("\nnot find any" + peers_tag + " peers\n"); } } string PeerHandler::ShowPeers(const string &query) { int max_peers_num = 100; string base64_infohash; string hex_infohash; { std::string::size_type pos = query.find('&'); if (pos != query.npos) { hex_infohash = query.substr(0, pos); max_peers_num = atoi(query.substr(pos + 1).c_str()); max_peers_num = max_peers_num < 0 ? numeric_limits<int>::max() : max_peers_num; } else { hex_infohash = query; } if (hex_infohash.empty() || !HexToBase64(hex_infohash, &base64_infohash)) { return "infohash is empty or invalid!"; } } std::string ret("mpn: max display peers num\n" "srn: set remote peers num\n" "s: need stop\n" "cnum: complete peers num\n" "d: is seed\n" "r: is set remote\n" "t: status\n\n\n" " infohash mpn timestamp srn s cnum\n"); { KeyTypeRWLock<LocalInfoHashMap> l_lock("local_info_hash_map", 'r'); InfoHashMap::iterator local_it = local_info_hash_map_->find(base64_infohash); if (local_it != local_info_hash_map_->end()) { boost::shared_ptr<SingleInfoHashInfo> &infohash_ptr = local_it->second; ret.append((boost::format("%40s %6d %10d %6d %1d %6d\n") % hex_infohash % max_peers_num % infohash_ptr->timestamp % infohash_ptr->remote_peer_count % infohash_ptr->need_stop % infohash_ptr->complete_num).str()); TravelsPeerMap(local_it->second, max_peers_num, "local", &ret); } else { ret.append(base64_infohash); } } { KeyTypeRWLock<RemoteInfoHashMap> r_lock("remote_info_hash_map", 'r'); InfoHashMap::iterator remote_it = remote_info_hash_map_->find(base64_infohash); if (remote_it != remote_info_hash_map_->end()) { TravelsPeerMap(remote_it->second, max_peers_num, "remote", &ret); } } return ret; } } }
bsd-2-clause
kerwinxu/barcodeManager
zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/dvips.py
3546
"""SCons.Tool.dvips Tool-specific initialization for dvips. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/dvips.py 5023 2010/06/14 22:05:46 scons" import SCons.Action import SCons.Builder import SCons.Tool.dvipdf import SCons.Util def DviPsFunction(target = None, source= None, env=None): result = SCons.Tool.dvipdf.DviPdfPsFunction(PSAction,target,source,env) return result def DviPsStrFunction(target = None, source= None, env=None): """A strfunction for dvipdf that returns the appropriate command string for the no_exec options.""" if env.GetOption("no_exec"): result = env.subst('$PSCOM',0,target,source) else: result = '' return result PSAction = None DVIPSAction = None PSBuilder = None def generate(env): """Add Builders and construction variables for dvips to an Environment.""" global PSAction if PSAction is None: PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR') global DVIPSAction if DVIPSAction is None: DVIPSAction = SCons.Action.Action(DviPsFunction, strfunction = DviPsStrFunction) global PSBuilder if PSBuilder is None: PSBuilder = SCons.Builder.Builder(action = PSAction, prefix = '$PSPREFIX', suffix = '$PSSUFFIX', src_suffix = '.dvi', src_builder = 'DVI', single_source=True) env['BUILDERS']['PostScript'] = PSBuilder env['DVIPS'] = 'dvips' env['DVIPSFLAGS'] = SCons.Util.CLVar('') # I'm not quite sure I got the directories and filenames right for variant_dir # We need to be in the correct directory for the sake of latex \includegraphics eps included files. env['PSCOM'] = 'cd ${TARGET.dir} && $DVIPS $DVIPSFLAGS -o ${TARGET.file} ${SOURCE.file}' env['PSPREFIX'] = '' env['PSSUFFIX'] = '.ps' def exists(env): return env.Detect('dvips') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
bsd-2-clause
wolffaxn/homebrew-core
Formula/velero.rb
1842
class Velero < Formula desc "Disaster recovery for Kubernetes resources and persistent volumes" homepage "https://github.com/heptio/velero" url "https://github.com/heptio/velero/archive/v1.1.0.tar.gz" sha256 "9313f059c9c973052fba4b307e652b1067b8542302277af1f610415e79cb32c0" bottle do cellar :any_skip_relocation sha256 "e4684ab704c35f8ee7f9843f2f106f693f87d7671864f9a20859c392b844adc7" => :catalina sha256 "713560c7ada1422f49cf04e4146e3afa483e5f00b50a67fcc4c7180e7018c394" => :mojave sha256 "74e077b085c10713f22c09fdc592ef6dce9e13a6a87a3d83b02ca9f66f1557c1" => :high_sierra sha256 "36bce9094dac8e3dd1ed7d108dea0237f90f101ff158ae7279a53907258e5ed0" => :sierra end depends_on "go" => :build def install ENV["GOPATH"] = buildpath dir = buildpath/"src/github.com/heptio/velero" dir.install buildpath.children - [buildpath/".brew_home"] cd dir do system "go", "build", "-o", bin/"velero", "-installsuffix", "static", "-ldflags", "-X github.com/heptio/velero/pkg/buildinfo.Version=v#{version}", "./cmd/velero" # Install bash completion output = Utils.popen_read("#{bin}/velero completion bash") (bash_completion/"velero").write output # Install zsh completion output = Utils.popen_read("#{bin}/velero completion zsh") (zsh_completion/"_velero").write output prefix.install_metafiles end end test do output = shell_output("#{bin}/velero 2>&1") assert_match "Velero is a tool for managing disaster recovery", output assert_match "Version: v#{version}", shell_output("#{bin}/velero version --client-only 2>&1") system bin/"velero", "client", "config", "set", "TEST=value" assert_match "value", shell_output("#{bin}/velero client config get 2>&1") end end
bsd-2-clause
DomT4/homebrew-versions
thrift090.rb
3060
# The 0.9.0 tag in homebrew repository isn't working in OSX Mavericks # this version fixes Cpp11 problems about syntax and tr1 headers # All patches and this file can be found in this public gist: # https://gist.githubusercontent.com/rafaelverger/58b6eeafaae7d28b06cc class Thrift090 < Formula desc "Framework for scalable cross-language services development" homepage "https://thrift.apache.org" url "https://archive.apache.org/dist/thrift/0.9.0/thrift-0.9.0.tar.gz" sha256 "71d129c49a2616069d9e7a93268cdba59518f77b3c41e763e09537cb3f3f0aac" bottle do cellar :any revision 1 sha256 "f655ec1f7bfec1b92b805394bee8495f5fb169ae46a0a7f3fec15d367983acba" => :el_capitan sha256 "ae37814213b3f3c6089784c26a008dd9159005fa1cd1625c169e45b57bf97d16" => :yosemite sha256 "dc59998ede12cd4dd30bbaf9689b17bc12f44f2e9a198e1e55e91305e55e5678" => :mavericks end # These patches are 0.9.0-specific and can go away once a newer version is release [ # patch-tsocket.patch %w[a1dc9e54ffacf04c6ba6d1e37b734684ff09d149a88ca7425a4237267f674829 tsocket.patch], # patch-cxx11-compat.patch %w[74fd5282f159bf4d7ee5ca977b36534e2182709fe4c17cc5907c6bd615cfe0ef cxx11-compat.patch], # patch-use-boost-cpp-client-server.patch %w[2ea5a69c5358a56ef945d4fb127c11a7797afc751743b20f58dfff0955a68117 use-boost-cpp-client-server.patch], # patch-remove-tr1-dependency.patch %w[c4419ce40b7fda9ffd58a5dad7856b64ee84e3c1b820f3a64fed0b01b4bc9c42 remove-tr1-dependency.patch], ].each do |sha, patch| patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/dee880b1baba827255f7b0806ca32d36c4d1c2ca/thrift/0.9.0/#{patch}" sha256 sha end end option "with-haskell", "Install Haskell binding" option "with-erlang", "Install Erlang binding" option "with-java", "Install Java binding" option "with-perl", "Install Perl binding" option "with-php", "Install Php binding" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "openssl" depends_on python: :optional def install args = ["--without-ruby", "--without-tests", "--without-php_extension"] args << "--without-python" if build.without? "python" args << "--without-haskell" if build.without? "haskell" args << "--without-java" if build.without? "java" args << "--without-perl" if build.without? "perl" args << "--without-php" if build.without? "php" args << "--without-erlang" if build.without? "erlang" ENV.cxx11 if MacOS.version >= :mavericks && ENV.compiler == :clang # Don't install extensions to /usr: ENV["PY_PREFIX"] = prefix ENV["PHP_PREFIX"] = prefix system "./configure", "--disable-debug", "--prefix=#{prefix}", "--libdir=#{lib}", *args ENV.j1 system "make", "install" end test do assert_match /Thrift/, shell_output("#{bin}/thrift --version", 1) end end
bsd-2-clause
gaker/tank-maven
tank_maven/models.py
1737
""" Models """ import bcrypt import os from sqlalchemy import ( Column, String, DateTime, Boolean, Integer, Text, ForeignKey) from sqlalchemy.ext.declarative import declarative_base from sqlite3 import dbapi2 as sqlite from tornado import options Base = declarative_base() class User(Base): """ User object """ __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(30), nullable=False) email = Column(String(255), nullable=False) password = Column(String(60), nullable=False) def __repr__(self): return "<User('{0}')>".format(self.username) def set_password(self, password): self.password = bcrypt.hashpw(password, bcrypt.gensalt()) class Configuration(Base): """ Configuration object """ __tablename__ = 'configuration' id = Column(Integer, primary_key=True) name = Column(String(30), nullable=False) value = Column(Text, nullable=False, default={}) def __repr__(self): return "<Configuration('{0}')>".format(self.name) class InputType(Base): """ Input types. """ __tablename__ = 'input_types' id = Column(Integer, primary_key=True) name = Column(String(30), nullable=False) def __repr__(self): return "<InputType('{0}')>".format(self.name) class Input(Base): """ Analog Input Model """ __tablename__ = 'input' id = Column(Integer, primary_key=True) pin_id = Column(Integer, nullable=True) address_id = Column(Integer, nullable=True) probe_type = ForeignKey(InputType.id) label = Column(String(30)) def __repr__(self): return "<Input('{0}: {1}')>".format( self.pin_id, self.probe_type)
bsd-2-clause
msklywenn/bitbox
tools/tracker/src/guibutton.cpp
300
#include "guibutton.h" GUIButton::GUIButton(int x, int y, int w, int h, Action * a) : GUIElement(x, y, w, h), action(a) { } bool GUIButton::process(SDL_Event * event) { if ( event->type == SDL_MOUSEBUTTONDOWN && test(event->button.x, event->button.y) ) { action->job(); } return false; }
bsd-2-clause
dreamsxin/ultimatepp
bazaar/OCETest/MakeBottle.cpp
6614
#include "MakeBottle.h" #include <BRep_Tool.hxx> #include <BRepAlgoAPI_Fuse.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <BRepBuilderAPI_Transform.hxx> #include <BRepFilletAPI_MakeFillet.hxx> #include <BRepLib.hxx> #include <BRepOffsetAPI_MakeThickSolid.hxx> #include <BRepOffsetAPI_ThruSections.hxx> #include <BRepPrimAPI_MakeCylinder.hxx> #include <BRepPrimAPI_MakePrism.hxx> #include <GC_MakeArcOfCircle.hxx> #include <GC_MakeSegment.hxx> #include <GCE2d_MakeSegment.hxx> #include <gp.hxx> #include <gp_Ax1.hxx> #include <gp_Ax2.hxx> #include <gp_Ax2d.hxx> #include <gp_Dir.hxx> #include <gp_Dir2d.hxx> #include <gp_Pnt.hxx> #include <gp_Pnt2d.hxx> #include <gp_Trsf.hxx> #include <gp_Vec.hxx> #include <Geom_CylindricalSurface.hxx> #include <Geom_Plane.hxx> #include <Geom_Surface.hxx> #include <Geom_TrimmedCurve.hxx> #include <Geom2d_Ellipse.hxx> #include <Geom2d_TrimmedCurve.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Wire.hxx> #include <TopoDS_Compound.hxx> #include <TopTools_ListOfShape.hxx> TopoDS_Shape MakeBottle(const Standard_Real myWidth, const Standard_Real myHeight, const Standard_Real myThickness) { //Profile : Define Support Points gp_Pnt aPnt1(-myWidth / 2. , 0 , 0); gp_Pnt aPnt2(-myWidth / 2. , -myThickness / 4. , 0); gp_Pnt aPnt3(0 , -myThickness / 2. , 0); gp_Pnt aPnt4(myWidth / 2. , -myThickness / 4. , 0); gp_Pnt aPnt5(myWidth / 2. , 0 , 0); //Profile : Define the Geometry Handle(Geom_TrimmedCurve) aArcOfCircle = GC_MakeArcOfCircle(aPnt2,aPnt3 ,aPnt4); Handle(Geom_TrimmedCurve) aSegment1 = GC_MakeSegment(aPnt1 , aPnt2); Handle(Geom_TrimmedCurve) aSegment2 = GC_MakeSegment(aPnt4 , aPnt5); //Profile : Define the Topology TopoDS_Edge aEdge1 = BRepBuilderAPI_MakeEdge(aSegment1); TopoDS_Edge aEdge2 = BRepBuilderAPI_MakeEdge(aArcOfCircle); TopoDS_Edge aEdge3 = BRepBuilderAPI_MakeEdge(aSegment2); TopoDS_Wire aWire = BRepBuilderAPI_MakeWire(aEdge1 , aEdge2 , aEdge3); //Complete Profile gp_Ax1 xAxis = gp::OX(); gp_Trsf aTrsf; aTrsf.SetMirror(xAxis); BRepBuilderAPI_Transform aBRepTrsf(aWire , aTrsf); TopoDS_Shape aMirroredShape = aBRepTrsf.Shape(); TopoDS_Wire aMirroredWire = TopoDS::Wire(aMirroredShape); BRepBuilderAPI_MakeWire mkWire; mkWire.Add(aWire); mkWire.Add(aMirroredWire); TopoDS_Wire myWireProfile = mkWire.Wire(); //Body : Prism the Profile TopoDS_Face myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile); gp_Vec aPrismVec(0 , 0 , myHeight); TopoDS_Shape myBody = BRepPrimAPI_MakePrism(myFaceProfile , aPrismVec); //Body : Apply Fillets BRepFilletAPI_MakeFillet mkFillet(myBody); TopExp_Explorer aEdgeExplorer(myBody , TopAbs_EDGE); while(aEdgeExplorer.More()){ TopoDS_Edge aEdge = TopoDS::Edge(aEdgeExplorer.Current()); //Add edge to fillet algorithm mkFillet.Add(myThickness / 12. , aEdge); aEdgeExplorer.Next(); } myBody = mkFillet.Shape(); //Body : Add the Neck gp_Pnt neckLocation(0 , 0 , myHeight); gp_Dir neckNormal = gp::DZ(); gp_Ax2 neckAx2(neckLocation , neckNormal); Standard_Real myNeckRadius = myThickness / 4.; Standard_Real myNeckHeight = myHeight / 10; BRepPrimAPI_MakeCylinder MKCylinder(neckAx2 , myNeckRadius , myNeckHeight); TopoDS_Shape myNeck = MKCylinder.Shape(); myBody = BRepAlgoAPI_Fuse(myBody , myNeck); //Body : Create a Hollowed Solid TopoDS_Face faceToRemove; Standard_Real zMax = -1; for(TopExp_Explorer aFaceExplorer(myBody , TopAbs_FACE) ; aFaceExplorer.More() ; aFaceExplorer.Next()){ TopoDS_Face aFace = TopoDS::Face(aFaceExplorer.Current()); //Check if <aFace> is the top face of the bottle's neck Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace); if(aSurface->DynamicType() == STANDARD_TYPE(Geom_Plane)){ Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(aSurface); gp_Pnt aPnt = aPlane->Location(); Standard_Real aZ = aPnt.Z(); if(aZ > zMax){ zMax = aZ; faceToRemove = aFace; } } } TopTools_ListOfShape facesToRemove; facesToRemove.Append(faceToRemove); myBody = BRepOffsetAPI_MakeThickSolid(myBody , facesToRemove , -myThickness / 50 , 1.e-3); //return myBody; //Threading : Create Surfaces Handle(Geom_CylindricalSurface) aCyl1 = new Geom_CylindricalSurface(neckAx2 , myNeckRadius * 0.99); Handle(Geom_CylindricalSurface) aCyl2 = new Geom_CylindricalSurface(neckAx2 , myNeckRadius * 1.05); //Threading : Define 2D Curves gp_Pnt2d aPnt(2. * M_PI , myNeckHeight / 2.); gp_Dir2d aDir(2. * M_PI , myNeckHeight / 4.); gp_Ax2d aAx2d(aPnt , aDir); Standard_Real aMajor = 2. * M_PI; Standard_Real aMinor = myNeckHeight / 10; Handle(Geom2d_Ellipse) anEllipse1 = new Geom2d_Ellipse(aAx2d , aMajor , aMinor); Handle(Geom2d_Ellipse) anEllipse2 = new Geom2d_Ellipse(aAx2d , aMajor , aMinor / 4); Handle(Geom2d_TrimmedCurve) aArc1 = new Geom2d_TrimmedCurve(anEllipse1 , 0 , M_PI); Handle(Geom2d_TrimmedCurve) aArc2 = new Geom2d_TrimmedCurve(anEllipse2 , 0 , M_PI); gp_Pnt2d anEllipsePnt1 = anEllipse1->Value(0); gp_Pnt2d anEllipsePnt2 = anEllipse1->Value(M_PI); Handle(Geom2d_TrimmedCurve) aSegment = GCE2d_MakeSegment(anEllipsePnt1 , anEllipsePnt2); //Threading : Build Edges and Wires TopoDS_Edge aEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(aArc1 , aCyl1); TopoDS_Edge aEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment , aCyl1); TopoDS_Edge aEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(aArc2 , aCyl2); TopoDS_Edge aEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment , aCyl2); TopoDS_Wire threadingWire1 = BRepBuilderAPI_MakeWire(aEdge1OnSurf1 , aEdge2OnSurf1); TopoDS_Wire threadingWire2 = BRepBuilderAPI_MakeWire(aEdge1OnSurf2 , aEdge2OnSurf2); BRepLib::BuildCurves3d(threadingWire1); BRepLib::BuildCurves3d(threadingWire2); //Create Threading BRepOffsetAPI_ThruSections aTool(Standard_True); aTool.AddWire(threadingWire1); aTool.AddWire(threadingWire2); aTool.CheckCompatibility(Standard_False); TopoDS_Shape myThreading = aTool.Shape(); //Building the resulting compound TopoDS_Compound aRes; BRep_Builder aBuilder; aBuilder.MakeCompound (aRes); aBuilder.Add (aRes, myBody); aBuilder.Add (aRes, myThreading); return aRes; }
bsd-2-clause
reelsense/homebrew-core
Formula/vapoursynth.rb
1749
class Vapoursynth < Formula include Language::Python::Virtualenv desc "Video processing framework with simplicity in mind" homepage "http://www.vapoursynth.com" url "https://github.com/vapoursynth/vapoursynth/archive/R43.tar.gz" sha256 "5c80d583f6891f4f5840edf09bc207c2e71653786b07606fdb4a164fd67470c2" head "https://github.com/vapoursynth/vapoursynth.git" bottle do sha256 "088826830fbb58149afbb4c525815154b3c5865975851b500542ddb48dd711b0" => :high_sierra sha256 "2ec6479c2b942c53eaed6f47adce5e5427eafb8ef58be99672650d3a7cc8b109" => :sierra sha256 "7ebb4559feae7e6b7dcd479575d7127cdce2fb9edec62fcaf3087d3b646e2b7d" => :el_capitan end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "nasm" => :build depends_on "libass" depends_on :macos => :el_capitan # due to zimg dependency depends_on "python3" depends_on "tesseract" depends_on "zimg" resource "Cython" do url "https://files.pythonhosted.org/packages/ee/2a/c4d2cdd19c84c32d978d18e9355d1ba9982a383de87d0fcb5928553d37f4/Cython-0.27.3.tar.gz" sha256 "6a00512de1f2e3ce66ba35c5420babaef1fe2d9c43a8faab4080b0dbcc26bc64" end def install venv = virtualenv_create(buildpath/"cython", "python3") venv.pip_install "Cython" system "./autogen.sh" system "./configure", "--prefix=#{prefix}", "--with-cython=#{buildpath}/cython/bin/cython" system "make", "install" end test do py3 = Language::Python.major_minor_version "python3" ENV.prepend_path "PYTHONPATH", lib/"python#{py3}/site-packages" system "python3", "-c", "import vapoursynth" system bin/"vspipe", "--version" end end
bsd-2-clause
GeosoftInc/gxpy
geosoft/gxapi/GXNumpy.py
772
import geosoft.gxapi as gxa import numpy as np def gs_from_np(dtype): dtype = np.dtype(dtype) if dtype == np.byte: return gxa.GS_BYTE elif dtype == np.ubyte: return gxa.GS_UBYTE elif dtype == np.int16: return gxa.GS_SHORT elif dtype == np.uint16: return gxa.GS_USHORT elif dtype == np.int32: return gxa.GS_LONG elif dtype == np.uint32: return gxa.GS_ULONG elif dtype == np.int64: return gxa.GS_LONG64 elif dtype == np.uint64: return gxa.GS_ULONG64 elif dtype == np.float32: return gxa.GS_FLOAT elif dtype == np.float64: return gxa.GS_DOUBLE else: raise gxa.GXAPIError("Numpy array type does not map to one of the supported GS_TYPES");
bsd-2-clause
expipiplus1/joelang
include/joelang/inl/state-inl.hpp
3119
/* Copyright 2012 Joe Hermaszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #pragma once #include <joelang/state.hpp> #include <functional> #include <map> #include <string> #include <utility> #include <vector> #include <joelang/types.hpp> namespace JoeLang { template<typename T> void DefaultStateSetCallback( T value ) { } template<typename T> State<T>::State( std::string name, EnumerantMap enumerations ) :StateBase( std::move(name), std::move(enumerations) ) ,m_SetCallback( DefaultStateSetCallback<T> ) ,m_ResetCallback( DefaultStateResetCallback ) ,m_ValidateCallback( DefaultStateValidateCallback ) { } template<typename T> void State<T>::SetCallbacks( std::function<void(T)> set_callback, std::function<void()> reset_callback, std::function<bool()> validate_callback ) { m_SetCallback = set_callback ? set_callback : DefaultStateSetCallback<T>; m_ResetCallback = reset_callback ? reset_callback : DefaultStateResetCallback; m_ValidateCallback = validate_callback ? validate_callback : DefaultStateValidateCallback; } template<typename T> void State<T>::SetState( T value ) const { m_SetCallback( value ); } template<typename T> void State<T>::ResetState() const { m_ResetCallback(); } template<typename T> bool State<T>::ValidateState() const { return m_ValidateCallback(); } template<typename T> Type State<T>::GetType() const { return JoeLangType<T>::value; } } // namespace JoeLang
bsd-2-clause
phdabel/MASBench
src/br/ufrgs/MASBench/BinaryMaxSum/Factor/SingleWeightFactor.java
3832
/* * Software License Agreement (BSD License) * * Copyright 2014 Marc Pujol <mpujol@iiia.csic.es>. * * Redistribution and use of this software in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of IIIA-CSIC, Artificial Intelligence Research Institute * nor the names of its contributors may be used to * endorse or promote products derived from this * software without specific prior written permission of * IIIA-CSIC, Artificial Intelligence Research Institute * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package br.ufrgs.MASBench.BinaryMaxSum.Factor; import java.util.Map; import br.ufrgs.MASBench.BinaryMaxSum.BMS.Factor; /** * Factor that composes (sums) an independent cost/utility for each neighbor with some * other <em>inner</em> (non-independent) factor. * <br> * The resulting complexity is the same as that of the inner factor. * * @author Toni Penya-Alba {@literal (tonipenya @ iiia.csic.es)} * @param <T> Type of the factor's identity. */ public class SingleWeightFactor<T> extends ProxyFactor<T> { private double potential = 0d; /** * Build a new weighting factor with the specified inner factor. * * @param innerFactor inner factor to compose (sum) with the per-neighbor weights. */ public SingleWeightFactor(Factor<T> innerFactor) { super(innerFactor); } @Override public double getMessage(T neighbor) { return super.getMessage(neighbor) - getPotential(); } /** * Get the cost/utility of activating a variable. * * @return cost of activating */ public double getPotential() { return potential; } /** * Set the independent cost of activating a variable. * * @param newPotential cost/utility of activating a variable */ public void setPotential(double newPotential) { for (T neighbor: getNeighbors()) { double originalMessage = getMessage(neighbor); super.receive(originalMessage + newPotential, neighbor); } potential = newPotential; } @Override public double evaluate(Map<T, Boolean> values) { double value = super.evaluate(values); for (T neighbor : getNeighbors()) { if (values.get(neighbor)) { value += potential; } } return value; } @Override public void receive(double message, T sender) { super.receive(message + potential, sender); } @Override public void send(double message, T recipient) { super.send(message + potential, recipient); } }
bsd-2-clause
dante1977/dtjs
index.js
4885
'use strict' module.exports = require('./lib/dtjs'); // //var dtjs = require('./lib/dtjs.js'); //var path = require('path'); //var fs = require('fs'); // ///** // * @namespace dtjs // */ //var index = module.exports = {}; // ///** // * 对应命令的处理 // * @type {{build: *}} // */ //index.cmd = { // build: require('./lib/cmd/build.js'), // output: require('./lib/cmd/output.js'), // widget: require('./lib/cmd/widget.js'), // project: require('./lib/cmd/project.js') //}; // ///** // * 命令的缩写 // * @type {{b: string, o: string, i: string, w: string}} // */ //var cmdAliases = { // i: 'install', //输出的文件目录 // lr: 'livereload', // w: 'watch', // v: 'version', // h: 'help', // //c: 'config', // m: 'media' //}; // //var cmdValue = { // build: 'media', // output: 'media' //}; // //var cmdVarExpr = /(-+)(\w+)/g; // ///** // * 开始运行 // */ //index.run = function (argv) { // //解析参数 // var argvRaw = argv; // argv = parseArgv(argv); // // //版本 // if (argv.version) { // version(); // return; // } // //帮助 // if (argv.help) { // help(); // return; // } // // //清除 // if (argv.clear) { // clear(); // return; // } // // process.on('uncaughtException', function (err) { // console.log(err); // }); // //console.log(argv); // //return ; // // // // dtjs.set('options', argv); // // //生成后台文件目录 // var dirObj = bgMkdir(argv); // //设置参数,路径行 // dtjs.set('project', dirObj); // // //加载配置文件 // var configName = argv.config || 'dtjs.config.js', // configPath = path.join(dirObj.realPath, configName); // // dtjs.set('project.configName', configName); // // try { // require(configPath); // dtjs.emit('config:loaded'); // } catch (e) { // dtjs.log.warn('load config error [%s]', e.message); // } // // var cmd = index.cmd[argv.command]; // if (!cmd) { // dtjs.log.error('invalid commend [%s]', argv.command); // } // dtjs.log.info('Currently running dtjs %s', argv.command); // //dtjs.log.timer(); // cmd.run(argv); // //console.log(dtjs.config); //}; // ///** // * 生成后台文件目录 // */ //function bgMkdir(argv) { // var tempDir = ''; // ['LOCALAPPDATA', 'HOME', 'APPDATA'].every(function (temp) { // if (tempDir = process.env[temp]) { // return false; // } // return true; // }); // tempDir = tempDir || (__dirname + '/..'); // // var realPath = path.resolve('.'); // // var bgProjectPath = ''; // var projectName = dtjs.$.md5(realPath); // var bgTmpPath = path.join(tempDir, '.dtjs-temp/temp', projectName); // // if (argv.command === 'output') { // bgProjectPath = path.join(realPath, dtjs.get('project.outputDir')); // } else { // bgProjectPath = path.join(tempDir, '.dtjs-temp/project', projectName); // } // // [bgTmpPath].forEach(function (dir) { // dtjs.$.mkdir(dir); // }); // // return { // bgTmpPath: bgTmpPath, // realPath: realPath, // realTargetPath: bgProjectPath // } //} // ///** // * 输出本版信息 // */ //function version() { // var ver = require('./package.json').version; // dtjs.log.info('dtjs version %s', ver); // return ver; //}; // ///** // * 帮助 // */ //function help() { // dtjs.log.info([ // ' Usage: dtjs <Command>', // '', // ' Command:', // '', // ' Options:', // '' // ].join('\r\n')); //}; // // ///** // * 解析参数 // * @param argv // */ //function parseArgv(argv) { // var argvJson = {}; // if (!argv) { // return argvJson; // } // // argvJson.command = index.cmd[argv[2]] ? argv[2] : 'build'; // //if (cmdAliases[argvJson.command]) { // // argvJson.command = cmdAliases[argvJson.command]; // //} // // if(argvJson.command == 'build') { // argvJson.watch = true; // argvJson.livereload = true; // } // // // // var key = '', // value = ''; // argv = argv.slice(2, argv.length); // // argv.forEach(function (arg, index) { // if(cmdVarExpr.test(arg)) { // arg.replace(cmdVarExpr, function(mch, $1, $2) { // if($1.length == 1) { // $2 = cmdAliases[$2]; // } // argvJson[$2] = true; // }); // } else { // argvJson[cmdValue[argvJson.command]] = arg; // } // /* // if (arg.charAt(0) === '-') { // key = arg.substr(1, arg.length); // key = cmdAliases[key] ? cmdAliases[key] : key; // argvJson[key] = true; // } else if (key) { // if (argvJson[key] !== true) { // if (typeof argvJson[key] === 'string') { // argvJson[key] = [argvJson[key], arg]; // } else { // argvJson[key].push(arg); // } // } else { // argvJson[key] = arg; // } // } // */ // }); // return argvJson; //}; // ///** // * 清除 // */ //function clear() { // dtjs.log.info('Currently running dtjs clear'); //} // ////exprots //index.version = version;
bsd-2-clause
stefan-loewe/Woody
source/ws/loewe/Woody/System/WindowConstraints.php
2316
<?php namespace ws\loewe\Woody\System; use \ws\loewe\Utils\Geom\Dimension; class WindowConstraints { /** * the lowest width that is possible for a window on the current machine, with the current display settings * * @var int */ private $minWidth = null; /** * the lowest height that is possible for a window on the current machine, with the current display settings * * @var int */ private $minHeight = null; /** * the instance that this singleton encapsulates * * @var ws\loewe\Woody\System\WindowConstraints */ private static $instance = null; /** * a winbinder window handle to derive the constraints * * @var int */ private $window = null; /** * This method acts as the constructor of the class. */ private function __construct() { $this->window = wb_create_window( NULL, AppWindow, 'initializing ...', WBC_CENTER, WBC_CENTER, 0, 0, WBC_INVISIBLE ); $this->determineMinima(); wb_destroy_window($this->window); } /** * This method returns the sole instance of this class. * * @return ws\loewe\Woody\System\WindowConstraints the sole instance of this class */ public static function getInstance() { if(self::$instance === null) { self::$instance = new WindowConstraints(); } return self::$instance; } /** * This method calculates and sets the minimal width and height a window may have with the current display settings. * * @return ws\loewe\Woody\System\WindowConstraints $this */ private function determineMinima() { wb_set_size($this->window, 0, 0); $dimension = wb_get_size($this->window); $this->minWidth = $dimension[0]; $this->minHeight = $dimension[1]; return $this; } /** * This method enforces the contraints on the given dimension, and mutates it accordingly. * * @param Dimension $dimension the dimension to enforce the contraints on * @return ws\loewe\Utils\Geom\Dimension the dimension with the contraints enforced */ public function enforceConstraints(Dimension $dimension) { $width = max($this->minWidth, $dimension->width); $height = max($this->minHeight, $dimension->height); return Dimension::createInstance($width, $height); } }
bsd-2-clause
spartango/EMExperiments
src/edu/harvard/mcb/leschziner/core/ParticleSource.java
429
package edu.harvard.mcb.leschziner.core; import java.util.concurrent.BlockingQueue; /** * Generates particles to be processed by consumers * * @author spartango * */ public interface ParticleSource { /** * Get the queue in which particles that are built can be found * * @return the particle queue from which the consumer should take */ public BlockingQueue<Particle> getParticleQueue(); }
bsd-2-clause
Priyaaks/libDAI_P
examples/3NodeBN1_createfg.cpp
2650
/* This file is part of libDAI - http://www.libdai.org/ * * Copyright (c) 2006-2011, The libDAI authors. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <dai/factorgraph.h> #include <iostream> #include <fstream> using namespace std; using namespace dai; int main() { // This example program illustrates how to construct a factorgraph // by means of the sprinkler network example discussed at // http://www.cs.ubc.ca/~murphyk/Bayes/bnintro.html Var C(0, 2); // Define binary variable Cloudy (with label 0) Var S(1, 2); // Define binary variable Sprinkler (with label 1) Var D(2, 2); // Define binary variable Sprinkler (with label 2) // Define probability distribution for C Factor P_C( C ); P_C.set(0, 0.5); // C = 0 P_C.set(1, 0.5); // C = 1 // Define conditional probability of S given C Factor P_S_given_C( VarSet( S, C ) ); P_S_given_C.set(0, 0.5); // C = 0, S = 0 P_S_given_C.set(1, 0.9); // C = 1, S = 0 P_S_given_C.set(2, 0.5); // C = 0, S = 1 P_S_given_C.set(3, 0.1); // C = 1, S = 1 // Define conditional probability of D given S Factor P_D_given_S( VarSet( D, S ) ); P_D_given_S.set(0, 0.3); // S = 0, D = 0 P_D_given_S.set(1, 0.9); // S = 1, D = 0 P_D_given_S.set(2, 0.7); // S = 0, D = 1 P_D_given_S.set(3, 0.1); // S = 1, D = 1 // Build factor graph consisting of those four factors vector<Factor> SprinklerFactors; SprinklerFactors.push_back( P_C ); SprinklerFactors.push_back( P_S_given_C ); SprinklerFactors.push_back( P_D_given_S ); FactorGraph SprinklerNetwork( SprinklerFactors ); // Write factorgraph to a file SprinklerNetwork.WriteToFile( "3NodeBN1.fg" ); cout << "Sprinkler network written to 3NodeBN1.fg" << endl; // Output some information about the factorgraph cout << SprinklerNetwork.nrVars() << " variables" << endl; cout << SprinklerNetwork.nrFactors() << " factors" << endl; // Calculate joint probability of all four variables Factor P; for( size_t I = 0; I < SprinklerNetwork.nrFactors(); I++ ) P *= SprinklerNetwork.factor( I ); // P.normalize(); // Not necessary: a Bayesian network is already normalized by definition // Calculate some probabilities /*Real denom = P.marginal( W )[1]; cout << "P(W=1) = " << denom << endl; cout << "P(S=1 | W=1) = " << P.marginal( VarSet( S, W ) )[3] / denom << endl; cout << "P(R=1 | W=1) = " << P.marginal( VarSet( R, W ) )[3] / denom << endl; */ return 0; }
bsd-2-clause
cirlabs/concealed-carry
app/scripts/main.js
4297
// jshint devel:true 'use strict'; var touch; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { touch = true; var wrapper = document.getElementById('interactive-wrapper'); wrapper.className += ' touch-device'; } function circleTooltip(circle) { var $this = circle; var lawsuit = $this.data('lawsuit'); var court = $this.data('court'); var decision = $this.data('decision'); var tooltip = $('.map-tooltip'); var html = '<span class="close">close</span><span class="label">Lawsuit</span><table><tr><td>Case</td><td>' + lawsuit + '</td></tr><tr><td>Court</td><td>' + court + '</td></tr><tr><td>Decided</td><td>' + decision + '</td></tr></table>'; tooltip.addClass('lawsuit').css('display', 'block'); tooltip.find('.tooltip-inner').each(function(){ $(this).html(html); }); } /* For concealed carry map only */ function initAccordion(){ $('.filter-title').click(function(){ var $parent = $(this).closest('.filter'); var siblings = $parent.siblings(); siblings.removeClass('filtered'); siblings.find('.filter-description').each(function(){ $(this).slideUp('fast'); }); $parent.toggleClass('filtered'); $parent.find('.filter-description').each(function(){ $(this).slideToggle('fast'); }); var id = parseInt( $parent.attr('id').replace('filter-', '') ); var map = $('#interactive-wrapper'); var clear = $('.clear-filter'); if ($parent.hasClass('filtered')){ map.attr('data-filter', id); clear.css('visibility', 'visible'); } else { map.attr('data-filter', ''); clear.css('visibility', 'hidden'); } }); $('.clear-filter').click(function(){ $('.filtered').find('.filter-title').trigger('click'); }).keydown(function(e){ var code = e.which; // 13 = Return, 32 = Space if ((code === 13) || (code === 32)) { $(this).trigger('click'); } }); $('.filter').keydown(function(e){ // Trigger the click event from the keyboard var code = e.which; // 13 = Return, 32 = Space if ((code === 13) || (code === 32)) { $(this).find('.filter-title').trigger('click'); } }); if (!touch){ $('.cir-map-state').click(function(){ var $this = $(this); var group = parseInt( $this.data('color') ) + 1; var filter = $('.filter:nth-child(' + group + ')'); if ( !filter.hasClass('filtered') ) { filter.find('.filter-title').trigger('click'); } }); $('.cir-map-state').keydown(function(e){ // Trigger the click event from the keyboard var code = e.which; // 13 = Return, 32 = Space if ((code === 13) || (code === 32)) { $(this).trigger('click'); } }); } if (!touch){ $('#us-map circle').hover(function(){ var $this = $(this); circleTooltip($this); }, function() { $('.map-tooltip').removeClass('lawsuit').css('display', 'none'); }); $('#us-map circle').focus(function(){ var $this = $(this); circleTooltip($this); $('.map-tooltip').css({ 'left':'30%', 'top':'-50px' }); }); $('#us-map circle').blur(function(){ $('.map-tooltip').css('display', 'none'); }); } else { $('#us-map circle').click(function(){ var $this = $(this); circleTooltip($this); }); $('path').click(function(){ var $this = $(this); var circles = $('#us-map circle'); $this.closest('svg').append(circles); }); $(document).mouseup(function (e){ var tooltip = $('.map-tooltip'); if (!tooltip.is(e.target) && tooltip.has(e.target).length === 0) { tooltip.hide(); } if ($(e.target).hasClass('close')){ tooltip.hide(); } }); } } var lastFocusedElement = null; var isClick = false; if (!touch){ $('#us-map *').mousedown(function() { isClick= true; }).focus(function(e){ var tooltip = $('.map-tooltip'); // To prevent focus firing when element already had focus if (lastFocusedElement !== e.target) { if (isClick) { tooltip.addClass('hide'); } else { tooltip.removeClass('hide'); } lastFocusedElement = e.target; isClick = false; } }).mousemove(function(){ var tooltip = $('.map-tooltip'); tooltip.removeClass('hide'); }); } $(document.body).focus(function(){ lastFocusedElement = document.body; }); $(document).ready(function(){ initAccordion(); });
bsd-2-clause
andreasprlic/karyotypeSVG
js/kt/util.js
8367
/*jshint unused: false */ define(function (require) { var exports = {}; var attr_name_cache = {}; var pako = require('pako'); var NS_SVG = 'http://www.w3.org/2000/svg'; exports.indexOf = function (needle) { var indexOf; if (typeof Array.prototype.indexOf === 'function') { indexOf = Array.prototype.indexOf; } else { indexOf = function (needle) { var i = -1, index = -1; for (i = 0; i < this.length; i++) { if (this[i] === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle); }; exports.endsWith = function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }; exports.isNumber = function (n) { return !isNaN(parseFloat(n)) && isFinite(n); }; var reA = /[^a-zA-Z]/g; var reN = /[^0-9]/g; exports.sortAlphaNum = function (a, b) { var aA = a.replace(reA, ""); var bA = b.replace(reA, ""); if (aA === bA) { var aN = parseInt(a.replace(reN, ""), 10); var bN = parseInt(b.replace(reN, ""), 10); return aN === bN ? 0 : aN > bN ? 1 : -1; } else { return aA > bA ? 1 : -1; } }; exports.setAttr = function (node, key, value) { var attr = attr_name_cache[key]; if (!attr) { var _attr = ''; for (var c = 0; c < key.length; ++c) { var cc = key.substring(c, c + 1); var lcc = cc.toLowerCase(); if (lcc !== cc) { _attr = _attr + '-' + lcc; } else { _attr = _attr + cc; } } attr_name_cache[key] = _attr; attr = _attr; } node.setAttribute(attr, value); }; exports.setAttrs = function (node, attribs) { if (attribs) { for (var l in attribs) { if (attribs.hasOwnProperty(l)) { this.setAttr(node, l, attribs[l]); } } } }; exports.makeElement = function (tag, children, attribs, styles) { var ele = document.createElement(tag); if (children) { if (!(children instanceof Array)) { children = [children]; } for (var i = 0; i < children.length; ++i) { var c = children[i]; if (c) { if (typeof c === 'string') { c = document.createTextNode(c); } else if (typeof c === 'number') { c = document.createTextNode('' + c); } ele.appendChild(c); } } } if (attribs) { for (var l in attribs) { if (attribs.hasOwnProperty(l)) { ele[l] = attribs[l]; } } } if (styles) { for (var s in styles) { if (styles.hasOwnProperty(s)) { ele.style[s] = styles[s]; } } } return ele; }; exports.makeElementNS = function (namespace, tag, children, attribs) { var ele = document.createElementNS(namespace, tag); if (children) { if (!(children instanceof Array)) { children = [children]; } for (var i = 0; i < children.length; ++i) { var c = children[i]; if (typeof c === 'string') { c = document.createTextNode(c); } ele.appendChild(c); } } this.setAttrs(ele, attribs); return ele; }; exports.removeChildren = function (node) { if (!node || !node.childNodes) { return; } while (node.childNodes.length > 0) { node.removeChild(node.firstChild); } }; var timer = null; exports.makeTooltip = function (ele, text, popupHolder) { var isin = false; var thisB = this; var outlistener; outlistener = function (ev) { isin = false; if (timer) { clearTimeout(timer); timer = null; } ele.removeEventListener('mouseout', outlistener, false); }; var setup; setup = function (ev) { var mx = ev.clientX + window.scrollX, my = ev.clientY + window.scrollY; if (!timer) { var that = this; timer = setTimeout(function () { var popup = exports.makeElement('div', text, {}, { position: 'absolute', top: '' + (my + 20) + 'px', left: '' + Math.max(mx - 30, 20) + 'px', backgroundColor: 'white', borderWidth: '1px', borderColor: 'black', borderStyle: 'solid', padding: '2px', maxWidth: '400px' }); popupHolder.appendChild(popup); var moveHandler; moveHandler = function (ev) { try { popupHolder.removeChild(popup); } catch (e) { // May have been removed by other code which clears the popup layer. } window.removeEventListener('mousemove', moveHandler, false); if (isin) { if (ele.offsetParent === null) { // dlog('Null parent...'); } else { setup(ev); } } }; window.addEventListener('mousemove', moveHandler, false); timer = null; }, 200); } }; ele.addEventListener('mouseover', function (ev) { isin = true; ele.addEventListener('mouseout', outlistener, false); setup(ev); }, false); ele.addEventListener('DOMNodeRemovedFromDocument', function (ev) { isin = false; if (timer) { clearTimeout(timer); timer = null; } }, false); }; exports.createText = function(text,x,y){ var newText = document.createElementNS(NS_SVG,"text"); newText.setAttributeNS(null,"x",x); newText.setAttributeNS(null,"y",y); return newText; }; exports.getTextNodeWidth = function (textNode) { var width = 0; var range, rect; if (document.createRange) { range = document.createRange(); if (range.getBoundingClientRect) { range.selectNodeContents(textNode); rect = range.getBoundingClientRect(); console.log(rect); if (rect) { width = rect.right - rect.left; } } } return width; }; exports.gzipSuccessFunction = function (result) { try { // we need to convert the response to binary var bytes = []; for (var i = 0; i < result.length; ++i) { bytes.push(result.charCodeAt(i)); } var binData = new Uint8Array(bytes); // now we use the pako library to uncompress the binary response var pdata = pako.inflate(binData); // and convert the uncompressed data back to string var data = String.fromCharCode.apply(null, new Uint16Array(pdata)); return data; } catch (err) { console.log(err); // probably conent is already uncompressed return result; } }; return exports; });
bsd-2-clause
MG-RAST/golib
pool/examples/web_crawler.go
2761
// Exercise: Web Crawler - http://tour.golang.org/#70 // modified to use the worker pool package main import ( "fmt" "github.com/stefantalpalaru/pool" "runtime" ) type Fetcher interface { // Fetch returns the body of URL and // a slice of URLs found on that page. Fetch(url string) (body string, urls []string, err error) } type crawlResult struct { body string urls []string err error } // work uses fetcher to recursively crawl // pages starting with url, to a maximum of depth. func work(args ...interface{}) interface{} { url := args[0].(string) depth := args[1].(int) fetcher := args[2].(Fetcher) if depth <= 0 { return crawlResult{} } body, urls, err := fetcher.Fetch(url) return crawlResult{body, urls, err} } func url_already_processed(urls []string, u string) bool { for _, url := range urls { if url == u { return true } } return false } var mypool = pool.New(6) // number of workers func main() { cpus := runtime.NumCPU() runtime.GOMAXPROCS(cpus) mypool.Run() first_url := "http://golang.org/" seen_urls := []string{first_url} mypool.Add(work, first_url, 4, fetcher) for { job := mypool.WaitForJob() if job == nil { break } if job.Result == nil { fmt.Println("got error:", job.Err) } else { result := job.Result.(crawlResult) if result.err != nil { fmt.Println(result.err) } else { url := job.Args[0].(string) depth := job.Args[1].(int) if depth <= 0 { continue } fmt.Printf("found: %s %q\n", url, result.body) for _, u := range result.urls { if url_already_processed(seen_urls, u) { continue } mypool.Add(work, u, depth-1, fetcher) seen_urls = append(seen_urls, u) } } } } mypool.Stop() } // fakeFetcher is Fetcher that returns canned results. type fakeFetcher map[string]*fakeResult type fakeResult struct { body string urls []string } func (f *fakeFetcher) Fetch(url string) (string, []string, error) { if res, ok := (*f)[url]; ok { return res.body, res.urls, nil } return "", nil, fmt.Errorf("not found: %s", url) } // fetcher is a populated fakeFetcher. var fetcher = &fakeFetcher{ "http://golang.org/": &fakeResult{ "The Go Programming Language", []string{ "http://golang.org/pkg/", "http://golang.org/cmd/", }, }, "http://golang.org/pkg/": &fakeResult{ "Packages", []string{ "http://golang.org/", "http://golang.org/cmd/", "http://golang.org/pkg/fmt/", "http://golang.org/pkg/os/", }, }, "http://golang.org/pkg/fmt/": &fakeResult{ "Package fmt", []string{ "http://golang.org/", "http://golang.org/pkg/", }, }, "http://golang.org/pkg/os/": &fakeResult{ "Package os", []string{ "http://golang.org/", "http://golang.org/pkg/", }, }, }
bsd-2-clause
jamesturk/jellyfish
jellyfish/__init__.py
757
import warnings try: from .cjellyfish import * # noqa library = "C" except ImportError: from ._jellyfish import * # noqa library = "Python" def jaro_winkler(s1, s2, long_tolerance=False): warnings.warn( "the name 'jaro_winkler' is deprecated and will be removed in jellyfish 1.0, " "for the same functionality please use jaro_winkler_similarity", DeprecationWarning, ) return jaro_winkler_similarity(s1, s2, long_tolerance) # noqa def jaro_distance(s1, s2): warnings.warn( "the jaro_distance function incorrectly returns the jaro similarity, " "replace your usage with jaro_similarity before 1.0", DeprecationWarning, ) return jaro_similarity(s1, s2) # noqa
bsd-2-clause
ess-dmsc/event-formation-unit
src/modules/freia/test/GeometryTest.cpp
1496
// Copyright (C) 2021 European Spallation Source, ERIC. See LICENSE file //===----------------------------------------------------------------------===// /// /// \file //===----------------------------------------------------------------------===// #include <freia/geometry/Geometry.h> #include <common/testutils/TestBase.h> using namespace Freia; class GeometryTest : public TestBase { protected: Geometry Geom; uint16_t VMM0{0}; uint16_t VMM1{1}; void SetUp() override {} void TearDown() override {} }; // Should match the ICD TEST_F(GeometryTest, DefaultFreia) { ASSERT_TRUE(Geom.isXCoord(VMM1)); ASSERT_TRUE(Geom.isYCoord(VMM0)); } // Freia is already default so we need to first swap to AMOR TEST_F(GeometryTest, SelectFreia) { ASSERT_TRUE(Geom.setGeometry("AMOR")); ASSERT_TRUE(Geom.setGeometry("Freia")); ASSERT_TRUE(Geom.isXCoord(VMM1)); ASSERT_TRUE(Geom.isYCoord(VMM0)); } // x- and y- vmms are swapped compared with Freia TEST_F(GeometryTest, SelectAMOR) { ASSERT_TRUE(Geom.setGeometry("AMOR")); ASSERT_TRUE(Geom.isXCoord(VMM0)); ASSERT_TRUE(Geom.isYCoord(VMM1)); } TEST_F(GeometryTest, SelectInvalid) { ASSERT_FALSE(Geom.setGeometry("")); ASSERT_TRUE(Geom.isXCoord(VMM1)); ASSERT_TRUE(Geom.isYCoord(VMM0)); ASSERT_FALSE(Geom.setGeometry("InvalidInstrument")); ASSERT_TRUE(Geom.isXCoord(VMM1)); ASSERT_TRUE(Geom.isYCoord(VMM0)); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
bsd-2-clause
mvbattista/homebrew-core
Formula/minetest.rb
2572
class Minetest < Formula desc "Free, open source voxel game engine and game" homepage "https://www.minetest.net/" revision 1 stable do url "https://github.com/minetest/minetest/archive/0.4.16.tar.gz" sha256 "0ef3793de9f569746ea78af7a66fe96ef65400019e5e64a04a5c3fa26a707655" resource "minetest_game" do url "https://github.com/minetest/minetest_game/archive/0.4.16.tar.gz" sha256 "ea914555949b4faccda5e13143cb021d2f9a5fa19abd1f5e4b7b65004cbd2b5a" end end bottle do sha256 "bd1bb5708000861f5406b4e95355f4474b372136e96db374076c29dc9464fa74" => :sierra sha256 "8ba27901ec54f9f141c3afb94406d22ec49f907f4e1c873375b5338703e1d3e2" => :el_capitan sha256 "a56489395aa0d13f322ced52167d8e46974bfd6e8302a0e6b0335df3082eed4e" => :yosemite end head do url "https://github.com/minetest/minetest.git" resource "minetest_game" do url "https://github.com/minetest/minetest_game.git", :branch => "master" end end depends_on :x11 depends_on "cmake" => :build depends_on "irrlicht" depends_on "jpeg" depends_on "libogg" depends_on "libvorbis" depends_on "luajit" => :recommended depends_on "freetype" => :recommended depends_on "gettext" => :recommended depends_on "leveldb" => :optional depends_on "redis" => :optional def install (buildpath/"games/minetest_game").install resource("minetest_game") args = std_cmake_args - %w[-DCMAKE_BUILD_TYPE=None] args << "-DCMAKE_BUILD_TYPE=Release" << "-DBUILD_CLIENT=1" << "-DBUILD_SERVER=0" args << "-DENABLE_REDIS=1" if build.with? "redis" args << "-DENABLE_LEVELDB=1" if build.with? "leveldb" args << "-DENABLE_FREETYPE=1" << "-DCMAKE_EXE_LINKER_FLAGS='-L#{Formula["freetype"].opt_lib}'" if build.with? "freetype" args << "-DENABLE_GETTEXT=1" << "-DCUSTOM_GETTEXT_PATH=#{Formula["gettext"].opt_prefix}" if build.with? "gettext" # -ffast-math compiler flag is an issue on Mac # https://github.com/minetest/minetest/issues/4274 inreplace "src/CMakeLists.txt", "-ffast-math", "" system "cmake", ".", *args system "make", "package" system "unzip", "minetest-*-osx.zip" prefix.install "minetest.app" end def caveats; <<-EOS.undent Put additional subgames and mods into "games" and "mods" folders under "~/Library/Application Support/minetest/", respectively (you may have to create those folders first). If you would like to start the Minetest server from a terminal, run "/Applications/minetest.app/Contents/MacOS/minetest --server". EOS end end
bsd-2-clause
depp/oubliette
src/base/image.cpp
5661
/* Copyright 2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "image.hpp" #include "defs.hpp" #include "surface.hpp" #include <SDL.h> #include <SDL_image.h> #include <cstdio> #include <cstdlib> namespace image { static sdl::surface load_image(const std::string &path) { sdl::surface image; image.surfptr = IMG_Load(path.c_str()); if (!image.surfptr) { core::check_sdl_error(HERE); std::fprintf(stderr, "Error: failed to load image: %s\n", path.c_str()); core::die("Failed to load image"); } std::printf( "loading %s (%dx%d, %s)\n", path.c_str(), image->w, image->h, SDL_GetPixelFormatName(image->format->format)); if (image->format->format == SDL_PIXELFORMAT_ARGB8888) return image; sdl::surface converted; converted.surfptr = SDL_ConvertSurfaceFormat( image.surfptr, SDL_PIXELFORMAT_ARGB8888, 0); if (!converted.surfptr) { core::check_sdl_error(HERE); std::fprintf(stderr, "Error: failed to load image: %s\n", path.c_str()); core::die("Failed to load image"); } return converted; } static int round_up_pow2(int x) { unsigned v = x - 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1; } bitmap::bitmap() : data(nullptr), width(0), height(0), rowbytes(0) { } bitmap::bitmap(bitmap &&other) : data(other.data), width(other.width), height(other.height), rowbytes(other.rowbytes) { other.data = nullptr; other.width = 0; other.height = 0; other.rowbytes = 0; } bitmap::~bitmap() { std::free(data); } bitmap &bitmap::operator=(bitmap &&other) { if (this == &other) return *this; if (data) std::free(data); data = other.data; width = other.width; height = other.height; rowbytes = other.rowbytes; other.data = nullptr; other.width = 0; other.height = 0; other.rowbytes = 0; return *this; } void bitmap::alloc(int w, int h) { std::free(data); data = nullptr; width = 0; height = 0; rowbytes = 0; int rb = ((unsigned)w + 15) & ~15u; if (w < 1 || w > 0x8000 || h < 1 || h > 0x8000) core::die("bitmap too large"); data = static_cast<unsigned char *>(std::malloc(rb * h)); if (data == nullptr) core::die_alloc(); width = w; height = h; rowbytes = rb; } bitmap bitmap::load(const std::string &path) { sdl::surface image = load_image(path); int r = SDL_LockSurface(image.surfptr); if (r) core::die_sdl(HERE, "Failed to load image"); int iw = image->w, ih = image->h; bitmap bmap; bmap.alloc(iw, ih); const unsigned char *ip = static_cast<unsigned char *>(image->pixels); unsigned char *op = static_cast<unsigned char *>(bmap.data); unsigned irb = image->pitch, orb = bmap.rowbytes; for (int y = 0; y < ih; y++) { const unsigned *irow = reinterpret_cast<const unsigned *>(ip + irb * y); unsigned char *orow = op + orb * (ih - 1 - y); for (int x = 0; x < iw; x++) { orow[x] = irow[x] >> 24; } } return bmap; } texture::texture() : tex(0), iwidth(0), iheight(0), twidth(0), theight(0) { } texture texture::load(const std::string &path) { sdl::surface image = load_image(path); texture tex; int r = SDL_LockSurface(image.surfptr); if (r) core::die_sdl(HERE, "Failed to load image"); tex.iwidth = image->w; tex.iheight = image->h; tex.twidth = round_up_pow2(tex.iwidth); tex.theight = round_up_pow2(tex.iheight); tex.scale[0] = 1.0 / tex.twidth; tex.scale[1] = 1.0 / tex.theight; glGenTextures(1, &tex.tex); glBindTexture(GL_TEXTURE_2D, tex.tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, tex.twidth, tex.theight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, tex.iwidth, tex.iheight, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image->pixels); glBindTexture(GL_TEXTURE_2D, 0); // 0x00ff0000u, 0x0000ff00u, 0x000000ff, 0xff000000u core::check_gl_error(HERE); return tex; } texture texture::load_1d(const std::string &path) { sdl::surface image = load_image(path); texture tex; int r = SDL_LockSurface(image.surfptr); if (r) core::die_sdl(HERE, "Failed to load image"); tex.iwidth = image->w; tex.iheight = 1; tex.twidth = round_up_pow2(tex.iwidth); tex.theight = 1; tex.scale[0] = 1.0 / tex.twidth; tex.scale[1] = 1.0; glGenTextures(1, &tex.tex); glBindTexture(GL_TEXTURE_1D, tex.tex); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage1D( GL_TEXTURE_1D, 0, GL_RGBA8, tex.twidth, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr); glTexSubImage1D( GL_TEXTURE_1D, 0, 0, tex.iwidth, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image->pixels); glBindTexture(GL_TEXTURE_1D, 0); core::check_gl_error(HERE); return tex; } }
bsd-2-clause
golovnin/pgjdbc
pgjdbc/src/main/java/org/postgresql/util/PGTimestamp.java
3491
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.util; import java.sql.Timestamp; import java.util.Calendar; /** * This class augments the Java built-in Timestamp to allow for explicit setting of the time zone. */ public class PGTimestamp extends Timestamp { /** * The serial version UID. */ private static final long serialVersionUID = -6245623465210738466L; /** * The optional calendar for this timestamp. */ private Calendar calendar; /** * Constructs a <code>PGTimestamp</code> without a time zone. The integral seconds are stored in * the underlying date value; the fractional seconds are stored in the <code>nanos</code> field of * the <code>Timestamp</code> object. * * @param time milliseconds since January 1, 1970, 00:00:00 GMT. A negative number is the number * of milliseconds before January 1, 1970, 00:00:00 GMT. * @see Timestamp#Timestamp(long) */ public PGTimestamp(long time) { this(time, null); } /** * <p>Constructs a <code>PGTimestamp</code> with the given time zone. The integral seconds are stored * in the underlying date value; the fractional seconds are stored in the <code>nanos</code> field * of the <code>Timestamp</code> object.</p> * * <p>The calendar object is optional. If absent, the driver will treat the timestamp as * <code>timestamp without time zone</code>. When present, the driver will treat the timestamp as * a <code>timestamp with time zone</code> using the <code>TimeZone</code> in the calendar object. * Furthermore, this calendar will be used instead of the calendar object passed to * {@link java.sql.PreparedStatement#setTimestamp(int, Timestamp, Calendar)}.</p> * * @param time milliseconds since January 1, 1970, 00:00:00 GMT. A negative number is the number * of milliseconds before January 1, 1970, 00:00:00 GMT. * @param calendar the calendar object containing the time zone or <code>null</code>. * @see Timestamp#Timestamp(long) */ public PGTimestamp(long time, Calendar calendar) { super(time); this.setCalendar(calendar); } /** * Sets the calendar object for this timestamp. * * @param calendar the calendar object or <code>null</code>. */ public void setCalendar(Calendar calendar) { this.calendar = calendar; } /** * Returns the calendar object for this timestamp. * * @return the calendar object or <code>null</code>. */ public Calendar getCalendar() { return calendar; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((calendar == null) ? 0 : calendar.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof PGTimestamp)) { return false; } PGTimestamp other = (PGTimestamp) obj; if (calendar == null) { if (other.calendar != null) { return false; } } else if (!calendar.equals(other.calendar)) { return false; } return true; } @Override public Object clone() { PGTimestamp clone = (PGTimestamp) super.clone(); if (getCalendar() != null) { clone.setCalendar((Calendar) getCalendar().clone()); } return clone; } }
bsd-2-clause
ggobbe/vivre-uo
Scripts/Vivre/Items/Potions/Clumsy Potions/GreaterClumsyPotion.cs
733
using System; using Server; namespace Server.Items { public class GreaterClumsyPotion : BaseAgilityPotion { public override int DexOffset{ get{ return IntensifiedStrength?15:12; } } public override TimeSpan Duration{ get{ return TimeSpan.FromMinutes( IntensifiedTime?2.5:1.5 ); } } [Constructable] public GreaterClumsyPotion() : base( PotionEffect.ClumsyGreater ) { } public GreaterClumsyPotion( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
bsd-2-clause
vjoel/tupelo
lib/tupelo/app/remote.rb
2488
require 'tupelo/app' module Tupelo class AppBuilder # Perform client operations on another host. # # There are two modes: drb and eval. In the drb mode, a block executes # locally, performing tuplespace operations by proxy to the remote # tupelo client instance. Results of the ops are available in the local # process. This is very useful for testing and examples. # # In the eval mode, a string is evaluated on the remote host in the context # of a client instance. # # There are some minor limitations compared to #child: # # In eval mode, the code string is always treated as in the arity 0 case # of #child, in other words "DSL mode", in other words the self is the # client. # # Unlike #child, there is no mode that returns a Client instance. # # Note that EasyServe options apply, including the `tunnel: true` option. # The default for this option is true if the `--tunnel` switch is present # on the command line. # def remote client_class = Client, client_lib: 'tupelo/client', host: nil, **opts require 'easy-serve/remote' ## detach option so that remote process doesn't keep ssh connection snames = :seqd, :cseqd, :arcd if tunnel_default and not opts.key?(:tunnel) opts[:tunnel] = true end if opts[:eval] ez.remote *snames, host: host, **opts, eval: %{ require #{client_lib.inspect} seqd, cseqd, arcd = *conns client_class = Object.const_get(#{client_class.name.inspect}) begin log.progname = "client <starting in \#{log.progname}>" client = client_class.new( seq: seqd, cseq: cseqd, arc: arcd, log: log) client.start do log.progname = "client \#{client.client_id}" end client.instance_eval #{opts[:eval].inspect} ensure client.stop if client end } elsif block_given? block = Proc.new ez.remote *snames, host: host, **opts do |seqd, cseqd, arcd| run_client client_class, seq: seqd, cseq: cseqd, arc: arcd, log: log do |client| if block.arity == 0 client.instance_eval &block else yield client end end end else raise ArgumentError, "cannot select remote mode based on arguments" end end end end
bsd-2-clause
sitescout/api-example
src/main/java/com/sitescout/dsp/api/type/SpendCapType.java
767
package com.sitescout.dsp.api.type; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum SpendCapType { none("none"), daily("daily"), allTime("all_time"); private String valueStr; SpendCapType(String valueStr) { this.valueStr = valueStr; } @JsonCreator public static SpendCapType fromString(String value) { if (value == null) { return null; } for (SpendCapType spendCapType : values()) { if (spendCapType.valueStr.equals(value.toLowerCase())) { return spendCapType; } } return null; } @JsonValue public String toJsonString() { return valueStr; } }
bsd-2-clause
highsource/javascript-codemodel
parser/src/test/java/org/hisrc/jscm/parser/literal/tests/DecimalParserTest.java
1665
package org.hisrc.jscm.parser.literal.tests; import java.math.BigDecimal; import org.hisrc.jscm.parser.ParseException; import org.hisrc.jscm.parser.literal.DecimalParser; import org.junit.Assert; import org.junit.Test; public class DecimalParserTest { @Test public void check() throws ParseException { Assert.assertEquals(new BigDecimal("1"), DecimalParser.INSTANCE.parse("1")); Assert.assertEquals(new BigDecimal("1"), DecimalParser.INSTANCE.parse("1.")); Assert.assertEquals(new BigDecimal("1.0"), DecimalParser.INSTANCE.parse("1.0")); Assert.assertEquals(new BigDecimal("1.2"), DecimalParser.INSTANCE.parse("1.2")); Assert.assertEquals(new BigDecimal("1E+2"), DecimalParser.INSTANCE.parse("1.E2")); Assert.assertEquals(new BigDecimal("1E+2"), DecimalParser.INSTANCE.parse("1.E+2")); Assert.assertEquals(new BigDecimal("0.01"), DecimalParser.INSTANCE.parse("1.E-2")); Assert.assertEquals(new BigDecimal("123"), DecimalParser.INSTANCE.parse("1.23E2")); Assert.assertEquals(new BigDecimal("123"), DecimalParser.INSTANCE.parse("1.23E+2")); Assert.assertEquals(new BigDecimal("0.0123"), DecimalParser.INSTANCE.parse("1.23E-2")); Assert.assertEquals(new BigDecimal("1.2"), DecimalParser.INSTANCE.parse("1.2")); Assert.assertEquals(new BigDecimal("12.3"), DecimalParser.INSTANCE.parse(".123E2")); Assert.assertEquals(new BigDecimal("12.3"), DecimalParser.INSTANCE.parse(".123E+2")); Assert.assertEquals(new BigDecimal("0.00123"), DecimalParser.INSTANCE.parse(".123E-2")); Assert.assertEquals(new BigDecimal(".12"), DecimalParser.INSTANCE.parse(".12")); } }
bsd-2-clause
0x5542/LanTexter
src/main/java/de/ulfbiallas/lantexter/model/Constants.java
1466
package de.ulfbiallas.lantexter.model; /** * This class holds a set of global constants. * * @author Ulf Biallas * */ public class Constants { /** Image file for the window and tray icon. */ public static final String ICON_FILE = "icon.png"; /** Name of the application. */ public static final String PROGRAM_NAME = "LAN Texter"; /** Current version of the application. */ public static final String VERSION = "1.0"; /** Path and file name of the properties file. */ public static final String PROPERTIES_FILE = "settings.properties"; /** Default port which is opened by the application. */ public static final int DEFAULT_PORT = 12345; /** Default language */ public static final String DEFAULT_LANGUAGE = "language_english"; /** * Time interval in [s] to broadcast an alive message and * to ask for other participants. */ public static final int ALIVE_TIMER_INTERVAL = 20; /** Time interval in [s] after which a participant is set offline. */ public static final int NOT_ALIVE_INTERVAL = 70; /** Text color of a notification in the chat history. */ public static final String NOTIFICATION_COLOR = "#aaaaaa"; /** Text for the about view */ public static final String CREDITS = "by Ulf Biallas | 2013"; /** List of used libraries. */ public static final String USED_LIBRARIES = "Json-lib (Apache License Version 2.0)\n" + "JGoodies Common (BSD open source license)\n" + "JGoodies Forms (BSD open source license)"; }
bsd-2-clause