code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * $RCSfile: USB_AI16_Family.java,v $ * $Date: 2009/12/23 22:45:27 $ * $Revision: 1.15 $ * jEdit:tabSize=4:indentSize=4:collapseFolds=1: */ package com.acces.aiousb; // {{{ imports import java.io.*; import java.util.*; // }}} /** * Class USB_AI16_Family represents a USB-AI16-family device, which encompasses the following product IDs:<br> * {@link USBDeviceManager#USB_AI16_16A USB_AI16_16A}, {@link USBDeviceManager#USB_AI16_16E USB_AI16_16E}, * {@link USBDeviceManager#USB_AI12_16A USB_AI12_16A}, {@link USBDeviceManager#USB_AI12_16 USB_AI12_16}, * {@link USBDeviceManager#USB_AI12_16E USB_AI12_16E}, {@link USBDeviceManager#USB_AI16_64MA USB_AI16_64MA}, * {@link USBDeviceManager#USB_AI16_64ME USB_AI16_64ME}, {@link USBDeviceManager#USB_AI12_64MA USB_AI12_64MA},<br> * {@link USBDeviceManager#USB_AI12_64M USB_AI12_64M}, {@link USBDeviceManager#USB_AI12_64ME USB_AI12_64ME}, * {@link USBDeviceManager#USB_AI16_32A USB_AI16_32A}, {@link USBDeviceManager#USB_AI16_32E USB_AI16_32E}, * {@link USBDeviceManager#USB_AI12_32A USB_AI12_32A}, {@link USBDeviceManager#USB_AI12_32 USB_AI12_32}, * {@link USBDeviceManager#USB_AI12_32E USB_AI12_32E}, {@link USBDeviceManager#USB_AI16_64A USB_AI16_64A},<br> * {@link USBDeviceManager#USB_AI16_64E USB_AI16_64E}, {@link USBDeviceManager#USB_AI12_64A USB_AI12_64A}, * {@link USBDeviceManager#USB_AI12_64 USB_AI12_64}, {@link USBDeviceManager#USB_AI12_64E USB_AI12_64E}, * {@link USBDeviceManager#USB_AI16_96A USB_AI16_96A}, {@link USBDeviceManager#USB_AI16_96E USB_AI16_96E}, * {@link USBDeviceManager#USB_AI12_96A USB_AI12_96A}, {@link USBDeviceManager#USB_AI12_96 USB_AI12_96},<br> * {@link USBDeviceManager#USB_AI12_96E USB_AI12_96E}, {@link USBDeviceManager#USB_AI16_128A USB_AI16_128A}, * {@link USBDeviceManager#USB_AI16_128E USB_AI16_128E}, {@link USBDeviceManager#USB_AI12_128A USB_AI12_128A}, * {@link USBDeviceManager#USB_AI12_128 USB_AI12_128}, {@link USBDeviceManager#USB_AI12_128E USB_AI12_128E}.<br><br> * Instances of class <i>USB_AI16_Family</i> are automatically created by the USB device manager when they are * detected on the bus. You should use one of the <i>{@link USBDeviceManager}</i> search methods, such as * <i>{@link USBDeviceManager#getDeviceByProductID( int productID ) USBDeviceManager.getDeviceByProductID()}</i>, * to obtain a reference to a <i>USB_AI16_Family</i> instance. You can then cast the <i>{@link USBDevice}</i> * reference obtained from one of those methods to a <i>USB_AI16_Family</i> and make use of this class' methods, like so: * <pre>USBDevice[] devices = deviceManager.getDeviceByProductID( USBDeviceManager.USB_AI12_32A, USBDeviceManager.USB_AI12_32E ); *if( devices.length > 0 ) * USB_AI16_Family device = ( USB_AI16_Family ) devices[ 0 ];</pre> */ public class USB_AI16_Family extends USBDevice { // {{{ static members private static int[] supportedProductIDs; static { supportedProductIDs = new int[] { USBDeviceManager.USB_AI16_16A , USBDeviceManager.USB_AI16_16E , USBDeviceManager.USB_AI12_16A , USBDeviceManager.USB_AI12_16 , USBDeviceManager.USB_AI12_16E , USBDeviceManager.USB_AI16_64MA , USBDeviceManager.USB_AI16_64ME , USBDeviceManager.USB_AI12_64MA , USBDeviceManager.USB_AI12_64M , USBDeviceManager.USB_AI12_64ME , USBDeviceManager.USB_AI16_32A , USBDeviceManager.USB_AI16_32E , USBDeviceManager.USB_AI12_32A , USBDeviceManager.USB_AI12_32 , USBDeviceManager.USB_AI12_32E , USBDeviceManager.USB_AI16_64A , USBDeviceManager.USB_AI16_64E , USBDeviceManager.USB_AI12_64A , USBDeviceManager.USB_AI12_64 , USBDeviceManager.USB_AI12_64E , USBDeviceManager.USB_AI16_96A , USBDeviceManager.USB_AI16_96E , USBDeviceManager.USB_AI12_96A , USBDeviceManager.USB_AI12_96 , USBDeviceManager.USB_AI12_96E , USBDeviceManager.USB_AI16_128A , USBDeviceManager.USB_AI16_128E , USBDeviceManager.USB_AI12_128A , USBDeviceManager.USB_AI12_128 , USBDeviceManager.USB_AI12_128E }; // supportedProductIDs[] Arrays.sort( supportedProductIDs ); } // static // }}} // {{{ protected members protected AnalogInputSubsystem analogInputSubsystem; protected DigitalIOSubsystem digitalIOSubsystem; protected CounterSubsystem counterSubsystem; // }}} // {{{ protected methods protected USB_AI16_Family( int productID, int deviceIndex ) { super( productID, deviceIndex ); if( ! isSupportedProductID( productID ) ) throw new IllegalArgumentException( "Invalid product ID: " + productID ); analogInputSubsystem = new AnalogInputSubsystem( this ); digitalIOSubsystem = new DigitalIOSubsystem( this ); counterSubsystem = new CounterSubsystem( this ); } // USB_AI16_Family() // }}} // {{{ public methods /* * properties */ /** * Gets an array of all the product names supported by this USB device family. * <br><br>Although this method is <i>static</i>, an instance of USBDeviceManager must be created * and be "open" for use before this method can be used. This stipulation is imposed because the * underlying library must be initialized in order for product name/ID lookups to succeed, and that * initialization occurs only when an instance of USBDeviceManager is created and its * <i>{@link USBDeviceManager#open() open()}</i> method is called. * @return An array of product names, sorted in ascending order of product ID. */ public static String[] getSupportedProductNames() { return USBDeviceManager.productIDToName( supportedProductIDs ); } // getSupportedProductNames() /** * Gets an array of all the product IDs supported by this USB device family. * @return An array of product IDs, sorted in ascending order. */ public static int[] getSupportedProductIDs() { return supportedProductIDs.clone(); } // getSupportedProductIDs() /** * Tells if a given product ID is supported by this USB device family. * @param productID the product ID to check. * @return <i>True</i> if the given product ID is supported by this USB device family; otherwise, <i>false</i>. */ public static boolean isSupportedProductID( int productID ) { return Arrays.binarySearch( supportedProductIDs, productID ) >= 0; } // isSupportedProductID() /** * Prints the properties of this device and all of its subsystems. Mainly useful for diagnostic purposes. * @param stream the print stream where properties will be printed. * @return The print stream. */ public PrintStream print( PrintStream stream ) { super.print( stream ); analogInputSubsystem.print( stream ); digitalIOSubsystem.print( stream ); counterSubsystem.print( stream ); return stream; } // print() /* * subsystems */ /** * Gets a reference to the analog input subsystem of this device. * @return A reference to the analog input subsystem. */ public AnalogInputSubsystem adc() { return analogInputSubsystem; } // adc() /** * Gets a reference to the digital I/O subsystem of this device. * @return A reference to the digital I/O subsystem. */ public DigitalIOSubsystem dio() { return digitalIOSubsystem; } // dio() /** * Gets a reference to the counter/timer subsystem of this device. * @return A reference to the counter/timer subsystem. */ public CounterSubsystem ctr() { return counterSubsystem; } // ctr() // }}} } // class USB_AI16_Family /* end of file */
accesio/AIOUSB
AIOUSB/deprecated/java/com/acces/aiousb/USB_AI16_Family.java
Java
lgpl-3.0
7,364
package org.nustaq.kontraktor.remoting.http.servlet; import org.nustaq.kontraktor.remoting.http.KHttpExchange; import org.nustaq.kontraktor.util.Log; import javax.servlet.AsyncContext; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Created by ruedi on 19.06.17. */ public class ServletKHttpExchangeImpl implements KHttpExchange { KontraktorServlet servlet; AsyncContext aCtx; public ServletKHttpExchangeImpl(KontraktorServlet servlet, AsyncContext aCtx) { this.servlet = servlet; this.aCtx = aCtx; } @Override public void endExchange() { aCtx.complete(); } @Override public void setResponseContentLength(int length) { aCtx.getResponse().setContentLength(length); } @Override public void setResponseCode(int i) { ((HttpServletResponse) aCtx.getResponse()).setStatus(i); } @Override public void send(String s) { try { aCtx.getResponse().setCharacterEncoding("UTF-8"); aCtx.getResponse().setContentType("text/html; charset=utf-8"); aCtx.getResponse().getWriter().write(s); } catch (IOException e) { Log.Warn(this,e); } } @Override public void send(byte[] b) { try { send(new String(b,"UTF-8")); } catch (UnsupportedEncodingException e) { Log.Error(this,e); } } @Override public void sendAuthResponse(byte[] response, String sessionId) { try { send(new String(response,"UTF-8")); aCtx.complete(); } catch (UnsupportedEncodingException e) { Log.Error(this,e); } } }
RuedigerMoeller/kontraktor
modules/kontraktor-http/src/main/java/org/nustaq/kontraktor/remoting/http/servlet/ServletKHttpExchangeImpl.java
Java
lgpl-3.0
1,761
/** ****************************************************************************** * @file wlan_hal.c * @author Matthew McGowan * @version V1.0.0 * @date 27-Sept-2014 * @brief ****************************************************************************** Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. ****************************************************************************** */ #include "wlan_hal.h" uint32_t HAL_NET_SetNetWatchDog(uint32_t timeOutInMS) { return 0; } int wlan_clear_credentials() { return 1; } int wlan_has_credentials() { return 1; } int wlan_connect_init() { return 0; } wlan_result_t wlan_activate() { return 0; } wlan_result_t wlan_deactivate() { return 0; } bool wlan_reset_credentials_store_required() { return false; } wlan_result_t wlan_reset_credentials_store() { return 0; } /** * Do what is needed to finalize the connection. * @return */ wlan_result_t wlan_connect_finalize() { // enable connection from stored profiles return 0; } void Set_NetApp_Timeout(void) { } wlan_result_t wlan_disconnect_now() { return 0; } wlan_result_t wlan_connected_rssi(char* ssid) { return 0; } int wlan_connected_info(void* reserved, wlan_connected_info_t* inf, void* reserved1) { return -1; } int wlan_set_credentials(WLanCredentials* c) { return -1; } void wlan_smart_config_init() { } bool wlan_smart_config_finalize() { return false; } void wlan_smart_config_cleanup() { } void wlan_setup() { } void wlan_set_error_count(uint32_t errorCount) { } int wlan_fetch_ipconfig(WLanConfig* config) { return -1; } void SPARK_WLAN_SmartConfigProcess() { } void wlan_connect_cancel(bool called_from_isr) { } /** * Sets the IP source - static or dynamic. */ void wlan_set_ipaddress_source(IPAddressSource source, bool persist, void* reserved) { } /** * Sets the IP Addresses to use when the device is in static IP mode. * @param device * @param netmask * @param gateway * @param dns1 * @param dns2 * @param reserved */ void wlan_set_ipaddress(const HAL_IPAddress* device, const HAL_IPAddress* netmask, const HAL_IPAddress* gateway, const HAL_IPAddress* dns1, const HAL_IPAddress* dns2, void* reserved) { } IPAddressSource wlan_get_ipaddress_source(void* reserved) { return DYNAMIC_IP; } int wlan_get_ipaddress(IPConfig* conf, void* reserved) { return -1; } int wlan_scan(wlan_scan_result_t callback, void* cookie) { return -1; } int wlan_restart(void* reserved) { return -1; } int wlan_get_hostname(char* buf, size_t len, void* reserved) { // Unsupported if (buf) { buf[0] = '\0'; } return -1; } int wlan_set_hostname(const char* hostname, void* reserved) { // Unsupported return -1; }
spark/firmware
hal/src/template/wlan_hal.cpp
C++
lgpl-3.0
3,455
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "mediaconnectresponse.h" #include "mediaconnectresponse_p.h" #include <QDebug> #include <QXmlStreamReader> namespace QtAws { namespace MediaConnect { /*! * \class QtAws::MediaConnect::MediaConnectResponse * \brief The MediaConnectResponse class provides an interface for MediaConnect responses. * * \inmodule QtAwsMediaConnect */ /*! * Constructs a MediaConnectResponse object with parent \a parent. */ MediaConnectResponse::MediaConnectResponse(QObject * const parent) : QtAws::Core::AwsAbstractResponse(new MediaConnectResponsePrivate(this), parent) { } /*! * \internal * Constructs a MediaConnectResponse object with private implementation \a d, * and parent \a parent. * * This overload allows derived classes to provide their own private class * implementation that inherits from MediaConnectResponsePrivate. */ MediaConnectResponse::MediaConnectResponse(MediaConnectResponsePrivate * const d, QObject * const parent) : QtAws::Core::AwsAbstractResponse(d, parent) { } /*! * \reimp */ void MediaConnectResponse::parseFailure(QIODevice &response) { //Q_D(MediaConnectResponse); Q_UNUSED(response); /*QXmlStreamReader xml(&response); if (xml.readNextStartElement()) { if (xml.name() == QLatin1String("ErrorResponse")) { d->parseErrorResponse(xml); } else { qWarning() << "ignoring" << xml.name(); xml.skipCurrentElement(); } } setXmlError(xml);*/ } /*! * \class QtAws::MediaConnect::MediaConnectResponsePrivate * \brief The MediaConnectResponsePrivate class provides private implementation for MediaConnectResponse. * \internal * * \inmodule QtAwsMediaConnect */ /*! * Constructs a MediaConnectResponsePrivate object with public implementation \a q. */ MediaConnectResponsePrivate::MediaConnectResponsePrivate( MediaConnectResponse * const q) : QtAws::Core::AwsAbstractResponsePrivate(q) { } } // namespace MediaConnect } // namespace QtAws
pcolby/libqtaws
src/mediaconnect/mediaconnectresponse.cpp
C++
lgpl-3.0
2,716
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Fileharbor.Common.Database; namespace Fileharbor.Services.Entities { [Table("collections")] public class CollectionEntity { [Key] [ColumnName("id")] public Guid Id { get; set; } [Required] [ColumnName("name")] public string Name { get; set; } [Required] [ColumnName("quota")] public long Quota { get; set; } [Required] [ColumnName("bytes_used")] public long BytesUsed { get; set; } [ColumnName("template_id")] public Guid? TemplateId { get; set; } [ColumnName("description")] public string Description { get; set; } } }
dennisbappert/fileharbor
src/Services/Entities/CollectionEntity.cs
C#
lgpl-3.0
789
using UnityEngine; using System.Collections; public class SimpleDebug : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { float val = FalconUnity.getFPS(); GUI.Label(new Rect(5,5,200,30), val.ToString() ); } }
kbogert/falconunity
UnityDemoProject/Assets/SimpleDebug.cs
C#
lgpl-3.0
323
/** * This file is part of the nestk library. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Nicolas Burrus <nicolas.burrus@uc3m.es>, (C) 2010 */ # include "table_object_detector.h" # include <ntk/utils/time.h> # include <boost/make_shared.hpp> using namespace pcl; using cv::Point3f; namespace ntk { template <class PointType> TableObjectDetector<PointType> :: TableObjectDetector() : m_max_dist_to_plane(0.03) { // ---[ Create all PCL objects and set their parameters setObjectVoxelSize(); setBackgroundVoxelSize(); setDepthLimits(); setObjectHeightLimits(); // Normal estimation parameters k_ = 10; // 50 k-neighbors by default // Table model fitting parameters sac_distance_threshold_ = 0.01; // 1cm // Don't know ? normal_distance_weight_ = 0.1; // Clustering parameters object_cluster_tolerance_ = 0.05; // 5cm between two objects object_cluster_min_size_ = 100; // 100 points per object cluster } template <class PointType> void TableObjectDetector<PointType> :: initialize() { grid_.setLeafSize (downsample_leaf_, downsample_leaf_, downsample_leaf_); grid_objects_.setLeafSize (downsample_leaf_objects_, downsample_leaf_objects_, downsample_leaf_objects_); grid_.setFilterFieldName ("z"); pass_.setFilterFieldName ("z"); grid_.setFilterLimits (min_z_bounds_, max_z_bounds_); pass_.setFilterLimits (min_z_bounds_, max_z_bounds_); grid_.setDownsampleAllData (false); grid_objects_.setDownsampleAllData (false); #ifdef HAVE_PCL_GREATER_THAN_1_2_0 normals_tree_ = boost::make_shared<pcl::search::KdTree<Point> > (); clusters_tree_ = boost::make_shared<pcl::search::KdTree<Point> > (); #else normals_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > (); clusters_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > (); #endif clusters_tree_->setEpsilon (1); //tree_.setSearchWindowAsK (10); //tree_.setMaxDistance (0.5); n3d_.setKSearch (k_); n3d_.setSearchMethod (normals_tree_); normal_distance_weight_ = 0.1; seg_.setNormalDistanceWeight (normal_distance_weight_); seg_.setOptimizeCoefficients (true); seg_.setModelType (pcl::SACMODEL_NORMAL_PLANE); seg_.setMethodType (pcl::SAC_RANSAC); seg_.setProbability (0.99); seg_.setDistanceThreshold (sac_distance_threshold_); seg_.setMaxIterations (10000); proj_.setModelType (pcl::SACMODEL_NORMAL_PLANE); prism_.setHeightLimits (object_min_height_, object_max_height_); cluster_.setClusterTolerance (object_cluster_tolerance_); cluster_.setMinClusterSize (object_cluster_min_size_); cluster_.setSearchMethod (clusters_tree_); } template <class PointType> bool TableObjectDetector<PointType> :: detect(PointCloudConstPtr cloud) { ntk::TimeCount tc("TableObjectDetector::detect", 1); m_object_clusters.clear(); initialize(); ntk_dbg(1) << cv::format("PointCloud with %d data points.\n", cloud->width * cloud->height); // ---[ Convert the dataset cloud_ = cloud; // FIXME: Find out whether the removal of the (deep-copying) cloud.makeShared() call sped things up. // ---[ Create the voxel grid pcl::PointCloud<Point> cloud_filtered; pass_.setInputCloud (cloud_); pass_.filter (cloud_filtered); cloud_filtered_.reset (new pcl::PointCloud<Point> (cloud_filtered)); ntk_dbg(1) << cv::format("Number of points left after filtering (%f -> %f): %d out of %d.\n", min_z_bounds_, max_z_bounds_, (int)cloud_filtered.points.size (), (int)cloud->points.size ()); pcl::PointCloud<Point> cloud_downsampled; grid_.setInputCloud (cloud_filtered_); grid_.filter (cloud_downsampled); cloud_downsampled_.reset (new pcl::PointCloud<Point> (cloud_downsampled)); if ((int)cloud_filtered_->points.size () < k_) { ntk_dbg(0) << cv::format("WARNING Filtering returned %d points! Continuing.\n", (int)cloud_filtered_->points.size ()); return false; } // ---[ Estimate the point normals pcl::PointCloud<pcl::Normal> cloud_normals; n3d_.setInputCloud (cloud_downsampled_); n3d_.compute (cloud_normals); cloud_normals_.reset (new pcl::PointCloud<pcl::Normal> (cloud_normals)); ntk_dbg(1) << cv::format("%d normals estimated.", (int)cloud_normals.points.size ()); //ROS_ASSERT (cloud_normals_->points.size () == cloud_filtered_->points.size ()); // ---[ Perform segmentation pcl::PointIndices table_inliers; pcl::ModelCoefficients table_coefficients; seg_.setInputCloud (cloud_downsampled_); seg_.setInputNormals (cloud_normals_); seg_.segment (table_inliers, table_coefficients); table_inliers_.reset (new pcl::PointIndices (table_inliers)); table_coefficients_.reset (new pcl::ModelCoefficients (table_coefficients)); if (table_coefficients.values.size () > 3) ntk_dbg(1) << cv::format("Model found with %d inliers: [%f %f %f %f].\n", (int)table_inliers.indices.size (), table_coefficients.values[0], table_coefficients.values[1], table_coefficients.values[2], table_coefficients.values[3]); if (table_inliers_->indices.size () == 0) return false; m_plane = ntk::Plane (table_coefficients.values[0], table_coefficients.values[1], table_coefficients.values[2], table_coefficients.values[3]); // ---[ Extract the table pcl::PointCloud<Point> table_projected; proj_.setInputCloud (cloud_downsampled_); proj_.setIndices (table_inliers_); proj_.setModelCoefficients (table_coefficients_); proj_.filter (table_projected); table_projected_.reset (new pcl::PointCloud<Point> (table_projected)); ntk_dbg(1) << cv::format("Number of projected inliers: %d.\n", (int)table_projected.points.size ()); // ---[ Estimate the convex hull pcl::PointCloud<Point> table_hull; hull_.setInputCloud (table_projected_); hull_.reconstruct (table_hull); table_hull_.reset (new pcl::PointCloud<Point> (table_hull)); // ---[ Get the objects on top of the table pcl::PointIndices cloud_object_indices; prism_.setInputCloud (cloud_filtered_); prism_.setInputPlanarHull (table_hull_); prism_.segment (cloud_object_indices); ntk_dbg(1) << cv::format("Number of object point indices: %d.\n", (int)cloud_object_indices.indices.size ()); pcl::PointCloud<Point> cloud_objects; pcl::ExtractIndices<Point> extract_object_indices; //extract_object_indices.setInputCloud (cloud_all_minus_table_ptr); extract_object_indices.setInputCloud (cloud_filtered_); // extract_object_indices.setInputCloud (cloud_downsampled_); extract_object_indices.setIndices (boost::make_shared<const pcl::PointIndices> (cloud_object_indices)); extract_object_indices.filter (cloud_objects); cloud_objects_.reset (new pcl::PointCloud<Point> (cloud_objects)); ntk_dbg(1) << cv::format("Number of object point candidates: %d.\n", (int)cloud_objects.points.size ()); if (cloud_objects.points.size () == 0) return false; // ---[ Downsample the points pcl::PointCloud<Point> cloud_objects_downsampled; grid_objects_.setInputCloud (cloud_objects_); grid_objects_.filter (cloud_objects_downsampled); cloud_objects_downsampled_.reset (new pcl::PointCloud<Point> (cloud_objects_downsampled)); ntk_dbg(1) << cv::format("Number of object point candidates left after downsampling: %d.\n", (int)cloud_objects_downsampled.points.size ()); // ---[ Split the objects into Euclidean clusters std::vector< PointIndices > object_clusters; cluster_.setInputCloud (cloud_objects_downsampled_); cluster_.extract (object_clusters); ntk_dbg(1) << cv::format("Number of clusters found matching the given constraints: %d.\n", (int)object_clusters.size ()); for (size_t i = 0; i < object_clusters.size (); ++i) { std::vector<Point3f> object_points; foreach_idx(k, object_clusters[i].indices) { int index = object_clusters[i].indices[k]; Point p = cloud_objects_downsampled_->points[index]; object_points.push_back(Point3f(p.x,p.y,p.z)); } float min_dist_to_plane = FLT_MAX; for (int j = 0; j < object_points.size(); ++j) { Point3f pobj = object_points[j]; min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane); } ntk_dbg_print(min_dist_to_plane, 1); if (min_dist_to_plane > m_max_dist_to_plane) continue; m_object_clusters.push_back(object_points); } tc.stop(); return true; } template <class PointType> int TableObjectDetector<PointType> :: getMostCentralCluster() const { // Look for the most central cluster which is not flying. int selected_object = -1; float min_x = FLT_MAX; for (int i = 0; i < objectClusters().size(); ++i) { const std::vector<Point3f>& object_points = objectClusters()[i]; float min_dist_to_plane = FLT_MAX; for (int j = 0; j < object_points.size(); ++j) { Point3f pobj = object_points[j]; min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane); } if (min_dist_to_plane > m_max_dist_to_plane) continue; ntk::Rect3f bbox = bounding_box(object_points); if (std::abs(bbox.centroid().x) < min_x) { min_x = std::abs(bbox.centroid().x); selected_object = i; } } return selected_object; } } // ntk
tjbwyk/myrgbdemo
nestk/ntk/detection/table_object_detector.hpp
C++
lgpl-3.0
10,289
package com.silicolife.textmining.processes.ir.patentpipeline.components.searchmodule.googlesearch; public class IRPatentIDRetrievalGoogleSearchConfigurationImpl implements IIRPatentIDRecoverGoogleSearchConfiguration { private String accessToken; private String CustomSearchID; public IRPatentIDRetrievalGoogleSearchConfigurationImpl(String accessToken, String CustomSearchID) { this.accessToken=accessToken; this.CustomSearchID=CustomSearchID; } @Override public String getAccessToken() { return accessToken; } @Override public String getCustomSearchID() { return CustomSearchID; } }
biotextmining/processes
src/main/java/com/silicolife/textmining/processes/ir/patentpipeline/components/searchmodule/googlesearch/IRPatentIDRetrievalGoogleSearchConfigurationImpl.java
Java
lgpl-3.0
614
public class PlstEscape { public void harvestConstructors( int stage ) { super.harvestConstructors( stage-1 ); } }
SergiyKolesnikov/fuji
examples/AHEAD/j2jast/PlstEscape.java
Java
lgpl-3.0
140
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\world\sound; use pocketmine\math\Vector3; use pocketmine\network\mcpe\protocol\LevelEventPacket; class IgniteSound implements Sound{ public function encode(?Vector3 $pos) : array{ return [LevelEventPacket::create(LevelEventPacket::EVENT_SOUND_IGNITE, 0, $pos)]; } }
JackNoordhuis/PocketMine-MP
src/world/sound/IgniteSound.php
PHP
lgpl-3.0
1,028
/*! @file @author Albert Semenov @date 11/2007 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_LayerItem.h" #include <algorithm> namespace MyGUI { LayerItem::LayerItem() : mLayer(nullptr), mLayerNode(nullptr), mSaveLayerNode(nullptr), mTexture(nullptr) { } LayerItem::~LayerItem() { } void LayerItem::addChildItem(LayerItem* _item) { mLayerItems.push_back(_item); if (mLayerNode != nullptr) { _item->attachToLayerItemNode(mLayerNode, false); } } void LayerItem::removeChildItem(LayerItem* _item) { VectorLayerItem::iterator item = std::remove(mLayerItems.begin(), mLayerItems.end(), _item); MYGUI_ASSERT(item != mLayerItems.end(), "item not found"); mLayerItems.erase(item); } void LayerItem::addChildNode(LayerItem* _item) { mLayerNodes.push_back(_item); if (mLayerNode != nullptr) { // создаем оверлаппеду новый айтем ILayerNode* child_node = mLayerNode->createChildItemNode(); _item->attachToLayerItemNode(child_node, true); } } void LayerItem::removeChildNode(LayerItem* _item) { VectorLayerItem::iterator item = std::remove(mLayerNodes.begin(), mLayerNodes.end(), _item); MYGUI_ASSERT(item != mLayerNodes.end(), "item not found"); mLayerNodes.erase(item); } void LayerItem::addRenderItem(ISubWidget* _item) { mDrawItems.push_back(_item); } void LayerItem::removeAllRenderItems() { detachFromLayerItemNode(false); mDrawItems.clear(); } void LayerItem::setRenderItemTexture(ITexture* _texture) { mTexture = _texture; if (mLayerNode) { ILayerNode* node = mLayerNode; // позже сделать детач без текста detachFromLayerItemNode(false); attachToLayerItemNode(node, false); } } void LayerItem::saveLayerItem() { mSaveLayerNode = mLayerNode; } void LayerItem::restoreLayerItem() { mLayerNode = mSaveLayerNode; if (mLayerNode) { attachToLayerItemNode(mLayerNode, false); } } void LayerItem::attachItemToNode(ILayer* _layer, ILayerNode* _node) { mLayer = _layer; mLayerNode = _node; attachToLayerItemNode(_node, true); } void LayerItem::detachFromLayer() { // мы уже отдетачены в доску if (nullptr == mLayer) return; // такого быть не должно MYGUI_ASSERT(mLayerNode, "mLayerNode == nullptr"); // отписываемся от пиккинга mLayerNode->detachLayerItem(this); // при детаче обнулиться ILayerNode* save = mLayerNode; // физически отсоединяем detachFromLayerItemNode(true); // отсоединяем леер и обнуляем у рутового виджета mLayer->destroyChildItemNode(save); mLayerNode = nullptr; mLayer = nullptr; } void LayerItem::upLayerItem() { if (mLayerNode) mLayerNode->getLayer()->upChildItemNode(mLayerNode); } void LayerItem::attachToLayerItemNode(ILayerNode* _item, bool _deep) { MYGUI_DEBUG_ASSERT(nullptr != _item, "attached item must be valid"); // сохраняем, чтобы последующие дети могли приаттачиться mLayerNode = _item; for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin) { (*skin)->createDrawItem(mTexture, _item); } for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item) { (*item)->attachToLayerItemNode(_item, _deep); } for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item) { // создаем оверлаппеду новый айтем if (_deep) { ILayerNode* child_node = _item->createChildItemNode(); (*item)->attachToLayerItemNode(child_node, _deep); } } } void LayerItem::detachFromLayerItemNode(bool _deep) { for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item) { (*item)->detachFromLayerItemNode(_deep); } for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item) { if (_deep) { ILayerNode* node = (*item)->mLayerNode; (*item)->detachFromLayerItemNode(_deep); if (node) { node->getLayer()->destroyChildItemNode(node); } } } // мы уже отаттачены ILayerNode* node = mLayerNode; if (node) { //for (VectorWidgetPtr::iterator widget = mWidgetChildSkin.begin(); widget != mWidgetChildSkin.end(); ++widget) (*widget)->_detachFromLayerItemKeeperByStyle(_deep); for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin) { (*skin)->destroyDrawItem(); } // при глубокой очистке, если мы оверлаппед, то для нас создавали айтем /*if (_deep && !this->isRootWidget() && mWidgetStyle == WidgetStyle::Overlapped) { node->destroyItemNode(); }*/ // очищаем mLayerNode = nullptr; } } ILayer* LayerItem::getLayer() const { return mLayer; } ILayerNode* LayerItem::getLayerNode() const { return mLayerNode; } } // namespace MyGUI
blunted2night/MyGUI
MyGUIEngine/src/MyGUI_LayerItem.cpp
C++
lgpl-3.0
5,791
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "describeidentityusagerequest.h" #include "describeidentityusagerequest_p.h" #include "describeidentityusageresponse.h" #include "cognitosyncrequest_p.h" namespace QtAws { namespace CognitoSync { /*! * \class QtAws::CognitoSync::DescribeIdentityUsageRequest * \brief The DescribeIdentityUsageRequest class provides an interface for CognitoSync DescribeIdentityUsage requests. * * \inmodule QtAwsCognitoSync * * <fullname>Amazon Cognito Sync</fullname> * * Amazon Cognito Sync provides an AWS service and client library that enable cross-device syncing of application-related * user data. High-level client libraries are available for both iOS and Android. You can use these libraries to persist * data locally so that it's available even if the device is offline. Developer credentials don't need to be stored on the * mobile device to access the service. You can use Amazon Cognito to obtain a normalized user ID and credentials. User * data is persisted in a dataset that can store up to 1 MB of key-value pairs, and you can have up to 20 datasets per user * * identity> * * With Amazon Cognito Sync, the data stored for each identity is accessible only to credentials assigned to that identity. * In order to use the Cognito Sync service, you need to make API calls using credentials retrieved with <a * href="http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/Welcome.html">Amazon Cognito Identity * * service</a>> * * If you want to use Cognito Sync in an Android or iOS application, you will probably want to make API calls via the AWS * Mobile SDK. To learn more, see the <a * href="http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-sync.html">Developer Guide for Android</a> * and the <a href="http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-sync.html">Developer Guide for * * \sa CognitoSyncClient::describeIdentityUsage */ /*! * Constructs a copy of \a other. */ DescribeIdentityUsageRequest::DescribeIdentityUsageRequest(const DescribeIdentityUsageRequest &other) : CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DescribeIdentityUsageRequest object. */ DescribeIdentityUsageRequest::DescribeIdentityUsageRequest() : CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(CognitoSyncRequest::DescribeIdentityUsageAction, this)) { } /*! * \reimp */ bool DescribeIdentityUsageRequest::isValid() const { return false; } /*! * Returns a DescribeIdentityUsageResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DescribeIdentityUsageRequest::response(QNetworkReply * const reply) const { return new DescribeIdentityUsageResponse(*this, reply); } /*! * \class QtAws::CognitoSync::DescribeIdentityUsageRequestPrivate * \brief The DescribeIdentityUsageRequestPrivate class provides private implementation for DescribeIdentityUsageRequest. * \internal * * \inmodule QtAwsCognitoSync */ /*! * Constructs a DescribeIdentityUsageRequestPrivate object for CognitoSync \a action, * with public implementation \a q. */ DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate( const CognitoSyncRequest::Action action, DescribeIdentityUsageRequest * const q) : CognitoSyncRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DescribeIdentityUsageRequest * class' copy constructor. */ DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate( const DescribeIdentityUsageRequestPrivate &other, DescribeIdentityUsageRequest * const q) : CognitoSyncRequestPrivate(other, q) { } } // namespace CognitoSync } // namespace QtAws
pcolby/libqtaws
src/cognitosync/describeidentityusagerequest.cpp
C++
lgpl-3.0
4,598
from pymongo import MongoClient import config class Database: def __init__(self, db_name=None): self.mongodb_client = create_mongodb_client() self.db = self.create_db(db_name) self.authenticate_user() def create_db(self, db_name): if db_name is None: return self.mongodb_client[config.get_database_name()] return self.mongodb_client[db_name] def authenticate_user(self): if config.is_database_authentication_enabled(): self.db.authenticate(config.get_database_user(), config.get_database_password()) def insert_document_in_collection(self, doc, collection_name): collection = self.db[collection_name] collection.insert_one(doc) def exist_doc_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] query_result = collection.find(search_condition).limit(1) return doc_found(query_result) def search_text_with_regex_in_collection(self, regex, field, collection_name): collection = self.db[collection_name] return collection.find({field: get_regex_dict(regex)}) def search_text_with_regex_in_collection_mul(self, regex_a, regex_b, field_a, field_b, collection_name): collection = self.db[collection_name] return collection.find({'$and': [{field_a: get_regex_dict(regex_a)}, {field_b: get_regex_dict(regex_b)}]}) def search_document_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] return collection.find_one(search_condition, {'_id': 0}) def search_documents_in_collection(self, search_condition, collection_name): collection = self.db[collection_name] return collection.find(search_condition, {'_id': 0}) def search_documents_and_aggregate(self, search_condition, aggregation, collection_name): collection = self.db[collection_name] return list(collection.aggregate([{'$match': search_condition}, {'$project': aggregation}])) def get_number_of_documents_in_collection(self, collection_name, filter_=None): collection = self.db[collection_name] return collection.count(filter_) def update_document_in_collection(self, filter_, update, collection_name, insert_if_not_exists=False): collection = self.db[collection_name] collection.update_one(filter_, {'$set': update}, upsert=insert_if_not_exists) def update_documents_in_collection(self, docs, find_filter, collection_name): if len(docs) > 0: bulk = self.db[collection_name].initialize_ordered_bulk_op() for doc in docs: bulk.find({find_filter: doc.get(find_filter)}).upsert().update({'$set': doc}) bulk.execute() def get_documents_from_collection(self, collection_name): collection = self.db[collection_name] return list(collection.find({}, {'_id': 0})) def get_documents_from_collection_in_range(self, collection_name, skip=0, limit=0): collection = self.db[collection_name] return list(collection.find({}, {'_id': 0}).skip(skip).limit(limit)) def delete_document_from_collection(self, query, collection_name): collection = self.db[collection_name] collection.delete_one(query) def close(self): self.mongodb_client.close() def drop_collection(self, collection_name): collection = self.db[collection_name] collection.drop() def insert_documents_in_collection(self, documents, collection_name): collection = self.db[collection_name] collection.insert_many(documents=documents) def create_mongodb_client(): return MongoClient(config.get_database_host(), config.get_database_port()) def doc_found(query_result): found = query_result.count() > 0 query_result.close() return found def get_regex_dict(regex): return {'$regex': regex}
fkie-cad/iva
database.py
Python
lgpl-3.0
3,952
/******************************************************************************* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2009-2011 by sprylab technologies GmbH * * WebInLoop - a program for testing web applications * * This file is part of WebInLoop. * * WebInLoop is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * WebInLoop is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with WebInLoop. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html> * for a copy of the LGPLv3 License. ******************************************************************************/ package com.sprylab.webinloop.util.mailer.tests; import javax.mail.MessagingException; import org.testng.Assert; import org.testng.annotations.Test; import com.sprylab.webinloop.util.mailer.MailAccountParseResult; @Test public class MailAccountParseResultTest { private String buildMailTargetString(String account, Integer lowerBound, Integer upperBound, String target) { String result = account; if (lowerBound != null && upperBound != null) { result += ":" + lowerBound + "-" + upperBound; } if (target != null) { result += ":" + target; } return result; } private void testParseMailTargetString(String account, Integer lowerBound, Integer upperBound, String target) throws MessagingException { String mailTarget = buildMailTargetString(account, lowerBound, upperBound, target); MailAccountParseResult result = MailAccountParseResult.parse(mailTarget); if (lowerBound == null) { lowerBound = 0; } if (upperBound == null) { upperBound = Integer.MAX_VALUE; } Assert.assertEquals(result.getMailAccount(), account); Assert.assertEquals(result.getLowerBound(), lowerBound); Assert.assertEquals(result.getUpperBound(), upperBound); Assert.assertEquals(result.getTarget(), target); } @Test public void parseAccount() throws MessagingException { String account = "mail1"; Integer lowerBound = null; Integer upperBound = null; String target = null; testParseMailTargetString(account, lowerBound, upperBound, target); } @Test public void parseAccountAndTarget() throws MessagingException { String account = "mail1"; Integer lowerBound = null; Integer upperBound = null; String target = "subject"; testParseMailTargetString(account, lowerBound, upperBound, target); } @Test public void parseAccountRangeAndTarget() throws MessagingException { String account = "mail1"; Integer lowerBound = 1; Integer upperBound = 10; String target = "subject"; testParseMailTargetString(account, lowerBound, upperBound, target); } }
sprylab/webinloop
webinloop/src/test/java/com/sprylab/webinloop/util/mailer/tests/MailAccountParseResultTest.java
Java
lgpl-3.0
3,415
/** * This file is part of the CRISTAL-iSE REST API. * Copyright (c) 2001-2016 The CRISTAL Consortium. All rights reserved. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * http://www.fsf.org/licensing/licenses/lgpl.html */ package org.cristalise.restapi; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import java.net.URLDecoder; import java.util.Date; import java.util.Map; import java.util.concurrent.Semaphore; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.cristalise.kernel.common.InvalidDataException; import org.cristalise.kernel.entity.proxy.ItemProxy; import org.cristalise.kernel.persistency.outcome.Outcome; import org.cristalise.kernel.persistency.outcome.Schema; import org.cristalise.kernel.scripting.Script; import org.cristalise.kernel.scripting.ScriptingEngineException; import org.cristalise.kernel.utils.CastorHashMap; import org.cristalise.kernel.utils.LocalObjectLoader; import org.cristalise.kernel.utils.Logger; import org.json.JSONObject; import org.json.XML; public class ScriptUtils extends ItemUtils { static Semaphore mutex = new Semaphore(1); public ScriptUtils() { super(); } /** * * @param item * @param script * @return * @throws ScriptingEngineException * @throws InvalidDataException */ protected Object executeScript(ItemProxy item, final Script script, CastorHashMap inputs) throws ScriptingEngineException, InvalidDataException { Object scriptResult = null; try { scriptResult = script.evaluate(item == null ? script.getItemPath() : item.getPath(), inputs, null, null); } catch (ScriptingEngineException e) { throw e; } catch (Exception e) { throw new InvalidDataException(e.getMessage()); } return scriptResult; } public Response executeScript(HttpHeaders headers, ItemProxy item, String scriptName, Integer scriptVersion, String inputJson, Map<String, Object> additionalInputs) { // FIXME: version should be retrieved from the current item or the Module // String view = "last"; if (scriptVersion == null) scriptVersion = 0; Script script = null; if (scriptName != null) { try { script = LocalObjectLoader.getScript(scriptName, scriptVersion); JSONObject json = new JSONObject( inputJson == null ? "{}" : URLDecoder.decode(inputJson, "UTF-8")); CastorHashMap inputs = new CastorHashMap(); for (String key: json.keySet()) { inputs.put(key, json.get(key)); } inputs.putAll(additionalInputs); return returnScriptResult(scriptName, item, null, script, inputs, produceJSON(headers.getAcceptableMediaTypes())); } catch (Exception e) { Logger.error(e); throw ItemUtils.createWebAppException("Error executing script, please contact support", e, Response.Status.NOT_FOUND); } } else { throw ItemUtils.createWebAppException("Name or UUID of Script was missing", Response.Status.NOT_FOUND); } } public Response returnScriptResult(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag) throws ScriptingEngineException, InvalidDataException { try { mutex.acquire(); return runScript(scriptName, item, schema, script, inputs, jsonFlag); } catch (ScriptingEngineException e) { throw e; } catch (Exception e) { throw new InvalidDataException(e.getMessage()); } finally { mutex.release(); } } /** * * @param scriptName * @param item * @param schema * @param script * @param jsonFlag whether the response is a JSON or XML * @return * @throws ScriptingEngineException * @throws InvalidDataException */ protected Response runScript(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag) throws ScriptingEngineException, InvalidDataException { String xmlOutcome = null; Object scriptResult = executeScript(item, script, inputs); if (scriptResult instanceof String) { xmlOutcome = (String)scriptResult; } else if (scriptResult instanceof Map) { //the map shall have one Key only String key = ((Map<?,?>) scriptResult).keySet().toArray(new String[0])[0]; xmlOutcome = (String)((Map<?,?>) scriptResult).get(key); } else throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND); if (xmlOutcome == null) throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND); if (schema != null) return getOutcomeResponse(new Outcome(xmlOutcome, schema), new Date(), jsonFlag); else { if (jsonFlag) return Response.ok(XML.toJSONObject(xmlOutcome).toString()).build(); else return Response.ok((xmlOutcome)).build(); } } }
cristal-ise/restapi
src/main/java/org/cristalise/restapi/ScriptUtils.java
Java
lgpl-3.0
6,223
/*-------------------------------------------------------------------- (C) Copyright 2006-2011 Barcelona Supercomputing Center Centro Nacional de Supercomputacion This file is part of Mercurium C/C++ source-to-source compiler. See AUTHORS file in the top level directory for information regarding developers and contributors. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Mercurium C/C++ source-to-source compiler is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Mercurium C/C++ source-to-source compiler; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------*/ #ifndef TL_PRAGMASUPPORT_HPP #define TL_PRAGMASUPPORT_HPP #include "tl-common.hpp" #include <string> #include <stack> #include <algorithm> #include "tl-clauses-info.hpp" #include "tl-compilerphase.hpp" #include "tl-langconstruct.hpp" #include "tl-handler.hpp" #include "tl-traverse.hpp" #include "tl-source.hpp" #include "cxx-attrnames.h" namespace TL { class LIBTL_CLASS ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const = 0; virtual ~ClauseTokenizer() { } }; class LIBTL_CLASS NullClauseTokenizer : public ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { ObjectList<std::string> result; result.append(str); return result; } }; class LIBTL_CLASS ExpressionTokenizer : public ClauseTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { int bracket_nesting = 0; ObjectList<std::string> result; std::string temporary(""); for (std::string::const_iterator it = str.begin(); it != str.end(); it++) { const char & c(*it); if (c == ',' && bracket_nesting == 0 && temporary != "") { result.append(temporary); temporary = ""; } else { if (c == '(' || c == '{' || c == '[') { bracket_nesting++; } else if (c == ')' || c == '}' || c == ']') { bracket_nesting--; } temporary += c; } } if (temporary != "") { result.append(temporary); } return result; } }; class LIBTL_CLASS ExpressionTokenizerTrim : public ExpressionTokenizer { public: virtual ObjectList<std::string> tokenize(const std::string& str) const { ObjectList<std::string> result; result = ExpressionTokenizer::tokenize(str); std::transform(result.begin(), result.end(), result.begin(), trimExp); return result; } private: static std::string trimExp (const std::string &str) { ssize_t first = str.find_first_not_of(" \t"); ssize_t last = str.find_last_not_of(" \t"); return str.substr(first, last - first + 1); } }; //! This class wraps a clause in a PragmaCustomConstruct /*! This class allows a clause to be named several times, thus #pragma prefix name clause(a) clause(b) will be equivalent as if the user had written #pragma prefix name clause(a, b) There is no way to tell apart these two cases, except for using PragmaCustomClause::get_arguments_unflattened, see below. Pragma clauses are pretty flexible on what they allow as arguments. Free, well parenthesized, text is allowed in clauses. Thus forwarding the responsability of giving a syntactic validity and semantic meaning to PragmaCustomCompilerPhase classes. Since the raw string is most of the time of little use, the class can cook some usual cases: When the clause should contain a list of expressions, use PragmaCustomClause::get_expression_list When the clause should contain a list of variable-names (but not general expressions), use PragmaCustomClause::get_id_expressions You can always get raw versions of the clause content (in case you have very special syntax in it requiring special parsing) using PragmaCustomClause::get_arguments and PragmaCustomClause::get_arguments_unflattened. The second version returns a list of lists of strings, one list per occurrence of the clause while the first flats them in a single list. */ class LIBTL_CLASS PragmaCustomClause : public LangConstruct { private: ObjectList<std::string> _clause_names; ObjectList<AST_t> filter_pragma_clause(); public: PragmaCustomClause(const std::string& src, AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link) { _clause_names.push_back(src); } PragmaCustomClause(const ObjectList<std::string> & src, AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link), _clause_names(src) { } //! Returns the name of the current clause std::string get_clause_name() { return _clause_names[0]; } //! States whether the clause was actually in the pragma /*! Since PragmaCustomConstruct always returns a PragmaCustomClause use this function to know whether the clause was actually in the pragma line. No other function of PragmaCustomClause should be used if this function returns false */ bool is_defined(); //! Convenience function, it returns all the arguments of the clause parsed as expressions ObjectList<Expression> get_expression_list(); //! Convenience function, it returns all arguments of the clause parsed as id-expressions ObjectList<IdExpression> get_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS); //! Do not use this one, its name is deprecated, use get_id_expressions instead ObjectList<IdExpression> id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS); //! Returns the string contents of the clause arguments /*! This function actually returns a list of a single element */ ObjectList<std::string> get_arguments(); //! Returns the string contents of the clause arguments but using a tokenizer /*! The tokenizer can further split the text in additional substrings */ ObjectList<std::string> get_arguments(const ClauseTokenizer&); //! Returns the string contents of the clause arguments but using a tokenizer /*! This function is similar to get_arguments but does not combine them in a single list. There is a list per each clause occurrence in the pragma */ ObjectList<ObjectList<std::string> > get_arguments_unflattened(); //! This is like get_arguments but at tree level. This function is of little use /*! It is highly unlikely that you need this function. Check the others */ ObjectList<AST_t> get_arguments_tree(); }; class LIBTL_CLASS PragmaCustomConstruct : public LangConstruct, public LinkData { private: DTO* _dto; public: PragmaCustomConstruct(AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link), _dto(NULL) { } //! Returns the name of the pragma prefix std::string get_pragma() const; //! Returns the name of the pragma directive std::string get_directive() const; //! States if this is a directive /*! When this function is true it means that the pragma itself is a sole entity */ bool is_directive() const; //! States if this is a construct /*! When this function is true it means that the pragma acts as a header of another language construct. Functions get_statement and get_declaration can then, be used to retrieve that language construct. For pragma constructs at block-scope only get_statement should be used, otherwise use get_declaration as the nested construct can be a declaration or a function definition (or even something else) */ bool is_construct() const; //! Returns the statement associated to this pragma construct /*! Using this function is only valid when the pragma is in block-scope and function is_construct returned true */ Statement get_statement() const; //! Returns the tree associated to this pragma construct /*! Using this function is only valid when the pragma is in a scope other than block and function is_construct returned true This tree can be a Declaration, FunctionDefinition or some other tree not wrapped yet in a LangConstruct (e.g. a Namespace definition) */ AST_t get_declaration() const; //! This function returns the tree related to the pragma itself /*! This function is rarely needed, only when a change of the pragma itself is required */ AST_t get_pragma_line() const; //! This is used internally to initialize clauses information /*! Use it only if you want automatic clause checks but you never call get_clause on it It is safe to call it more than once. */ void init_clause_info() const; //! States if the pragma encloses a function definition /*! This is useful when using get_declaration, to quickly know if we can use a FunctionDefinition or we should use a Declaration instead */ bool is_function_definition() const; //! States if the pragma is followed by a first clause-alike parenthesis pair /*! #pragma prefix directive(a,b) 'a,b' is sort of an unnamed clause which is called the parameter of the pragma This function states if this pragma has this syntax */ bool is_parameterized() const; //! Returns a list of IdExpression's found in the parameter of the pragma ObjectList<IdExpression> get_parameter_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS) const; //! Returns a list of Expressions in the parameter of the pragma /*! Parameters allow well-parenthesized free text. This function interprets the content of the parameter as a list of comma-separated expressions, parses them at this moment (if not parsed already) and returns it as a list */ ObjectList<Expression> get_parameter_expressions() const; //! Returns the string of the parameter of the pragma /*! Parameters allow well-parenthesized free text. This function returns the whole text with no tokenization. This function will always return one element, but for parallelism with the equivalent function of PragmaCustomClause it returns a list (that will contain a single element) */ ObjectList<std::string> get_parameter_arguments() const; //! Returns the string of the parameter of the pragma using a tokenizer /*! This function is identical to get_parameter_arguments() but uses \a tokenizer to split the contents of the string. */ ObjectList<std::string> get_parameter_arguments(const ClauseTokenizer& tokenizer) const; //! This function returns all the clauses of this pragma ObjectList<std::string> get_clause_names() const; //! This function returns a PragmaCustomClause object for a named clause /*! Note that this function always returns a PragmaCustomClause object even if no clause with the given /a name exists. Use PragmaCustomClause::is_defined to check its existence. Adds to the DTO of PragmaCustomCompilerPhase the clause only if /a name exists. */ PragmaCustomClause get_clause(const std::string& name) const; PragmaCustomClause get_clause(const ObjectList<std::string>& names) const; //! This function set to the object _dto the dto get from de compiler phase void set_dto(DTO* dto); //! This function returns a boolean that show if some warnings must be printed out bool get_show_warnings(); }; LIBTL_EXTERN bool is_pragma_custom(const std::string& pragma_preffix, AST_t ast, ScopeLink scope_link); LIBTL_EXTERN bool is_pragma_custom_directive(const std::string& pragma_preffix, const std::string& pragma_directive, AST_t ast, ScopeLink scope_link); LIBTL_EXTERN bool is_pragma_custom_construct(const std::string& pragma_preffix, const std::string& pragma_directive, AST_t ast, ScopeLink scope_link); typedef std::map<std::string, Signal1<PragmaCustomConstruct> > CustomFunctorMap; class LIBTL_CLASS PragmaCustomDispatcher : public TraverseFunctor { private: std::string _pragma_handled; CustomFunctorMap& _pre_map; CustomFunctorMap& _post_map; DTO* _dto; bool _warning_clauses; std::stack<PragmaCustomConstruct*> _construct_stack; void dispatch_pragma_construct(CustomFunctorMap& search_map, PragmaCustomConstruct& pragma_custom_construct); public: PragmaCustomDispatcher(const std::string& pragma_handled, CustomFunctorMap& pre_map, CustomFunctorMap& post_map, bool warning_clauses); virtual void preorder(Context ctx, AST_t node); virtual void postorder(Context ctx, AST_t node); void set_dto(DTO* dto); void set_warning_clauses(bool warning); }; //! Base class for all compiler phases working on user defined pragma lines /*! * Configuration of mcxx will require a 'pragma_prefix' line in order * to properly parse these pragma lines. In addition, the phases * will have to call register_directive and register_construct * accordingly to register specific constructs and directives. */ class LIBTL_CLASS PragmaCustomCompilerPhase : public CompilerPhase { private: std::string _pragma_handled; PragmaCustomDispatcher _pragma_dispatcher; public: //! Constructor /*! * \param pragma_handled The pragma prefix actually handled in this phase. */ PragmaCustomCompilerPhase(const std::string& pragma_handled); virtual void pre_run(DTO& data_flow); //! Entry point of the phase /*! * This function registers traverse functors to perform * a traversal on all the constructs and directives. */ virtual void run(DTO& data_flow); //! Custom functor map for directives found in preorder CustomFunctorMap on_directive_pre; //! Custom functor map for directives found in postorder CustomFunctorMap on_directive_post; //! Function to register a directive /*! * This is required for successful parsing of directives */ void register_directive(const std::string& name); //! Function to register a construct /*! * This is required for successful parsing of construct * * \param bound_to_statement This parameter is only meaningful in * Fortran and will have no effect in C/C++. If true, the * construct is bounded to the next single statement. By default in * Fortran a construct 'name' is bound to a block of statements, * thus requiring a 'end name' directive to know where such block * ends. By binding the construct to the next statement, such 'end * name' it is not strictly needed anymore thus becoming optional. * This parameter does not have any effect in C/C++ since in those * languages pragma constructs are always bound to the next * statement since blocks are expressed by compound-statements * which are statements (recursively) containing other statements */ void register_construct(const std::string& name, bool bound_to_statement = false); //! Function to activate a flag in order to warning about all the unused clauses of a pragma /*! * Each fase must activate this flag if wants to show the warnings */ void warning_pragma_unused_clauses(bool warning); }; } #endif // TL_PRAGMASUPPORT_HPP
sdruix/AutomaticParallelization
src/tl/tl-pragmasupport.hpp
C++
lgpl-3.0
18,927
""" useful decorators """ __author__ = "Philippe Guglielmetti" __copyright__ = "Copyright 2015, Philippe Guglielmetti" __credits__ = ["http://include.aorcsik.com/2014/05/28/timeout-decorator/"] __license__ = "LGPL + MIT" import multiprocessing from multiprocessing import TimeoutError from threading import Timer import weakref import threading import _thread as thread from multiprocessing.pool import ThreadPool import logging import functools import sys import logging _gettrace = getattr(sys, 'gettrace', None) debugger = _gettrace and _gettrace() logging.info('debugger ' + ('ACTIVE' if debugger else 'INACTIVE')) # http://wiki.python.org/moin/PythonDecoratorLibrary def memoize(obj): """speed up repeated calls to a function by caching its results in a dict index by params :see: https://en.wikipedia.org/wiki/Memoization """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer def debug(func): # Customize these messages ENTRY_MESSAGE = 'Entering {}' EXIT_MESSAGE = 'Exiting {}' @functools.wraps(func) def wrapper(*args, **kwds): logger = logging.getLogger() logger.info(ENTRY_MESSAGE.format(func.__name__)) level = logger.getEffectiveLevel() logger.setLevel(logging.DEBUG) f_result = func(*args, **kwds) logger.setLevel(level) logger.info(EXIT_MESSAGE.format(func.__name__)) return f_result return wrapper def nodebug(func): @functools.wraps(func) def wrapper(*args, **kwds): logger = logging.getLogger() level = logger.getEffectiveLevel() logger.setLevel(logging.INFO) f_result = func(*args, **kwds) logger.setLevel(level) return f_result return wrapper # https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d def timeit(method): import time def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() logging.info('%r %2.2f ms' % (method.__name__, (te - ts) * 1000)) return result return timed # http://include.aorcsik.com/2014/05/28/timeout-decorator/ # BUT read http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python thread_pool = None def get_thread_pool(): global thread_pool if thread_pool is None: # fix for python <2.7.2 if not hasattr(threading.current_thread(), "_children"): threading.current_thread()._children = weakref.WeakKeyDictionary() thread_pool = ThreadPool(processes=1) return thread_pool def timeout(timeout): def wrap_function(func): if not timeout: return func @functools.wraps(func) def __wrapper(*args, **kwargs): try: async_result = get_thread_pool().apply_async(func, args=args, kwds=kwargs) return async_result.get(timeout) except thread.error: return func(*args, **kwargs) return __wrapper return wrap_function # https://gist.github.com/goulu/45329ef041a368a663e5 def itimeout(iterable, timeout): """timeout for loops :param iterable: any iterable :param timeout: float max running time in seconds :yield: items in iterator until timeout occurs :raise: multiprocessing.TimeoutError if timeout occured """ if False: # handle debugger better one day ... n = 100 * timeout for i, x in enumerate(iterable): yield x if i > n: break else: timer = Timer(timeout, lambda: None) timer.start() for x in iterable: yield x if timer.finished.is_set(): raise TimeoutError # don't forget it, otherwise the thread never finishes... timer.cancel() # https://www.artima.com/weblogs/viewpost.jsp?thread=101605 registry = {} class MultiMethod(object): def __init__(self, name): self.name = name self.typemap = {} def __call__(self, *args): types = tuple(arg.__class__ for arg in args) # a generator expression! function = self.typemap.get(types) if function is None: raise TypeError("no match") return function(*args) def register(self, types, function): if types in self.typemap: raise TypeError("duplicate registration") self.typemap[types] = function def multimethod(*types): """ allows to overload functions for various parameter types @multimethod(int, int) def foo(a, b): ...code for two ints... @multimethod(float, float): def foo(a, b): ...code for two floats... @multimethod(str, str): def foo(a, b): ...code for two strings... """ def register(function): name = function.__name__ mm = registry.get(name) if mm is None: mm = registry[name] = MultiMethod(name) mm.register(types, function) return mm return register
goulu/Goulib
Goulib/decorators.py
Python
lgpl-3.0
5,279
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' Created on 18.02.2015 @author: marscher ''' import os import numpy as np from deeptime.clustering import ClusterModel, metrics from pyemma._base.serialization.serialization import SerializableMixIn from pyemma._base.model import Model from pyemma._base.parallel import NJobsMixIn from pyemma._ext.sklearn.base import ClusterMixin from pyemma.coordinates.data._base.transformer import StreamingEstimationTransformer from pyemma.util.annotators import fix_docs, aliased, alias from pyemma.util.discrete_trajectories import index_states, sample_indexes_by_state from pyemma.util.files import mkdir_p @fix_docs @aliased class AbstractClustering(StreamingEstimationTransformer, Model, ClusterMixin, NJobsMixIn, SerializableMixIn): """ provides a common interface for cluster algorithms. Parameters ---------- metric: str, default='euclidean' metric to pass to c extension n_jobs: int or None, default=None How much threads to use during assignment If None, all available CPUs will be used. """ def __init__(self, metric='euclidean', n_jobs=None): super(AbstractClustering, self).__init__() from ._ext import rmsd metrics.register("minRMSD", rmsd) self.metric = metric self.clustercenters = None self._previous_stride = -1 self._dtrajs = [] self._overwrite_dtrajs = False self._index_states = [] self.n_jobs = n_jobs __serialize_fields = ('_dtrajs', '_previous_stride', '_index_states', '_overwrite_dtrajs', '_precentered') __serialize_version = 0 def set_model_params(self, clustercenters): self.clustercenters = clustercenters @property @alias('cluster_centers_') # sk-learn compat. def clustercenters(self): """ Array containing the coordinates of the calculated cluster centers. """ return self._clustercenters @clustercenters.setter def clustercenters(self, val): self._clustercenters = np.asarray(val, dtype='float32', order='C')[:] if val is not None else None self._precentered = False @property def overwrite_dtrajs(self): """ Should existing dtraj files be overwritten. Set this property to True to overwrite. """ return self._overwrite_dtrajs @overwrite_dtrajs.setter def overwrite_dtrajs(self, value): self._overwrite_dtrajs = value @property #@alias('labels_') # TODO: for fully sklearn-compat this would have to be a flat array! def dtrajs(self): """Discrete trajectories (assigned data to cluster centers).""" if len(self._dtrajs) == 0: # nothing assigned yet, doing that now self._dtrajs = self.assign(stride=1) return self._dtrajs # returning what we have saved @property def index_clusters(self): """Returns trajectory/time indexes for all the clusters Returns ------- indexes : list of ndarray( (N_i, 2) ) For each state, all trajectory and time indexes where this cluster occurs. Each matrix has a number of rows equal to the number of occurrences of the corresponding state, with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. """ if len(self._dtrajs) == 0: # nothing assigned yet, doing that now self._dtrajs = self.assign() if len(self._index_states) == 0: # has never been run self._index_states = index_states(self._dtrajs) return self._index_states def sample_indexes_by_cluster(self, clusters, nsample, replace=True): """Samples trajectory/time indexes according to the given sequence of states. Parameters ---------- clusters : iterable of integers It contains the cluster indexes to be sampled nsample : int Number of samples per cluster. If replace = False, the number of returned samples per cluster could be smaller if less than nsample indexes are available for a cluster. replace : boolean, optional Whether the sample is with or without replacement Returns ------- indexes : list of ndarray( (N, 2) ) List of the sampled indices by cluster. Each element is an index array with a number of rows equal to N=len(sequence), with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory. """ # Check if the catalogue (index_states) if len(self._index_states) == 0: # has never been run self._index_states = index_states(self.dtrajs) return sample_indexes_by_state(self._index_states[clusters], nsample, replace=replace) def _transform_array(self, X): """get closest index of point in :attr:`clustercenters` to x.""" X = np.require(X, dtype=np.float32, requirements='C') # for performance reasons we pre-center the cluster centers for minRMSD. if self.metric == 'minRMSD' and not self._precentered: self._precentered = True model = ClusterModel(cluster_centers=self.clustercenters, metric=self.metric) dtraj = model.transform(X) res = dtraj[:, None] # always return a column vector in this function return res def dimension(self): """output dimension of clustering algorithm (always 1).""" return 1 def output_type(self): return np.int32() def assign(self, X=None, stride=1): """ Assigns the given trajectory or list of trajectories to cluster centers by using the discretization defined by this clustering method (usually a Voronoi tesselation). You can assign multiple times with different strides. The last result of assign will be saved and is available as the attribute :func:`dtrajs`. Parameters ---------- X : ndarray(T, n) or list of ndarray(T_i, n), optional, default = None Optional input data to map, where T is the number of time steps and n is the number of dimensions. When a list is provided they can have differently many time steps, but the number of dimensions need to be consistent. When X is not provided, the result of assign is identical to get_output(), i.e. the data used for clustering will be assigned. If X is given, the stride argument is not accepted. stride : int, optional, default = 1 If set to 1, all frames of the input data will be assigned. Note that this could cause this calculation to be very slow for large data sets. Since molecular dynamics data is usually correlated at short timescales, it is often sufficient to obtain the discretization at a longer stride. Note that the stride option used to conduct the clustering is independent of the assign stride. This argument is only accepted if X is not given. Returns ------- Y : ndarray(T, dtype=int) or list of ndarray(T_i, dtype=int) The discretized trajectory: int-array with the indexes of the assigned clusters, or list of such int-arrays. If called with a list of trajectories, Y will also be a corresponding list of discrete trajectories """ if X is None: # if the stride did not change and the discrete trajectory is already present, # just return it if self._previous_stride is stride and len(self._dtrajs) > 0: return self._dtrajs self._previous_stride = stride skip = self.skip if hasattr(self, 'skip') else 0 # map to column vectors mapped = self.get_output(stride=stride, chunk=self.chunksize, skip=skip) # flatten and save self._dtrajs = [np.transpose(m)[0] for m in mapped] # return return self._dtrajs else: if stride != 1: raise ValueError('assign accepts either X or stride parameters, but not both. If you want to map '+ 'only a subset of your data, extract the subset yourself and pass it as X.') # map to column vector(s) mapped = self.transform(X) # flatten if isinstance(mapped, np.ndarray): mapped = np.transpose(mapped)[0] else: mapped = [np.transpose(m)[0] for m in mapped] # return return mapped def save_dtrajs(self, trajfiles=None, prefix='', output_dir='.', output_format='ascii', extension='.dtraj'): """saves calculated discrete trajectories. Filenames are taken from given reader. If data comes from memory dtrajs are written to a default filename. Parameters ---------- trajfiles : list of str (optional) names of input trajectory files, will be used generate output files. prefix : str prepend prefix to filenames. output_dir : str save files to this directory. output_format : str if format is 'ascii' dtrajs will be written as csv files, otherwise they will be written as NumPy .npy files. extension : str file extension to append (eg. '.itraj') """ if extension[0] != '.': extension = '.' + extension # obtain filenames from input (if possible, reader is a featurereader) if output_format == 'ascii': from msmtools.dtraj import write_discrete_trajectory as write_dtraj else: from msmtools.dtraj import save_discrete_trajectory as write_dtraj import os.path as path output_files = [] if trajfiles is not None: # have filenames available? for f in trajfiles: p, n = path.split(f) # path and file basename, _ = path.splitext(n) if prefix != '': name = "%s_%s%s" % (prefix, basename, extension) else: name = "%s%s" % (basename, extension) # name = path.join(p, name) output_files.append(name) else: for i in range(len(self.dtrajs)): if prefix != '': name = "%s_%i%s" % (prefix, i, extension) else: name = str(i) + extension output_files.append(name) assert len(self.dtrajs) == len(output_files) if not os.path.exists(output_dir): mkdir_p(output_dir) for filename, dtraj in zip(output_files, self.dtrajs): dest = path.join(output_dir, filename) self.logger.debug('writing dtraj to "%s"' % dest) try: if path.exists(dest) and not self.overwrite_dtrajs: raise EnvironmentError('Attempted to write dtraj "%s" which already existed. To automatically' ' overwrite existing files, set source.overwrite_dtrajs=True.' % dest) write_dtraj(dest, dtraj) except IOError: self.logger.exception('Exception during writing dtraj to "%s"' % dest)
markovmodel/PyEMMA
pyemma/coordinates/clustering/interface.py
Python
lgpl-3.0
12,270
<import resource="classpath:/alfresco/templates/org/alfresco/import/alfresco-util.js"> /** * Cloud Sync Status Information * */ function main() { AlfrescoUtil.param("nodeRef"); AlfrescoUtil.param("site", "defaultSite"); AlfrescoUtil.param("rootPage", "documentlibrary"); AlfrescoUtil.param("rootLabelId", "path.documents"); var nodeDetails = AlfrescoUtil.getNodeDetails(model.nodeRef, model.site); if (nodeDetails) { model.item = nodeDetails.item; model.node = nodeDetails.item.node; model.paths = AlfrescoUtil.getPaths(nodeDetails, model.rootPage, model.rootLabelId); } } main();
loftuxab/community-edition-old
projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/node-details/node-path.get.js
JavaScript
lgpl-3.0
650
/* * Gene.java * * Copyright (c) 2013, Pablo Garcia-Sanchez. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * Contributors: */ package es.ugr.osgiliath.evolutionary.individual; import java.io.Serializable; public interface Gene extends Serializable, Cloneable{ public Object clone(); }
fergunet/osgiliath
OsgiliathEvolutionaryAlgorithm/src/es/ugr/osgiliath/evolutionary/individual/Gene.java
Java
lgpl-3.0
1,022
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.propagation.sampling; import org.orekit.errors.OrekitException; import org.orekit.errors.PropagationException; import org.orekit.propagation.SpacecraftState; import org.orekit.time.AbsoluteDate; /** * This class wraps an object implementing {@link OrekitFixedStepHandler} * into a {@link OrekitStepHandler}. * <p>It mirrors the <code>StepNormalizer</code> interface from <a * href="http://commons.apache.org/math/">commons-math</a> but * provides a space-dynamics interface to the methods.</p> * @author Luc Maisonobe * @version $Revision$ $Date$ */ public class OrekitStepNormalizer implements OrekitStepHandler { /** Serializable UID. */ private static final long serialVersionUID = 6335110162884693078L; /** Fixed time step. */ private double h; /** Underlying step handler. */ private OrekitFixedStepHandler handler; /** Last step date. */ private AbsoluteDate lastDate; /** Last State vector. */ private SpacecraftState lastState; /** Integration direction indicator. */ private boolean forward; /** Simple constructor. * @param h fixed time step (sign is not used) * @param handler fixed time step handler to wrap */ public OrekitStepNormalizer(final double h, final OrekitFixedStepHandler handler) { this.h = Math.abs(h); this.handler = handler; reset(); } /** Determines whether this handler needs dense output. * This handler needs dense output in order to provide data at * regularly spaced steps regardless of the steps the propagator * uses, so this method always returns true. * @return always true */ public boolean requiresDenseOutput() { return true; } /** Reset the step handler. * Initialize the internal data as required before the first step is * handled. */ public void reset() { lastDate = null; lastState = null; forward = true; } /** * Handle the last accepted step. * @param interpolator interpolator for the last accepted step. For * efficiency purposes, the various propagators reuse the same * object on each call, so if the instance wants to keep it across * all calls (for example to provide at the end of the propagation a * continuous model valid throughout the propagation range), it * should build a local copy using the clone method and store this * copy. * @param isLast true if the step is the last one * @throws PropagationException this exception is propagated to the * caller if the underlying user function triggers one */ public void handleStep(final OrekitStepInterpolator interpolator, final boolean isLast) throws PropagationException { try { if (lastState == null) { // initialize lastState in the first step case lastDate = interpolator.getPreviousDate(); interpolator.setInterpolatedDate(lastDate); lastState = interpolator.getInterpolatedState(); // take the propagation direction into account forward = interpolator.getCurrentDate().compareTo(lastDate) >= 0; if (!forward) { h = -h; } } // use the interpolator to push fixed steps events to the underlying handler AbsoluteDate nextTime = lastDate.shiftedBy(h); boolean nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0); while (nextInStep) { // output the stored previous step handler.handleStep(lastState, false); // store the next step lastDate = nextTime; interpolator.setInterpolatedDate(lastDate); lastState = interpolator.getInterpolatedState(); // prepare next iteration nextTime = nextTime.shiftedBy(h); nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0); } if (isLast) { // there will be no more steps, // the stored one should be flagged as being the last handler.handleStep(lastState, true); } } catch (OrekitException oe) { // recover a possible embedded PropagationException for (Throwable t = oe; t != null; t = t.getCause()) { if (t instanceof PropagationException) { throw (PropagationException) t; } } throw new PropagationException(oe.getMessage(), oe); } } }
haisamido/SFDaaS
src/org/orekit/propagation/sampling/OrekitStepNormalizer.java
Java
lgpl-3.0
5,548
namespace MBINCompiler.Models.Structs { public class TkCameraWanderData : NMSTemplate { public bool CamWander; public float CamWanderPhase; public float CamWanderAmplitude; [NMS(Size = 4, Ignore = true)] public byte[] PaddingC; } }
Bananasft/MBINCompiler
MBINCompiler/Models/Structs/TkCameraWanderData.cs
C#
lgpl-3.0
287
#include "visservotask.h" void VisuoServoTask::switchtotask(VISTaskNameT tn){ curtaskname.vist = tn; } void VisuoServoTask::switchtoglobalframe(){ mft = GLOBAL; } void VisuoServoTask::switchtolocalframe(){ mft = LOCAL; } VisuoServoTask::VisuoServoTask(VISTaskNameT tn) { curtaskname.vist = tn; desired_pose_range.setZero(); desired_dis = 0; } Eigen::Vector3d VisuoServoTask::get_desired_rotation_range(){ Eigen::Vector3d des; des.setZero(); des = desired_pose_range; return des; } double VisuoServoTask::get_desired_mv_dis(){ return desired_dis; } void VisuoServoTask::set_desired_mv_dis(double s){ desired_dis =s; }
liqiang1980/VTFS
src/TaskModule/visservotask.cpp
C++
lgpl-3.0
670
package de.invesdwin.nowicket.examples.guide.page.documentation.tagtransformations.tablesandchoices; import javax.annotation.concurrent.NotThreadSafe; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import de.invesdwin.nowicket.generated.binding.GeneratedBinding; import de.invesdwin.nowicket.generated.binding.processor.element.SelectHtmlElement; import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.BindingInterceptor; import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.component.palette.ModelPalette; @NotThreadSafe public class TablesAndChoicesPanel extends Panel { public TablesAndChoicesPanel(final String id, final IModel<TablesAndChoices> model) { super(id, model); new GeneratedBinding(this).withBindingInterceptor(new BindingInterceptor() { @Override public Component createSelect(final SelectHtmlElement e) { if (TablesAndChoicesConstants.asMultiselectPalette.equals(e.getWicketId())) { return new ModelPalette(e); } return super.createSelect(e); } }).bind(); } }
subes/invesdwin-nowicket
invesdwin-nowicket-examples/invesdwin-nowicket-examples-guide/src/main/java/de/invesdwin/nowicket/examples/guide/page/documentation/tagtransformations/tablesandchoices/TablesAndChoicesPanel.java
Java
lgpl-3.0
1,236
<?php namespace Google\AdsApi\Dfp\v201711; /** * This file was generated from WSDL. DO NOT EDIT. */ class LongCreativeTemplateVariable extends \Google\AdsApi\Dfp\v201711\CreativeTemplateVariable { /** * @var int $defaultValue */ protected $defaultValue = null; /** * @param string $label * @param string $uniqueName * @param string $description * @param boolean $isRequired * @param int $defaultValue */ public function __construct($label = null, $uniqueName = null, $description = null, $isRequired = null, $defaultValue = null) { parent::__construct($label, $uniqueName, $description, $isRequired); $this->defaultValue = $defaultValue; } /** * @return int */ public function getDefaultValue() { return $this->defaultValue; } /** * @param int $defaultValue * @return \Google\AdsApi\Dfp\v201711\LongCreativeTemplateVariable */ public function setDefaultValue($defaultValue) { $this->defaultValue = (!is_null($defaultValue) && PHP_INT_SIZE === 4) ? floatval($defaultValue) : $defaultValue; return $this; } }
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/LongCreativeTemplateVariable.php
PHP
lgpl-3.0
1,178
/* $Id: BioTreeContainer.hpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ /// @file BioTreeContainer.hpp /// User-defined methods of the data storage class. /// /// This file was originally generated by application DATATOOL /// using the following specifications: /// 'biotree.asn'. /// /// New methods or data members can be added to it if needed. /// See also: BioTreeContainer_.hpp #ifndef OBJECTS_BIOTREE_BIOTREECONTAINER_HPP #define OBJECTS_BIOTREE_BIOTREECONTAINER_HPP // generated includes #include <objects/biotree/BioTreeContainer_.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: ///////////////////////////////////////////////////////////////////////////// class NCBI_BIOTREE_EXPORT CBioTreeContainer : public CBioTreeContainer_Base { typedef CBioTreeContainer_Base Tparent; public: // constructor CBioTreeContainer(void); // destructor ~CBioTreeContainer(void); size_t GetNodeCount() const; size_t GetLeafCount() const; private: // Prohibit copy constructor and assignment operator CBioTreeContainer(const CBioTreeContainer& value); CBioTreeContainer& operator=(const CBioTreeContainer& value); }; /////////////////// CBioTreeContainer inline methods // constructor inline CBioTreeContainer::CBioTreeContainer(void) { } /////////////////// end of CBioTreeContainer inline methods END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_BIOTREE_BIOTREECONTAINER_HPP /* Original file checksum: lines: 94, chars: 2716, CRC32: ccfc4edf */
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/include/objects/biotree/BioTreeContainer.hpp
C++
lgpl-3.0
2,831
package ch.hefr.gridgroup.magate.em; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.hefr.gridgroup.magate.MaGateEntity; import ch.hefr.gridgroup.magate.em.ssl.BlatAntNestController; import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestController; import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestObserver; import ch.hefr.gridgroup.magate.env.MaGateMessage; import ch.hefr.gridgroup.magate.env.MaGateParam; import ch.hefr.gridgroup.magate.storage.*; public class SSLService implements IResDiscovery { private static Log log = LogFactory.getLog(SSLService.class); private MaGateEntity maGate; private String maGateIdentity; // private int timeout = 500; private int counter = 0; private Map<String, String> results = new HashMap<String, String>(); private HashMap<String,Object> maGateProfile = new HashMap<String,Object>(); public SSLService(MaGateEntity maGate) { this.maGate = maGate; this.maGateIdentity = maGate.getMaGateIdentity(); // Create and preserve the profile of MaGate Node this.maGateProfile = new HashMap<String,Object>(); maGateProfile.put(MaGateMessage.MatchProfile_OS, this.maGate.getLRM().getOsType()); maGateProfile.put(MaGateMessage.MatchProfile_CPUCount, new Integer(this.maGate.getLRM().getNumOfPEPerResource())); maGateProfile.put(MaGateMessage.MatchProfile_VO, this.maGate.getLRM().getVO()); // maGateProfile.put(MaGateMessage.MatchProfile_ExePrice, new Double(-1.0)); this.maGate.setMaGateProfile(maGateProfile); // IMPORTANT: register a Nest for resource discovery try { this.maGate.getMaGateInfra().updateProfile(maGateIdentity, maGateProfile); } catch (Exception e) { e.printStackTrace(); } } /** * Send synchronous query for searching remote MaGates */ public String[] syncSearchRemoteNode(ConcurrentHashMap<String,Object> extQuery) { String queryId = this.maGateIdentity + "_" + java.util.UUID.randomUUID().toString(); String[] resultArray = null; this.results.put(queryId, ""); HashMap<String,Object> query = new HashMap<String,Object>(); query.put(MaGateMessage.MatchProfile_OS, extQuery.get(MaGateMessage.MatchProfile_OS)); query.put(MaGateMessage.MatchProfile_CPUCount, extQuery.get(MaGateMessage.MatchProfile_CPUCount)); try { // send the query this.maGate.getMaGateInfra().startQuery(this.maGateIdentity, queryId, query); // record the search issue int currentCommunitySearch = this.maGate.getStorage().getCommunitySearch().get(); this.maGate.getStorage().setCommunitySearch(new AtomicInteger(currentCommunitySearch + 1)); /*************************************************************************** * Sleep a while and collect the returned results while the time is reached ***************************************************************************/ Thread.sleep(MaGateParam.timeSearchCommunity); String result = this.results.get(queryId); resultArray = result.split("_"); // Remove Redundancy this.results.remove(queryId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // In case new nodes discovered, put them into the cached netowrkNeighbor Map NetworkNeighborsManager.cacheNetworkNeighbors(this.maGate, resultArray); return resultArray; } /** * Result found from the infrastructure */ public void onResultFound(String queryId, String matchedResult) { if(this.results.containsKey(queryId)) { String existResult = this.results.get(queryId); this.results.put(queryId, existResult + matchedResult + "_"); } else { this.results.put(queryId, matchedResult + "_"); } } public HashMap<String, Object> getMaGateProfile() { return maGateProfile; } }
huangye177/magate
src/main/java/ch/hefr/gridgroup/magate/em/SSLService.java
Java
lgpl-3.0
4,030
<?php /** * https://neofr.ag * @author: Michaël BILCOT <michael.bilcot@neofr.ag> */ namespace NF\Modules\Monitoring; use NF\NeoFrag\Addons\Module; class Monitoring extends Module { protected function __info() { return [ 'title' => 'Monitoring', 'description' => '', 'icon' => 'fas fa-heartbeat', 'link' => 'https://neofr.ag', 'author' => 'Michaël BILCOT & Jérémy VALENTIN <contact@neofrag.com>', 'license' => 'LGPLv3 <https://neofr.ag/license>', 'admin' => FALSE ]; } public function need_checking() { return ($this->config->nf_monitoring_last_check < ($time = strtotime('01:00')) && time() > $time) || !file_exists('cache/monitoring/monitoring.json'); } public function display() { if (file_exists('cache/monitoring/monitoring.json')) { foreach (array_merge(array_fill_keys(['danger', 'warning', 'info'], 0), array_count_values(array_map(function($a){ return $a[1]; }, json_decode(file_get_contents('cache/monitoring/monitoring.json'))->notifications))) as $class => $count) { if ($count) { return '<span class="float-right badge badge-'.$class.'">'.$count.'</span>'; } } } return ''; } }
NeoFragCMS/neofrag-cms
modules/monitoring/monitoring.php
PHP
lgpl-3.0
1,215
#include "precice/impl/DataContext.hpp" #include <memory> namespace precice { namespace impl { logging::Logger DataContext::_log{"impl::DataContext"}; DataContext::DataContext(mesh::PtrData data, mesh::PtrMesh mesh) { PRECICE_ASSERT(data); _providedData = data; PRECICE_ASSERT(mesh); _mesh = mesh; } mesh::PtrData DataContext::providedData() { PRECICE_ASSERT(_providedData); return _providedData; } mesh::PtrData DataContext::toData() { PRECICE_ASSERT(_toData); return _toData; } std::string DataContext::getDataName() const { PRECICE_ASSERT(_providedData); return _providedData->getName(); } int DataContext::getProvidedDataID() const { PRECICE_ASSERT(_providedData); return _providedData->getID(); } int DataContext::getFromDataID() const { PRECICE_TRACE(); PRECICE_ASSERT(hasMapping()); PRECICE_ASSERT(_fromData); return _fromData->getID(); } void DataContext::resetProvidedData() { PRECICE_TRACE(); _providedData->toZero(); } void DataContext::resetToData() { PRECICE_TRACE(); _toData->toZero(); } int DataContext::getToDataID() const { PRECICE_TRACE(); PRECICE_ASSERT(hasMapping()); PRECICE_ASSERT(_toData); return _toData->getID(); } int DataContext::getDataDimensions() const { PRECICE_TRACE(); PRECICE_ASSERT(_providedData); return _providedData->getDimensions(); } std::string DataContext::getMeshName() const { PRECICE_ASSERT(_mesh); return _mesh->getName(); } int DataContext::getMeshID() const { PRECICE_ASSERT(_mesh); return _mesh->getID(); } void DataContext::setMapping(MappingContext mappingContext, mesh::PtrData fromData, mesh::PtrData toData) { PRECICE_ASSERT(!hasMapping()); PRECICE_ASSERT(fromData); PRECICE_ASSERT(toData); _mappingContext = mappingContext; PRECICE_ASSERT(fromData == _providedData || toData == _providedData, "Either fromData or toData has to equal _providedData."); PRECICE_ASSERT(fromData->getName() == getDataName()); _fromData = fromData; PRECICE_ASSERT(toData->getName() == getDataName()); _toData = toData; PRECICE_ASSERT(_toData != _fromData); } bool DataContext::hasMapping() const { return hasReadMapping() || hasWriteMapping(); } bool DataContext::hasReadMapping() const { return _toData == _providedData; } bool DataContext::hasWriteMapping() const { return _fromData == _providedData; } const MappingContext DataContext::mappingContext() const { PRECICE_ASSERT(hasMapping()); return _mappingContext; } } // namespace impl } // namespace precice
precice/precice
src/precice/impl/DataContext.cpp
C++
lgpl-3.0
2,508
/* global shoproot */ /** * 编辑分类 * @description Hope You Do Good But Not Evil * @copyright Copyright 2014-2015 <ycchen@iwshop.cn> * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @author Chenyong Cai <ycchen@iwshop.cn> * @package Wshop * @link http://www.iwshop.cn */ requirejs(['jquery', 'util', 'fancyBox', 'jUploader'], function ($, Util, fancyBox, jUploader) { $(function () { $("#pd-cat-select").find("option[value='" + $('#cat_parent').val() + "']").get(0).selected = true; $('#del-cate').click(function () { if (confirm('你确定要删除这个分类吗')) { $.post('?/wProduct/ajaxDelCategroy/', { id: $('#cat_id').val() }, function (r) { r = parseInt(r); if (r > 0) { alert('删除成功'); window.parent.fnDelSelectCat(); window.parent.location.reload(); } }); } }); // alter $('#save-cate').click(function () { var data = $('#catForm').serializeArray(); $.post('?/wProduct/ajaxAlterCategroy/', { id: $('#cat_id').val(), data: data }, function (r) { r = parseInt(r); if (r > 0) { Util.Alert('保存成功'); window.parent.fnReloadTree(); } else { Util.Alert('保存失败'); } }); }); $.jUploader({ button: 'alter_categroy_image', action: '?/wImages/ImageUpload/', onComplete: function (fileName, response) { if (response.ret_code == 0) { $('#cat_image_src').val(response.ret_msg); $('#catimage').attr('src', response.ret_msg).show(); $('#cat_none_pic').hide(); Util.Alert('上传图片成功'); } else { Util.Alert('上传图片失败'); } } }); }); });
mentallxm/iwshop
static/script/Wdmin/products/alter_categroy.js
JavaScript
lgpl-3.0
2,214
class DropCommunityPlans < ActiveRecord::Migration def up drop_table :community_plans end def down create_table "community_plans" do |t| t.integer "community_id", :null => false t.integer "plan_level", :default => 0, :null => false t.datetime "expires_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end end end
ziyoucaishi/marketplace
db/migrate/20151204083028_drop_community_plans.rb
Ruby
lgpl-3.0
452
<?php /** * Contao Open Source CMS, Copyright (C) 2005-2013 Leo Feyer * * Module Backend User Online - DCA * * @copyright Glen Langer 2012..2013 <http://www.contao.glen-langer.de> * @author Glen Langer (BugBuster) * @package BackendUserOnline * @license LGPL * @filesource * @see https://github.com/BugBuster1701/backend_user_online */ /** * DCA Config, overwrite label_callback */ $GLOBALS['TL_DCA']['tl_member']['list']['label']['label_callback'] = array('BugBuster\BackendUserOnline\DCA_member_onlineicon','addIcon');
BugBuster1701/backend_user_online
dca/tl_member.php
PHP
lgpl-3.0
560
""" X """ import cPickle as pickle import os import numpy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class PlotInterface(object): def plot_timeseries(self, times, values): pass def plot_sinwave(self, times, sinewave): pass def plot_area_ratio(self, on_period_area, off_period_area): pass def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): pass def plot_acf(self, times, acf): pass def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): pass def show(self): pass class ImageOutput(PlotInterface): """ Output the timeseries data and the period estimate as plot in png format """ def __init__(self, jobid, metricname): ijobid = int(jobid) top = (ijobid / 1000000) middle = (ijobid / 1000) % 1000 try: os.makedirs("{}/{}".format(top, middle)) except OSError: pass self.outfilename = "{}/{}/{}_{}.png".format(top, middle, jobid, metricname) self.fig = plt.figure() self.data_ax = plt.subplot(211, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)') self.sine_ax = None self.verbose = False def plot_timeseries(self, times, values): self.data_ax.plot(times, values / 1024.0 / 1024.0, label='Timeseries') def plot_sinwave(self, times, sinewave): self.sine_ax = plt.subplot(212, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)') self.sine_ax.plot(times, sinewave / 1024.0 / 1024.0, label='Estimate') def show(self): self.fig.tight_layout() self.fig.savefig(self.outfilename, format='png', transparent=True) class Dumper(object): def __init__(self, filename='data.dat'): self.filename = filename self.data = {} self.verbose = True def plot_timeseries(self, times, values): self.data['timeseries'] = (times, values) def plot_sinwave(self, times, sinewave): self.data['sinewave'] = (times, sinewave) def plot_area_ratio(self, on_period_area, off_period_area): self.data['area_ratio'] = (on_period_area, off_period_area) def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): self.data['periodogram'] = (periods, powers, hints, power_threshold, time_threshold) def plot_acf(self, times, acf): self.data['acf'] = (times, acf) def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): self.data['acf_validation'] = (times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx) def show(self): with open(self.filename, 'wb') as fp: pickle.dump(self.data, fp) def load(self): with open(self.filename, 'rb') as fp: self.data = pickle.load(fp) class Plotter(object): def __init__(self, title="Autoperiod", filename='output.pdf', figsize=(4, 3), verbose=False): self.title = title self.filename = filename self.fig = plt.figure() self.figsize = figsize self.verbose = verbose self.timeseries_ax = plt.subplot2grid((3, 10), (0, 0), colspan=9, xlabel='Times', ylabel='Values') self.area_ratio_ax = plt.subplot2grid((3, 10), (0, 9), colspan=1, xticks=(1, 2), xticklabels=("on", "off")) self.area_ratio_ax.get_yaxis().set_visible(False) self.periodogram_ax = plt.subplot2grid((3, 10), (1, 0), colspan=10, xlabel='Period', ylabel='Power') self.acf_ax = plt.subplot2grid((3, 10), (2, 0), colspan=10, xlabel='Lag', ylabel='Correlation') self.time_threshold = None def plot_timeseries(self, times, values): self.timeseries_ax.plot(times, values, label='Timeseries') self.timeseries_ax.legend() def plot_sinwave(self, times, sinwave): self.timeseries_ax.plot(times, sinwave, label='Estimated Period') self.timeseries_ax.legend() def plot_area_ratio(self, on_period_area, off_period_area): self.area_ratio_ax.bar(1, on_period_area) self.area_ratio_ax.bar(2, off_period_area) self.area_ratio_ax.legend() def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold): self.time_threshold = time_threshold self.periodogram_ax.plot(periods, powers, label='Periodogram') self.periodogram_ax.scatter([p for i, p in hints], [powers[i] for i, p in hints], c='red', marker='x', label='Period Hints') self.periodogram_ax.axhline(power_threshold, color='green', linewidth=1, linestyle='dashed', label='Min Power') #self.periodogram_ax.axvline(time_threshold, c='purple', linewidth=1, linestyle='dashed', label='Max Period') self.periodogram_ax.legend() self.periodogram_ax.set_xlim([0, self.time_threshold]) def plot_acf(self, times, acf): self.acf_ax.plot(times, acf, '-o', lw=0.5, ms=2, label='Autocorrelation') if self.time_threshold is not None: self.acf_ax.set_xlim([0, self.time_threshold]) self.acf_ax.legend() def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx): self.acf_ax.plot(times1, c1 + m1 * times1, c='r', label='Slope: {}, Error: {}'.format(m1, err1)) self.acf_ax.plot(times2, c2 + m2 * times2, c='r', label='Slope: {}, Error: {}'.format(m2, err2)) self.acf_ax.scatter(times[split_idx], acf[split_idx], c='y', label='Split point: {}'.format(times[split_idx])) self.acf_ax.scatter(times[peak_idx], acf[peak_idx], c='g', label='Peak point: {}'.format(times[peak_idx])) self.acf_ax.legend() def show(self): self.fig.tight_layout() if self.filename: self.fig.set_size_inches(*self.figsize) self.fig.savefig(self.filename, format='pdf', facecolor=self.fig.get_facecolor()) def main(): """ X """ d = Dumper('gpfs-fsios-write_bytes_data.dat') d.load() p = Plotter() p.plot_timeseries(*d.data['timeseries']) p.plot_sinwave(*d.data['sinewave']) p.plot_area_ratio(*d.data['area_ratio']) p.plot_periodogram(*d.data['periodogram']) p.plot_acf(*d.data['acf']) p.plot_acf_validation(*d.data['acf_validation']) p.show() if __name__ == "__main__": main()
ubccr/supremm
src/supremm/datadumper.py
Python
lgpl-3.0
6,457
<?php // ---------- CREDITS ---------- // Mirrored from pocketmine\network\mcpe\protocol\PlayerActionPacket.php // Mirroring was done by @CortexPE of @LeverylTeam :D // // NOTE: We know that this was hacky... But It's here to still provide support for old plugins // ---------- CREDITS ---------- namespace pocketmine\network\protocol; use pocketmine\network\mcpe\protocol\PlayerActionPacket as Original; class PlayerActionPacket extends Original { }
LeverylTeam/Leveryl
src/pocketmine/network/protocol/PlayerActionPacket.php
PHP
lgpl-3.0
461
# Copyright (c) 2010-2018 Benjamin Peterson # # 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. """ Utilities for writing code that runs on Python 2 and 3 WARNING: THIS VERSION OF SIX HAS BEEN MODIFIED. Changed line 658: def u(s): s = s.replace(r'\\', r'\\\\') if isinstance(s, unicode): return s else: return unicode(s, "unicode_escape") """ from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <benjamin@python.org>" __version__ = "1.12.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), MovedAttribute("parse_http_list", "urllib2", "urllib.request"), MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s, encoding=None): return str(s) unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s, encoding="unicode_escape"): if not isinstance(s, basestring): s = unicode(s, encoding) s = s.replace(r'\\', r'\\\\') if isinstance(s, unicode): return s else: return unicode(s, encoding) unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): try: raise tp, value, tb finally: tb = None """) if sys.version_info[:2] == (3, 2): exec_("""def raise_from(value, from_value): try: if from_value is None: raise value raise value from from_value finally: value = None """) elif sys.version_info[:2] > (3, 2): exec_("""def raise_from(value, from_value): try: raise value from from_value finally: value = None """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) if hasattr(cls, '__qualname__'): orig_vars['__qualname__'] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding='utf-8', errors='strict'): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding='utf-8', errors='strict'): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
krathjen/studiolibrary
src/studiovendor/six.py
Python
lgpl-3.0
32,901
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: ....... * * File Description: * ....... * * Remark: * This code was originally generated by application DATATOOL * using the following specifications: * 'mmdb2.asn'. */ // standard includes #include <ncbi_pch.hpp> // generated includes #include <objects/mmdb2/Reference_frame.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // destructor CReference_frame::~CReference_frame(void) { } END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE /* Original file checksum: lines: 57, chars: 1738, CRC32: 6dc78079 */
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/objects/mmdb2/Reference_frame.cpp
C++
lgpl-3.0
1,865
/* * This file is part of MyPet * * Copyright © 2011-2016 Keyle * MyPet is licensed under the GNU Lesser General Public License. * * MyPet is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.Keyle.MyPet.api.skill.experience; import org.bukkit.entity.EntityType; import java.util.HashMap; import java.util.Map; public class MonsterExperience { public static final Map<String, MonsterExperience> mobExp = new HashMap<>(); private static MonsterExperience unknown = new MonsterExperience(0., "UNKNOWN"); static { mobExp.put("SKELETON", new MonsterExperience(5., "SKELETON")); mobExp.put("ZOMBIE", new MonsterExperience(5., "ZOMBIE")); mobExp.put("SPIDER", new MonsterExperience(5., "SPIDER")); mobExp.put("WOLF", new MonsterExperience(1., 3., "WOLF")); mobExp.put("CREEPER", new MonsterExperience(5., "CREEPER")); mobExp.put("GHAST", new MonsterExperience(5., "GHAST")); mobExp.put("PIG_ZOMBIE", new MonsterExperience(5., "PIG_ZOMBIE")); mobExp.put("ENDERMAN", new MonsterExperience(5., "ENDERMAN")); mobExp.put("ENDERMITE", new MonsterExperience(3., "ENDERMITE")); mobExp.put("CAVE_SPIDER", new MonsterExperience(5., "CAVE_SPIDER")); mobExp.put("MAGMA_CUBE", new MonsterExperience(1., 4., "MAGMA_CUBE")); mobExp.put("SLIME", new MonsterExperience(1., 4., "SLIME")); mobExp.put("SILVERFISH", new MonsterExperience(5., "SILVERFISH")); mobExp.put("BLAZE", new MonsterExperience(10., "BLAZE")); mobExp.put("GIANT", new MonsterExperience(25., "GIANT")); mobExp.put("GUARDIAN", new MonsterExperience(10., "GUARDIAN")); mobExp.put("COW", new MonsterExperience(1., 3., "COW")); mobExp.put("PIG", new MonsterExperience(1., 3., "PIG")); mobExp.put("CHICKEN", new MonsterExperience(1., 3., "CHICKEN")); mobExp.put("SQUID", new MonsterExperience(1., 3., "SQUID")); mobExp.put("SHEEP", new MonsterExperience(1., 3., "SHEEP")); mobExp.put("OCELOT", new MonsterExperience(1., 3., "OCELOT")); mobExp.put("MUSHROOM_COW", new MonsterExperience(1., 3., "MUSHROOM_COW")); mobExp.put("VILLAGER", new MonsterExperience(0., "VILLAGER")); mobExp.put("SHULKER", new MonsterExperience(5., "SHULKER")); mobExp.put("SNOWMAN", new MonsterExperience(0., "SNOWMAN")); mobExp.put("IRON_GOLEM", new MonsterExperience(0., "IRON_GOLEM")); mobExp.put("ENDER_DRAGON", new MonsterExperience(20000., "ENDER_DRAGON")); mobExp.put("WITCH", new MonsterExperience(10., "WITCH")); mobExp.put("BAT", new MonsterExperience(1., "BAT")); mobExp.put("ENDER_CRYSTAL", new MonsterExperience(10., "ENDER_CRYSTAL")); mobExp.put("WITHER", new MonsterExperience(100., "WITHER")); mobExp.put("RABBIT", new MonsterExperience(1., "RABBIT")); mobExp.put("VINDICATOR", new MonsterExperience(5., "VINDICATOR")); mobExp.put("EVOKER", new MonsterExperience(10., "EVOKER")); mobExp.put("VEX", new MonsterExperience(3., "VEX")); mobExp.put("LLAMA", new MonsterExperience(0., "LLAMA")); } private double min; private double max; private String entityType; public MonsterExperience(double min, double max, String entityType) { if (max >= min) { this.max = max; this.min = min; } else if (max <= min) { this.max = min; this.min = max; } this.entityType = entityType; } public MonsterExperience(double exp, String entityType) { this.max = exp; this.min = exp; this.entityType = entityType; } public double getRandomExp() { return max == min ? max : ((int) (doubleRandom(min, max) * 100)) / 100.; } public double getMin() { return min; } public double getMax() { return max; } public EntityType getEntityType() { return EntityType.valueOf(entityType); } public void setMin(double min) { this.min = min; if (min > max) { max = min; } } public void setMax(double max) { this.max = max; if (max < min) { min = max; } } public void setExp(double exp) { max = (min = exp); } private static double doubleRandom(double low, double high) { return Math.random() * (high - low) + low; } @Override public String toString() { return entityType + "{min=" + min + ", max=" + max + "}"; } public static MonsterExperience getMonsterExperience(EntityType type) { if (mobExp.containsKey(type.name())) { return mobExp.get(type.name()); } return unknown; } }
jjm223/MyPet
modules/API/src/main/java/de/Keyle/MyPet/api/skill/experience/MonsterExperience.java
Java
lgpl-3.0
5,371
/** * Copyright (c) 2012-2014, Andrea Funto'. All rights reserved. See LICENSE for details. */ package org.dihedron.patterns.visitor.nodes; import java.util.Map; import org.dihedron.core.License; import org.dihedron.patterns.visitor.VisitorException; /** * @author Andrea Funto' */ @License public class ModifiableMapEntryNode extends UnmodifiableMapEntryNode { /** * Constructor. * * @param name * the pseudo-OGNL path of the node. * @param map * the map owning this node. * @param key * the key of this entry in the map. */ public ModifiableMapEntryNode(String name, Map<?, ?> map, Object key) { super(name, map, key); } /** * @see org.dihedron.patterns.visitor.nodes.AbstractNode#getValue() */ @SuppressWarnings("unchecked") public void setValue(Object value) throws VisitorException { ((Map<Object, Object>)map).put(key, value); } }
dihedron/dihedron-commons
src/main/java/org/dihedron/patterns/visitor/nodes/ModifiableMapEntryNode.java
Java
lgpl-3.0
888
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2015 Ricardo Mariaca * http://www.dynamicreports.org * * This file is part of DynamicReports. * * DynamicReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DynamicReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.report.builder.condition; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.constant.Constants; import net.sf.dynamicreports.report.definition.DRIValue; import net.sf.dynamicreports.report.definition.ReportParameters; import org.apache.commons.lang3.Validate; /** * @author Ricardo Mariaca (r.mariaca@dynamicreports.org) */ public class EqualExpression extends AbstractSimpleExpression<Boolean> { private static final long serialVersionUID = Constants.SERIAL_VERSION_UID; private DRIValue<?> value; private Object[] values; public <T> EqualExpression(DRIValue<T> value, T ...values) { Validate.notNull(value, "value must not be null"); Validate.noNullElements(values, "values must not contains null value"); this.value = value; this.values = values; } @Override public Boolean evaluate(ReportParameters reportParameters) { Object actualValue = reportParameters.getValue(value); for (Object value : values) { if (value.equals(actualValue)) { return true; } } return false; } @Override public Class<Boolean> getValueClass() { return Boolean.class; } }
svn2github/dynamicreports-jasper
dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/condition/EqualExpression.java
Java
lgpl-3.0
2,144
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the n2n module ROCKET. * * ROCKET is free software: you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation, either * version 2.1 of the License, or (at your option) any later version. * * ROCKET is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg...........: Architect, Lead Developer, Concept * Bert Hofmänner.............: Idea, Frontend UI, Design, Marketing, Concept * Thomas Günther.............: Developer, Frontend UI, Rocket Capability for Hangar */ namespace rocket\si\content\impl\split; use n2n\util\ex\IllegalStateException; use rocket\si\content\impl\OutSiFieldAdapter; class SplitOutSiField extends OutSiFieldAdapter { private $subFields = []; private $splitContents = []; function __construct() { } /** * {@inheritDoc} * @see \rocket\si\content\SiField::getType() */ function getType(): string { return 'split-out'; } /** * {@inheritDoc} * @see \rocket\si\content\SiField::getData() */ function getData(): array { return [ 'splitContentsMap' => $this->splitContents ]; } /** * {@inheritDoc} * @see \rocket\si\content\impl\OutSiFieldAdapter::handleInput() */ function handleInput(array $data): array { throw new IllegalStateException(); } }
n2n/rocket
src/app/rocket/si/content/impl/split/SplitOutSiField.php
PHP
lgpl-3.0
1,814
/******************************************************************** ** Image Component Library (ICL) ** ** ** ** Copyright (C) 2006-2013 CITEC, University of Bielefeld ** ** Neuroinformatics Group ** ** Website: www.iclcv.org and ** ** http://opensource.cit-ec.de/projects/icl ** ** ** ** File : ICLUtils/src/ICLUtils/CLBuffer.cpp ** ** Module : ICLUtils ** ** Authors: Viktor Losing ** ** ** ** ** ** GNU LESSER GENERAL PUBLIC LICENSE ** ** This file may be used under the terms of the GNU Lesser General ** ** Public License version 3.0 as published by the ** ** ** ** Free Software Foundation and appearing in the file LICENSE.GPL ** ** included in the packaging of this file. Please review the ** ** following information to ensure the license requirements will ** ** be met: http://www.gnu.org/licenses/lgpl-3.0.txt ** ** ** ** The development of this software was supported by the ** ** Excellence Cluster EXC 277 Cognitive Interaction Technology. ** ** The Excellence Cluster EXC 277 is a grant of the Deutsche ** ** Forschungsgemeinschaft (DFG) in the context of the German ** ** Excellence Initiative. ** ** ** ********************************************************************/ #ifdef ICL_HAVE_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <ICLUtils/CLImage2D.h> #include <ICLUtils/Macros.h> #include <ICLUtils/CLIncludes.h> #include <iostream> #include <sstream> #include <set> #include <map> using namespace std; namespace icl { namespace utils { struct CLImage2D::Impl { size_t width; size_t height; cl::Image2D image2D; cl::CommandQueue cmdQueue; std::map< uint32_t, set<uint32_t> > supported_channel_orders; static cl_mem_flags stringToMemFlags(const string &accessMode) { switch(accessMode.length()) { case 1: if(accessMode[0] == 'w') return CL_MEM_WRITE_ONLY; if(accessMode[0] == 'r') return CL_MEM_READ_ONLY; case 2: if( (accessMode[0] == 'r' && accessMode[1] == 'w') || (accessMode[0] == 'w' && accessMode[1] == 'r') ) { return CL_MEM_READ_WRITE; } default: throw CLBufferException("undefined access-mode '"+accessMode+"' (allowed are 'r', 'w' and 'rw')"); return CL_MEM_READ_WRITE; } } static cl_channel_order parseChannelOrder(const int num_channels) { cl_channel_order order = CL_R; switch(num_channels) { case(1): order = CL_R; break; case(2): order = CL_RA; break; case(3): order = CL_RGB; break; case(4): order = CL_RGBA; break; default: { std::stringstream sstream; sstream << num_channels; throw CLBufferException("unsupported number of channels: "+sstream.str()); } } return order; } bool checkSupportedImageFormat(cl_channel_order order, cl_channel_type type) { if (supported_channel_orders.count(order)) { return supported_channel_orders[order].count(type); } return false; } Impl() {} ~Impl() {} Impl(Impl& other):cmdQueue(other.cmdQueue) { width = other.width; height = other.height; image2D = other.image2D; supported_channel_orders = other.supported_channel_orders; } Impl(cl::Context &context, cl::CommandQueue &cmdQueue, const string &accessMode, const size_t width, const size_t height, int depth, int num_channel, const void *src = 0, const std::map<uint32_t, std::set<uint32_t> > &supported_formats = std::map< uint32_t,std::set<uint32_t> >()) :cmdQueue(cmdQueue), supported_channel_orders(supported_formats) { cl_mem_flags memFlags = stringToMemFlags(accessMode); if (src) { memFlags = memFlags | CL_MEM_COPY_HOST_PTR; } this->width = width; this->height = height; try { cl_channel_type channelType; switch(depth) { case 0: channelType = CL_UNSIGNED_INT8; break; case 1: channelType = CL_SIGNED_INT16; break; case 2: channelType = CL_SIGNED_INT32; break; case 3: channelType = CL_FLOAT; break; default: throw CLBufferException("unknown depth value"); } cl_channel_order order = parseChannelOrder(num_channel); if (!checkSupportedImageFormat(order,channelType)) { std::stringstream sstream; sstream << "channel: " << num_channel << ", depth-type: " << depth; throw CLBufferException("No such image type is supported: "+sstream.str()); } image2D = cl::Image2D(context, memFlags, cl::ImageFormat(order, channelType), width, height, 0, (void*) src); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } void regionToCLTypes(const utils::Rect &region, cl::size_t<3> &clOrigin, cl::size_t<3> &clRegion) { clOrigin[0] = region.x; clOrigin[1] = region.y; clOrigin[2] = 0; if (region == Rect::null) { clRegion[0] = width; clRegion[1] = height; } else { clRegion[0] = region.width; clRegion[1] = region.height; } clRegion[2] = 1; } void read(void *dst, const utils::Rect &region=utils::Rect::null, bool block = true) { cl_bool blocking; if (block) blocking = CL_TRUE; else blocking = CL_FALSE; try { cl::size_t<3> clOrigin; cl::size_t<3> clRegion; regionToCLTypes(region, clOrigin, clRegion); cmdQueue.enqueueReadImage(image2D, blocking, clOrigin, clRegion, 0, 0, dst); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } void write(void *src, const utils::Rect &region=utils::Rect::null, bool block = true) { cl_bool blocking; if (block) blocking = CL_TRUE; else blocking = CL_FALSE; try { cl::size_t<3> clOrigin; cl::size_t<3> clRegion; regionToCLTypes(region, clOrigin, clRegion); cmdQueue.enqueueWriteImage(image2D, blocking, clOrigin, clRegion, 0, 0, src); } catch (cl::Error& error) { throw CLBufferException(CLException::getMessage(error.err(), error.what())); } } static const icl32s iclDepthToByteDepth(int icl_depth) { switch (icl_depth) { case(0): return 1; case(1): return 2; case(2): return 4; case(3): return 4; case(4): return 8; default: return 1; // maybe better to throw an exception here? } } }; CLImage2D::CLImage2D(cl::Context &context, cl::CommandQueue &cmdQueue, const string &accessMode, const size_t width, const size_t height, int depth, int num_channel, const void *src, const std::map<uint32_t, std::set<uint32_t> > &supported_formats) : CLMemory(CLMemory::Image2D) { impl = new Impl(context, cmdQueue, accessMode, width, height, depth, num_channel, src, supported_formats); setDimensions(width,height,num_channel); m_byte_depth = Impl::iclDepthToByteDepth(depth); } CLImage2D::CLImage2D() : CLMemory(CLMemory::Image2D) { impl = new Impl(); } CLImage2D::CLImage2D(const CLImage2D& other) : CLMemory(other) { impl = new Impl(*(other.impl)); } CLImage2D& CLImage2D::operator=(CLImage2D const& other) { CLMemory::operator=(other); impl->cmdQueue = other.impl->cmdQueue; impl->image2D = other.impl->image2D; impl->width = other.impl->width; impl->height = other.impl->height; impl->supported_channel_orders = other.impl->supported_channel_orders; return *this; } CLImage2D::~CLImage2D() { delete impl; } void CLImage2D::read(void *dst, const utils::Rect &region, bool block) { impl->read(dst, region, block); } void CLImage2D::write(const void *src, const utils::Rect &region, bool block) { impl->write((void *)src, region, block); } cl::Image2D CLImage2D::getImage2D() { return impl->image2D; } const cl::Image2D CLImage2D::getImage2D() const { return impl->image2D; } } } #endif
iclcv/icl
ICLUtils/src/ICLUtils/CLImage2D.cpp
C++
lgpl-3.0
10,270
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.scanner.scan; import java.util.Optional; import javax.annotation.concurrent.Immutable; @Immutable public interface ExternalProjectKeyAndOrganization { Optional<String> getProjectKey(); Optional<String> getOrganization(); }
Godin/sonar
sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ExternalProjectKeyAndOrganization.java
Java
lgpl-3.0
1,091
package com.silicolife.textmining.processes.ir.pubmed; public class PubMedConfiguration { public static final int timeToWaitbetweenQueries = 3000; public static final int numberOFRetries = 5; public static final int blockSearchSize = 50; public static final int searchMetaInfoblockSize = 5; }
biotextmining/processes
src/main/java/com/silicolife/textmining/processes/ir/pubmed/PubMedConfiguration.java
Java
lgpl-3.0
299
// Copyright 2015 The daxxcoreAuthors // This file is part of the daxxcore library. // // The daxxcore library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The daxxcore library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the daxxcore library. If not, see <http://www.gnu.org/licenses/>. // +build none //sed -e 's/_N_/Hash/g' -e 's/_S_/32/g' -e '1d' types_template.go | gofmt -w hash.go package common import "math/big" type _N_ [_S_]byte func BytesTo_N_(b []byte) _N_ { var h _N_ h.SetBytes(b) return h } func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) } func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) } func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) } // Don't use the default 'String' method in case we want to overwrite // Get the string representation of the underlying hash func (h _N_) Str() string { return string(h[:]) } func (h _N_) Bytes() []byte { return h[:] } func (h _N_) Big() *big.Int { return Bytes2Big(h[:]) } func (h _N_) Hex() string { return "0x" + Bytes2Hex(h[:]) } // Sets the hash to the value of b. If b is larger than len(h) it will panic func (h *_N_) SetBytes(b []byte) { // Use the right most bytes if len(b) > len(h) { b = b[len(b)-_S_:] } // Reverse the loop for i := len(b) - 1; i >= 0; i-- { h[_S_-len(b)+i] = b[i] } } // Set string `s` to h. If s is larger than len(h) it will panic func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) } // Sets h to other func (h *_N_) Set(other _N_) { for i, v := range other { h[i] = v } }
daxxcoin/daxxcore
common/types_template.go
GO
lgpl-3.0
2,033
/* * Copyright (C) 2022 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * sklintyg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.inera.statistics.service.warehouse; import java.time.Clock; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.inera.statistics.integration.hsa.model.HsaIdEnhet; import se.inera.statistics.integration.hsa.model.HsaIdLakare; import se.inera.statistics.integration.hsa.model.HsaIdVardgivare; import se.inera.statistics.service.helper.ConversionHelper; import se.inera.statistics.service.helper.HSAServiceHelper; import se.inera.statistics.service.helper.Patientdata; import se.inera.statistics.service.hsa.HsaInfo; import se.inera.statistics.service.processlog.Arbetsnedsattning; import se.inera.statistics.service.processlog.EventType; import se.inera.statistics.service.processlog.IntygDTO; import se.inera.statistics.service.report.util.Icd10; import se.inera.statistics.service.report.util.Icd10.Kategori; import se.inera.statistics.service.warehouse.model.db.WideLine; @Component public class WidelineConverter extends AbstractWidlineConverter { private static final LocalDate ERA = LocalDate.parse("2000-01-01"); public static final int QUARTER = 25; public static final int HALF = 50; public static final int THREE_QUARTER = 75; public static final int FULL = 100; public static final int MAX_LENGTH_VGID = 50; public static final int MAX_LENGTH_ENHETNAME = 255; public static final int MAX_LENGTH_VARDGIVARE_NAMN = 255; public static final int MAX_LENGTH_LAN_ID = 50; public static final int MAX_LENGTH_KOMMUN_ID = 4; public static final int MAX_LENGTH_VERKSAMHET_TYP = Integer.MAX_VALUE; public static final int MAX_LENGTH_LAKARE_ID = 128; public static final int MAX_LENGTH_TILLTALSNAMN = 128; public static final int MAX_LENGTH_EFTERNAMN = 128; private static final int DATE20100101 = 3653; // 365*10 + 3 private static final int MAX_YEARS_INTO_FUTURE = 5; private static final int MAX_LENGTH_CORRELATION_ID = 50; public static final String UNKNOWN_DIAGNOS = "unknown"; @Autowired private Icd10 icd10; @Autowired private Clock clock; public List<WideLine> toWideline(IntygDTO dto, HsaInfo hsa, long logId, String correlationId, EventType type) { String lkf = getLkf(hsa); String huvudenhet = HSAServiceHelper.getHuvudEnhetId(hsa); String underenhet = HSAServiceHelper.getUnderenhetId(hsa); String vardenhet = huvudenhet != null ? huvudenhet : underenhet; String enhet = huvudenhet != null ? underenhet : null; HsaIdVardgivare vardgivare = HSAServiceHelper.getVardgivarId(hsa); if (vardenhet == null) { vardenhet = dto.getEnhet(); } String patient = dto.getPatientid(); Patientdata patientData = dto.getPatientData(); int kon = patientData.getKon().getNumberRepresentation(); int alder = patientData.getAlder(); String diagnos = dto.getDiagnoskod(); final Diagnos dx = parseDiagnos(diagnos); int lakarkon = HSAServiceHelper.getLakarkon(hsa); int lakaralder = HSAServiceHelper.getLakaralder(hsa); String lakarbefattning = HSAServiceHelper.getLakarbefattning(hsa); HsaIdLakare lakareid = new HsaIdLakare(dto.getLakareId()); final boolean active = !EventType.REVOKED.equals(type); List<WideLine> lines = new ArrayList<>(); for (Arbetsnedsattning arbetsnedsattning : dto.getArbetsnedsattnings()) { WideLine line = createWideLine(logId, correlationId, type, lkf, vardenhet, enhet, vardgivare, patient, kon, alder, dx, lakarkon, lakaralder, lakarbefattning, lakareid, arbetsnedsattning, active); lines.add(line); } return lines; } // CHECKSTYLE:OFF ParameterNumberCheck @java.lang.SuppressWarnings("squid:S00107") // Suppress parameter number warning in Sonar private WideLine createWideLine(long logId, String correlationId, EventType type, String lkf, String vardenhet, String enhet, HsaIdVardgivare vardgivare, String patient, int kon, int alder, Diagnos dx, int lakarkon, int lakaralder, String lakarbefattning, HsaIdLakare lakareid, Arbetsnedsattning arbetsnedsattning, boolean active) { WideLine line = new WideLine(); int sjukskrivningsgrad = arbetsnedsattning.getNedsattning(); LocalDate kalenderStart = arbetsnedsattning.getStart(); LocalDate kalenderEnd = arbetsnedsattning.getSlut(); line.setCorrelationId(correlationId); line.setLakarintyg(logId); line.setIntygTyp(type); line.setActive(active); line.setLkf(lkf); line.setEnhet(new HsaIdEnhet(enhet)); line.setVardenhet(new HsaIdEnhet(vardenhet)); line.setVardgivareId(vardgivare); line.setStartdatum(toDay(kalenderStart)); line.setSlutdatum(toDay(kalenderEnd)); line.setDiagnoskapitel(dx.diagnoskapitel); line.setDiagnosavsnitt(dx.diagnosavsnitt); line.setDiagnoskategori(dx.diagnoskategori); line.setDiagnoskod(dx.diagnoskod); line.setSjukskrivningsgrad(sjukskrivningsgrad); line.setPatientid(patient); line.setAlder(alder); line.setKon(kon); line.setLakaralder(lakaralder); line.setLakarkon(lakarkon); line.setLakarbefattning(lakarbefattning); line.setLakareId(lakareid); return line; } // CHECKSTYLE:ON ParameterNumberCheck private Diagnos parseDiagnos(String diagnos) { boolean isUnknownDiagnos = diagnos == null || UNKNOWN_DIAGNOS.equals(diagnos); final Icd10.Kod kod = isUnknownDiagnos ? null : icd10.findKod(diagnos); final Kategori kategori = kod != null ? kod.getKategori() : isUnknownDiagnos ? null : icd10.findKategori(diagnos); final Diagnos dx = new Diagnos(); dx.diagnoskod = kod != null ? kod.getId() : null; if (kategori != null) { dx.diagnoskapitel = kategori.getAvsnitt().getKapitel().getId(); dx.diagnosavsnitt = kategori.getAvsnitt().getId(); dx.diagnoskategori = kategori.getId(); } else if (UNKNOWN_DIAGNOS.equals(diagnos)) { dx.diagnoskapitel = null; dx.diagnosavsnitt = null; dx.diagnoskategori = UNKNOWN_DIAGNOS; } else { dx.diagnoskapitel = null; dx.diagnosavsnitt = null; dx.diagnoskategori = null; } return dx; } private void checkSjukskrivningsgrad(List<String> errors, int grad) { if (!(grad == QUARTER || grad == HALF || grad == THREE_QUARTER || grad == FULL)) { errors.add("Illegal sjukskrivningsgrad: " + grad); } } private void checkStartdatum(List<String> errors, int startdatum) { if (startdatum < DATE20100101 || startdatum > toDay(LocalDate.now(clock).plusYears(MAX_YEARS_INTO_FUTURE))) { errors.add("Illegal startdatum: " + startdatum); } } private void checkSlutdatum(List<String> errors, int slutdatum) { if (slutdatum > toDay(LocalDate.now(clock).plusYears(MAX_YEARS_INTO_FUTURE))) { errors.add("Illegal slutdatum: " + slutdatum); } } private String getLkf(HsaInfo hsa) { String lkf = HSAServiceHelper.getKommun(hsa); if (lkf.isEmpty()) { lkf = HSAServiceHelper.getLan(hsa); } else if (lkf.length() == 2) { lkf = HSAServiceHelper.getLan(hsa) + lkf; } return lkf; } public static int toDay(LocalDate dayDate) { return (int) ChronoUnit.DAYS.between(ERA, dayDate); } public static LocalDate toDate(int day) { return ERA.plusDays(day); } public List<String> validate(WideLine line) { List<String> errors = new ArrayList<>(); checkField(errors, line.getLkf(), "LKF"); checkField(errors, line.getVardgivareId(), "Vårdgivare", MAX_LENGTH_VGID); checkField(errors, line.getVardenhet(), "Vardenhet"); checkField(errors, line.getPatientid(), "Patient"); checkAge(errors, line.getAlder()); checkField(errors, line.getCorrelationId(), "CorrelationId", MAX_LENGTH_CORRELATION_ID); checkSjukskrivningsgrad(errors, line.getSjukskrivningsgrad()); checkDates(errors, line.getStartdatum(), line.getSlutdatum()); return errors; } private void checkDates(List<String> errors, int startdatum, int slutdatum) { checkStartdatum(errors, startdatum); checkSlutdatum(errors, slutdatum); if (startdatum > slutdatum) { errors.add("Illegal dates. Start date (" + startdatum + ") must be before end date (" + slutdatum + ")"); } } private void checkAge(List<String> errors, int alder) { if (alder == ConversionHelper.NO_AGE) { errors.add("Error in patient age"); } } private static class Diagnos { private String diagnoskod; private String diagnoskapitel; private String diagnosavsnitt; private String diagnoskategori; } }
sklintyg/statistik
service/src/main/java/se/inera/statistics/service/warehouse/WidelineConverter.java
Java
lgpl-3.0
10,101
package nif.compound; import java.io.IOException; import java.nio.ByteBuffer; import nif.ByteConvert; public class NifbhkCMSDMaterial { /** * <compound name="bhkCMSDMaterial"> per-chunk material, used in bhkCompressedMeshShapeData <add name="Material ID" type="uint">Unknown</add> <add name="Unknown Integer" type="uint">Always 1?</add> </compound> */ public int MaterialID; public int UnknownInteger; public NifbhkCMSDMaterial(ByteBuffer stream) throws IOException { MaterialID = ByteConvert.readInt(stream); UnknownInteger = ByteConvert.readInt(stream); } }
philjord/jnif
jnif/src/nif/compound/NifbhkCMSDMaterial.java
Java
lgpl-3.0
623
/** * Copyright (C) 2013-2014 Kametic <epo.jemba@kametic.com> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * or any later version * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nuun.plugin.spring.sample; public class Service3Internal implements Service3 { @Override public String serve() { return this.getClass().getName(); } }
nuun-io/nuun-spring-plugin
src/test/java/io/nuun/plugin/spring/sample/Service3Internal.java
Java
lgpl-3.0
875
package org.mysqlmv.cd.workers; import org.apache.commons.lang3.exception.ExceptionUtils; import org.mysqlmv.Switch; import org.mysqlmv.cd.dao.CdDao; import org.mysqlmv.cd.workers.impl.DefaultLogFileChangeProcessor; import org.mysqlmv.cd.workers.impl.LogFileScanStatus; import org.mysqlmv.common.config.reader.ConfigFactory; import org.slf4j.Logger; import java.io.*; import java.sql.SQLException; /** * Created by Kelvin Li on 11/18/2014 2:38 PM. */ public class LogFileChangeDetector implements Runnable { public static Logger logger = org.slf4j.LoggerFactory.getLogger(LogFileChangeDetector.class); private volatile long lastChangeTimeStamp; private volatile String logRoot; private LogFileChangeProcessor processor = new DefaultLogFileChangeProcessor(); @Override public void run() { logRoot = ConfigFactory.getINSTANCE().getProperty("log-root-folder"); Switch controller = Switch.getSwitch(); while(controller.getStatus()) { scannLog(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } private void scannLog() { try { // When mysql is shutdown normally, a stop event will appears in the log file, // then should handle this situation. LogFileScanStatus status = LogFileScanStatus.SUCCESS; File logFile = new File(findCurrentLogFile()); boolean isNewFile = false; while(true) { status = processor.onFileChange(logFile, isNewFile); if(status.equals(LogFileScanStatus.SUCCESS)) { break; } else if(status.equals(LogFileScanStatus.STOP)) { isNewFile = true; logger.warn("Mysql DB service is shutdown."); } else if(status.equals(LogFileScanStatus.CONTINUE_NEXT)) { logFile = findNextFile(); isNewFile = true; } } } catch (IOException e) { logger.error("Error happened when reading bin-log."); logger.error(ExceptionUtils.getStackTrace(e)); // throw new RuntimeException(e); } catch (SQLException e) { e.printStackTrace(); } } private File findNextFile() throws SQLException, IOException { String logFullName = CdDao.findCurrentLogFileName(); String curFileName = new File(logFullName).getName(); File indexFile = findIndexLogfile(); BufferedReader indexReader = new BufferedReader(new FileReader(indexFile)); if(indexReader == null) { return null; } String line = null; while((line = indexReader.readLine()) != null) { if(line.contains(".\\")) { line = line.replace(".\\", ""); if(curFileName.equals(line)) { line = indexReader.readLine().replace(".\\", ""); break; } } } if("".equals(line)) { return null; } return new File(logRoot + "/" + line); } public File findIndexLogfile() { File logDir = new File(logRoot); File indexFile = null; for(File ff : logDir.listFiles()) { if(ff.getName().endsWith(".index")) { indexFile = ff; } } return indexFile; } private String findCurrentLogFile() throws IOException { String currentLogFile = null; File indexFile = findIndexLogfile(); BufferedReader indexReader = new BufferedReader(new FileReader(indexFile)); if(indexReader == null) { return null; } String line = null; while((line = indexReader.readLine()) != null) { if(line.contains(".\\")) { currentLogFile = line.replace(".\\", ""); } } return logRoot + "/" + currentLogFile; } }
Kelvinli1988/mysqlmv
src/main/java/org/mysqlmv/cd/workers/LogFileChangeDetector.java
Java
lgpl-3.0
4,083
//------------------------------------------------------------------------------ // <copyright company="Tunynet"> // Copyright (c) Tunynet Inc. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using PetaPoco; using Tunynet.Caching; namespace Tunynet.Common { /// <summary> /// 公告实体类 /// </summary> [TableName("spb_Announcements")] [PrimaryKey("Id", autoIncrement = true)] [CacheSetting(true)] [Serializable] public class Announcement : IEntity { /// <summary> /// 新建实体时使用 /// </summary> public static Announcement New() { Announcement announcement = new Announcement() { Subject = string.Empty, SubjectStyle = string.Empty, Body = string.Empty, HyperLinkUrl = string.Empty, ReleaseDate = DateTime.UtcNow, ExpiredDate = DateTime.UtcNow, LastModified = DateTime.UtcNow, CreatDate = DateTime.UtcNow.ToLocalTime() }; return announcement; } #region 需持久化属性 /// <summary> ///Primary key /// </summary> public long Id { get; protected set; } /// <summary> ///公告主题 /// </summary> public string Subject { get; set; } /// <summary> ///主题字体风格 /// </summary> public string SubjectStyle { get; set; } /// <summary> ///公告内容 /// </summary> public string Body { get; set; } /// <summary> ///是否是连接 /// </summary> public bool IsHyperLink { get; set; } /// <summary> ///链接地址 /// </summary> public string HyperLinkUrl { get; set; } /// <summary> ///是否启用 /// </summary> public bool EnabledDescription { get; set; } /// <summary> ///发布时间 /// </summary> public DateTime ReleaseDate { get; set; } /// <summary> ///过期时间 /// </summary> public DateTime ExpiredDate { get; set; } /// <summary> ///更新时间 /// </summary> public DateTime LastModified { get; set; } /// <summary> ///创建时间 /// </summary> [SqlBehavior(~SqlBehaviorFlags.Update)] public DateTime CreatDate { get; set; } /// <summary> ///创建人Id /// </summary> public long UserId { get; set; } /// <summary> ///显示顺序 /// </summary> public long DisplayOrder { get; set; } /// <summary> ///展示区域 /// </summary> public string DisplayArea { get; set; } #endregion #region 扩展属性和方法 /// <summary> /// 浏览数 /// </summary> [Ignore] public int HitTimes { get { CountService countService = new CountService(TenantTypeIds.Instance().Announcement()); return countService.Get(CountTypes.Instance().HitTimes(), this.Id); } } /// <summary> /// 撰稿人 /// </summary> [Ignore] public string UserName { get; set; } /// <summary> /// 管理员标示 /// </summary> [Ignore] public bool IsAdministrator { get; set; } #endregion #region IEntity 成员 object IEntity.EntityId { get { return this.Id; } } bool IEntity.IsDeletedInDatabase { get; set; } #endregion } }
yesan/Spacebuilder
BusinessComponents/ContentOrganization/Announcements/Announcement.cs
C#
lgpl-3.0
3,858
#include "CInterpreter.h" #include "ErrorDefinitions.h" #include "main.h" CInterpreter::CInterpreter() {} CInterpreter::~CInterpreter() {} void CInterpreter::SetFileTree(CFileTree fileTree) { m_fileTree = fileTree; } unsigned int CInterpreter::CompileFileList() { char msg[512] = {0}; unsigned int* result = new unsigned int[m_fileTree.GetNumberOfFiles()]; for(int i = 0; i < m_fileTree.GetNumberOfFiles(); i++) { result[i] = CompileFile(m_fileTree.GetFile(i)); } for(int i = 0; i < m_fileTree.GetNumberOfFiles(); i++) { if(result[i] == NO_ERROR) m_fileTree.GetFile(i)->doScript(); else { sprintf(msg, "Could Not Run Script: %s | %s\n", m_fileTree.GetFile(i)->GetFilename(), GetErrorText(result[i])); debug.Log(msg); } } return NO_ERROR; } unsigned int CInterpreter::CompileFile(CScriptFile* file) { m_scanner.SetFile(file); unsigned int result = m_scanner.ScanFile(); if(result != NO_ERROR) return result; m_lexer.SetCharacters(m_scanner.GetCharacters(), m_scanner.GetCharacterCount()); result = m_lexer.ProcessCharacters(); if(result != NO_ERROR) return result; m_parser.SetScript(file); m_parser.SetTokenList(m_lexer.GetTokens(), m_lexer.GetTokenCount()); result = m_parser.ParseTokens(); return result; }
patrickmortensen/Elektro
Source To Merge/Interpreter/CInterpreter.cpp
C++
lgpl-3.0
1,413
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.scanner.repository; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.scanner.bootstrap.ScannerProperties; import org.sonar.scanner.rule.QualityProfiles; import org.springframework.context.annotation.Bean; public class QualityProfilesProvider { private static final Logger LOG = Loggers.get(QualityProfilesProvider.class); private static final String LOG_MSG = "Load quality profiles"; @Bean("QualityProfiles") public QualityProfiles provide(QualityProfileLoader loader, ScannerProperties props) { Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); QualityProfiles profiles = new QualityProfiles(loader.load(props.getProjectKey())); profiler.stopInfo(); return profiles; } }
SonarSource/sonarqube
sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/QualityProfilesProvider.java
Java
lgpl-3.0
1,663
using System; using System.Runtime.InteropServices; using NvAPIWrapper.Native.Helpers; using NvAPIWrapper.Native.Interfaces; namespace NvAPIWrapper.Native.GPU.Structures { /// <summary> /// Holds information regarding a piecewise linear RGB control method /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct IlluminationZoneControlDataPiecewiseLinearRGB : IInitializable { private const int NumberColorEndPoints = 2; [MarshalAs(UnmanagedType.ByValArray, SizeConst = NumberColorEndPoints)] internal IlluminationZoneControlDataManualRGBParameters[] _EndPoints; internal IlluminationZoneControlDataPiecewiseLinear _PiecewiseLinearData; /// <summary> /// Creates a new instance of <see cref="IlluminationZoneControlDataPiecewiseLinearRGB" />. /// </summary> /// <param name="endPoints">The list of RGB piecewise function endpoints.</param> /// <param name="piecewiseLinearData">The piecewise function settings.</param> public IlluminationZoneControlDataPiecewiseLinearRGB( IlluminationZoneControlDataManualRGBParameters[] endPoints, IlluminationZoneControlDataPiecewiseLinear piecewiseLinearData) { if (endPoints?.Length != NumberColorEndPoints) { throw new ArgumentOutOfRangeException(nameof(endPoints)); } this = typeof(IlluminationZoneControlDataPiecewiseLinearRGB) .Instantiate<IlluminationZoneControlDataPiecewiseLinearRGB>(); _PiecewiseLinearData = piecewiseLinearData; Array.Copy(endPoints, 0, _EndPoints, 0, endPoints.Length); } /// <summary> /// Gets the piecewise function settings /// </summary> public IlluminationZoneControlDataPiecewiseLinear PiecewiseLinearData { get => _PiecewiseLinearData; } /// <summary> /// Gets the list of RGB function endpoints /// </summary> public IlluminationZoneControlDataManualRGBParameters[] EndPoints { get => _EndPoints; } } }
falahati/NvAPIWrapper
NvAPIWrapper/Native/GPU/Structures/IlluminationZoneControlDataPiecewiseLinearRGB.cs
C#
lgpl-3.0
2,194
#include <Guirlande.h> static int h; long EffectShade(long step) { if (step == 0) { h = 17; } for(byte i = 0; i < STRIP_LEN; i++) { stripSetHL(i, h, (i+1) * 3); } stripUpdate(); h = h * 4; return -1; }
piif/Guirlande
EffectShade.cpp
C++
lgpl-3.0
216
/* Sound_enhance.cpp * * Copyright (C) 1992-2011 Paul Boersma * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * pb 2002/07/16 GPL * pb 2004/11/22 simplified Sound_to_Spectrum () * pb 2007/01/28 made compatible with stereo sounds (by rejecting them) * pb 2007/07/22 renamed the overlap-add method in such a way that it does not sound like a trademark for diphone concatenation * pb 2008/01/19 double * pb 2011/06/07 C++ */ #include "Manipulation.h" #include "Sound_to_Pitch.h" #include "Pitch_to_PitchTier.h" #include "Pitch_to_PointProcess.h" #include "Sound_and_Spectrum.h" Sound Sound_lengthen_overlapAdd (Sound me, double fmin, double fmax, double factor) { try { if (my ny > 1) Melder_throw ("Overlap-add works only on mono sounds."); autoSound sound = Data_copy (me); Vector_subtractMean (sound.peek()); autoPitch pitch = Sound_to_Pitch (sound.peek(), 0.8 / fmin, fmin, fmax); autoPointProcess pulses = Sound_Pitch_to_PointProcess_cc (sound.peek(), pitch.peek()); autoPitchTier pitchTier = Pitch_to_PitchTier (pitch.peek()); autoDurationTier duration = DurationTier_create (my xmin, my xmax); RealTier_addPoint (duration.peek(), 0.5 * (my xmin + my xmax), factor); autoSound thee = Sound_Point_Pitch_Duration_to_Sound (sound.peek(), pulses.peek(), pitchTier.peek(), duration.peek(), 1.5 / fmin); return thee.transfer(); } catch (MelderError) { Melder_throw (me, ": not lengthened."); } } Sound Sound_deepenBandModulation (Sound me, double enhancement_dB, double flow, double fhigh, double slowModulation, double fastModulation, double bandSmoothing) { try { autoSound thee = Data_copy (me); double maximumFactor = pow (10, enhancement_dB / 20), alpha = sqrt (log (2.0)); double alphaslow = alpha / slowModulation, alphafast = alpha / fastModulation; for (long channel = 1; channel <= my ny; channel ++) { autoSound channelSound = Sound_extractChannel (me, channel); autoSpectrum orgspec = Sound_to_Spectrum (channelSound.peek(), TRUE); /* * Keep the part of the sound that is outside the filter bank. */ autoSpectrum spec = Data_copy (orgspec.peek()); Spectrum_stopHannBand (spec.peek(), flow, fhigh, bandSmoothing); autoSound filtered = Spectrum_to_Sound (spec.peek()); long n = thy nx; double *amp = thy z [channel]; for (long i = 1; i <= n; i ++) amp [i] = filtered -> z [1] [i]; autoMelderProgress progress (L"Deepen band modulation..."); double fmin = flow; while (fmin < fhigh) { /* * Take a one-bark frequency band. */ double fmid_bark = NUMhertzToBark (fmin) + 0.5, ceiling; double fmax = NUMbarkToHertz (NUMhertzToBark (fmin) + 1); if (fmax > fhigh) fmax = fhigh; Melder_progress (fmin / fhigh, L"Band: ", Melder_fixed (fmin, 0), L" ... ", Melder_fixed (fmax, 0), L" Hz"); NUMmatrix_copyElements (orgspec -> z, spec -> z, 1, 2, 1, spec -> nx); Spectrum_passHannBand (spec.peek(), fmin, fmax, bandSmoothing); autoSound band = Spectrum_to_Sound (spec.peek()); /* * Compute a relative intensity contour. */ autoSound intensity = Data_copy (band.peek()); n = intensity -> nx; amp = intensity -> z [1]; for (long i = 1; i <= n; i ++) amp [i] = 10 * log10 (amp [i] * amp [i] + 1e-6); autoSpectrum intensityFilter = Sound_to_Spectrum (intensity.peek(), TRUE); n = intensityFilter -> nx; for (long i = 1; i <= n; i ++) { double frequency = intensityFilter -> x1 + (i - 1) * intensityFilter -> dx; double slow = alphaslow * frequency, fast = alphafast * frequency; double factor = exp (- fast * fast) - exp (- slow * slow); intensityFilter -> z [1] [i] *= factor; intensityFilter -> z [2] [i] *= factor; } intensity.reset (Spectrum_to_Sound (intensityFilter.peek())); n = intensity -> nx; amp = intensity -> z [1]; for (long i = 1; i <= n; i ++) amp [i] = pow (10, amp [i] / 2); /* * Clip to maximum enhancement. */ ceiling = 1 + (maximumFactor - 1.0) * (0.5 - 0.5 * cos (NUMpi * fmid_bark / 13)); for (long i = 1; i <= n; i ++) amp [i] = 1 / (1 / amp [i] + 1 / ceiling); n = thy nx; amp = thy z [channel]; for (long i = 1; i <= n; i ++) amp [i] += band -> z [1] [i] * intensity -> z [1] [i]; fmin = fmax; } } Vector_scale (thee.peek(), 0.99); /* Truncate. */ thy xmin = my xmin; thy xmax = my xmax; thy nx = my nx; thy x1 = my x1; return thee.transfer(); } catch (MelderError) { Melder_throw (me, ": band modulation not deepened."); } } /* End of file Sound_enhance.cpp */
PeterWolf-tw/NeoPraat
sources_5401/fon/Sound_enhance.cpp
C++
lgpl-3.0
5,230
/* Copyright (C) 2010 Zone Five Software This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ // Author: Aaron Averill using System; using System.Collections.Generic; using System.Text; namespace ZoneFiveSoftware.SportTracks.Device.Globalsat { public class GhPacketBase { //Public properties - Mostly response, send handles PacketData public byte CommandId; public Int16 PacketLength; //PacketData contains the usefuldata, not everything to send public byte[] PacketData; //Only used when receiving - sending is only included in the sent data //Not stored now //public byte Checksum; public void InitPacket(byte CommandId, Int16 PacketLength) { this.CommandId = CommandId; this.PacketLength = PacketLength; this.PacketData = new byte[PacketLength]; for (int i = 0; i < this.PacketData.Length; i++ ) { this.PacketData[i] = 0; } } //The Gloabalsat specs does not explicitly write that the format is same for all public const byte CommandWhoAmI = 0xBF; public const byte CommandGetSystemInformation = 0x85; public const byte CommandGetSystemConfiguration = 0x86; public const byte CommandSetSystemConfiguration = 0x96; public const byte CommandSetSystemInformation = 0x98; public const byte CommandGetScreenshot = 0x83; public const byte CommandGetWaypoints = 0x77; public const byte CommandSendWaypoint = 0x76; public const byte CommandDeleteWaypoints = 0x75; public const byte CommandSendRoute = 0x93; public const byte CommandDeleteAllRoutes = 0x97; public const byte CommandGetTrackFileHeaders = 0x78; public const byte CommandGetTrackFileSections = 0x80; public const byte CommandGetNextTrackSection = 0x81; //public const byte CommandReGetLastSection = 0x82; public const byte CommandId_FINISH = 0x8A; public const byte CommandSendTrackStart = 0x90; public const byte CommandSendTrackSection = 0x91; public const byte CommandDeleteTracks = 0x79; //505, 580, 625XT, determines info in the trackpackets at TrainHeaderCTypeOffset public const byte HeaderTypeLaps = 0xAA; public const byte HeaderTypeTrackPoints = 0x55; //Certain appearing responses, likely more exists public const byte ResponseInsuficientMemory = 0x95; public const byte ResponseResendTrackSection = 0x92; public const byte ResponseSendTrackFinish = 0x9A; public class Header { public DateTime StartTime; public Int32 TrackPointCount; //Int16 in all but 625XT public TimeSpan TotalTime; public Int32 TotalDistanceMeters; public Int16 LapCount; //Not used in all } public class Train : Header { //public Int16 StartPointIndex=0; //public Int16 EndPointIndex=0; //public bool Multisport; public Int16 TotalCalories = 0; public double MaximumSpeed = 0; public byte MaximumHeartRate = 0; public byte AverageHeartRate = 0; public Int16 TotalAscend = 0; public Int16 TotalDescend = 0; //public Int16 MinimumAltitude; //public Int16 MaximumAltitude; public Int16 AverageCadence = 0; public Int16 MaximumCadence = 0; public Int16 AveragePower = 0; public Int16 MaximumPower = 0; //byte Sport1; //byte Sport2; //byte Sport3; //byte Sport4; //byte Sport5; //public Int16 AverageTemperature; //GB580P //public Int16 MaximumTemperature; //public Int16 MaximumTemperature; public IList<TrackPoint> TrackPoints = new List<TrackPoint>(); public IList<Lap> Laps = new List<Lap>(); //data related to the import, for instance if start date is changed public string Comment = ""; } public class TrackFileHeader : Header { public Int32 TrackPointIndex; } public class Lap { public TimeSpan EndTime; public TimeSpan LapTime; public Int32 LapDistanceMeters; public Int16 LapCalories; public double MaximumSpeed; //Int16 for some devices public byte MaximumHeartRate; public byte AverageHeartRate; public Int16 MinimumAltitude; public Int16 MaximumAltitude; public Int16 AverageCadence; public Int16 MaximumCadence; public Int16 AveragePower; public Int16 MaximumPower; //public bool Multisport; //public Int16 AverageTemperature; //GB580P //public Int16 MaximumTemperature; //public Int16 MaximumTemperature; // public Int16 StartPointIndex; // public Int16 EndPointIndex; } //Superset of all trackpoints public class TrackPoint { //Same in all public double Latitude; //4bit, Degrees * 1000000 public double Longitude; //4bit, Degrees * 1000000 //Int32 in GB580, Int16 in GH625XT, GH505, GH625, GH615 public Int32 Altitude; // Meters //Int32 in GH625XT, Int16 in GB580, GH505, GH625, GH615 public double Speed=0; //4bit, Kilometers per hour * 100 public Byte HeartRate=0; //Int32 in GH625XT, GB580, GH505, Int16 in GH625, GH615 public double IntervalTime=0; // Seconds * 10 //Int16 in GH625XT, GB580, GH505, (but not available?) public Int16 Power=0; // Power, unknown units //Int16 in GH625XT, GB580 (but not available, unknown use) public Int16 PowerCadence=0; // unknown units //Int16 in GH625XT, GB580, GH505, (but not available?) public Int16 Cadence=0; // Cadence, RPM - revolutions per minute public Int16 Temperature=0x7fff; //GB580P } public byte[] ConstructPayload(bool bigEndianPacketLength) { byte[] data = new byte[5 + this.PacketLength]; data[0] = 0x02; //Add CommandId to length, always big endian //Write(true, data, 1, (Int16)(this.PacketLength + 1)); byte[] b = BitConverter.GetBytes((Int16)(this.PacketLength + 1)); if (bigEndianPacketLength) { data[1] = b[1]; data[2] = b[0]; } else { //Only for the 561 data[1] = b[0]; data[2] = b[1]; } data[3] = this.CommandId; for (int i = 0; i < this.PacketLength; i++) { data[4 + i] = this.PacketData[i]; } data[this.PacketLength + 4] = GetCrc(false); return data; } private byte GetCrc(bool received) { byte checksum = 0; int len = this.PacketLength; if (!received) { //For sent packets, include the packetid len++; } byte[] b = BitConverter.GetBytes(len); checksum ^= b[0]; checksum ^= b[1]; if (!received) { checksum ^= this.CommandId; } for (int i = 0; i < this.PacketLength; i++) { checksum ^= this.PacketData[i]; } return checksum; } public bool ValidResponseCrc(byte checksum) { return (GetCrc(true) == checksum); } /// <summary> /// Read a six byte representation of a date and time starting at the offset in the following format: /// Year = 2000 + byte[0] /// Month = byte[1] /// Day = byte[2] /// Hour = byte[3] /// Minute = byte[4] /// Second = byte[5] /// </summary> protected DateTime ReadDateTime(int offset) { return new DateTime(PacketData[offset + 0] + 2000, PacketData[offset + 1], PacketData[offset + 2], PacketData[offset + 3], PacketData[offset + 4], PacketData[offset + 5]); } protected int Write(int offset, DateTime t) { int year = (int)Math.Max(0, t.Year - 2000); this.PacketData[offset+0] = (byte)year; this.PacketData[offset+1] = (byte)t.Month; this.PacketData[offset+2] = (byte)t.Day; this.PacketData[offset+3] = (byte)t.Hour; this.PacketData[offset+4] = (byte)t.Minute; this.PacketData[offset+5] = (byte)t.Second; return 6; } /// <summary> /// Read a string starting at the offset. /// </summary> public string ByteArr2String(int startIndex, int length) { for (int i = startIndex; i < Math.Min(startIndex + length, PacketData.Length); i++) { if (PacketData[i] == 0x0) { length = i - startIndex; break; } } string str = UTF8Encoding.UTF8.GetString(PacketData, startIndex, length); return str; } public int Write(int startIndex, int length, string s) { for (int j = 0; j < length; j++) { byte c = (byte)(j < s.Length ? s[j] : '\0'); this.PacketData[startIndex + j] = c; } //Ensure null termination this.PacketData[startIndex + length - 1] = 0; return length; } /// <summary> /// Read a two byte integer starting at the offset. /// </summary> protected Int16 ReadInt16(int offset) { if (!IsLittleEndian) { return (Int16)((this.PacketData[offset] << 8) + this.PacketData[offset + 1]); } else { return BitConverter.ToInt16(this.PacketData, offset); } } /// <summary> /// Read a four byte integer starting at the offset. /// </summary> protected Int32 ReadInt32(int offset) { if (!IsLittleEndian) { return (this.PacketData[offset] << 24) + (this.PacketData[offset + 1] << 16) + (this.PacketData[offset + 2] << 8) + this.PacketData[offset + 3]; } else { return BitConverter.ToInt32(this.PacketData, offset); } } protected double ReadLatLon(int offset) { return ReadInt32(offset) / 1000000.0; } //Some static methods for standard field formats static public Int32 ToGlobLatLon(double latlon) { return (int)Math.Round(latlon * 1000000); } static public Int16 ToGlobSpeed(double speed) { return (Int16)Math.Round(speed * 100 * 3.6); } static public double FromGlobSpeed(int speed) { return speed / 100.0 / 3.6; } static public Int32 ToGlobTime(double time) { return (Int32)Math.Round(time * 10); } static public Int16 ToGlobTime16(double time) { return (Int16)ToGlobTime(time); } static public double FromGlobTime(int time) { return time/10.0; } /// <summary> /// Write a two byte integer starting at the offset. /// </summary> protected int Write(int offset, Int16 i) { return Write(offset, i, this.IsLittleEndian); } protected int Write(int offset, Int16 i, bool isLittleEndian) { byte[] b = BitConverter.GetBytes(i); if (!isLittleEndian) { this.PacketData[offset + 0] = b[1]; this.PacketData[offset + 1] = b[0]; } else { this.PacketData[offset + 0] = b[0]; this.PacketData[offset + 1] = b[1]; } return 2; } /// <summary> /// Write a four byte integer in little-endian format starting at the offset. /// </summary> //No overload to make sure correct protected int Write32(int offset, Int32 i) { byte[] b = BitConverter.GetBytes(i); if (!IsLittleEndian) { this.PacketData[offset + 0] = b[3]; this.PacketData[offset + 1] = b[2]; this.PacketData[offset + 2] = b[1]; this.PacketData[offset + 3] = b[0]; } else { this.PacketData[offset + 0] = b[0]; this.PacketData[offset + 1] = b[1]; this.PacketData[offset + 2] = b[2]; this.PacketData[offset + 3] = b[3]; } return 4; } //Note: The assumption is that the platform is LittleEndian protected virtual bool IsLittleEndian { get { return false; } } } }
xeonvs/globalsat-sporttracks-plugin
Device/GhPacketBase.cs
C#
lgpl-3.0
14,491
/** * Kopernicus Planetary System Modifier * ==================================== * Created by: - Bryce C Schroeder (bryce.schroeder@gmail.com) * - Nathaniel R. Lewis (linux.robotdude@gmail.com) * * Maintained by: - Thomas P. * - NathanKell * * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace * ------------------------------------------------------------- * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * * This library is intended to be used as a plugin for Kerbal Space Program * which is copyright 2011-2014 Squad. Your usage of Kerbal Space Program * itself is governed by the terms of its EULA, not the license above. * * https://kerbalspaceprogram.com */ using System; namespace Kopernicus { namespace Configuration { /** * Exception representing a missing field **/ public class ParserTargetMissingException : Exception { public ParserTargetMissingException (string message) : base(message) { } } } }
HappyFaceIndustries/Kopernicus
Kopernicus/Configuration/Parser/Exceptions/ParserTargetMissingException.cs
C#
lgpl-3.0
1,776
/* * jesadido-poc * Copyright (C) 2016 Stefan K. Baur * * Licensed under the GNU Lesser General Public License, Version 3.0 (LGPL-3.0) * https://www.gnu.org/licenses/lgpl-3.0.txt */ package org.jesadido.poc.core.semantics.translating.en; import java.util.Arrays; import java.util.LinkedList; import org.jesadido.poc.core.semantics.translating.TranslationResult; import org.jesadido.poc.core.semantics.translating.TransletParameters; import org.jesadido.poc.core.semantics.translating.Transletor; import org.jesadido.poc.core.syntax.tokens.TokenType; public final class EnTransletors { private static final Transletor NOMINAL_TRANSLETOR = new Transletor() .add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), new LinkedList<>()))) .add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 2)))) .add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 3)))) .add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 4)))) .add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), new LinkedList<>()))) .add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 3)))) .add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 4)))) .add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 5)))) ; private EnTransletors() { // A private utility class constructor } public static Transletor getNominalTransletor() { return NOMINAL_TRANSLETOR; } }
stefan-baur/jesadido-poc
src/main/java/org/jesadido/poc/core/semantics/translating/en/EnTransletors.java
Java
lgpl-3.0
3,102
namespace Microsoft.Web.Mvc.Resources { using System.Globalization; using System.Net; using System.Net.Mime; using System.Web; using System.Web.Mvc; using Microsoft.Web.Resources; /// <summary> /// Returns the response in the format specified by the request. By default, supports returning the model /// as a HTML view, XML and JSON. /// If the response format requested is not supported, then the NotAcceptable status code is returned /// </summary> public class MultiFormatActionResult : ActionResult { object model; ContentType responseFormat; HttpStatusCode statusCode; public MultiFormatActionResult(object model, ContentType responseFormat) : this(model, responseFormat, HttpStatusCode.OK) { } public MultiFormatActionResult(object model, ContentType responseFormat, HttpStatusCode statusCode) { this.model = model; this.responseFormat = responseFormat; this.statusCode = statusCode; } public override void ExecuteResult(ControllerContext context) { if (!TryExecuteResult(context, this.model, this.responseFormat)) { throw new HttpException((int)HttpStatusCode.NotAcceptable, string.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.responseFormat)); } } public virtual bool TryExecuteResult(ControllerContext context, object model, ContentType responseFormat) { if (!FormatManager.Current.CanSerialize(responseFormat)) { return false; } context.HttpContext.Response.ClearContent(); context.HttpContext.Response.StatusCode = (int)this.statusCode; FormatManager.Current.Serialize(context, model, responseFormat); return true; } } }
consumentor/Server
trunk/tools/ASP.NET MVC 2/trunk/src/MvcFutures/Mvc/Resources/MultiFormatActionResult.cs
C#
lgpl-3.0
1,935
from pyactor.context import set_context, create_host, sleep, shutdown,\ serve_forever class Someclass(object): _tell = {'show_things'} def __init__(self, op, thing): self.things = [op, thing] def show_things(self): print(self.things) if __name__ == '__main__': set_context() h = create_host() params = ["hi", "you"] # kparams = {"op":"hi", "thing":"you"} # t = h.spawn('t', Someclass, *params) t = h.spawn('t', Someclass, *["hi", "you"]) t.show_things() shutdown()
pedrotgn/pyactor
examples/initparams.py
Python
lgpl-3.0
539
/* * Copyright (c) 2008, 2011 Poesys Associates. All rights reserved. * * This file is part of Poesys-DB. * * Poesys-DB is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * Poesys-DB is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * Poesys-DB. If not, see <http://www.gnu.org/licenses/>. */ package com.poesys.db.dao.delete; import java.sql.PreparedStatement; import com.poesys.db.dto.IDbDto; import com.poesys.db.pk.IPrimaryKey; /** * SQL statement specification for deleting a standard object. The concrete * subclass contains the SQL statement and an implementation of * <code>IDeleteSql.getSql()</code> that calls the <code>getSql</code> method in * this class: * * <pre> * public class DeleteTestSql extends AbstractDeleteSql { * * private static final String SQL = &quot;DELETE FROM Test WHERE &quot;; * * public String getSql(IPrimaryKey key) { * return super.getSql(key, SQL); * } * } * </pre> * * @author Robert J. Muller * @param <T> the DTO type */ public abstract class AbstractDeleteSql<T extends IDbDto> implements IDeleteSql<T> { /** * A helper method that takes the SQL from the caller (usually a concrete * subclass of this class) and builds a complete SQL statement by adding the * key to the WHERE clause * * @param key the primary key to add to the WHERE clause * @param sql the SQL statement * @return a complete SQL statement */ public String getSql(IPrimaryKey key, String sql) { StringBuilder builder = new StringBuilder(sql); builder.append(key.getSqlWhereExpression("")); return builder.toString(); } @Override public <P extends IDbDto> int setParams(PreparedStatement stmt, int next, P dto) { next = dto.getPrimaryKey().setParams(stmt, next); return next; } }
Poesys-Associates/poesys-db
poesys-db/src/com/poesys/db/dao/delete/AbstractDeleteSql.java
Java
lgpl-3.0
2,290
/* * Copyright (C) 2005-2019 Alfresco Software Limited. * * This file is part of Gytheio * * Gytheio is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gytheio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Gytheio. If not, see <http://www.gnu.org/licenses/>. */ package org.gytheio.content.handler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import org.gytheio.content.ContentIOException; import org.gytheio.content.ContentReference; import org.gytheio.content.file.FileProvider; import org.gytheio.content.file.FileProviderImpl; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class DelegatingContentHandlerImplTest { private ContentReferenceHandler handlerA; private ContentReferenceHandler handlerB; private FileContentReferenceHandler delegatingHandler; private ContentReference contentReferenceFile1a; private ContentReference contentReferenceFile1b; private ContentReference contentReferenceFile1c; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws Exception { FileProvider fileProviderA = new FileProviderImpl("content-handler-a"); handlerA = new MockFileContentReferenceHandlerImpl("content-handler-a"); ((FileContentReferenceHandlerImpl) handlerA).setFileProvider(fileProviderA); FileProvider fileProviderB = new FileProviderImpl("content-handler-b"); handlerB = new MockFileContentReferenceHandlerImpl("content-handler-b"); ((FileContentReferenceHandlerImpl) handlerB).setFileProvider(fileProviderB); ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>(); delegates.add(handlerA); delegates.add(handlerB); delegatingHandler = new DelegatingContentHandlerImpl(); ((DelegatingContentHandlerImpl) delegatingHandler).setDelegates(delegates); contentReferenceFile1a = getTextReference("/content-handler-a/file-a-1.txt"); contentReferenceFile1b = getTextReference("/content-handler-b/file-b-1.txt"); contentReferenceFile1c = getTextReference("/content-handler-c/file-c-1.txt"); } private ContentReference getTextReference(String testPath) throws URISyntaxException { return getContentReference(testPath, "text/plain"); } private ContentReference getContentReference(String testPath, String mediaType) throws URISyntaxException { return new ContentReference(this.getClass().getResource(testPath).toURI().toString(), mediaType); } @Test public void testIsAvailable() { assertTrue(delegatingHandler.isAvailable()); ((FileContentReferenceHandlerImpl) handlerA).setFileProvider(null); assertFalse(delegatingHandler.isAvailable()); } @Test public void testIsContentReferenceSupported() { assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1a)); assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1b)); assertFalse(delegatingHandler.isContentReferenceSupported(contentReferenceFile1c)); } @Test public void testIsContentReferenceExists() { assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1a)); assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1b)); thrown.expect(UnsupportedOperationException.class); delegatingHandler.isContentReferenceExists(contentReferenceFile1c); } @Test public void testCreateContentReference() { thrown.expect(UnsupportedOperationException.class); delegatingHandler.createContentReference("testCreate.txt", "text/plain"); } @Test public void testGetFile() throws Exception { File sourceFile = delegatingHandler.getFile(contentReferenceFile1a, false); assertTrue(sourceFile.exists()); } @Test public void testNonFileDelegate() throws Exception { MockEmptyContentReferenceHandlerImpl handlerC = new MockEmptyContentReferenceHandlerImpl(); ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>(); delegates.add(handlerA); delegates.add(handlerB); delegates.add(handlerC); ContentReference contentReference = new ContentReference("mock://empty.txt", "text/plain"); thrown.expect(UnsupportedOperationException.class); delegatingHandler.getFile(contentReference, false); } @Test public void testGetInputStream() throws Exception { InputStream sourceInputStream = delegatingHandler.getInputStream(contentReferenceFile1a, false); assertEquals(15, sourceInputStream.available()); } @Test public void testPutFile() throws Exception { File sourceFile = new File(this.getClass().getResource( "/content-handler-a/file-a-1.txt").toURI()); String targetFolder = "/content-handler-a"; ContentReference targetContentReference = getTextReference(targetFolder); targetContentReference.setUri(targetContentReference.getUri() + "/file-a-3.txt"); delegatingHandler.putFile(sourceFile, targetContentReference); File targetFile = new File(new URI(targetContentReference.getUri())); assertTrue(targetFile.exists()); } @Test public void testPutInputStream() throws Exception { InputStream sourceInputStream = (this.getClass().getResourceAsStream( "/content-handler-a/file-a-1.txt")); String targetFolder = "/content-handler-a"; ContentReference targetContentReference = getTextReference(targetFolder); targetContentReference.setUri(targetContentReference.getUri() + "/file-a-4.txt"); delegatingHandler.putInputStream(sourceInputStream, targetContentReference); File targetFile = new File(new URI(targetContentReference.getUri())); assertTrue(targetFile.exists()); } @Test public void testDelete() throws Exception { File sourceFile = new File(this.getClass().getResource( "/content-handler-b/file-b-1.txt").toURI()); ContentReference targetContentReferenceToDelete = getTextReference("/content-handler-b"); targetContentReferenceToDelete.setUri(targetContentReferenceToDelete.getUri() + "/file-b-3.txt"); delegatingHandler.putFile(sourceFile, targetContentReferenceToDelete); File fileToDelete = new File(new URI(targetContentReferenceToDelete.getUri())); assertTrue(fileToDelete.exists()); delegatingHandler.delete(targetContentReferenceToDelete); assertFalse(fileToDelete.exists()); } /** * Test class that allows checking for specific paths */ public class MockFileContentReferenceHandlerImpl extends FileContentReferenceHandlerImpl { private String supportedUriPath; public MockFileContentReferenceHandlerImpl(String supportedUriPath) { this.supportedUriPath = supportedUriPath; } @Override public boolean isContentReferenceSupported(ContentReference contentReference) { if (contentReference == null) { return false; } return contentReference.getUri().contains(supportedUriPath); } } /** * Test class for non-file content references */ public class MockEmptyContentReferenceHandlerImpl implements ContentReferenceHandler { @Override public boolean isContentReferenceSupported(ContentReference contentReference) { return contentReference.getUri().startsWith("mock:/"); } @Override public boolean isContentReferenceExists(ContentReference contentReference) { return true; } @Override public ContentReference createContentReference(String fileName, String mediaType) throws ContentIOException { return null; } @Override public InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability) throws ContentIOException, InterruptedException { return null; } @Override public long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference) throws ContentIOException { return 0; } @Override public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { return 0; } @Override public void delete(ContentReference contentReference) throws ContentIOException { } @Override public boolean isAvailable() { return true; } } }
Alfresco/gytheio
gytheio-commons/src/test/java/org/gytheio/content/handler/DelegatingContentHandlerImplTest.java
Java
lgpl-3.0
9,751
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* Generated By:JJTree: Do not edit this line. AstFalse.java */ package org.apache.el.parser; import javax.el.ELException; import org.apache.el.lang.EvaluationContext; /** * @author Jacob Hookom [jacob@hookom.net] * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: remy.maucherat@jboss.com $ */ public final class AstFalse extends BooleanNode { public AstFalse(int id) { super(id); } public Object getValue(EvaluationContext ctx) throws ELException { return Boolean.FALSE; } }
benothman/jboss-web-nio2
java/org/apache/el/parser/AstFalse.java
Java
lgpl-3.0
1,350
# *-* encoding: utf-8 *-* import os import codecs import unicodedata try: from lxml import etree except ImportError: try: # Python 2.5 - cElementTree import xml.etree.cElementTree as etree except ImportError: try: # Python 2.5 - ElementTree import xml.etree.ElementTree as etree except ImportError: try: # Instalacao normal do cElementTree import cElementTree as etree except ImportError: try: # Instalacao normal do ElementTree import elementtree.ElementTree as etree except ImportError: raise Exception('Falhou ao importar lxml/ElementTree') try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import flags # from geraldo.utils import memoize # @memoize def so_numeros(texto): """Retorna o texto informado mas somente os numeros""" return ''.join(filter(lambda c: ord(c) in range(48, 58), texto)) # @memoize def obter_pais_por_codigo(codigo): # TODO if codigo == '1058': return 'Brasil' CAMINHO_DATA = os.path.join(os.path.dirname( os.path.abspath(__file__)), '..', 'data') CAMINHO_MUNICIPIOS = os.path.join(CAMINHO_DATA, 'MunIBGE') CARACTERS_ACENTUADOS = { ord(u'á'): u'a', ord(u'â'): u'a', ord(u'à'): u'a', ord(u'ã'): u'a', ord(u'é'): u'e', ord(u'ê'): u'e', ord(u'í'): u'i', ord(u'ó'): u'o', ord(u'õ'): u'o', ord(u'ô'): u'o', ord(u'ú'): u'u', ord(u'ç'): u'c', } # @memoize def normalizar_municipio(municipio): if not isinstance(municipio, unicode): municipio = municipio.decode('utf-8') return municipio.lower().translate(CARACTERS_ACENTUADOS).upper() # @memoize def carregar_arquivo_municipios(uf, reverso=False): if isinstance(uf, basestring): try: uf = int(uf) except ValueError: uf = flags.CODIGOS_ESTADOS[uf.upper()] caminho_arquivo = os.path.join(CAMINHO_MUNICIPIOS, 'MunIBGE-UF%s.txt' % uf) # Carrega o conteudo do arquivo fp = codecs.open(caminho_arquivo, "r", "utf-8-sig") linhas = list(fp.readlines()) fp.close() municipios_dict = {} for linha in linhas: codigo, municipio = linha.split('\t') codigo = codigo.strip() municipio = municipio.strip() if not reverso: municipios_dict[codigo] = municipio else: municipios_dict[normalizar_municipio(municipio)] = codigo return municipios_dict # @memoize def obter_codigo_por_municipio(municipio, uf): # TODO: fazer UF ser opcional municipios = carregar_arquivo_municipios(uf, True) return municipios[normalizar_municipio(municipio)] # @memoize def obter_municipio_por_codigo(codigo, uf, normalizado=False): # TODO: fazer UF ser opcional municipios = carregar_arquivo_municipios(uf) municipio = municipios.get(unicode(codigo)) if municipio is None: raise ValueError if normalizado: return normalizar_municipio(municipio) return municipio # @memoize def obter_municipio_e_codigo(dados, uf): '''Retorna código e município municipio_ou_codigo - espera receber um dicionário no formato: {codigo: 121212, municipio: u'municipio'} ''' cod = dados.get('codigo', '') mun = normalizar_municipio(dados.get('municipio', '')) try: cod = int(cod) except ValueError: cod = obter_codigo_por_municipio(mun, uf) # TODO: se ainda com este teste apresentar erros de nessa seção # desenvolver um retorno que informe ao cliente quais nfes estão com erro # e não explodir esse a geração das outras nfes municipio = obter_municipio_por_codigo(cod, uf, normalizado=True) return cod, municipio # @memoize def extrair_tag(root): return root.tag.split('}')[-1] def formatar_decimal(dec): if dec * 100 - int(dec * 100): return str(dec) else: return "%.2f" % dec def safe_str(str_): if not isinstance(str_, unicode): if isinstance(str_, str): str_ = str_.decode('utf8') else: str_ = unicode(str_) return unicodedata.normalize('NFKD', str_).encode('ascii', 'ignore') def obter_uf_por_codigo(codigo_uf): if isinstance(codigo_uf, basestring) and codigo_uf.isalpha(): return codigo_uf estados = {v: k for k, v in flags.CODIGOS_ESTADOS.items()} return estados[unicode(codigo_uf)]
YACOWS/PyNFe
pynfe/utils/__init__.py
Python
lgpl-3.0
4,553
using System; namespace HookManager { public static partial class Hooker { public enum WM : uint { NULL = 0x0000, CREATE = 0x0001, DESTROY = 0x0002, MOVE = 0x0003, SIZE = 0x0005, ACTIVATE = 0x0006, SETFOCUS = 0x0007, KILLFOCUS = 0x0008, ENABLE = 0x000A, SETREDRAW = 0x000B, SETTEXT = 0x000C, GETTEXT = 0x000D, GETTEXTLENGTH = 0x000E, PAINT = 0x000F, CLOSE = 0x0010, QUERYENDSESSION = 0x0011, QUERYOPEN = 0x0013, ENDSESSION = 0x0016, QUIT = 0x0012, ERASEBKGND = 0x0014, SYSCOLORCHANGE = 0x0015, SHOWWINDOW = 0x0018, WININICHANGE = 0x001A, SETTINGCHANGE = WININICHANGE, DEVMODECHANGE = 0x001B, ACTIVATEAPP = 0x001C, FONTCHANGE = 0x001D, TIMECHANGE = 0x001E, CANCELMODE = 0x001F, SETCURSOR = 0x0020, MOUSEACTIVATE = 0x0021, CHILDACTIVATE = 0x0022, QUEUESYNC = 0x0023, GETMINMAXINFO = 0x0024, PAINTICON = 0x0026, ICONERASEBKGND = 0x0027, NEXTDLGCTL = 0x0028, SPOOLERSTATUS = 0x002A, DRAWITEM = 0x002B, MEASUREITEM = 0x002C, DELETEITEM = 0x002D, VKEYTOITEM = 0x002E, CHARTOITEM = 0x002F, SETFONT = 0x0030, GETFONT = 0x0031, SETHOTKEY = 0x0032, GETHOTKEY = 0x0033, QUERYDRAGICON = 0x0037, COMPAREITEM = 0x0039, GETOBJECT = 0x003D, COMPACTING = 0x0041, [Obsolete] COMMNOTIFY = 0x0044, WINDOWPOSCHANGING = 0x0046, WINDOWPOSCHANGED = 0x0047, [Obsolete] POWER = 0x0048, COPYDATA = 0x004A, CANCELJOURNAL = 0x004B, NOTIFY = 0x004E, INPUTLANGCHANGEREQUEST = 0x0050, INPUTLANGCHANGE = 0x0051, TCARD = 0x0052, HELP = 0x0053, USERCHANGED = 0x0054, NOTIFYFORMAT = 0x0055, CONTEXTMENU = 0x007B, STYLECHANGING = 0x007C, STYLECHANGED = 0x007D, DISPLAYCHANGE = 0x007E, GETICON = 0x007F, SETICON = 0x0080, NCCREATE = 0x0081, NCDESTROY = 0x0082, NCCALCSIZE = 0x0083, NCHITTEST = 0x0084, NCPAINT = 0x0085, NCACTIVATE = 0x0086, GETDLGCODE = 0x0087, SYNCPAINT = 0x0088, NCMOUSEMOVE = 0x00A0, NCLBUTTONDOWN = 0x00A1, NCLBUTTONUP = 0x00A2, NCLBUTTONDBLCLK = 0x00A3, NCRBUTTONDOWN = 0x00A4, NCRBUTTONUP = 0x00A5, NCRBUTTONDBLCLK = 0x00A6, NCMBUTTONDOWN = 0x00A7, NCMBUTTONUP = 0x00A8, NCMBUTTONDBLCLK = 0x00A9, NCXBUTTONDOWN = 0x00AB, NCXBUTTONUP = 0x00AC, NCXBUTTONDBLCLK = 0x00AD, INPUT_DEVICE_CHANGE = 0x00FE, INPUT = 0x00FF, KEYFIRST = 0x0100, KEYDOWN = 0x0100, KEYUP = 0x0101, CHAR = 0x0102, DEADCHAR = 0x0103, SYSKEYDOWN = 0x0104, SYSKEYUP = 0x0105, SYSCHAR = 0x0106, SYSDEADCHAR = 0x0107, UNICHAR = 0x0109, KEYLAST = 0x0109, IME_STARTCOMPOSITION = 0x010D, IME_ENDCOMPOSITION = 0x010E, IME_COMPOSITION = 0x010F, IME_KEYLAST = 0x010F, INITDIALOG = 0x0110, COMMAND = 0x0111, SYSCOMMAND = 0x0112, TIMER = 0x0113, HSCROLL = 0x0114, VSCROLL = 0x0115, INITMENU = 0x0116, INITMENUPOPUP = 0x0117, MENUSELECT = 0x011F, MENUCHAR = 0x0120, ENTERIDLE = 0x0121, MENURBUTTONUP = 0x0122, MENUDRAG = 0x0123, MENUGETOBJECT = 0x0124, UNINITMENUPOPUP = 0x0125, MENUCOMMAND = 0x0126, CHANGEUISTATE = 0x0127, UPDATEUISTATE = 0x0128, QUERYUISTATE = 0x0129, CTLCOLORMSGBOX = 0x0132, CTLCOLOREDIT = 0x0133, CTLCOLORLISTBOX = 0x0134, CTLCOLORBTN = 0x0135, CTLCOLORDLG = 0x0136, CTLCOLORSCROLLBAR = 0x0137, CTLCOLORSTATIC = 0x0138, MOUSEFIRST = 0x0200, MOUSEMOVE = 0x0200, LBUTTONDOWN = 0x0201, LBUTTONUP = 0x0202, LBUTTONDBLCLK = 0x0203, RBUTTONDOWN = 0x0204, RBUTTONUP = 0x0205, RBUTTONDBLCLK = 0x0206, MBUTTONDOWN = 0x0207, MBUTTONUP = 0x0208, MBUTTONDBLCLK = 0x0209, MOUSEWHEEL = 0x020A, XBUTTONDOWN = 0x020B, XBUTTONUP = 0x020C, XBUTTONDBLCLK = 0x020D, MOUSEHWHEEL = 0x020E, MOUSELAST = 0x020E, PARENTNOTIFY = 0x0210, ENTERMENULOOP = 0x0211, EXITMENULOOP = 0x0212, NEXTMENU = 0x0213, SIZING = 0x0214, CAPTURECHANGED = 0x0215, MOVING = 0x0216, POWERBROADCAST = 0x0218, DEVICECHANGE = 0x0219, MDICREATE = 0x0220, MDIDESTROY = 0x0221, MDIACTIVATE = 0x0222, MDIRESTORE = 0x0223, MDINEXT = 0x0224, MDIMAXIMIZE = 0x0225, MDITILE = 0x0226, MDICASCADE = 0x0227, MDIICONARRANGE = 0x0228, MDIGETACTIVE = 0x0229, MDISETMENU = 0x0230, ENTERSIZEMOVE = 0x0231, EXITSIZEMOVE = 0x0232, DROPFILES = 0x0233, MDIREFRESHMENU = 0x0234, IME_SETCONTEXT = 0x0281, IME_NOTIFY = 0x0282, IME_CONTROL = 0x0283, IME_COMPOSITIONFULL = 0x0284, IME_SELECT = 0x0285, IME_CHAR = 0x0286, IME_REQUEST = 0x0288, IME_KEYDOWN = 0x0290, IME_KEYUP = 0x0291, MOUSEHOVER = 0x02A1, MOUSELEAVE = 0x02A3, NCMOUSEHOVER = 0x02A0, NCMOUSELEAVE = 0x02A2, WTSSESSION_CHANGE = 0x02B1, TABLET_FIRST = 0x02c0, TABLET_LAST = 0x02df, CUT = 0x0300, COPY = 0x0301, PASTE = 0x0302, CLEAR = 0x0303, UNDO = 0x0304, RENDERFORMAT = 0x0305, RENDERALLFORMATS = 0x0306, DESTROYCLIPBOARD = 0x0307, DRAWCLIPBOARD = 0x0308, PAINTCLIPBOARD = 0x0309, VSCROLLCLIPBOARD = 0x030A, SIZECLIPBOARD = 0x030B, ASKCBFORMATNAME = 0x030C, CHANGECBCHAIN = 0x030D, HSCROLLCLIPBOARD = 0x030E, QUERYNEWPALETTE = 0x030F, PALETTEISCHANGING = 0x0310, PALETTECHANGED = 0x0311, HOTKEY = 0x0312, PRINT = 0x0317, PRINTCLIENT = 0x0318, APPCOMMAND = 0x0319, THEMECHANGED = 0x031A, CLIPBOARDUPDATE = 0x031D, DWMCOMPOSITIONCHANGED = 0x031E, DWMNCRENDERINGCHANGED = 0x031F, DWMCOLORIZATIONCOLORCHANGED = 0x0320, DWMWINDOWMAXIMIZEDCHANGE = 0x0321, GETTITLEBARINFOEX = 0x033F, HANDHELDFIRST = 0x0358, HANDHELDLAST = 0x035F, AFXFIRST = 0x0360, AFXLAST = 0x037F, PENWINFIRST = 0x0380, PENWINLAST = 0x038F, APP = 0x8000, USER = 0x0400, CPL_LAUNCH = USER + 0x1000, CPL_LAUNCHED = USER + 0x1001, SYSTIMER = 0x118 } public enum HookType : int { WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, WH_KEYBOARD = 2, WH_GETMESSAGE = 3, WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, WH_CALLWNDPROCRET = 12, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } public const int WH_KEYBOARD = 2; public const int WH_MOUSE = 7; public const int WH_KEYBOARD_LL = 13; public const int WH_MOUSE_LL = 14; public const int VK_SHIFT = 0x10; public const int VK_CAPITAL = 0x14; public const int VK_NUMLOCK = 0x90; public const int WM_KEYDOWN = 0x100; public const int WM_KEYUP = 0x101; public const int WM_SYSKEYDOWN = 0x104; public const int WM_SYSKEYUP = 0x105; public const int WM_MOUSEMOVE = 0x200; public const int WM_LBUTTONDOWN = 0x201; public const int WM_LBUTTONUP = 0x202; public const int WM_LBUTTONDBLCLK = 0x203; public const int WM_RBUTTONDOWN = 0x204; public const int WM_RBUTTONUP = 0x205; public const int WM_RBUTTONDBLCLK = 0x206; public const int WM_MBUTTONDOWN = 0x207; public const int WM_MBUTTONUP = 0x208; public const int WM_MBUTTONDBLCLK = 0x209; public const int WM_MOUSEWHEEL = 0x20A; } }
shurizzle/Scroto
HookManager/Hooker.Constants.cs
C#
lgpl-3.0
7,936
# (C) British Crown Copyright 2016, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cartopy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with cartopy. If not, see <https://www.gnu.org/licenses/>. """ Tests for the NearsidePerspective projection. """ from __future__ import (absolute_import, division, print_function) import unittest from numpy.testing import assert_almost_equal from nose.tools import assert_equal from cartopy.tests.crs.test_geostationary import (GeostationaryTestsMixin, check_proj4_params) from cartopy.crs import NearsidePerspective class TestEquatorialDefault(unittest.TestCase, GeostationaryTestsMixin): # Check that it behaves just like Geostationary, in the absence of a # central_latitude parameter. test_class = NearsidePerspective expected_proj_name = 'nsper' class TestOwnSpecifics(unittest.TestCase): def test_central_latitude(self): # Check the effect of the added 'central_latitude' key. geos = NearsidePerspective(central_latitude=53.7) expected = ['+ellps=WGS84', 'h=35785831', 'lat_0=53.7', 'lon_0=0.0', 'no_defs', 'proj=nsper', 'units=m', 'x_0=0', 'y_0=0'] check_proj4_params(geos, expected) assert_almost_equal(geos.boundary.bounds, (-5372584.78443894, -5372584.78443894, 5372584.78443894, 5372584.78443894), decimal=4) if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
zak-k/cartopy
lib/cartopy/tests/crs/test_nearside_perspective.py
Python
lgpl-3.0
2,158
// Version information for the "groupsock" library // Copyright (c) 1996-2018 Live Networks, Inc. All rights reserved. #ifndef _GROUPSOCK_VERSION_HH #define _GROUPSOCK_VERSION_HH #define GROUPSOCK_LIBRARY_VERSION_STRING "2018.08.28" #define GROUPSOCK_LIBRARY_VERSION_INT 1535414400 #endif
xanview/live555
groupsock/include/groupsock_version.hh
C++
lgpl-3.0
294
package zeditor.tools.banque; import java.awt.Point; import java.util.Arrays; import zeditor.tools.tiles.Banque; import zeditor.tools.tiles.GraphChange; // Foret4 = exteria8 (194 tiles) public class Foret4 extends Banque { public Foret4() { coords = new Point[] { /* Ruines */ /* Bordures de collines */ // Orange flower new Point(0, 0), new Point(16, 0), new Point(32, 0), new Point(48, 0), new Point(0, 16), new Point(16, 16), new Point(32, 16), new Point(48, 16), new Point(0, 32), new Point(32, 32), new Point(48, 32), new Point(0, 48), new Point(16, 48), new Point(32, 48), new Point(48, 48), /* Sols */ new Point(32, 64), new Point(48, 64), new Point(64, 64), new Point(32, 80), new Point(64, 48), /* Grand pilier */ new Point(96, 0), new Point(112, 0), new Point(144, 0), new Point(192, 0), new Point(96, 16), new Point(112, 16), new Point(192, 16), new Point(128, 16), new Point(144, 16), new Point(96, 32), new Point(112, 32), new Point(128, 32), new Point(144, 32), new Point(96, 48), new Point(112, 48), new Point(128, 48), new Point(144, 48), /* Statues */ new Point(0, 64), new Point(16, 64), new Point(0, 80), new Point(16, 80), new Point(160, 0), new Point(176, 0), new Point(160, 16), new Point(176, 16), new Point(160, 32), new Point(176, 32), /* Maison jaune */ new Point(208, 0), new Point(224, 0), new Point(272, 0), new Point(208, 16), new Point(224, 16), new Point(240, 16), new Point(256, 16), new Point(272, 16), new Point(208, 32), new Point(224, 32), new Point(272, 32), new Point(208, 48), new Point(224, 48), /* Déco de palais */ new Point(64, 0), new Point(64, 16), new Point(64, 32), new Point(80, 0), new Point(80, 16), new Point(80, 32), new Point(192, 32), new Point(0, 96), new Point(16, 96), new Point(0, 112), new Point(16, 112), new Point(32, 112), new Point(48, 112), /* Forˆt enchant‚e */ /* Sols bosquet */ new Point(240, 80), new Point(240, 96), new Point(240, 112), /* Bordures forˆt */ new Point(224, 64), new Point(240, 64), new Point(256, 64), new Point(224, 80), new Point(256, 80), new Point(208, 96), new Point(272, 96), new Point(208, 112), new Point(224, 112), new Point(256, 112), new Point(272, 112), new Point(224, 128), new Point(240, 128), new Point(256, 128), /* Bas du grand arbre */ new Point(96, 64), new Point(112, 64), new Point(128, 64), new Point(144, 64), new Point(96, 80), new Point(112, 80), new Point(128, 80), new Point(144, 80), /* Petits arbres */ new Point(288, 80), new Point(304, 80), new Point(288, 96), new Point(304, 96), new Point(272, 48), new Point(288, 48), new Point(272, 64), new Point(288, 64), /* Tronc d'arbre tunnel */ new Point(160, 48), new Point(176, 48), new Point(192, 48), new Point(160, 64), new Point(176, 64), new Point(192, 64), new Point(160, 80), new Point(176, 80), new Point(192, 80), new Point(160, 96), new Point(176, 96), new Point(192, 96), new Point(160, 112), new Point(176, 112), new Point(192, 112), new Point(160, 128), new Point(176, 128), new Point(192, 128), new Point(96, 96), new Point(112, 96), /* Souche creuse */ new Point(128, 96), new Point(144, 96), new Point(128, 112), new Point(144, 112), new Point(128, 128), new Point(144, 128), /* Clairière */ /* Feuillage */ new Point(0, 128), new Point(16, 128), new Point(32, 128), new Point(48, 128), new Point(0, 144), new Point(16, 144), new Point(32, 144), new Point(48, 144), new Point(0, 160), new Point(16, 160), new Point(32, 160), new Point(48, 160), new Point(0, 176), new Point(16, 176), new Point(32, 176), new Point(64, 128), new Point(80, 128), new Point(96, 128), new Point(112, 128), new Point(64, 144), new Point(80, 144), new Point(96, 144), new Point(112, 144), new Point(64, 160), new Point(80, 160), new Point(96, 160), new Point(112, 160), new Point(80, 176), new Point(96, 176), new Point(112, 176), /* Ombres */ new Point(144, 144), new Point(160, 144), new Point(128, 160), new Point(144, 160), new Point(176, 160), new Point(144, 176), new Point(160, 176), /* Estrade de pierre */ new Point(224, 144), new Point(240, 144), new Point(256, 144), new Point(208, 144), new Point(208, 160), new Point(224, 160), new Point(240, 160), new Point(256, 160), new Point(192, 144), new Point(192, 160), new Point(176, 176), new Point(192, 176), new Point(208, 176), new Point(224, 176), new Point(240, 176), new Point(256, 176), new Point(272, 176), new Point(288, 176), /* Piédestal */ new Point(272, 144), new Point(288, 144), new Point(272, 160), new Point(288, 160), /* Close trees */ new Point(304, 0), new Point(304, 16), new Point(304, 32), new Point(304, 48), new Point(304, 64), /* Buche creuse */ new Point(208, 112), /* Wood stairs */ new Point(272, 128), /* Hole in the ground */ new Point(304, 112), /* Ill tree */ new Point(0, 304), new Point(16, 304), new Point(32, 304), new Point(48, 304), new Point(0, 320), new Point(16, 320), new Point(32, 320), new Point(48, 320), new Point(0, 336), new Point(16, 336), new Point(32, 336), new Point(48, 336), new Point(0, 352), new Point(16, 352), new Point(32, 352), new Point(48, 352), // Flowers (215) new Point(208, 112), new Point(224, 112), new Point(240, 112), // Blue new Point(208, 128), new Point(224, 128), new Point(240, 128), // Blue pack new Point(176, 128), new Point(192, 144), new Point(208, 144), // Red flower // Water mud (224) new Point(224, 144), // Higher stump new Point(144, 176), new Point(160, 176), new Point(144, 192), new Point(160, 192), // Water mud border new Point(176, 160), new Point(192, 160), // Nettle new Point(160, 48), new Point(176, 48), // Higher stump top new Point(144, 208), new Point(160, 208), // Birch (bouleau) 235 new Point(0, 208), new Point(16, 208), new Point(32, 208), new Point(48, 208), new Point(0, 224), new Point(16, 224), new Point(32, 224), new Point(48, 224), new Point(0, 240), new Point(16, 240), new Point(32, 240), new Point(48, 240), new Point(0, 256), new Point(16, 256), new Point(32, 256), new Point(48, 256), new Point(0, 272), new Point(16, 272), new Point(32, 272), new Point(48, 272) }; pkmChanges = Arrays.asList(new GraphChange[] { new GraphChange("exteria8", 0, 0), new GraphChange("exteria1", 215, 80), new GraphChange("exteria1", 235, -80)}); } }
tchegito/zildo
zeditor/src/zeditor/tools/banque/Foret4.java
Java
lgpl-3.0
6,694
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.portal.model.impl; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import com.liferay.portal.model.LayoutRevision; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; /** * The cache model class for representing LayoutRevision in entity cache. * * @author Brian Wing Shun Chan * @see LayoutRevision * @generated */ public class LayoutRevisionCacheModel implements CacheModel<LayoutRevision>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(63); sb.append("{layoutRevisionId="); sb.append(layoutRevisionId); sb.append(", groupId="); sb.append(groupId); sb.append(", companyId="); sb.append(companyId); sb.append(", userId="); sb.append(userId); sb.append(", userName="); sb.append(userName); sb.append(", createDate="); sb.append(createDate); sb.append(", modifiedDate="); sb.append(modifiedDate); sb.append(", layoutSetBranchId="); sb.append(layoutSetBranchId); sb.append(", layoutBranchId="); sb.append(layoutBranchId); sb.append(", parentLayoutRevisionId="); sb.append(parentLayoutRevisionId); sb.append(", head="); sb.append(head); sb.append(", major="); sb.append(major); sb.append(", plid="); sb.append(plid); sb.append(", privateLayout="); sb.append(privateLayout); sb.append(", name="); sb.append(name); sb.append(", title="); sb.append(title); sb.append(", description="); sb.append(description); sb.append(", keywords="); sb.append(keywords); sb.append(", robots="); sb.append(robots); sb.append(", typeSettings="); sb.append(typeSettings); sb.append(", iconImage="); sb.append(iconImage); sb.append(", iconImageId="); sb.append(iconImageId); sb.append(", themeId="); sb.append(themeId); sb.append(", colorSchemeId="); sb.append(colorSchemeId); sb.append(", wapThemeId="); sb.append(wapThemeId); sb.append(", wapColorSchemeId="); sb.append(wapColorSchemeId); sb.append(", css="); sb.append(css); sb.append(", status="); sb.append(status); sb.append(", statusByUserId="); sb.append(statusByUserId); sb.append(", statusByUserName="); sb.append(statusByUserName); sb.append(", statusDate="); sb.append(statusDate); sb.append("}"); return sb.toString(); } @Override public LayoutRevision toEntityModel() { LayoutRevisionImpl layoutRevisionImpl = new LayoutRevisionImpl(); layoutRevisionImpl.setLayoutRevisionId(layoutRevisionId); layoutRevisionImpl.setGroupId(groupId); layoutRevisionImpl.setCompanyId(companyId); layoutRevisionImpl.setUserId(userId); if (userName == null) { layoutRevisionImpl.setUserName(StringPool.BLANK); } else { layoutRevisionImpl.setUserName(userName); } if (createDate == Long.MIN_VALUE) { layoutRevisionImpl.setCreateDate(null); } else { layoutRevisionImpl.setCreateDate(new Date(createDate)); } if (modifiedDate == Long.MIN_VALUE) { layoutRevisionImpl.setModifiedDate(null); } else { layoutRevisionImpl.setModifiedDate(new Date(modifiedDate)); } layoutRevisionImpl.setLayoutSetBranchId(layoutSetBranchId); layoutRevisionImpl.setLayoutBranchId(layoutBranchId); layoutRevisionImpl.setParentLayoutRevisionId(parentLayoutRevisionId); layoutRevisionImpl.setHead(head); layoutRevisionImpl.setMajor(major); layoutRevisionImpl.setPlid(plid); layoutRevisionImpl.setPrivateLayout(privateLayout); if (name == null) { layoutRevisionImpl.setName(StringPool.BLANK); } else { layoutRevisionImpl.setName(name); } if (title == null) { layoutRevisionImpl.setTitle(StringPool.BLANK); } else { layoutRevisionImpl.setTitle(title); } if (description == null) { layoutRevisionImpl.setDescription(StringPool.BLANK); } else { layoutRevisionImpl.setDescription(description); } if (keywords == null) { layoutRevisionImpl.setKeywords(StringPool.BLANK); } else { layoutRevisionImpl.setKeywords(keywords); } if (robots == null) { layoutRevisionImpl.setRobots(StringPool.BLANK); } else { layoutRevisionImpl.setRobots(robots); } if (typeSettings == null) { layoutRevisionImpl.setTypeSettings(StringPool.BLANK); } else { layoutRevisionImpl.setTypeSettings(typeSettings); } layoutRevisionImpl.setIconImage(iconImage); layoutRevisionImpl.setIconImageId(iconImageId); if (themeId == null) { layoutRevisionImpl.setThemeId(StringPool.BLANK); } else { layoutRevisionImpl.setThemeId(themeId); } if (colorSchemeId == null) { layoutRevisionImpl.setColorSchemeId(StringPool.BLANK); } else { layoutRevisionImpl.setColorSchemeId(colorSchemeId); } if (wapThemeId == null) { layoutRevisionImpl.setWapThemeId(StringPool.BLANK); } else { layoutRevisionImpl.setWapThemeId(wapThemeId); } if (wapColorSchemeId == null) { layoutRevisionImpl.setWapColorSchemeId(StringPool.BLANK); } else { layoutRevisionImpl.setWapColorSchemeId(wapColorSchemeId); } if (css == null) { layoutRevisionImpl.setCss(StringPool.BLANK); } else { layoutRevisionImpl.setCss(css); } layoutRevisionImpl.setStatus(status); layoutRevisionImpl.setStatusByUserId(statusByUserId); if (statusByUserName == null) { layoutRevisionImpl.setStatusByUserName(StringPool.BLANK); } else { layoutRevisionImpl.setStatusByUserName(statusByUserName); } if (statusDate == Long.MIN_VALUE) { layoutRevisionImpl.setStatusDate(null); } else { layoutRevisionImpl.setStatusDate(new Date(statusDate)); } layoutRevisionImpl.resetOriginalValues(); return layoutRevisionImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { layoutRevisionId = objectInput.readLong(); groupId = objectInput.readLong(); companyId = objectInput.readLong(); userId = objectInput.readLong(); userName = objectInput.readUTF(); createDate = objectInput.readLong(); modifiedDate = objectInput.readLong(); layoutSetBranchId = objectInput.readLong(); layoutBranchId = objectInput.readLong(); parentLayoutRevisionId = objectInput.readLong(); head = objectInput.readBoolean(); major = objectInput.readBoolean(); plid = objectInput.readLong(); privateLayout = objectInput.readBoolean(); name = objectInput.readUTF(); title = objectInput.readUTF(); description = objectInput.readUTF(); keywords = objectInput.readUTF(); robots = objectInput.readUTF(); typeSettings = objectInput.readUTF(); iconImage = objectInput.readBoolean(); iconImageId = objectInput.readLong(); themeId = objectInput.readUTF(); colorSchemeId = objectInput.readUTF(); wapThemeId = objectInput.readUTF(); wapColorSchemeId = objectInput.readUTF(); css = objectInput.readUTF(); status = objectInput.readInt(); statusByUserId = objectInput.readLong(); statusByUserName = objectInput.readUTF(); statusDate = objectInput.readLong(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeLong(layoutRevisionId); objectOutput.writeLong(groupId); objectOutput.writeLong(companyId); objectOutput.writeLong(userId); if (userName == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(userName); } objectOutput.writeLong(createDate); objectOutput.writeLong(modifiedDate); objectOutput.writeLong(layoutSetBranchId); objectOutput.writeLong(layoutBranchId); objectOutput.writeLong(parentLayoutRevisionId); objectOutput.writeBoolean(head); objectOutput.writeBoolean(major); objectOutput.writeLong(plid); objectOutput.writeBoolean(privateLayout); if (name == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(name); } if (title == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(title); } if (description == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(description); } if (keywords == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(keywords); } if (robots == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(robots); } if (typeSettings == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(typeSettings); } objectOutput.writeBoolean(iconImage); objectOutput.writeLong(iconImageId); if (themeId == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(themeId); } if (colorSchemeId == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(colorSchemeId); } if (wapThemeId == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(wapThemeId); } if (wapColorSchemeId == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(wapColorSchemeId); } if (css == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(css); } objectOutput.writeInt(status); objectOutput.writeLong(statusByUserId); if (statusByUserName == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(statusByUserName); } objectOutput.writeLong(statusDate); } public long layoutRevisionId; public long groupId; public long companyId; public long userId; public String userName; public long createDate; public long modifiedDate; public long layoutSetBranchId; public long layoutBranchId; public long parentLayoutRevisionId; public boolean head; public boolean major; public long plid; public boolean privateLayout; public String name; public String title; public String description; public String keywords; public String robots; public String typeSettings; public boolean iconImage; public long iconImageId; public String themeId; public String colorSchemeId; public String wapThemeId; public String wapColorSchemeId; public String css; public int status; public long statusByUserId; public String statusByUserName; public long statusDate; }
km-works/portal-rpc
portal-rpc-client/src/main/java/com/liferay/portal/model/impl/LayoutRevisionCacheModel.java
Java
lgpl-3.0
10,917
/* -------------------------------------------------------------------------- * * * Simple test of the HCOD class with assertion. * * -------------------------------------------------------------------------- */ #define SOTH_DEBUG #define SOTH_DEBUG_MODE 10 #define SOTH_TEMPLATE_DEBUG_MODE 10 #include "RandomGenerator.hpp" #include "soth/HCOD.hpp" #include "soth/Random.hpp" #include "soth/debug.hpp" using namespace soth; int main(int, char**) { soth::sotDebugTrace::openFile(); soth::Random::setSeed(7); const int NB_STAGE = 3; const int RANKFREE[] = {3, 4, 3, 5, 3}; const int RANKLINKED[] = {2, 2, 1, 5, 3}; const int NR[] = {5, 4, 5, 5, 8}; const int NC = 12; /* Initialize J and b. */ std::vector<Eigen::MatrixXd> J(NB_STAGE); std::vector<soth::VectorBound> b(NB_STAGE); soth::generateDeficientDataSet(J, b, NB_STAGE, RANKFREE, RANKLINKED, NR, NC); b[0][1] = std::make_pair(-0.1, 2.37); for (int i = 0; i < NB_STAGE; ++i) { sotDEBUG(0) << "J" << i + 1 << " = " << (soth::MATLAB)J[i] << std::endl; sotDEBUG(0) << "e" << i + 1 << " = " << b[i] << ";" << std::endl; } std::cout << J[0](0, 0) << std::endl; assert(std::abs(J[0](0, 0) - 0.544092) < 1e-5); /* SOTH structure construction. */ soth::HCOD hcod(NC, NB_STAGE); for (int i = 0; i < NB_STAGE; ++i) { hcod.pushBackStage(J[i], b[i]); assert(NR[i] > 0); } hcod.setInitialActiveSet(); hcod.setNameByOrder("stage_"); hcod.initialize(); hcod.Y.computeExplicitly(); hcod.computeSolution(true); std::cout << hcod.rank() << " " << hcod[0].rank() << " " << hcod[1].rank() << " " << hcod[2].rank() << std::endl; assert((hcod.rank() == 4) && (hcod[0].rank() == 0) && (hcod[1].rank() == 2) && (hcod[2].rank() == 2)); double tau = hcod.computeStepAndUpdate(); hcod.makeStep(tau); std::cout << "tau:" << tau << " " << std::abs(tau - 0.486522) << " " << soth::Stage::EPSILON << std::endl; assert((std::abs(tau - 0.486522) <= 50 * soth::Stage::EPSILON) && "Check bound test failed."); hcod.computeLagrangeMultipliers(hcod.nbStages()); bool testL = hcod.testLagrangeMultipliers(hcod.nbStages(), std::cout); sotDEBUG(5) << "Test multipliers: " << ((testL) ? "Passed!" : "Failed...") << std::endl; assert(testL && "Lagrange Multipliers test failed."); }
stack-of-tasks/soth
unitTesting/thcod.cpp
C++
lgpl-3.0
2,350
/* * Copyright (c) 2005-2010 Substance Kirill Grouchnikov. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of Substance Kirill Grouchnikov 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. */ package org.pushingpixels.substance.api; /** * Defines transformation on a color scheme. * * @author Kirill Grouchnikov */ public interface ColorSchemeTransform { /** * Transforms the specified color scheme. * * @param scheme * The original color scheme to transform. * @return The transformed color scheme. */ public SubstanceColorScheme transform(SubstanceColorScheme scheme); }
Depter/JRLib
NetbeansProject/jreserve-dummy/substance/src/main/java/org/pushingpixels/substance/api/ColorSchemeTransform.java
Java
lgpl-3.0
2,058
/** Copyright 2015 W. Max Lees This file is part of Jarvis OS. Jarvis OS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Jarvis OS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Jarvis OS. If not, see <http://www.gnu.org/licenses/>. */ /** FILE: SNLayer.cpp @author W. Max Lees @docdate 06.12.2015 @descr Layer of neurons for the Sigmoid Neuron Network implementation */ #include "SNLayer.hpp" namespace Jarvis { namespace JarvisNLP { /*! Initializes the layer based on the number of previous neurons and the size of the current layer */ template <typename T> void SigmoidNeuronLayer<T>::init(int prevLayerSize, int layerSize) { } } }
Wmaxlees/jarvis-os
jarvis-nlp/src/SNLayer.cpp
C++
lgpl-3.0
1,179
# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE). # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """utilities methods and classes for reporters""" import sys import locale import os from .. import utils CMPS = ['=', '-', '+'] # py3k has no more cmp builtin if sys.version_info >= (3, 0): def cmp(a, b): return (a > b) - (a < b) def diff_string(old, new): """given a old and new int value, return a string representing the difference """ diff = abs(old - new) diff_str = "%s%s" % (CMPS[cmp(old, new)], diff and ('%.2f' % diff) or '') return diff_str class Message(object): """This class represent a message to be issued by the reporters""" def __init__(self, reporter, msg_id, location, msg): self.msg_id = msg_id self.abspath, self.module, self.obj, self.line, self.column = location self.path = self.abspath.replace(reporter.path_strip_prefix, '') self.msg = msg self.C = msg_id[0] self.category = utils.MSG_TYPES[msg_id[0]] self.symbol = reporter.linter.check_message_id(msg_id).symbol def format(self, template): """Format the message according to the given template. The template format is the one of the format method : cf. http://docs.python.org/2/library/string.html#formatstrings """ return template.format(**(self.__dict__)) class BaseReporter(object): """base class for reporters symbols: show short symbolic names for messages. """ extension = '' def __init__(self, output=None): self.linter = None # self.include_ids = None # Deprecated # self.symbols = None # Deprecated self.section = 0 self.out = None self.out_encoding = None self.encode = None self.set_output(output) # Build the path prefix to strip to get relative paths self.path_strip_prefix = os.getcwd() + os.sep def add_message(self, msg_id, location, msg): """Client API to send a message""" # Shall we store the message objects somewhere, do some validity checking ? raise NotImplementedError def set_output(self, output=None): """set output stream""" self.out = output or sys.stdout # py3k streams handle their encoding : if sys.version_info >= (3, 0): self.encode = lambda x: x return def encode(string): if not isinstance(string, unicode): return string encoding = (getattr(self.out, 'encoding', None) or locale.getdefaultlocale()[1] or sys.getdefaultencoding()) # errors=replace, we don't want to crash when attempting to show # source code line that can't be encoded with the current locale # settings return string.encode(encoding, 'replace') self.encode = encode def writeln(self, string=''): """write a line in the output buffer""" print >> self.out, self.encode(string) def display_results(self, layout): """display results encapsulated in the layout tree""" self.section = 0 if hasattr(layout, 'report_id'): layout.children[0].children[0].data += ' (%s)' % layout.report_id self._display(layout) def _display(self, layout): """display the layout""" raise NotImplementedError() # Event callbacks def on_set_current_module(self, module, filepath): """starting analyzis of a module""" pass def on_close(self, stats, previous_stats): """global end of analyzis""" pass def initialize(linter): """initialize linter with reporters in this package """ utils.register_plugins(linter, __path__[0])
lukaszpiotr/pylama_with_gjslint
pylama/checkers/pylint/reporters/__init__.py
Python
lgpl-3.0
4,482
package de.lmu.ifi.bio.croco.cyto.ui; import java.awt.Component; import java.util.List; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; public class OperationsTable extends JTable { class OperationModel extends AbstractTableModel{ private static final long serialVersionUID = 1L; List<JButton> possibleOperations = null; public OperationModel(List<JButton> possibleOperations) { this.possibleOperations = possibleOperations; } @Override public Class<?> getColumnClass(int columnIndex) { return JButton.class; } @Override public int getColumnCount() { return 1; } @Override public int getRowCount() { return possibleOperations.size(); } @Override public String getColumnName(int column) { return "Operation"; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return possibleOperations.get(rowIndex); } } //class OperationRendered im class Renderer implements TableCellRenderer{ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return (JButton)value; } } public OperationsTable( List<JButton> possibleOperations){ this.setModel(new OperationModel(possibleOperations)); this.setDefaultRenderer(JButton.class, new Renderer() ); } }
croco-bio/croco-cyto
src/main/java/de/lmu/ifi/bio/croco/cyto/ui/OperationsTable.java
Java
lgpl-3.0
1,482
package de.ovgu.variantsync; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipse.ui.texteditor.ITextEditor; import org.osgi.framework.BundleContext; import de.ovgu.variantsync.applicationlayer.ModuleFactory; import de.ovgu.variantsync.applicationlayer.Util; import de.ovgu.variantsync.applicationlayer.context.ContextProvider; import de.ovgu.variantsync.applicationlayer.context.IContextOperations; import de.ovgu.variantsync.applicationlayer.datamodel.context.Context; import de.ovgu.variantsync.applicationlayer.datamodel.context.FeatureExpressions; import de.ovgu.variantsync.applicationlayer.datamodel.monitoring.MonitorItemStorage; import de.ovgu.variantsync.applicationlayer.deltacalculation.DeltaOperationProvider; import de.ovgu.variantsync.applicationlayer.features.FeatureProvider; import de.ovgu.variantsync.applicationlayer.features.IFeatureOperations; import de.ovgu.variantsync.applicationlayer.monitoring.ChangeListener; import de.ovgu.variantsync.applicationlayer.monitoring.MonitorNotifier; import de.ovgu.variantsync.applicationlayer.synchronization.SynchronizationProvider; import de.ovgu.variantsync.persistencelayer.IPersistanceOperations; import de.ovgu.variantsync.presentationlayer.controller.ControllerHandler; import de.ovgu.variantsync.presentationlayer.controller.ControllerTypes; import de.ovgu.variantsync.presentationlayer.view.AbstractView; import de.ovgu.variantsync.presentationlayer.view.console.ChangeOutPutConsole; import de.ovgu.variantsync.presentationlayer.view.context.MarkerHandler; import de.ovgu.variantsync.presentationlayer.view.context.PartAdapter; import de.ovgu.variantsync.presentationlayer.view.eclipseadjustment.VSyncSupportProjectNature; import de.ovgu.variantsync.utilitylayer.UtilityModel; import de.ovgu.variantsync.utilitylayer.log.LogOperations; /** * Entry point to start plugin variantsync. Variantsync supports developers to * synchronize similar software projects which are developed in different * variants. This version is based on first version of variantsync which was * developed by Lei Luo in 2012. * * @author Tristan Pfofe (tristan.pfofe@st.ovgu.de) * @version 2.0 * @since 14.05.2015 */ public class VariantSyncPlugin extends AbstractUIPlugin { // shared instance private static VariantSyncPlugin plugin; private ChangeOutPutConsole console; private List<IProject> projectList = new ArrayList<IProject>(); private Map<IProject, MonitorItemStorage> synchroInfoMap = new HashMap<IProject, MonitorItemStorage>(); private ChangeListener resourceModificationListener; private IPersistanceOperations persistenceOp = ModuleFactory .getPersistanceOperations(); private IContextOperations contextOp = ModuleFactory.getContextOperations(); private IFeatureOperations featureOp = ModuleFactory.getFeatureOperations(); private ControllerHandler controller = ControllerHandler.getInstance(); @Override public void start(BundleContext context) { try { super.start(context); } catch (Exception e) { LogOperations.logError("Plugin could not be started.", e); } plugin = this; console = new ChangeOutPutConsole(); removeAllMarkers(); initMVC(); initContext(); initFeatureExpressions(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { listenForActiveClass(); } }); try { initResourceMonitoring(); } catch (CoreException e) { LogOperations.logError( "Resouce monitoring could not be initialized.", e); } } /** * Listen whether the active file in the java editor changes. */ public void listenForActiveClass() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow ww = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = ww.getActivePage(); if (page == null) return; page.addPartListener(new PartAdapter()); } @Override public void stop(BundleContext context) { persistenceOp.saveFeatureExpressions(featureOp.getFeatureExpressions()); // stop default-context or any other active context try { contextOp.stopRecording(); persistenceOp.saveContext(contextOp .getContext(VariantSyncConstants.DEFAULT_CONTEXT), Util .parseStorageLocation(contextOp .getContext(VariantSyncConstants.DEFAULT_CONTEXT))); } catch (NullPointerException e) { // recordings was already stopped and contexts were cleaned up } plugin = null; try { super.stop(context); } catch (Exception e) { LogOperations.logError("Plugin could not be started.", e); } IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.removeResourceChangeListener(resourceModificationListener); } public String getWorkspaceLocation() { return ResourcesPlugin.getWorkspace().getRoot().getLocation() .toString(); } /** * Returns list of projects which has eclipse nature support and variantsync * nature id. * * @return list of projects */ public List<IProject> getSupportProjectList() { this.projectList.clear(); for (IProject project : ResourcesPlugin.getWorkspace().getRoot() .getProjects()) { try { if (project.isOpen() && project .hasNature(VSyncSupportProjectNature.NATURE_ID)) { this.projectList.add(project); } } catch (CoreException e) { UtilityModel.getInstance().handleError(e, "nature support could not be checked"); } } return new ArrayList<IProject>(projectList); } /** * Updates synchroInfoMap. This map contains IProject-objects mapped to * SynchroInfo objects. */ public void updateSynchroInfo() { this.synchroInfoMap.clear(); List<IProject> projects = this.getSupportProjectList(); for (IProject project : projects) { IFile infoFile = project.getFolder( VariantSyncConstants.ADMIN_FOLDER).getFile( VariantSyncConstants.ADMIN_FILE); MonitorItemStorage info = new MonitorItemStorage(); if (infoFile.exists()) { try { info = persistenceOp.readSynchroXMLFile(infoFile .getContents()); } catch (CoreException e) { UtilityModel.getInstance().handleError(e, "info file could not be read"); } } this.synchroInfoMap.put(project, info); } } /** * Initializes model view controller implementation to encapsulate gui * elements from business logic. */ private void initMVC() { // register models as request handler for controller controller.addModel(new SynchronizationProvider(), ControllerTypes.SYNCHRONIZATION); controller .addModel(new DeltaOperationProvider(), ControllerTypes.DELTA); controller.addModel(new FeatureProvider(), ControllerTypes.FEATURE); controller.addModel(new ContextProvider(), ControllerTypes.CONTEXT); controller.addModel(MonitorNotifier.getInstance(), ControllerTypes.MONITOR); } /** * Loads all contexts which are saved in a XML-file. */ private void initContext() { String storageLocation = VariantSyncPlugin.getDefault() .getWorkspaceLocation() + VariantSyncConstants.CONTEXT_PATH; File folder = new File(storageLocation); if (folder.exists() && folder.isDirectory()) { File[] files = folder.listFiles(); for (File f : files) { Context c = persistenceOp.loadContext(f.getPath()); if (c != null) contextOp.addContext(c); else System.out.println(f.toString()); } } contextOp.activateContext(VariantSyncConstants.DEFAULT_CONTEXT); } /** * Loads all feature expressions which are saved in a XML-file. */ private void initFeatureExpressions() { String storageLocation = VariantSyncPlugin.getDefault() .getWorkspaceLocation() + VariantSyncConstants.FEATURE_EXPRESSION_PATH; File folder = new File(storageLocation.substring(0, storageLocation.lastIndexOf("/"))); if (folder.exists() && folder.isDirectory()) { File[] files = folder.listFiles(); for (File f : files) { FeatureExpressions featureExpressions = persistenceOp .loadFeatureExpressions(f.getPath()); Iterator<String> it = featureExpressions .getFeatureExpressions().iterator(); while (it.hasNext()) { featureOp.addFeatureExpression(it.next()); } it = featureOp.getFeatureModel().getFeatureNames().iterator(); while (it.hasNext()) { featureOp.addFeatureExpression(it.next()); } } } } /** * Prepares resource monitoring in eclipse workspace. Resource monitoring * means that projects will be watches. If a projects´s resource changes and * change was saved, monitoring will notice changed resource (POST_CHANGE). * A resource is a file or folder. * * @throws CoreException * resources could not be monitored */ private void initResourceMonitoring() throws CoreException { resourceModificationListener = new ChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener( resourceModificationListener, IResourceChangeEvent.POST_CHANGE); resourceModificationListener.registerSaveParticipant(); } /** * Returns monitored items of specific project. * * @param project * the project to get monitored items from * @return MonitorItemStorage */ public MonitorItemStorage getSynchroInfoFrom(IProject project) { if (this.synchroInfoMap.get(project) == null) { this.updateSynchroInfo(); } return this.synchroInfoMap.get(project); } /** * Registers a view. If a model fires an event, all registered views receive * this element. * * @param view * view to register */ public void registerView(AbstractView view, ControllerTypes type) { controller.addView(view, type); } /** * Removes a view from controller. If a model fires an event, this view will * no longer receive this event. * * @param view * view to remove */ public void removeView(AbstractView view, ControllerTypes type) { controller.removeView(view, type); } /** * @return the display */ public static Display getStandardDisplay() { Display display = Display.getCurrent(); if (display == null) { display = Display.getDefault(); } return display; } /** * Logs a message on eclipse console. * * @param msg * the message to log */ public void logMessage(String msg) { console.logMessage(msg); } /** * @return the console */ public ChangeOutPutConsole getConsole() { return console; } /** * @return the controller */ public ControllerHandler getController() { return controller; } /** * Returns the shared instance * * @return the shared instance */ public static VariantSyncPlugin getDefault() { return plugin; } /** * Always good to have this static method as when dealing with IResources * having a interface to get the editor is very handy * * @return */ public static ITextEditor getEditor() { return (ITextEditor) getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); } public static Shell getShell() { return getActiveWorkbenchWindow().getShell(); } public static IWorkbenchWindow getActiveWorkbenchWindow() { return getDefault().getWorkbench().getActiveWorkbenchWindow(); } private void removeAllMarkers() { List<IProject> projects = getSupportProjectList(); for (IProject p : projects) { MarkerHandler.getInstance().clearAllMarker(p); } } public ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(VariantSyncConstants.PLUGIN_ID, path); } }
1Tristan/VariantSync
src/de/ovgu/variantsync/VariantSyncPlugin.java
Java
lgpl-3.0
12,061
/* MOD_V2.0 * Copyright (c) 2012 OpenDA Association * All rights reserved. * * This file is part of OpenDA. * * OpenDA is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * OpenDA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with OpenDA. If not, see <http://www.gnu.org/licenses/>. */ package org.openda.model_hspf; import java.io.File; import java.text.ParseException; import java.util.*; import org.openda.blackbox.interfaces.IoObjectInterface; import org.openda.exchange.DoubleExchangeItem; import org.openda.exchange.timeseries.TimeUtils; import org.openda.interfaces.IExchangeItem; import org.openda.interfaces.IExchangeItem.Role; import org.openda.utils.Results; /** * IoObject for one WDM (Watershed Data Management) file. * * See http://water.usgs.gov/cgi-bin/man_wrdapp?wdm(1) : * A WDM file is a binary, direct-access file used to store * hydrologic, hydraulic, meteorologic, water-quality, and * physiographic data. The WDM file is organized into data * sets (DSN = Data Set Number). Each data set contains a specific type of data, such * as streamflow at a specific site or air temperature at a * weather station. Each data set contains attributes that * describe the data, such as station identification number, * time step of data, latitude, and longitude. A WDM file may * contain a single data set or as many as 200,000 data sets. * A data set may be described by a few attributes or by * hundreds of attributes. Data can be added, deleted, and * modified without restructuring the data in the file. Space * from deleted data sets is reused. * * To manually open and edit a wdm file use WDMUtil, which * is installed as part of the BASINS package, which is available from: * http://water.epa.gov/scitech/datait/models/basins/index.cfm * * The HSPF model can be installed as part of the BASINS package, * which is available from: * http://water.epa.gov/scitech/datait/models/basins/index.cfm * * @author Arno Kockx */ @Deprecated //use WdmTimeSeriesDataObject instead. public class WdmTimeSeriesIoObject implements IoObjectInterface { /** * The timeZone that is used by the model. * This is required to convert the times of the data values * to/from the timeZone that is used by the model. * Default is GMT. */ private TimeZone timeZone = TimeZone.getTimeZone("GMT"); /** * Absolute path name of the file containing the data for this IoObject. */ private String wdmTimeSeriesFilePath; private int wdmTimeSeriesFileNumber; /** * Absolute path name of the wdm message file. * The wdm message file is required for the fortran wdm library * methods to work properly. */ private String wdmMessageFilePath; private WdmDll wdmDll; private Role role; private IExchangeItem startTimeExchangeItem = null; private IExchangeItem endTimeExchangeItem = null; private double startTimeDouble = Double.NaN; private double endTimeDouble = Double.NaN; private List<WdmTimeSeriesExchangeItem> wdmTimeSeriesExchangeItems = new ArrayList<WdmTimeSeriesExchangeItem>(); /** * @param workingDir the working directory. * @param fileName the pathname of the file containing the data for this IoObject (relative to the working directory). * @param arguments the first argument should be the pathname of the wdm.dll file (relative to the working directory), * the second argument should be the pathname of the message file (relative to working directory), * the third argument should be the role of this IoObject. Role can be 'input' or 'output', * the fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12), * for role INPUT the fifth and sixth arguments should be the ids of the startTime and endTime exchangeItems respectively, * for role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run, * the (optional) seventh and further arguments should be the location and parameter ids of the time series for which exchange items should be made, * if no seventh and further arguments present then exchange items will be created for all time series in the file. */ public void initialize(File workingDir, String fileName, String[] arguments) { //initialize wdmTimeSeriesFilePath. File wdmTimeSeriesFile = new File(workingDir, fileName); if (!wdmTimeSeriesFile.exists()) { throw new IllegalArgumentException(getClass().getSimpleName() + ": Time series file '" + wdmTimeSeriesFile.getAbsolutePath() + "' does not exist."); } this.wdmTimeSeriesFilePath = wdmTimeSeriesFile.getAbsolutePath(); //create a unique fortran file unit number to use for the wdmTimeSeriesFile. this.wdmTimeSeriesFileNumber = WdmUtils.generateUniqueFortranFileUnitNumber(); //initialize wdmDll. if (arguments == null || arguments.length < 1) { throw new IllegalArgumentException(getClass().getSimpleName() + ": No arguments specified. The first argument should be the path of the wdm.dll file (relative to working directory)."); } this.wdmDll = WdmUtils.initializeWdmDll(workingDir, arguments[0]); //initialize wdmMessageFilePath. if (arguments.length < 2) { throw new IllegalArgumentException(getClass().getSimpleName() + ": No arguments specified. The second argument should be the path of the message file (relative to working directory)."); } this.wdmMessageFilePath = WdmUtils.initializeWdmMessageFilePath(workingDir, arguments[1]); //initialize role. if (arguments.length < 3) { throw new IllegalArgumentException(getClass().getSimpleName() + ": No role argument specified. The third argument should be the role of this IoObject. Role can be 'input' or 'output'."); } this.role = WdmUtils.initializeRole(arguments[2]); //get timeZone. if (arguments.length < 4) { throw new IllegalArgumentException("No timeZone argument specified for " + getClass().getSimpleName() + ". The fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12)."); } try { double timeZoneOffsetInHours = Double.parseDouble(arguments[3]); this.timeZone = TimeUtils.createTimeZoneFromDouble(timeZoneOffsetInHours); } catch (Exception e) { throw new IllegalArgumentException("Cannot parse fourth argument '" + arguments[3] + "' for " + getClass().getSimpleName() + ". The fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12).", e); } //this object can be used for either input or output. In both cases the run startTime and endTime //are needed. However the timeInfoExchangeItems are only set for input ioObjects (see BBModelInstance.compute) //and the aliases are only available for output ioObjects (because the aliases are set after the input ioObjects //have already been initialized). Therefore depending on the role use different arguments to get the //startTime and endTime here. //Note: the timeInfoExchangeItems are also set after the input ioObjects have already been initialized, //but the timeInfoExchangeItems need only be created during ioObject initialization and can then be //used later, after they have been set. if (this.role == Role.Input) { //create exchange items. if (arguments.length < 6) { throw new IllegalArgumentException("No start/endTime exchange item ids arguments specified for " + getClass().getSimpleName() + ". For role INPUT the fifth and sixth arguments should be the ids of the startTime and endTime exchangeItems respectively."); } //get start and end time. this.startTimeExchangeItem = new DoubleExchangeItem(arguments[4], 0); this.endTimeExchangeItem = new DoubleExchangeItem(arguments[5], 0); } else { if (arguments.length < 6) { throw new IllegalArgumentException("No start/endTime arguments specified for " + getClass().getSimpleName() + ". For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run."); } //get start time. try { this.startTimeDouble = TimeUtils.date2Mjd(arguments[4]); } catch (ParseException e) { throw new IllegalArgumentException("Invalid startTime argument specified for " + getClass().getSimpleName() + ". Cannot parse fifth argument '" + arguments[4] + "'. For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run.", e); } //get end time. try { this.endTimeDouble = TimeUtils.date2Mjd(arguments[5]); } catch (ParseException e) { throw new IllegalArgumentException("Invalid endTime argument specified for " + getClass().getSimpleName() + ". Cannot parse sixth argument '" + arguments[5] + "'. For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run.", e); } } //initialize wdmTimeSeriesExchangeItems. if (arguments.length < 7) { Results.putMessage(getClass().getSimpleName() + ": No time series ids arguments specified. Exchange items will be created for all time series in the file."); createWdmTimeSeriesExchangeItemsFromFile(); } else { //create exchange items for specified time series only. Results.putMessage(getClass().getSimpleName() + ": Time series ids arguments specified. Exchange items will be created for specified time series ids only."); String[] timeSeriesIdList = Arrays.copyOfRange(arguments, 6, arguments.length); createWdmTimeSeriesExchangeItemsFromList(timeSeriesIdList); } //read all values for all exchangeItems in one go, so that not needed to open/close same file for each read separately. readValuesAndTimesFromFile(); } private void createWdmTimeSeriesExchangeItemsFromList(String[] timeSeriesIdList) { //reset this.timeSeriesExchangeItems list. this.wdmTimeSeriesExchangeItems.clear(); //create exchange items for all time series ids in the list. WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath); this.wdmTimeSeriesExchangeItems.addAll(WdmUtils.createExchangeItemsFromList(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.role, timeSeriesIdList)); WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber); if (this.wdmTimeSeriesExchangeItems.isEmpty()) throw new IllegalStateException(this.getClass().getSimpleName() + ": this.wdmTimeSeriesExchangeItems.isEmpty()"); } private void createWdmTimeSeriesExchangeItemsFromFile() { //reset this.timeSeriesExchangeItems list. this.wdmTimeSeriesExchangeItems.clear(); //create exchange items for all time series in the file. WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath); this.wdmTimeSeriesExchangeItems.addAll(WdmUtils.createExchangeItemsFromFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.role)); WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber); if (this.wdmTimeSeriesExchangeItems.isEmpty()) throw new IllegalArgumentException(this.getClass().getSimpleName() + ": No time series found in time series file '" + this.wdmTimeSeriesFilePath + "'."); } public IExchangeItem[] getExchangeItems() { //return all available exchange items. List<IExchangeItem> exchangeItems = new ArrayList<IExchangeItem>(this.wdmTimeSeriesExchangeItems); if (this.startTimeExchangeItem != null && this.endTimeExchangeItem != null) { exchangeItems.add(this.startTimeExchangeItem); exchangeItems.add(this.endTimeExchangeItem); } return exchangeItems.toArray(new IExchangeItem[exchangeItems.size()]); } /** * If this IoObject has role Output (i.e. output from the model), then this method * reads the data from the wdm file and stores it in the wdmTimeSeriesExchangeItems * in this IoObject. * * Updates the in-memory stored values and times by reading from the wdm file. */ private void readValuesAndTimesFromFile() { if (this.role == Role.Input) { return; } if (Double.isNaN(this.startTimeDouble) || Double.isNaN(this.endTimeDouble)) { throw new IllegalStateException(getClass().getSimpleName() + " not initialized yet."); } Results.putMessage(getClass().getSimpleName() + ": reading " + this.wdmTimeSeriesExchangeItems.size() + " output time series from file " + this.wdmTimeSeriesFilePath + " with fortran unit number " + this.wdmTimeSeriesFileNumber + "."); //open wdm file. WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath); for (WdmTimeSeriesExchangeItem wdmTimeSeriesExchangeItem : this.wdmTimeSeriesExchangeItems) { //read data from file and set in wdmTimeSeriesExchangeItem. WdmUtils.readTimesAndValues(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, wdmTimeSeriesExchangeItem, this.startTimeDouble, this.endTimeDouble, this.timeZone); } //close wdm file. WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber); } /** * If this IoObject has role Input (i.e. input for the model), then this method writes the data * from all wdmTimeSeriesExchangeItems in this IoObject to the wdm file * so that it can be used as input by the model. */ public void finish() { if (this.role == Role.Output) { return; } if (this.startTimeExchangeItem == null || this.endTimeExchangeItem == null) { throw new IllegalStateException(getClass().getSimpleName() + " not initialized yet."); } Results.putMessage(getClass().getSimpleName() + ": writing " + this.wdmTimeSeriesExchangeItems.size() + " input time series to file " + this.wdmTimeSeriesFilePath + " with fortran unit number " + this.wdmTimeSeriesFileNumber + "."); //get start and end times. double startTime = (Double) this.startTimeExchangeItem.getValues(); double endTime = (Double) this.endTimeExchangeItem.getValues(); //open wdm file. WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath); for (WdmTimeSeriesExchangeItem wdmTimeSeriesExchangeItem : this.wdmTimeSeriesExchangeItems) { //write data from wdmTimeSeriesExchangeItem to file. WdmUtils.writeTimesAndValues(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, wdmTimeSeriesExchangeItem, startTime, endTime, this.timeZone); } //close wdm file. WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber); } }
OpenDA-Association/OpenDA
model_hspf/java/src/org/openda/model_hspf/WdmTimeSeriesIoObject.java
Java
lgpl-3.0
16,319
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package queueit.security.uribuilder; import java.lang.reflect.Array; import java.util.Arrays; /** * Miscellaneous object utility methods. * * <p>Mainly for internal use within the framework; consider * <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a> * for a more comprehensive suite of object utilities. * * <p>Thanks to Alex Ruiz for contributing several enhancements to this class! * * @author Juergen Hoeller * @author Keith Donald * @author Rod Johnson * @author Rob Harrop * @author Chris Beams * @since 19.03.2004 * @see org.apache.commons.lang.ObjectUtils */ public abstract class ObjectUtils { private static final int INITIAL_HASH = 7; private static final int MULTIPLIER = 31; private static final String EMPTY_STRING = ""; private static final String NULL_STRING = "null"; private static final String ARRAY_START = "{"; private static final String ARRAY_END = "}"; private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; private static final String ARRAY_ELEMENT_SEPARATOR = ", "; /** * Return whether the given throwable is a checked exception: * that is, neither a RuntimeException nor an Error. * @param ex the throwable to check * @return whether the throwable is a checked exception * @see java.lang.Exception * @see java.lang.RuntimeException * @see java.lang.Error */ public static boolean isCheckedException(Throwable ex) { return !(ex instanceof RuntimeException || ex instanceof Error); } /** * Check whether the given exception is compatible with the exceptions * declared in a throws clause. * @param ex the exception to checked * @param declaredExceptions the exceptions declared in the throws clause * @return whether the given exception is compatible */ public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) { if (!isCheckedException(ex)) { return true; } if (declaredExceptions != null) { int i = 0; while (i < declaredExceptions.length) { if (declaredExceptions[i].isAssignableFrom(ex.getClass())) { return true; } i++; } } return false; } /** * Determine whether the given object is an array: * either an Object array or a primitive array. * @param obj the object to check */ public static boolean isArray(Object obj) { return (obj != null && obj.getClass().isArray()); } /** * Determine whether the given array is empty: * i.e. {@code null} or of zero length. * @param array the array to check */ public static boolean isEmpty(Object[] array) { return (array == null || array.length == 0); } /** * Check whether the given array contains the given element. * @param array the array to check (may be {@code null}, * in which case the return value will always be {@code false}) * @param element the element to check for * @return whether the element has been found in the given array */ public static boolean containsElement(Object[] array, Object element) { if (array == null) { return false; } for (Object arrayEle : array) { if (nullSafeEquals(arrayEle, element)) { return true; } } return false; } /** * Check whether the given array of enum constants contains a constant with the given name, * ignoring case when determining a match. * @param enumValues the enum values to check, typically the product of a call to MyEnum.values() * @param constant the constant name to find (must not be null or empty string) * @return whether the constant has been found in the given array */ public static boolean containsConstant(Enum<?>[] enumValues, String constant) { return containsConstant(enumValues, constant, false); } /** * Check whether the given array of enum constants contains a constant with the given name. * @param enumValues the enum values to check, typically the product of a call to MyEnum.values() * @param constant the constant name to find (must not be null or empty string) * @param caseSensitive whether case is significant in determining a match * @return whether the constant has been found in the given array */ public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) { for (Enum<?> candidate : enumValues) { if (caseSensitive ? candidate.toString().equals(constant) : candidate.toString().equalsIgnoreCase(constant)) { return true; } } return false; } /** * Case insensitive alternative to {@link Enum#valueOf(Class, String)}. * @param <E> the concrete Enum type * @param enumValues the array of all Enum constants in question, usually per Enum.values() * @param constant the constant to get the enum value of * @throws IllegalArgumentException if the given constant is not found in the given array * of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception. */ public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) { for (E candidate : enumValues) { if(candidate.toString().equalsIgnoreCase(constant)) { return candidate; } } throw new IllegalArgumentException( String.format("constant [%s] does not exist in enum type %s", constant, enumValues.getClass().getComponentType().getName())); } /** * Append the given object to the given array, returning a new array * consisting of the input array contents plus the given object. * @param array the array to append to (can be {@code null}) * @param obj the object to append * @return the new array (of the same component type; never {@code null}) */ public static <A,O extends A> A[] addObjectToArray(A[] array, O obj) { Class<?> compType = Object.class; if (array != null) { compType = array.getClass().getComponentType(); } else if (obj != null) { compType = obj.getClass(); } int newArrLength = (array != null ? array.length + 1 : 1); @SuppressWarnings("unchecked") A[] newArr = (A[]) Array.newInstance(compType, newArrLength); if (array != null) { System.arraycopy(array, 0, newArr, 0, array.length); } newArr[newArr.length - 1] = obj; return newArr; } /** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array. * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; } //--------------------------------------------------------------------- // Convenience methods for content-based equality/hash-code handling //--------------------------------------------------------------------- /** * Determine if the given objects are equal, returning {@code true} * if both are {@code null} or {@code false} if only one is * {@code null}. * <p>Compares arrays with {@code Arrays.equals}, performing an equality * check based on the array elements rather than the array reference. * @param o1 first Object to compare * @param o2 second Object to compare * @return whether the given objects are equal * @see java.util.Arrays#equals */ public static boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.equals((Object[]) o1, (Object[]) o2); } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[]) o2); } if (o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[]) o1, (double[]) o2); } if (o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[]) o1, (float[]) o2); } if (o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[]) o1, (int[]) o2); } if (o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[]) o1, (long[]) o2); } if (o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[]) o1, (short[]) o2); } } return false; } /** * Return as hash code for the given object; typically the value of * {@code {@link Object#hashCode()}}. If the object is an array, * this method will delegate to any of the {@code nullSafeHashCode} * methods for arrays in this class. If the object is {@code null}, * this method returns 0. * @see #nullSafeHashCode(Object[]) * @see #nullSafeHashCode(boolean[]) * @see #nullSafeHashCode(byte[]) * @see #nullSafeHashCode(char[]) * @see #nullSafeHashCode(double[]) * @see #nullSafeHashCode(float[]) * @see #nullSafeHashCode(int[]) * @see #nullSafeHashCode(long[]) * @see #nullSafeHashCode(short[]) */ public static int nullSafeHashCode(Object obj) { if (obj == null) { return 0; } if (obj.getClass().isArray()) { if (obj instanceof Object[]) { return nullSafeHashCode((Object[]) obj); } if (obj instanceof boolean[]) { return nullSafeHashCode((boolean[]) obj); } if (obj instanceof byte[]) { return nullSafeHashCode((byte[]) obj); } if (obj instanceof char[]) { return nullSafeHashCode((char[]) obj); } if (obj instanceof double[]) { return nullSafeHashCode((double[]) obj); } if (obj instanceof float[]) { return nullSafeHashCode((float[]) obj); } if (obj instanceof int[]) { return nullSafeHashCode((int[]) obj); } if (obj instanceof long[]) { return nullSafeHashCode((long[]) obj); } if (obj instanceof short[]) { return nullSafeHashCode((short[]) obj); } } return obj.hashCode(); } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(Object[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + nullSafeHashCode(array[i]); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(boolean[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + hashCode(array[i]); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(byte[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + array[i]; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(char[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + array[i]; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(double[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + hashCode(array[i]); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(float[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + hashCode(array[i]); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(int[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + array[i]; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(long[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + hashCode(array[i]); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(short[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; int arraySize = array.length; for (int i = 0; i < arraySize; i++) { hash = MULTIPLIER * hash + array[i]; } return hash; } /** * Return the same value as {@link Boolean#hashCode()}}. * @see Boolean#hashCode() */ public static int hashCode(boolean bool) { return bool ? 1231 : 1237; } /** * Return the same value as {@link Double#hashCode()}}. * @see Double#hashCode() */ public static int hashCode(double dbl) { long bits = Double.doubleToLongBits(dbl); return hashCode(bits); } /** * Return the same value as {@link Float#hashCode()}}. * @see Float#hashCode() */ public static int hashCode(float flt) { return Float.floatToIntBits(flt); } /** * Return the same value as {@link Long#hashCode()}}. * @see Long#hashCode() */ public static int hashCode(long lng) { return (int) (lng ^ (lng >>> 32)); } //--------------------------------------------------------------------- // Convenience methods for toString output //--------------------------------------------------------------------- /** * Return a String representation of an object's overall identity. * @param obj the object (may be {@code null}) * @return the object's identity as String representation, * or an empty String if the object was {@code null} */ public static String identityToString(Object obj) { if (obj == null) { return EMPTY_STRING; } return obj.getClass().getName() + "@" + getIdentityHexString(obj); } /** * Return a hex String form of an object's identity hash code. * @param obj the object * @return the object's identity code in hex notation */ public static String getIdentityHexString(Object obj) { return Integer.toHexString(System.identityHashCode(obj)); } /** * Return a content-based String representation if {@code obj} is * not {@code null}; otherwise returns an empty String. * <p>Differs from {@link #nullSafeToString(Object)} in that it returns * an empty String rather than "null" for a {@code null} value. * @param obj the object to build a display String for * @return a display String representation of {@code obj} * @see #nullSafeToString(Object) */ public static String getDisplayString(Object obj) { if (obj == null) { return EMPTY_STRING; } return nullSafeToString(obj); } /** * Determine the class name for the given object. * <p>Returns {@code "null"} if {@code obj} is {@code null}. * @param obj the object to introspect (may be {@code null}) * @return the corresponding class name */ public static String nullSafeClassName(Object obj) { return (obj != null ? obj.getClass().getName() : NULL_STRING); } /** * Return a String representation of the specified Object. * <p>Builds a String representation of the contents in case of an array. * Returns {@code "null"} if {@code obj} is {@code null}. * @param obj the object to build a String representation for * @return a String representation of {@code obj} */ public static String nullSafeToString(Object obj) { if (obj == null) { return NULL_STRING; } if (obj instanceof String) { return (String) obj; } if (obj instanceof Object[]) { return nullSafeToString((Object[]) obj); } if (obj instanceof boolean[]) { return nullSafeToString((boolean[]) obj); } if (obj instanceof byte[]) { return nullSafeToString((byte[]) obj); } if (obj instanceof char[]) { return nullSafeToString((char[]) obj); } if (obj instanceof double[]) { return nullSafeToString((double[]) obj); } if (obj instanceof float[]) { return nullSafeToString((float[]) obj); } if (obj instanceof int[]) { return nullSafeToString((int[]) obj); } if (obj instanceof long[]) { return nullSafeToString((long[]) obj); } if (obj instanceof short[]) { return nullSafeToString((short[]) obj); } String str = obj.toString(); return (str != null ? str : EMPTY_STRING); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(Object[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(String.valueOf(array[i])); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(boolean[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(byte[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(char[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append("'").append(array[i]).append("'"); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(double[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(float[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(int[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(long[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). Returns * {@code "null"} if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(short[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { if (i == 0) { sb.append(ARRAY_START); } else { sb.append(ARRAY_ELEMENT_SEPARATOR); } sb.append(array[i]); } sb.append(ARRAY_END); return sb.toString(); } }
queueit/QueueIT.Security-JavaEE
QueueIT.Security/src/queueit/security/uribuilder/ObjectUtils.java
Java
lgpl-3.0
27,162
/* * Copyright (c) 2014, Fashiontec (http://fashiontec.org) * Licensed under LGPL, Version 3 */ package org.fashiontec.bodyapps.sync; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Class to handle main sync methods */ public class Sync { static final String TAG = Sync.class.getName(); protected String baseURL = "http://freelayers.org"; //base URL of the API public void setBaseURL(String baseURL) { this.baseURL = baseURL; } /** * Method which makes all the post calls * * @param url * @param json * @return */ public HttpResponse post(String url, String json, int conTimeOut, int socTimeOut) { HttpResponse response = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); StringEntity se = new StringEntity(json); httpPost.setEntity(se); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); response = httpclient.execute(httpPost); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return response; } /** * Downloads a file from given URL. * * @param url * @param file * @return */ public int download(String url, String file) { try { URL u = new URL(url); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setConnectTimeout(2000); c.setRequestProperty("Accept", "application/vnd.valentina.hdf"); c.connect(); FileOutputStream f = new FileOutputStream(new File(file)); InputStream in = c.getInputStream(); //download code byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); } catch (Exception e) { Log.e(TAG, e.getMessage()); return -1; } return 1; } /** * Manages get requests. * * @param url * @param conTimeOut * @param socTimeOut * @return */ public HttpResponse get(String url, int conTimeOut, int socTimeOut) { HttpResponse response = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(url); request.setHeader("Accept", "application/json"); response = client.execute(request); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return response; } /** * Manages put requests * * @param url * @param json * @param conTimeOut * @param socTimeOut * @return */ public HttpResponse put(String url, String json, int conTimeOut, int socTimeOut) { HttpResponse response = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut); HttpClient client = new DefaultHttpClient(httpParameters); HttpPut request = new HttpPut(url); StringEntity se = new StringEntity(json); request.setEntity(se); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); response = client.execute(request); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return response; } /** * Manages delete requests. * * @param url * @param conTimeOut * @param socTimeOut * @return */ public HttpResponse DELETE(String url, int conTimeOut, int socTimeOut) { HttpResponse response = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut); HttpClient client = new DefaultHttpClient(httpParameters); HttpDelete request = new HttpDelete(url); request.setHeader("Accept", "application/json"); response = client.execute(request); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return response; } }
fashiontec/bodyapps-android
app/src/main/java/org/fashiontec/bodyapps/sync/Sync.java
Java
lgpl-3.0
5,676
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: ....... * * File Description: * ....... * * Remark: * This code was originally generated by application DATATOOL * using the following specifications: * 'seqfeat.asn'. */ // standard includes #include <ncbi_pch.hpp> // generated includes #include <objects/seqfeat/MultiOrgName.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // destructor CMultiOrgName::~CMultiOrgName(void) { } END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE /* Original file checksum: lines: 57, chars: 1733, CRC32: 90d381d7 */
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/objects/seqfeat/MultiOrgName.cpp
C++
lgpl-3.0
1,860
package cm.gov.daf.sif.titrefoncier.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.validator.constraints.NotEmpty; import cm.gov.daf.sif.model.BaseEntity; /** * Encapsule les informations sur la parcelle * * @author Albert */ @Entity @Table(name = "parcelles") public class Parcelle extends BaseEntity { @Column(name = "num", length = 100) @NotEmpty private String num; @Column(name = "type", length = 100) @NotEmpty private String type; @Column(name = "superficie") @NotEmpty private Integer superficie; @ManyToOne @JoinColumn(name = "lot_id") private Lot lot; @ManyToOne @JoinColumn(name = "proprietaire_id") @NotEmpty private Proprietaire proprietaire; public Parcelle() { super(); // TODO Auto-generated constructor stub } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getSuperficie() { return superficie; } public void setSuperficie(Integer superficie) { this.superficie = superficie; } public Lot getLot() { return lot; } public void setLot(Lot lot) { this.lot = lot; } public Proprietaire getProprietaire() { return proprietaire; } public void setProprietaire(Proprietaire proprietaire) { this.proprietaire = proprietaire; } @Override public String toString() { return "Parcelle [num=" + num + ", superficie=" + superficie + ", id=" + id + "]"; } }
defus/daf-architcture
commons/src/main/java/cm/gov/daf/sif/titrefoncier/model/Parcelle.java
Java
lgpl-3.0
1,753
/* * Hex - a hex viewer and annotator * Copyright (C) 2009-2014,2016-2017,2021 Hakanai, Hex Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.trypticon.hex.plaf; import org.trypticon.hex.HexViewer; import javax.annotation.Nonnull; /** * Action to move the selection up one row. * * @author trejkaz */ // Swing's own guidelines say not to use serialisation. @SuppressWarnings("serial") class SelectionUpAction extends AbstractRelativeSelectionMoveAction { @Override protected int getShift(@Nonnull HexViewer viewer) { return -viewer.getBytesPerRow(); } }
trejkaz/hex-components
viewer/src/main/java/org/trypticon/hex/plaf/SelectionUpAction.java
Java
lgpl-3.0
1,229
// // Copyright 2011-2013, Xamarin Inc. // // 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. // using System; using CoreLocation; using System.Threading.Tasks; using System.Threading; using Foundation; using UIKit; using Xamarin.Forms; using WF.Player.Services.Geolocation; using Vernacular; using WF.Player.Services.Settings; [assembly: Dependency(typeof(WF.Player.iOS.Services.Geolocation.Geolocator))] namespace WF.Player.iOS.Services.Geolocation { public class Geolocator : IGeolocator { UIDeviceOrientation? _orientation; NSObject _observer; public Geolocator() { this.manager = GetManager(); this.manager.AuthorizationChanged += OnAuthorizationChanged; this.manager.Failed += OnFailed; // if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) this.manager.LocationsUpdated += OnLocationsUpdated; // else // this.manager.UpdatedLocation += OnUpdatedLocation; this.manager.UpdatedHeading += OnUpdatedHeading; } public event EventHandler<PositionErrorEventArgs> PositionError; public event EventHandler<PositionEventArgs> PositionChanged; public event EventHandler<PositionEventArgs> HeadingChanged; public double DesiredAccuracy { get; set; } public bool IsListening { get { return this.isListening; } } public bool SupportsHeading { get { return CLLocationManager.HeadingAvailable; } } public bool IsGeolocationAvailable { get { return true; } // all iOS devices support at least wifi geolocation } public bool IsGeolocationEnabled { get { return CLLocationManager.Status == CLAuthorizationStatus.Authorized; } } public Position LastKnownPosition { get { return _position; } } public Task<Position> GetPositionAsync (int timeout) { return GetPositionAsync (timeout, CancellationToken.None, false); } public Task<Position> GetPositionAsync (int timeout, bool includeHeading) { return GetPositionAsync (timeout, CancellationToken.None, includeHeading); } public Task<Position> GetPositionAsync (CancellationToken cancelToken) { return GetPositionAsync (Timeout.Infinite, cancelToken, false); } public Task<Position> GetPositionAsync (CancellationToken cancelToken, bool includeHeading) { return GetPositionAsync (Timeout.Infinite, cancelToken, includeHeading); } public Task<Position> GetPositionAsync (int timeout, CancellationToken cancelToken) { return GetPositionAsync (timeout, cancelToken, false); } public Task<Position> GetPositionAsync (int timeout, CancellationToken cancelToken, bool includeHeading) { if (timeout <= 0 && timeout != Timeout.Infinite) throw new ArgumentOutOfRangeException ("timeout", "Timeout must be positive or Timeout.Infinite"); TaskCompletionSource<Position> tcs; if (!IsListening) { var m = GetManager(); tcs = new TaskCompletionSource<Position> (m); var singleListener = new GeolocationSingleUpdateDelegate (m, DesiredAccuracy, includeHeading, timeout, cancelToken); m.Delegate = singleListener; m.StartUpdatingLocation (); if (includeHeading && SupportsHeading) m.StartUpdatingHeading (); return singleListener.Task; } else { tcs = new TaskCompletionSource<Position>(); if (this._position == null) { EventHandler<PositionErrorEventArgs> gotError = null; gotError = (s,e) => { tcs.TrySetException (new GeolocationException (e.Error)); PositionError -= gotError; }; PositionError += gotError; EventHandler<PositionEventArgs> gotPosition = null; gotPosition = (s, e) => { tcs.TrySetResult (e.Position); PositionChanged -= gotPosition; }; PositionChanged += gotPosition; } else tcs.SetResult (this._position); } return tcs.Task; } /// <summary> /// Starts the update process of the Geolocator. /// </summary> /// <param name="minTime">Minimum time in milliseconds.</param> /// <param name="minDistance">Minimum distance in meters.</param> public void StartListening (uint minTime, double minDistance) { StartListening (minTime, minDistance, false); } /// <summary> /// Starts the update process of the Geolocator. /// </summary> /// <param name="minTime">Minimum time in milliseconds.</param> /// <param name="minDistance">Minimum distance in meters.</param> /// <param name="includeHeading">Should the Geolocator update process update heading too.</param> public void StartListening (uint minTime, double minDistance, bool includeHeading) { // Get last known position from settings _position = _position ?? new Position(); _position.Latitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionLatitudeKey); _position.Longitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionLongitudeKey); _position.Altitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionAltitudeKey); if (minTime < 0) throw new ArgumentOutOfRangeException ("minTime"); if (minDistance < 0) throw new ArgumentOutOfRangeException ("minDistance"); if (this.isListening) throw new InvalidOperationException ("Already listening"); if(!CLLocationManager.LocationServicesEnabled || !(CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse)) { return; throw new NotImplementedException ("GPS not existing or not authorized"); } this.isListening = true; this.manager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation; this.manager.DistanceFilter = minDistance; this.manager.StartUpdatingLocation (); if (includeHeading && CLLocationManager.HeadingAvailable) { this.manager.HeadingFilter = 1; this.manager.StartUpdatingHeading (); } UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications(); _observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, OnDidRotate); } /// <summary> /// Stops the update process of the Geolocator. /// </summary> public void StopListening () { if (!this.isListening) return; this.isListening = false; if (CLLocationManager.HeadingAvailable) this.manager.StopUpdatingHeading (); this.manager.StopUpdatingLocation (); // Save last known position for later if (this._position != null) { Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionLatitudeKey, this._position.Latitude); Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionLongitudeKey, this._position.Longitude); Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionAltitudeKey, this._position.Altitude); } this._position = null; NSNotificationCenter.DefaultCenter.RemoveObserver (_observer); UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications(); _observer.Dispose(); } private readonly CLLocationManager manager; private bool isListening; private Position _position; private CLLocationManager GetManager() { CLLocationManager m = null; new NSObject().InvokeOnMainThread (() => m = new CLLocationManager()); if (m.RespondsToSelector (new ObjCRuntime.Selector("requestWhenInUseAuthorization"))) { m.RequestWhenInUseAuthorization (); } return m; } /// <summary> /// Raises the did rotate event. /// </summary> /// <remarks> /// Had to do this, because didn't find a property where to get the actual orientation. /// Seems to be the easies method. /// </remarks> /// <param name="notice">Notice.</param> private void OnDidRotate(NSNotification notice) { UIDevice device = (UIDevice)notice.Object; if (device.Orientation != UIDeviceOrientation.FaceUp && device.Orientation != UIDeviceOrientation.FaceDown && device.Orientation != UIDeviceOrientation.Unknown) _orientation = device.Orientation; } private void OnUpdatedHeading (object sender, CLHeadingUpdatedEventArgs e) { if (e.NewHeading.MagneticHeading == -1) return; Position p = (this._position == null) ? new Position () : new Position (this._position); // If HeadingAccuracy is below 0, than the heading is invalid if (e.NewHeading.HeadingAccuracy < 0) return; var newHeading = e.NewHeading.MagneticHeading; p.Heading = CheckDeviceOrientationForHeading(newHeading); this._position = p; OnHeadingChanged (new PositionEventArgs (p)); } private void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e) { foreach (CLLocation location in e.Locations) UpdatePosition (location); } private void OnUpdatedLocation (object sender, CLLocationUpdatedEventArgs e) { UpdatePosition (e.NewLocation); } private void UpdatePosition (CLLocation location) { Position p = (this._position == null) ? new Position () : new Position (this._position); if (location.HorizontalAccuracy > -1) { p.Accuracy = location.HorizontalAccuracy; p.Latitude = location.Coordinate.Latitude; p.Longitude = location.Coordinate.Longitude; } if (location.VerticalAccuracy > -1) { p.Altitude = location.Altitude; p.AltitudeAccuracy = location.VerticalAccuracy; } if (location.Speed > -1) p.Speed = location.Speed; p.Timestamp = new DateTimeOffset (location.Timestamp.ToDateTime()); this._position = p; OnPositionChanged (new PositionEventArgs (p)); location.Dispose(); } private void OnFailed (object sender, Foundation.NSErrorEventArgs e) { if ((CLError)(int)e.Error.Code == CLError.Network) OnPositionError (new PositionErrorEventArgs (GeolocationError.PositionUnavailable)); } private void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e) { if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted) OnPositionError (new PositionErrorEventArgs (GeolocationError.Unauthorized)); } private void OnPositionChanged (PositionEventArgs e) { var changed = PositionChanged; if (changed != null) changed (this, e); } private void OnHeadingChanged (PositionEventArgs e) { var changed = HeadingChanged; if (changed != null) changed (this, e); } private void OnPositionError (PositionErrorEventArgs e) { StopListening(); var error = PositionError; if (error != null) error (this, e); } double CheckDeviceOrientationForHeading(double heading) { double realHeading = heading; // Don't do this, because device orientation is set to portrait, // but device orientation changes when rotating device. // switch (_orientation) { // case UIDeviceOrientation.Portrait: // break; // case UIDeviceOrientation.PortraitUpsideDown: // realHeading = realHeading + 180.0f; // break; // case UIDeviceOrientation.LandscapeLeft: // realHeading = realHeading + 90.0f; // break; // case UIDeviceOrientation.LandscapeRight: // realHeading = realHeading - 90.0f; // break; // default: // break; // } while (realHeading < 0) realHeading += 360.0; realHeading = realHeading % 360; return realHeading; } } }
WFoundation/WF.Player
WF.Player.iOS/Services/Geolocation/Geolocator.cs
C#
lgpl-3.0
11,735
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.posimo; public class Mirror { private final double max; public Mirror(double max) { this.max = max; } public double getMirrored(double v) { if (v < 0 || v > max) { throw new IllegalArgumentException(); } //return v; return max - v; } }
mar9000/plantuml
src/net/sourceforge/plantuml/posimo/Mirror.java
Java
lgpl-3.0
1,402
<?php /** # Copyright Rakesh Shrestha (rakesh.shrestha@gmail.com) # 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 must retain the above copyright notice. */ final class Csv { private $enclosure; private $delimiter; private $rows; private $numfields; public function __construct() { $this->enclosure = "\""; $this->delimiter = ","; $this->rows = array(); $this->numfields = 0; } public function load($file, $headersonly = false) { $ext = mb_strtolower(mb_strrchr($file, '.')); if ($ext == '.csv' || $ext == '.txt') { $row = 1; $handle = fopen($file, 'r'); if ($ext == '.txt') $this->delimiter = "\t"; while (($data = fgetcsv($handle, 1000, $this->delimiter, $this->enclosure)) !== FALSE) { if ($row == 1) { foreach ($data as $key => $val) $headingTexts[] = mb_strtolower(mb_trim($val)); $this->numfields = count($headingTexts); } if ($this->numfields < 2) { fclose($handle); return 0; } if ($headersonly) { fclose($handle); return $headingTexts; } if ($row > 1) { foreach ($data as $key => $value) { unset($data[$key]); $data[mb_strtolower($headingTexts[$key])] = $value; } $this->rows[] = $data; } $row ++; } fclose($handle); } return $this->rows; } public function write($csv_delimiter, array $csv_headers_array, array $csv_write_res) { if (! isset($csv_delimiter)) { $csv_delimiter = $this->delimiter; } $data = ""; $data_temp = ''; foreach ($csv_headers_array as $val) { $data_temp .= $this->enclosure . mb_strtolower($val) . $this->enclosure . $csv_delimiter; } $data .= rtrim($data_temp, $csv_delimiter) . "\r\n"; echo $data; $data = ""; $data_temp = ''; foreach ($csv_write_res as $val) { $data_temp = ''; foreach ($val as $val2) { $data_temp .= $this->enclosure . $val2 . $this->enclosure . $csv_delimiter; } $data .= rtrim($data_temp, $csv_delimiter) . "\r\n"; } echo $data; } }
RakeshShrestha/Php-Web-Objects
admin/app/libraries/Csv.php
PHP
lgpl-3.0
2,754
#include "turnnotescontroller.h" #include "../models/talentdata.h" #include "../models/talentfile.h" #include "../models/turn.h" #include <QTextEdit> TurnNotesController::TurnNotesController(QObject* parent) : Controller(parent) { notes = ""; } void TurnNotesController::setWidgets(QTextEdit* turnNotes) { uiNotes = turnNotes; view.append(uiNotes); connect(uiNotes, SIGNAL(textChanged()), this, SLOT(on_viewUpdate())); } void TurnNotesController::toView() { uiNotes->setText(notes); } void TurnNotesController::toModel() { TalentData::lockTalentFile()->currentTurn()->setNotes(notes); TalentData::unlockTalentFile(); } void TurnNotesController::fromModel() { notes = TalentData::lockTalentFile()->currentTurn()->getNotes(); TalentData::unlockTalentFile(); } void TurnNotesController::fromView() { notes = uiNotes->toPlainText(); }
jaluk8/talented-gm
src/controllers/turnnotescontroller.cpp
C++
lgpl-3.0
879
/* $Id: rpsblast_local.cpp 448376 2014-10-06 09:52:42Z mcelhany $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Amelia Fong * */ /** @file rpsblast_local.cpp */ #include <ncbi_pch.hpp> #include <corelib/ncbifile.hpp> #include <corelib/ncbiapp.hpp> #include <algo/blast/api/local_blast.hpp> #include <algo/blast/api/objmgr_query_data.hpp> #include <corelib/ncbithr.hpp> #include <corelib/ncbitime.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/ncbiexpt.hpp> #include <algo/blast/api/rpsblast_local.hpp> #include <objtools/blast/seqdb_reader/seqdb.hpp> #include <algo/blast/api/blast_rps_options.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(blast) static const char delimiter[] = "#rps#"; static const size_t delimiter_len = sizeof(delimiter) - 1; // exclude \0 static void s_ConvertConcatStringToVectorOfString(const string & s, vector<string> & v) { int pos_start = 0; while(1) { size_t pos_find = s.find(delimiter, pos_start); if(pos_find == string::npos) break; TSeqPos length = pos_find - pos_start; v.push_back(s.substr(pos_start, length)); pos_start = pos_find + delimiter_len; } v.push_back(s.substr(pos_start, s.size() - pos_start )); } static void s_MergeAlignSet(CSeq_align_set & final_set, const CSeq_align_set & input_set) { CSeq_align_set::Tdata & final_list = final_set.Set(); const CSeq_align_set::Tdata & input_list = input_set.Get(); CSeq_align_set::Tdata::const_iterator input_it = input_list.begin(); CSeq_align_set::Tdata::iterator final_it = final_list.begin(); while(input_it != input_list.end()) { double final_evalue; double input_evalue; (*final_it)->GetNamedScore(CSeq_align::eScore_EValue, final_evalue); (*input_it)->GetNamedScore(CSeq_align::eScore_EValue, input_evalue); if(input_evalue == final_evalue) { //Pulling a trick here to keep the program flow simple //Replace the final evalue with input bitscore and vice versa (*final_it)->GetNamedScore(CSeq_align::eScore_BitScore, input_evalue); (*input_it)->GetNamedScore(CSeq_align::eScore_BitScore, final_evalue); } if(input_evalue < final_evalue) { CSeq_align_set::Tdata::const_iterator start_input_it = input_it; while(1) { const CSeq_id & id_prev = (*input_it)->GetSeq_id(1); input_it++; if(input_it == input_list.end()) { break; } if(! id_prev.Match((*input_it)->GetSeq_id(1))) { break; } } final_list.insert(final_it, start_input_it, input_it); } else { while(1) { const CSeq_id & id_prev = (*final_it)->GetSeq_id(1); final_it++; if(final_it == final_list.end()) { break; } if(! id_prev.Match((*final_it)->GetSeq_id(1))) { break; } } if(final_it == final_list.end()) { final_list.insert(final_it, input_it, input_list.end()); break; } } } } static CRef<CSearchResultSet> s_CombineSearchSets(vector<CRef<CSearchResultSet> > & t, unsigned int num_of_threads) { CRef<CSearchResultSet> aggregate_search_result_set (new CSearchResultSet()); aggregate_search_result_set->clear(); for(unsigned int i=0; i < t[0]->GetNumQueries(); i++) { vector< CRef<CSearchResults> > thread_results; thread_results.push_back (CRef<CSearchResults> (&((*(t[0]))[i]))); const CSeq_id & id = *(thread_results[0]->GetSeqId()); for(unsigned int d=1; d < num_of_threads; d++) { thread_results.push_back ((*(t[d]))[id]); } CRef<CSeq_align_set> align_set(new CSeq_align_set); TQueryMessages aggregate_messages; for(unsigned int d=0; d< num_of_threads; d++) { if(thread_results[d]->HasAlignments()) { CConstRef<CSeq_align_set> thread_align_set = thread_results[d]->GetSeqAlign(); if(align_set->IsEmpty()) { align_set->Set().insert(align_set->Set().begin(), thread_align_set->Get().begin(), thread_align_set->Get().end()); } else { s_MergeAlignSet(*align_set, *thread_align_set); } } aggregate_messages.Combine(thread_results[d]->GetErrors()); } TMaskedQueryRegions query_mask; thread_results[0]->GetMaskedQueryRegions(query_mask); CRef<CSearchResults> aggregate_search_results (new CSearchResults(thread_results[0]->GetSeqId(), align_set, aggregate_messages, thread_results[0]->GetAncillaryData(), &query_mask, thread_results[0]->GetRID())); aggregate_search_result_set->push_back(aggregate_search_results); } return aggregate_search_result_set; } static void s_ModifyVolumePaths(vector<string> & rps_database) { for(unsigned int i=0; i < rps_database.size(); i++) { size_t found = rps_database[i].find(".pal"); if(string::npos != found) rps_database[i]= rps_database[i].substr(0, found); } } static bool s_SortDbSize(const pair<string, Int8> & a, const pair<string, Int8> & b) { return(a.second > b.second); } static void s_MapDbToThread(vector<string> & db, unsigned int num_of_threads) { unsigned int db_size = db.size(); vector <pair <string, Int8> > p; for(unsigned int i=0; i < db_size; i++) { vector<string> path; CSeqDB::FindVolumePaths(db[i], CSeqDB::eProtein, path, NULL, true); _ASSERT(path.size() == 1); CFile f(path[0]+".loo"); Int8 length = f.GetLength(); _ASSERT(length > 0 ); //Scale down, just in case p.push_back(make_pair(db[i], length/1000)); } sort(p.begin(), p.end(),s_SortDbSize); db.resize(num_of_threads); vector<Int8> acc_size(num_of_threads, 0); for(unsigned char i=0; i < num_of_threads; i++) { db[i] = p[i].first; acc_size[i] = p[i].second; } for(unsigned int i= num_of_threads; i < db_size; i++) { unsigned int min_index = 0; for(unsigned int j=1; j<num_of_threads; j++) { if(acc_size[j] < acc_size[min_index]) min_index = j; } acc_size[min_index] += p[i].second; db[min_index] = db[min_index] + delimiter + p[i].first; } } CRef<CSearchResultSet> s_RunLocalRpsSearch(const string & db, CBlastQueryVector & query_vector, CRef<CBlastOptionsHandle> opt_handle) { CSearchDatabase search_db(db, CSearchDatabase::eBlastDbIsProtein); CRef<CLocalDbAdapter> db_adapter(new CLocalDbAdapter(search_db)); CRef<IQueryFactory> queries(new CObjMgr_QueryFactory(query_vector)); CLocalBlast lcl_blast(queries, opt_handle, db_adapter); CRef<CSearchResultSet> results = lcl_blast.Run(); return results; } class CRPSThread : public CThread { public: CRPSThread(CRef<CBlastQueryVector> query_vector, const string & db, CRef<CBlastOptions> options); void * Main(void); private: CRef<CSearchResultSet> RunTandemSearches(void); CRPSThread(const CRPSThread &); CRPSThread & operator=(const CRPSThread &); vector<string> m_db; CRef<CBlastOptionsHandle> m_opt_handle; CRef<CBlastQueryVector> m_query_vector; }; /* CRPSThread */ CRPSThread::CRPSThread(CRef<CBlastQueryVector> query_vector, const string & db, CRef<CBlastOptions> options): m_query_vector(query_vector) { m_opt_handle.Reset(new CBlastRPSOptionsHandle(options)); s_ConvertConcatStringToVectorOfString(db, m_db); } void* CRPSThread::Main(void) { CRef<CSearchResultSet> * result = new (CRef<CSearchResultSet>); if(m_db.size() == 1) { *result = s_RunLocalRpsSearch(m_db[0], *m_query_vector, m_opt_handle); } else { *result = RunTandemSearches(); } return result; } CRef<CSearchResultSet> CRPSThread::RunTandemSearches(void) { unsigned int num_of_db = m_db.size(); vector<CRef<CSearchResultSet> > results; for(unsigned int i=0; i < num_of_db; i++) { results.push_back(s_RunLocalRpsSearch(m_db[i], *m_query_vector, m_opt_handle)); } return s_CombineSearchSets(results, num_of_db); } /* CThreadedRpsBlast */ CLocalRPSBlast::CLocalRPSBlast(CRef<CBlastQueryVector> query_vector, const string & db, CRef<CBlastOptionsHandle> options, unsigned int num_of_threads): m_num_of_threads(num_of_threads), m_db_name(db), m_opt_handle(options), m_query_vector(query_vector), m_num_of_dbs(0) { CSeqDB::FindVolumePaths(db, CSeqDB::eProtein, m_rps_databases, NULL, false); m_num_of_dbs = m_rps_databases.size(); if( 1 == m_num_of_dbs) { m_num_of_threads = kDisableThreadedSearch; } } void CLocalRPSBlast::x_AdjustDbSize(void) { if(m_opt_handle->GetOptions().GetEffectiveSearchSpace()!= 0) return; if(m_opt_handle->GetOptions().GetDbLength()!= 0) return; CSeqDB db(m_db_name, CSeqDB::eProtein); Uint8 db_size = db.GetTotalLengthStats(); int num_seq = db.GetNumSeqsStats(); if(0 == db_size) db_size = db.GetTotalLength(); if(0 == num_seq) num_seq = db.GetNumSeqs(); m_opt_handle->SetOptions().SetDbLength(db_size); m_opt_handle->SetOptions().SetDbSeqNum(num_seq); return; } CRef<CSearchResultSet> CLocalRPSBlast::Run(void) { if(1 != m_num_of_dbs) { x_AdjustDbSize(); } if(kDisableThreadedSearch == m_num_of_threads) { if(1 == m_num_of_dbs) { return s_RunLocalRpsSearch(m_db_name, *m_query_vector, m_opt_handle); } else { s_ModifyVolumePaths(m_rps_databases); vector<CRef<CSearchResultSet> > results; for(unsigned int i=0; i < m_num_of_dbs; i++) { results.push_back(s_RunLocalRpsSearch(m_rps_databases[i], *m_query_vector, m_opt_handle)); } return s_CombineSearchSets(results, m_num_of_dbs); } } else { return RunThreadedSearch(); } } CRef<CSearchResultSet> CLocalRPSBlast::RunThreadedSearch(void) { s_ModifyVolumePaths(m_rps_databases); if((kAutoThreadedSearch == m_num_of_threads) || (m_num_of_threads > m_rps_databases.size())) { //Default num of thread : a thread for each db m_num_of_threads = m_rps_databases.size(); } else if(m_num_of_threads < m_rps_databases.size()) { // Combine databases, modified the size of rps_database s_MapDbToThread(m_rps_databases, m_num_of_threads); } vector<CRef<CSearchResultSet> * > thread_results(m_num_of_threads, NULL); vector <CRPSThread* > thread(m_num_of_threads, NULL); vector<CRef<CSearchResultSet> > results; for(unsigned int t=0; t < m_num_of_threads; t++) { // CThread destructor is protected, all threads destory themselves when terminated thread[t] = (new CRPSThread(m_query_vector, m_rps_databases[t], m_opt_handle->SetOptions().Clone())); thread[t]->Run(); } for(unsigned int t=0; t < m_num_of_threads; t++) { thread[t]->Join(reinterpret_cast<void**> (&thread_results[t])); } for(unsigned int t=0; t < m_num_of_threads; t++) { results.push_back(*(thread_results[t])); } CRef<CBlastRPSInfo> rpsInfo = CSetupFactory::CreateRpsStructures(m_db_name, CRef<CBlastOptions> (&(m_opt_handle->SetOptions()))); return s_CombineSearchSets(results, m_num_of_threads); } END_SCOPE(blast) END_NCBI_SCOPE
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/algo/blast/api/rpsblast_local.cpp
C++
lgpl-3.0
12,514
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.modelinglab.ocl.core.ast.types; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.modelinglab.ocl.core.ast.utils.ClassifierVisitor; import org.modelinglab.ocl.core.ast.utils.OclVisitor; /** * * @author Gonzalo Ortiz Jaureguizar (gortiz at software.imdea.org) */ public class CollectionType extends DataType { private static final long serialVersionUID = 1L; Classifier elementType; private static CollectionType genericInstance = null; public CollectionType() { } public CollectionType(Classifier elementType) { Preconditions.checkArgument(elementType != null, "Element type of collection types must be " + "different than (java) null."); this.elementType = elementType; } protected CollectionType(CollectionType other) { super(other); elementType = other.elementType.clone(); } public static CollectionType getGenericInstance() { if (genericInstance == null) { genericInstance = new CollectionType(); genericInstance.setElementType(TemplateParameterType.getGenericCollectionElement()); } return genericInstance; } public Classifier getElementType() { return elementType; } public void setElementType(Classifier elementType) { this.elementType = elementType; } public boolean isOrdered() { switch (getCollectionKind()) { case BAG: case SET: return false; case ORDERED_SET: case SEQUENCE: return true; default: throw new IllegalStateException("This function has no sense in abstract collections"); } } public boolean isUnique() { switch (getCollectionKind()) { case BAG: return false; case SEQUENCE: case ORDERED_SET: case SET: return true; default: throw new IllegalStateException("This function has no sense in abstract collections"); } } public static CollectionType newCollection(CollectionKind kind) { CollectionType result; switch (kind) { case BAG: result = new BagType(); break; case COLLECTION: result = new CollectionType(); break; case ORDERED_SET: result = new OrderedSetType(); break; case SEQUENCE: result = new SequenceType(); break; case SET: result = new SetType(); break; default: throw new AssertionError(); } return result; } @Override public void fixTemplates(TemplateRestrictions restrictions) { super.fixTemplates(restrictions); restrictions.instantiate("T", elementType, true); } @Override public List<Classifier> getSuperClassifiers() { assert getElementType() != null; List<Classifier> elementSuperClassifiers; elementSuperClassifiers = getElementType().getSuperClassifiers(); List<Classifier> result; CollectionType ct; if (getCollectionKind() != CollectionKind.COLLECTION) { /* * Result will have a collection foreach element in elementSuperClassifiers, a specific * collection type foreach element in elementSuperClassifiers, the AnyType, and a collection * and a specific collection type of elementType */ result = new ArrayList<Classifier>(elementSuperClassifiers.size() * 2 + 1 + 2); CollectionKind collectionKind = getCollectionKind(); ct = CollectionType.newCollection(collectionKind); ct.setElementType(getElementType()); result.add(ct); for (Classifier superElement : elementSuperClassifiers) { ct = CollectionType.newCollection(collectionKind); ct.setElementType(superElement); result.add(ct); } ct = new CollectionType(); ct.setElementType(getElementType()); result.add(ct); } else { result = new ArrayList<Classifier>(elementSuperClassifiers.size() + 1); } for (Classifier superElement : elementSuperClassifiers) { ct = new CollectionType(); ct.setElementType(superElement); result.add(ct); } result.add(AnyType.getInstance()); return result; } @Override public CollectionType getRestrictedType(TemplateRestrictions restrictions) { if (getElementType() instanceof TemplateParameterType) { TemplateParameterType template = (TemplateParameterType) getElementType(); Classifier newElement = restrictions.getInstance(template.getSpecification()); if (newElement != null) { CollectionType result = CollectionType.newCollection(getCollectionKind()); result.setElementType(newElement); return result; } else { //restrictions does not contains elementType return this; } } else { //elementType is not a tempate return this; } } @Override protected void conformsPreconditions(Classifier otherClassifier) { super.conformsPreconditions(otherClassifier); Preconditions.checkState(elementType != null, "To evaluate conforms with CollectionType#getElementType() must not be null"); } @Override protected boolean conformsToProtected(Classifier conformsTarget, TemplateRestrictions instanciatedTemplates) { if (!(conformsTarget instanceof CollectionType)) { return false; } final CollectionType otherCollection = (CollectionType) conformsTarget; if (!elementType.conformsTo(otherCollection.getElementType(), instanciatedTemplates)) { return false; } return otherCollection.getCollectionKind() == this.getCollectionKind() || otherCollection.getCollectionKind() == CollectionKind.COLLECTION; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CollectionType other = (CollectionType) obj; if (this.elementType != other.elementType && (this.elementType == null || !this.elementType.equals(other.elementType))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.elementType != null ? this.elementType.hashCode() : 0); return hash; } @Override public CollectionType clone() { return new CollectionType(this); } @Override public String getName() { return getCollectionKind().toString() + "(" + elementType + ')'; } @Override public ClassifierType getClassifierType() { return new ClassifierType(this); } public CollectionKind getCollectionKind() { return CollectionKind.COLLECTION; } @Override public <Result, Arg> Result accept(ClassifierVisitor<Result, Arg> visitor, Arg arguments) { return visitor.visit(this, arguments); } public <Result, Arg> Result accept(OclVisitor<Result, Arg> visitor, Arg arguments) { return visitor.visit(this, arguments); } public static enum CollectionKind { COLLECTION, BAG, SET, ORDERED_SET, SEQUENCE; @Override public String toString() { switch (this) { case COLLECTION: return "Collection"; case BAG: return "Bag"; case SET: return "Set"; case ORDERED_SET: return "OrderedSet"; case SEQUENCE: return "Sequence"; default: throw new AssertionError(); } } } }
modelinglab/ocl
core/src/main/java/org/modelinglab/ocl/core/ast/types/CollectionType.java
Java
lgpl-3.0
8,485
#ifndef BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED #define BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/boost/mpl/iterator_tags.hpp,v $ // $Date: 2004/12/01 02:44:52 $ // $Revision: 1.3.2.1 $ #include <boost/mpl/int.hpp> namespace boost { namespace mpl { struct forward_iterator_tag : int_<0> { typedef forward_iterator_tag type; }; struct bidirectional_iterator_tag : int_<1> { typedef bidirectional_iterator_tag type; }; struct random_access_iterator_tag : int_<2> { typedef random_access_iterator_tag type; }; }} #endif // BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED
pixelspark/corespark
Libraries/Spirit/boost/miniboost/boost/mpl/iterator_tags.hpp
C++
lgpl-3.0
880
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.es.request; import javax.annotation.ParametersAreNonnullByDefault;
lbndev/sonarqube
server/sonar-server/src/main/java/org/sonar/server/es/request/package-info.java
Java
lgpl-3.0
967
/* * jndn-management * Copyright (c) 2016, Regents of the University of California. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 3, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. */ package com.intel.jndn.management.types; import com.intel.jndn.management.enums.NfdTlv; import com.intel.jndn.management.helpers.EncodingHelper; import net.named_data.jndn.encoding.EncodingException; import net.named_data.jndn.encoding.tlv.TlvDecoder; import net.named_data.jndn.encoding.tlv.TlvEncoder; import net.named_data.jndn.util.Blob; import java.nio.ByteBuffer; /** * Represent a ChannelStatus object. * * @see <a href="http://redmine.named-data.net/projects/nfd/wiki/FaceMgmt#Channel-Dataset">Face Management</a> */ public class ChannelStatus implements Decodable { private String localUri = ""; ///////////////////////////////////////////////////////////////////////////// /** * Default constructor. */ public ChannelStatus() { // nothing to do } /** * Constructor from wire format. * * @param input wire format * @throws EncodingException when decoding fails */ public ChannelStatus(final ByteBuffer input) throws EncodingException { wireDecode(input); } /** * Encode using a new TLV encoder. * * @return The encoded buffer */ public final Blob wireEncode() { TlvEncoder encoder = new TlvEncoder(); wireEncode(encoder); return new Blob(encoder.getOutput(), false); } /** * Encode as part of an existing encode context. * * @param encoder TlvEncoder instance */ public final void wireEncode(final TlvEncoder encoder) { int saveLength = encoder.getLength(); encoder.writeBlobTlv(NfdTlv.LocalUri, new Blob(localUri).buf()); encoder.writeTypeAndLength(NfdTlv.ChannelStatus, encoder.getLength() - saveLength); } /** * Decode the input from its TLV format. * * @param input The input buffer to decode. This reads from position() to * limit(), but does not change the position. * @throws EncodingException when decoding fails */ public final void wireDecode(final ByteBuffer input) throws EncodingException { TlvDecoder decoder = new TlvDecoder(input); wireDecode(decoder); } /** * {@inheritDoc} */ @Override public void wireDecode(final TlvDecoder decoder) throws EncodingException { int endOffset = decoder.readNestedTlvsStart(NfdTlv.ChannelStatus); this.localUri = EncodingHelper.toString(decoder.readBlobTlv(NfdTlv.LocalUri)); decoder.finishNestedTlvs(endOffset); } /** * @return channel URI */ public String getLocalUri() { return localUri; } /** * Set channel URI. * * @param localUri channel URI * @return this */ public ChannelStatus setLocalUri(final String localUri) { this.localUri = localUri; return this; } @Override public String toString() { return "ChannelStatus(" + getLocalUri() + ")"; } }
01org/jndn-management
src/main/java/com/intel/jndn/management/types/ChannelStatus.java
Java
lgpl-3.0
3,314
/* * (C) Copyright Boris Litvin 2014, 2015 * This file is part of FSM4Java library. * * FSM4Java is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FSM4Java is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FSM4Java If not, see <http://www.gnu.org/licenses/>. */ package org.blitvin.statemachine; public class InvalidFactoryImplementation extends Exception { private static final long serialVersionUID = -5234585034138276392L; public InvalidFactoryImplementation(String message , Throwable cause) { super(message, cause); } public InvalidFactoryImplementation(String message){ super(message); } }
blitvin/fsm4java
src/main/java/org/blitvin/statemachine/InvalidFactoryImplementation.java
Java
lgpl-3.0
1,094
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jams.server.client.sync; import jams.JAMS; import jams.server.client.Controller; import jams.server.entities.Workspace; import jams.tools.StringTools; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractCellEditor; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * * @author christian */ public class SyncTable extends JTable { Component tableSyncModeCells[]; Font defaultFont = new Font("Times New Roman", Font.PLAIN, 10); File localWorkspace = null; Workspace serverWorkspace = null; Controller ctrl = null; final int COLUMN_COUNT = 5; final int COLUMN_SIZE[] = {25, 365, 75, 90, 50}; final String COLUMN_NAMES[] = {"", JAMS.i18n("Path"), JAMS.i18n("Extension"), JAMS.i18n("Operation"), JAMS.i18n("SIZE")}; final Class COLUMN_CLASSES[] = {Boolean.class, String.class, String.class, FileSync.SyncMode.class, Long.class}; final int SYNCMODE_COLUMN = 3; /** * * @param ctrl * @param defaultFont */ public SyncTable(Controller ctrl, Font defaultFont) { super(10, 5); this.ctrl = ctrl; if (defaultFont != null) { this.defaultFont = defaultFont; } } /** * * @param localWorkspace */ public void setLocalWorkspace(File localWorkspace) { this.localWorkspace = localWorkspace; initModel(); } /** * * @return */ public File getLocalWorkspace() { return this.localWorkspace; } /** * * @param serverWorkspace */ public void setServerWorkspace(Workspace serverWorkspace) { this.serverWorkspace = serverWorkspace; initModel(); } /** * * @return */ public Workspace getServerWorkspace() { return this.serverWorkspace; } private void initModel() { SyncTableModel syncTableModel = new SyncTableModel(ctrl, localWorkspace, serverWorkspace); setModel(syncTableModel); SyncWorkspaceTableRenderer renderer = new SyncWorkspaceTableRenderer(syncTableModel.getSyncList()); setDefaultRenderer(String.class, renderer); setDefaultRenderer(Long.class, renderer); getColumnModel().getColumn(SYNCMODE_COLUMN).setCellRenderer(renderer); getColumnModel().getColumn(SYNCMODE_COLUMN).setCellEditor(new SyncModeEditor()); setShowHorizontalLines(false); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int i = 0; i < COLUMN_COUNT; i++) { getColumnModel().getColumn(i).setPreferredWidth(COLUMN_SIZE[i]); } } @Override public SyncTableModel getModel() { if (super.getModel() instanceof SyncTableModel) { return (SyncTableModel) super.getModel(); } else { return null; } } /** * */ public class SyncTableModel extends AbstractTableModel { ArrayList<FileSync> syncList = null; /** * * @param ctrl * @param localWsDirectory * @param remoteWs */ public SyncTableModel(Controller ctrl, File localWsDirectory, Workspace remoteWs) { if (ctrl == null || localWsDirectory == null || remoteWs == null) { syncList = new ArrayList<>(); } else { syncList = ctrl.workspaces() .getSynchronizationList(localWsDirectory, remoteWs) .getList(null); } } /** * * @return */ public List<FileSync> getSyncList() { return syncList; } /** * * @return */ public FileSync getRoot() { if (syncList == null || syncList.isEmpty()) { return null; } return syncList.get(0).getRoot(); } @Override public int getRowCount() { return syncList.size(); } @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public String getColumnName(int columnIndex) { return COLUMN_NAMES[columnIndex]; } @Override public Class<?> getColumnClass(int columnIndex) { return COLUMN_CLASSES[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0 || (columnIndex == SYNCMODE_COLUMN && tableSyncModeCells[rowIndex] instanceof JComboBox); } @Override public Object getValueAt(int rowIndex, int columnIndex) { FileSync fs = syncList.get(rowIndex); switch (columnIndex) { case 0: return fs.isDoSync(); case 1: if (fs.getLocalFile() != null) { return fs.getLocalFile().getPath(); } return null; case 2: { String name = syncList.get(rowIndex).getLocalFile().getName(); int lastIndex = name.lastIndexOf("."); if (lastIndex == -1) { return ""; } else { return name.substring(lastIndex, name.length()); } } case 3: return syncList.get(rowIndex).getSyncMode(); case 4: if (fs.getServerFile() != null) { return fs.getServerFile().getFile().getFileSize(); } else { return 0; } } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { syncList.get(rowIndex).setDoSync((Boolean) aValue, true); //generateTableCells(); fireTableDataChanged(); } if (columnIndex == 3) { syncList.get(rowIndex).setSyncMode((FileSync.SyncMode) aValue); generateTableCells(syncList); fireTableDataChanged(); } } } private class SyncModeEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { JComboBox currentBox = null; public SyncModeEditor() { } @Override public void actionPerformed(ActionEvent e) { } //Implement the one CellEditor method that AbstractCellEditor doesn't. @Override public Object getCellEditorValue() { if (currentBox != null) { return currentBox.getSelectedItem(); } return null; } //Implement the one method defined by TableCellEditor. @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (tableSyncModeCells[row] instanceof JComboBox) { return currentBox = (JComboBox) tableSyncModeCells[row]; } else { return currentBox = null; } } } private class SyncWorkspaceTableRenderer extends JLabel implements TableCellRenderer { List<FileSync> syncList = null; public SyncWorkspaceTableRenderer(List<FileSync> syncList) { this.syncList = syncList; generateTableCells(syncList); setOpaque(true); //MUST do this for background to show up. } @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { //special handling of column 3 if (column == SYNCMODE_COLUMN) { return tableSyncModeCells[row]; } setBackground(Color.WHITE); setForeground(Color.BLACK); if (value instanceof Long) { setText(StringTools.humanReadableByteCount((Long) value, false)); setHorizontalAlignment(JLabel.RIGHT); } else if (value instanceof Integer) { setText(StringTools.humanReadableByteCount((Integer) value, false)); setHorizontalAlignment(JLabel.RIGHT); } else { setText(value.toString()); setHorizontalAlignment(JLabel.LEFT); } FileSync fs = syncList.get(row); if (!fs.isExisting()) { setBackground(Color.green); } else if (fs.isModified()) { setBackground(Color.red); } if (fs instanceof DirectorySync) { setBackground(Color.darkGray); setForeground(Color.white); } setFont(defaultFont); return this; } } private void generateTableCells(List<FileSync> syncList) { tableSyncModeCells = new Component[syncList.size()]; for (int i = 0; i < syncList.size(); i++) { FileSync fs = syncList.get(i); if (fs.getSyncOptions().length == 1) { tableSyncModeCells[i] = new JLabel( fs.getSyncOptions()[0].toString(), JLabel.CENTER); tableSyncModeCells[i].setBackground(Color.WHITE); tableSyncModeCells[i].setForeground(Color.BLACK); if (!syncList.get(i).isExisting()) { tableSyncModeCells[i].setBackground(Color.green); } else if (syncList.get(i).isModified()) { tableSyncModeCells[i].setBackground(Color.red); } if (syncList.get(i) instanceof DirectorySync) { tableSyncModeCells[i].setBackground(Color.darkGray); tableSyncModeCells[i].setForeground(Color.white); } ((JLabel) tableSyncModeCells[i]).setOpaque(true); } else { JComboBox box = new JComboBox(fs.getSyncOptions()); box.putClientProperty("row", new Integer(i)); box.setSelectedItem(fs.getSyncMode()); box.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JComboBox src = (JComboBox) e.getSource(); int row = (Integer) src.getClientProperty("row"); ((SyncTableModel) getModel()).setValueAt(src.getSelectedItem(), row, 3); } }); tableSyncModeCells[i] = box; tableSyncModeCells[i].setBackground(Color.WHITE); tableSyncModeCells[i].setForeground(Color.BLACK); } tableSyncModeCells[i].setFont(defaultFont); } } }
kralisch/jams
JAMSCloudClient/src/jams/server/client/sync/SyncTable.java
Java
lgpl-3.0
12,177
<?php namespace Google\AdsApi\Dfp\v201708; /** * This file was generated from WSDL. DO NOT EDIT. */ class ActivityError extends \Google\AdsApi\Dfp\v201708\ApiError { /** * @var string $reason */ protected $reason = null; /** * @param string $fieldPath * @param \Google\AdsApi\Dfp\v201708\FieldPathElement[] $fieldPathElements * @param string $trigger * @param string $errorString * @param string $reason */ public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null) { parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString); $this->reason = $reason; } /** * @return string */ public function getReason() { return $this->reason; } /** * @param string $reason * @return \Google\AdsApi\Dfp\v201708\ActivityError */ public function setReason($reason) { $this->reason = $reason; return $this; } }
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/ActivityError.php
PHP
lgpl-3.0
1,048
/* * Copyright (C) 2017 Premium Minds. * * This file is part of billy GIN. * * billy GIN is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * billy GIN is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with billy GIN. If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.billy.gin.services.export; import java.io.InputStream; public interface BillyTemplateBundle { /** * returns the path to the image file to be used as a logo * * @return The path of the logo image file */ public String getLogoImagePath(); /** * returns the path to the xslt file to be used as the pdf template * generator * * @return The path of the xslt template file. */ public InputStream getXSLTFileStream(); public String getPaymentMechanismTranslation(Enum<?> pmc); }
premium-minds/billy
billy-gin/src/main/java/com/premiumminds/billy/gin/services/export/BillyTemplateBundle.java
Java
lgpl-3.0
1,309
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\network\mcpe\protocol; use pocketmine\utils\Binary; use pocketmine\network\mcpe\NetworkSession; class CommandBlockUpdatePacket extends DataPacket{ const NETWORK_ID = ProtocolInfo::COMMAND_BLOCK_UPDATE_PACKET; /** @var bool */ public $isBlock; /** @var int */ public $x; /** @var int */ public $y; /** @var int */ public $z; /** @var int */ public $commandBlockMode; /** @var bool */ public $isRedstoneMode; /** @var bool */ public $isConditional; /** @var int */ public $minecartEid; /** @var string */ public $command; /** @var string */ public $lastOutput; /** @var string */ public $name; /** @var bool */ public $shouldTrackOutput; protected function decodePayload(){ $this->isBlock = (($this->get(1) !== "\x00")); if($this->isBlock){ $this->getBlockPosition($this->x, $this->y, $this->z); $this->commandBlockMode = $this->getUnsignedVarInt(); $this->isRedstoneMode = (($this->get(1) !== "\x00")); $this->isConditional = (($this->get(1) !== "\x00")); }else{ //Minecart with command block $this->minecartEid = $this->getEntityRuntimeId(); } $this->command = $this->getString(); $this->lastOutput = $this->getString(); $this->name = $this->getString(); $this->shouldTrackOutput = (($this->get(1) !== "\x00")); } protected function encodePayload(){ ($this->buffer .= ($this->isBlock ? "\x01" : "\x00")); if($this->isBlock){ $this->putBlockPosition($this->x, $this->y, $this->z); $this->putUnsignedVarInt($this->commandBlockMode); ($this->buffer .= ($this->isRedstoneMode ? "\x01" : "\x00")); ($this->buffer .= ($this->isConditional ? "\x01" : "\x00")); }else{ $this->putEntityRuntimeId($this->minecartEid); } $this->putString($this->command); $this->putString($this->lastOutput); $this->putString($this->name); ($this->buffer .= ($this->shouldTrackOutput ? "\x01" : "\x00")); } public function handle(NetworkSession $session) : bool{ return $session->handleCommandBlockUpdate($this); } }
DualNova-Team/DualNova
src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php
PHP
lgpl-3.0
2,760
<?php /* * This file is part of the Virtual-Identity Youtube package. * * (c) Virtual-Identity <dev.saga@virtual-identity.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace VirtualIdentity\YoutubeBundle\EventDispatcher; use Symfony\Component\EventDispatcher\Event; use VirtualIdentity\YoutubeBundle\Interfaces\YoutubeEntityInterface; class YoutubeChangedEvent extends Event { /** * The youtube that changed * * @var YoutubeEntityInterface */ protected $youtube; public function __construct(YoutubeEntityInterface $youtube) { $this->youtube = $youtube; } /** * Returns the changed youtube * * @return YoutubeEntityInterface */ public function getYoutube() { return $this->youtube; } }
virtualidentityag/hydra-youtube
src/VirtualIdentity/YoutubeBundle/EventDispatcher/YoutubeChangedEvent.php
PHP
lgpl-3.0
882
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the N2N FRAMEWORK. * * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation, either * version 2.1 of the License, or (at your option) any later version. * * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg.....: Architect, Lead Developer * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing * Thomas Günther.......: Developer, Hangar */ namespace n2n\web\dispatch\map\val; use n2n\web\dispatch\map\PropertyPathPart; use n2n\util\type\ArgUtils; abstract class SimplePropertyValidator extends SinglePropertyValidator { private $pathPart; protected function validateProperty($mapValue) { $managedProperty = $this->getManagedProperty(); if (!$managedProperty->isArray()) { $this->pathPart = new PropertyPathPart($managedProperty->getName()); $this->validateValue($mapValue); $this->pathPart = null; return; } ArgUtils::valArrayLike($mapValue); foreach ($mapValue as $aKey => $aValue) { $this->pathPart = new PropertyPathPart($managedProperty->getName(), true, $aKey); if ($this->getBindingErrors()->hasErrors($this->pathPart)) { continue; } $this->validateValue($aValue, $this->pathPart, $this->getBindingErrors()); $this->pathPart = null; } } protected function getPathPart() { return $this->pathPart; } protected abstract function validateValue($mapValue); }
n2n/n2n-web
src/app/n2n/web/dispatch/map/val/SimplePropertyValidator.php
PHP
lgpl-3.0
1,990
/* * AUTHOR : Emmanuel Pietriga (emmanuel.pietriga@inria.fr) * Copyright (c) INRIA, 2008-2010. All Rights Reserved * Licensed under the GNU LGPL. For full terms see the file COPYING. * * $Id: PieMenuR.java 4280 2011-02-28 15:36:54Z rprimet $ */ package fr.inria.zvtm.widgets; import fr.inria.zvtm.animation.Animation; import fr.inria.zvtm.animation.interpolation.IdentityInterpolator; import fr.inria.zvtm.engine.Utils; import fr.inria.zvtm.engine.VirtualSpaceManager; import fr.inria.zvtm.glyphs.VCircle; import fr.inria.zvtm.glyphs.VRing; import fr.inria.zvtm.glyphs.VText; import fr.inria.zvtm.glyphs.VTextOr; import java.awt.Color; import java.awt.Font; import java.awt.geom.Point2D; /** * Circular pie menu with dead zone at its center. */ public class PieMenuR extends PieMenu { public static final int animStartSize = 5; /** * Pie Menu constructor - should not be used directly * * @param stringLabels text label of each menu item * @param menuCenterCoordinates (mouse cursor's coordinates in virtual space as a Point2D.Double) * @param vsName name of the virtual space in which to create the pie menu * @param vsm instance of VirtualSpaceManager * @param radius radius of pie menu * @param irr Inner ring boundary radius as a percentage of outer ring boundary radius * @param startAngle first menu item will have an offset of startAngle interpreted relative to the X horizontal axis (counter clockwise) * @param fillColors menu items' fill colors (this array should have the same length as the stringLabels array) * @param borderColors menu items' border colors (this array should have the same length as the stringLabels array) * @param fillSColors menu items' fill colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change * @param borderSColors menu items' border colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change * @param alphaT menu items' translucency value: between 0 (transparent) and 1.0 (opaque) * @param animDuration duration in ms of animation creating the menu (expansion) - 0 for instantaneous display * @param sensitRadius sensitivity radius (as a percentage of the menu's actual radius) * @param font font used for menu labels * @param labelOffsets x,y offset of each menu label w.r.t their default posisition, in virtual space units<br>(this array should have the same length as the labels array) */ public PieMenuR(String[] stringLabels, Point2D.Double menuCenterCoordinates, String vsName, VirtualSpaceManager vsm, double radius, float irr, double startAngle, double angleWidth, Color[] fillColors, Color[] borderColors, Color[] fillSColors, Color[] borderSColors, Color[] labelColors, float alphaT, int animDuration, double sensitRadius, Font font, Point2D.Double[] labelOffsets) { this.vs = vsm.getVirtualSpace(vsName); double vx = menuCenterCoordinates.x; double vy = menuCenterCoordinates.y; items = new VRing[stringLabels.length]; labels = new VTextOr[stringLabels.length]; double angle = startAngle; double angleDelta = angleWidth / ((double)stringLabels.length); double pieMenuRadius = radius; double textAngle; for (int i = 0; i < labels.length; i++) { angle += angleDelta; items[i] = new VRing(vx, vy, 0, (animDuration > 0) ? animStartSize : pieMenuRadius, angleDelta, irr, angle, fillColors[i], borderColors[i], alphaT); items[i].setCursorInsideFillColor(fillSColors[i]); items[i].setCursorInsideHighlightColor(borderSColors[i]); vs.addGlyph(items[i], false, false); if (stringLabels[i] != null && stringLabels[i].length() > 0) { if (orientText) { textAngle = angle; if (angle > Utils.HALF_PI) { if (angle > Math.PI) { if (angle < Utils.THREE_HALF_PI) { textAngle -= Math.PI; } } else { textAngle += Math.PI; } } labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x, vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y, 0, labelColors[i], stringLabels[i], textAngle, VText.TEXT_ANCHOR_MIDDLE); } else { labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x, vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y, 0, labelColors[i], stringLabels[i], 0, VText.TEXT_ANCHOR_MIDDLE); } labels[i].setBorderColor(borderColors[i]); labels[i].setFont(font); labels[i].setSensitivity(false); vs.addGlyph(labels[i]); } } if (animDuration > 0) { for (int i = 0; i < items.length; i++) { Animation sizeAnim = vsm.getAnimationManager().getAnimationFactory().createGlyphSizeAnim(animDuration, items[i], (float)pieMenuRadius, false, IdentityInterpolator.getInstance(), null); vsm.getAnimationManager().startAnimation(sizeAnim, false); } } boundary = new VCircle(vx, vy, 0, pieMenuRadius * sensitRadius * 2, Color.white); boundary.setVisible(false); vs.addGlyph(boundary); vs.atBottom(boundary); } }
sharwell/zgrnbviewer
org-tvl-netbeans-zgrviewer/src/fr/inria/zvtm/widgets/PieMenuR.java
Java
lgpl-3.0
6,530
package de.synesthesy.music.key.nn; import org.encog.neural.networks.BasicNetwork; import de.synesthesy.csv.CSVTestSetInOutput; public interface IMusicKeyNN { public BasicNetwork getNetwork(); public int getIns(); public int getOuts(); public int[] getHiddenNeurons(); public double[] compute(double[] input); public void train(CSVTestSetInOutput testSet); }
synesthesy/synesthesy-core
src/main/java/de/synesthesy/music/key/nn/IMusicKeyNN.java
Java
lgpl-3.0
369
(function (window, $, undefined) { $.infinitescroll = function infscr(options, callback, element) { this.element = $(element); this._create(options, callback); }; $.infinitescroll.defaults = { loading: { finished: undefined, finishedMsg: "", img: "http://www.infinite-scroll.com/loading.gif", msg: null, msgText: "<em>Loading the next set of posts...</em>", selector: null, speed: 'fast', start: undefined }, state: { isDuringAjax: false, isInvalidPage: false, isDestroyed: false, isDone: false, isPaused: false, currPage: 1 }, callback: undefined, debug: false, behavior: undefined, binder: $(window), nextSelector: "div.navigation a:first", navSelector: "div.navigation", contentSelector: null, extraScrollPx: 150, itemSelector: "div.post", animate: false, pathParse: undefined, dataType: 'html', appendCallback: true, bufferPx: 40, errorCallback: function () { }, infid: 0, pixelsFromNavToBottom: undefined, path: undefined }; $.infinitescroll.prototype = { _binding: function infscr_binding(binding) { var instance = this, opts = instance.options; if (!!opts.behavior && this['_binding_' + opts.behavior] !== undefined) { this['_binding_' + opts.behavior].call(this); return; } if (binding !== 'bind' && binding !== 'unbind') { this._debug('Binding value ' + binding + ' not valid') return false; } if (binding == 'unbind') { (this.options.binder).unbind('smartscroll.infscr.' + instance.options.infid); } else { (this.options.binder)[binding]('smartscroll.infscr.' + instance.options.infid, function () { instance.scroll(); }); }; this._debug('Binding', binding); }, //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö loadDataOnCreat: function () { var _this = this; setTimeout(function () { if ($(document).height() - $(window).height() < 20) { _this.scroll(); _this.loadDataOnCreat(); } }, 3000); }, _create: function infscr_create(options, callback) { if (!this._validate(options)) { return false; } var opts = this.options = $.extend(true, {}, $.infinitescroll.defaults, options), relurl = /(.*?\/\/).*?(\/.*)/, path = $(opts.nextSelector).attr('href'); opts.contentSelector = opts.contentSelector || this.element; opts.loading.selector = opts.loading.selector || opts.contentSelector; if (!path) { this._debug('Navigation selector not found'); return; } opts.path = this._determinepath(path); opts.loading.msg = $('<div id="infscr-loading" class="tn-loading"></div>'); (new Image()).src = opts.loading.img; opts.pixelsFromNavToBottom = $(document).height() - $(opts.navSelector).offset().top; opts.loading.start = opts.loading.start || function () { $(opts.navSelector).hide(); opts.loading.msg.appendTo(opts.loading.selector).show(opts.loading.speed, function () { beginAjax(opts); }); }; opts.loading.finished = opts.loading.finished || function () { opts.loading.msg.fadeOut('normal'); }; opts.callback = function (instance, data) { if (!!opts.behavior && instance['_callback_' + opts.behavior] !== undefined) { instance['_callback_' + opts.behavior].call($(opts.contentSelector)[0], data); } if (callback) { callback.call($(opts.contentSelector)[0], data); } }; this._setup(); //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö this.loadDataOnCreat(); }, _debug: function infscr_debug() { if (this.options.debug) { return window.console && console.log.call(console, arguments); } }, _determinepath: function infscr_determinepath(path) { var opts = this.options; if (!!opts.behavior && this['_determinepath_' + opts.behavior] !== undefined) { this['_determinepath_' + opts.behavior].call(this, path); return; } if (!!opts.pathParse) { this._debug('pathParse manual'); return opts.pathParse; } else if (path.match(/^(.*?)\b2\b(.*?$)/)) { path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1); } else if (path.match(/^(.*?)2(.*?$)/)) { if (path.match(/^(.*?page=)2(\/.*|$)/)) { path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1); return path; } path = path.match(/^(.*?)2(.*?$)/).slice(1); } else { if (path.match(/^(.*?page=)1(\/.*|$)/)) { path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1); return path; } else { this._debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.'); opts.state.isInvalidPage = true; } } this._debug('determinePath', path); return path; }, _error: function infscr_error(xhr) { var opts = this.options; if (!!opts.behavior && this['_error_' + opts.behavior] !== undefined) { this['_error_' + opts.behavior].call(this, xhr); return; } if (xhr !== 'destroy' && xhr !== 'end') { xhr = 'unknown'; } this._debug('Error', xhr); if (xhr == 'end') { this._showdonemsg(); } opts.state.isDone = true; opts.state.currPage = 1; opts.state.isPaused = false; this._binding('unbind'); }, _loadcallback: function infscr_loadcallback(box, data) { var opts = this.options, callback = this.options.callback, result = (opts.state.isDone) ? 'done' : (!opts.appendCallback) ? 'no-append' : 'append', frag; if (!!opts.behavior && this['_loadcallback_' + opts.behavior] !== undefined) { this['_loadcallback_' + opts.behavior].call(this, box, data); return; } switch (result) { case 'done': this._showdonemsg(); return false; break; case 'no-append': if (opts.dataType == 'html') { data = '<div>' + data + '</div>'; data = $(data).find(opts.itemSelector); }; break; case 'append': var children = box.children(); if (children.length == 0) { return this._error('end'); } frag = document.createDocumentFragment(); while (box[0].firstChild) { frag.appendChild(box[0].firstChild); } this._debug('contentSelector', $(opts.contentSelector)[0]) $(opts.contentSelector)[0].appendChild(frag); data = children.get(); break; } opts.loading.finished.call($(opts.contentSelector)[0], opts) if (opts.animate) { var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px'; $('html,body').animate({ scrollTop: scrollTo }, 800, function () { opts.state.isDuringAjax = false; }); } if (!opts.animate) opts.state.isDuringAjax = false; callback(this, data); }, _nearbottom: function infscr_nearbottom() { var opts = this.options, pixelsFromWindowBottomToBottom = 0 + $(document).height() - (opts.binder.scrollTop()) - $(window).height(); if (!!opts.behavior && this['_nearbottom_' + opts.behavior] !== undefined) { this['_nearbottom_' + opts.behavior].call(this); return; } this._debug('math:', pixelsFromWindowBottomToBottom, opts.pixelsFromNavToBottom); return (pixelsFromWindowBottomToBottom - opts.bufferPx < opts.pixelsFromNavToBottom); }, _pausing: function infscr_pausing(pause) { var opts = this.options; if (!!opts.behavior && this['_pausing_' + opts.behavior] !== undefined) { this['_pausing_' + opts.behavior].call(this, pause); return; } if (pause !== 'pause' && pause !== 'resume' && pause !== null) { this._debug('Invalid argument. Toggling pause value instead'); }; pause = (pause && (pause == 'pause' || pause == 'resume')) ? pause : 'toggle'; switch (pause) { case 'pause': opts.state.isPaused = true; break; case 'resume': opts.state.isPaused = false; break; case 'toggle': opts.state.isPaused = !opts.state.isPaused; break; } this._debug('Paused', opts.state.isPaused); return false; }, _setup: function infscr_setup() { var opts = this.options; if (!!opts.behavior && this['_setup_' + opts.behavior] !== undefined) { this['_setup_' + opts.behavior].call(this); return; } this._binding('bind'); return false; }, _showdonemsg: function infscr_showdonemsg() { var opts = this.options; if (!!opts.behavior && this['_showdonemsg_' + opts.behavior] !== undefined) { this['_showdonemsg_' + opts.behavior].call(this); return; } opts.loading.msg.find('img').hide().parent().find('div').html(opts.loading.finishedMsg).animate({ opacity: 1 }, 2000, function () { $(this).parent().fadeOut('normal'); }); $('#infscr-loading').hide(); opts.errorCallback.call($(opts.contentSelector)[0], 'done'); }, _validate: function infscr_validate(opts) { for (var key in opts) { if (key.indexOf && key.indexOf('Selector') > -1 && $(opts[key]).length === 0) { this._debug('Your ' + key + ' found no elements.'); return false; } return true; } }, bind: function infscr_bind() { this._binding('bind'); }, destroy: function infscr_destroy() { this.options.state.isDestroyed = true; return this._error('destroy'); }, pause: function infscr_pause() { this._pausing('pause'); }, resume: function infscr_resume() { this._pausing('resume'); }, retrieve: function infscr_retrieve(pageNum) { var instance = this, opts = instance.options, path = opts.path, box, frag, desturl, method, condition, pageNum = pageNum || null, getPage = (!!pageNum) ? pageNum : opts.state.currPage; beginAjax = function infscr_ajax(opts) { opts.state.currPage++; instance._debug('heading into ajax', path); box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>'); desturl = path.join(opts.state.currPage); method = (opts.dataType == 'html' || opts.dataType == 'json') ? opts.dataType : 'html+callback'; if (opts.appendCallback && opts.dataType == 'html') method += '+callback' switch (method) { case 'html+callback': instance._debug('Using HTML via .load() method'); box.load(desturl + ' ' + opts.itemSelector, null, function infscr_ajax_callback(responseText) { instance._loadcallback(box, responseText); }); break; case 'html': case 'json': instance._debug('Using ' + (method.toUpperCase()) + ' via $.ajax() method'); $.ajax({ url: desturl, dataType: opts.dataType, complete: function infscr_ajax_callback(jqXHR, textStatus) { condition = (typeof (jqXHR.isResolved) !== 'undefined') ? (jqXHR.isResolved()) : (textStatus === "success" || textStatus === "notmodified"); (condition) ? instance._loadcallback(box, jqXHR.responseText) : instance._error('end'); } }); break; } }; if (!!opts.behavior && this['retrieve_' + opts.behavior] !== undefined) { this['retrieve_' + opts.behavior].call(this, pageNum); return; } if (opts.state.isDestroyed) { this._debug('Instance is destroyed'); return false; }; opts.state.isDuringAjax = true; opts.loading.start.call($(opts.contentSelector)[0], opts); }, scroll: function infscr_scroll() { var opts = this.options, state = opts.state; if (!!opts.behavior && this['scroll_' + opts.behavior] !== undefined) { this['scroll_' + opts.behavior].call(this); return; } if (state.isDuringAjax || state.isInvalidPage || state.isDone || state.isDestroyed || state.isPaused) return; if (!this._nearbottom()) return; this.retrieve(); }, toggle: function infscr_toggle() { this._pausing(); }, unbind: function infscr_unbind() { this._binding('unbind'); }, update: function infscr_options(key) { if ($.isPlainObject(key)) { this.options = $.extend(true, this.options, key); } } } $.fn.infinitescroll = function infscr_init(options, callback) { var thisCall = typeof options; switch (thisCall) { case 'string': var args = Array.prototype.slice.call(arguments, 1); this.each(function () { var instance = $.data(this, 'infinitescroll'); if (!instance) { return false; } if (!$.isFunction(instance[options]) || options.charAt(0) === "_") { return false; } instance[options].apply(instance, args); }); break; case 'object': this.each(function () { var instance = $.data(this, 'infinitescroll'); if (instance) { instance.update(options); } else { $.data(this, 'infinitescroll', new $.infinitescroll(options, callback, this)); } }); break; } return this; }; var event = $.event, scrollTimeout; event.special.smartscroll = { setup: function () { $(this).bind("scroll", event.special.smartscroll.handler); }, teardown: function () { $(this).unbind("scroll", event.special.smartscroll.handler); }, handler: function (event, execAsap) { var context = this, args = arguments; event.type = "smartscroll"; if (scrollTimeout) { clearTimeout(scrollTimeout); } scrollTimeout = setTimeout(function () { $.event.handle.apply(context, args); }, execAsap === "execAsap" ? 0 : 100); } }; $.fn.smartscroll = function (fn) { return fn ? this.bind("smartscroll", fn) : this.trigger("smartscroll", ["execAsap"]); }; })(window, jQuery);
yesan/Spacebuilder
Web/Scripts/jquery/masonry/jquery.infinitescroll.js
JavaScript
lgpl-3.0
17,301
/* * @BEGIN LICENSE * * Forte: an open-source plugin to Psi4 (https://github.com/psi4/psi4) * t hat implements a variety of quantum chemistry methods for strongly * correlated electrons. * * Copyright (c) 2012-2022 by its authors (see LICENSE, AUTHORS). * * The copyrights for code used from other parties are included in * the corresponding files. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * @END LICENSE */ #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include "helpers/helpers.h" #include "base_classes/rdms.h" namespace py = pybind11; using namespace pybind11::literals; namespace forte { /// Export the RDMs class void export_RDMs(py::module& m) { py::class_<RDMs>(m, "RDMs") .def("max_rdm_level", &RDMs::max_rdm_level, "Return the max RDM level") .def("ms_avg", &RDMs::ms_avg, "Return if RDMs setup is Ms-averaged") .def( "g1a", [](RDMs& rdm) { return ambit_to_np(rdm.g1a()); }, "Return the alpha 1RDM as a numpy array") .def( "g1b", [](RDMs& rdm) { return ambit_to_np(rdm.g1b()); }, "Return the beta 1RDM as a numpy array") .def( "g2aa", [](RDMs& rdm) { return ambit_to_np(rdm.g2aa()); }, "Return the alpha-alpha 2RDM as a numpy array") .def( "g2ab", [](RDMs& rdm) { return ambit_to_np(rdm.g2ab()); }, "Return the alpha-beta 2RDM as a numpy array") .def( "g2bb", [](RDMs& rdm) { return ambit_to_np(rdm.g2bb()); }, "Return the beta-beta 2RDM as a numpy array") .def( "g3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.g3aaa()); }, "Return the alpha-alpha-alpha 3RDM as a numpy array") .def( "g3aab", [](RDMs& rdm) { return ambit_to_np(rdm.g3aab()); }, "Return the alpha-alpha-beta 3RDM as a numpy array") .def( "g3abb", [](RDMs& rdm) { return ambit_to_np(rdm.g3abb()); }, "Return the alpha-beta-beta 3RDM as a numpy array") .def( "g3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.g3bbb()); }, "Return the beta-beta-beta 3RDM as a numpy array") .def( "L2aa", [](RDMs& rdm) { return ambit_to_np(rdm.L2aa()); }, "Return the alpha-alpha 2-cumulant as a numpy array") .def( "L2ab", [](RDMs& rdm) { return ambit_to_np(rdm.L2ab()); }, "Return the alpha-beta 2-cumulant as a numpy array") .def( "L2bb", [](RDMs& rdm) { return ambit_to_np(rdm.L2bb()); }, "Return the beta-beta 2-cumulant as a numpy array") .def( "L3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.L3aaa()); }, "Return the alpha-alpha-alpha 3-cumulant as a numpy array") .def( "L3aab", [](RDMs& rdm) { return ambit_to_np(rdm.L3aab()); }, "Return the alpha-alpha-beta 3-cumulant as a numpy array") .def( "L3abb", [](RDMs& rdm) { return ambit_to_np(rdm.L3abb()); }, "Return the alpha-beta-beta 3-cumulant as a numpy array") .def( "L3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.L3bbb()); }, "Return the beta-beta-beta 3-cumulant as a numpy array") .def("SF_G1mat", py::overload_cast<>(&RDMs::SF_G1mat), "Return the spin-free 1RDM as a Psi4 Matrix without symmetry") .def("SF_G1mat", py::overload_cast<const psi::Dimension&>(&RDMs::SF_G1mat), "Return the spin-free 1RDM as a Psi4 Matrix with symmetry given by input") .def( "SF_G1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G1()); }, "Return the spin-free 1RDM as a numpy array") .def( "SF_G2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G2()); }, "Return the spin-free 2RDM as a numpy array") .def( "SF_L1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L1()); }, "Return the spin-free 1RDM as a numpy array") .def( "SF_L2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L2()); }, "Return the spin-free (Ms-averaged) 2-cumulant as a numpy array") .def( "SF_L3", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L3()); }, "Return the spin-free (Ms-averaged) 2-cumulant as a numpy array") .def("rotate", &RDMs::rotate, "Ua"_a, "Ub"_a, "Rotate RDMs using the input unitary matrices"); } } // namespace forte
evangelistalab/forte
forte/api/rdms_api.cc
C++
lgpl-3.0
5,090