code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#ifndef IJENGINE_MOUSE_EVENT_H #define IJENGINE_MOUSE_EVENT_H #include "event.h" #define MOUSE_EVENT_ID 0x03 #define BUTTONS_COUNT 3 #include <sstream> using std::ostringstream; namespace ijengine { class MouseEvent : public Event { public: typedef enum {PRESSED, RELEASED, MOTION} State; typedef enum { LEFT, MIDDLE, RIGHT } Button; MouseEvent(unsigned t, State s, State left, State middle, State right, int xv, int yv, int dxv, int dyv) : Event(t), m_state(s), m_buttons_state { left, middle, right }, m_x(xv), m_y(yv), m_dx(dxv), m_dy(dyv) {} State state() const { return m_state; } State button_state(Button button) const { return m_buttons_state[button]; } int x() const { return m_x; } int y() const { return m_y; } int dx() const { return m_dx; } int dy() const { return m_dy; } string serialize() const { ostringstream os; os << MOUSE_EVENT_ID << "," << (int) m_state << "," << (int) m_buttons_state[LEFT] << "," << (int) m_buttons_state[MIDDLE] << "," << (int) m_buttons_state[RIGHT] << "," << m_x << "," << m_y << m_dx << "," << m_dy; return os.str(); } private: State m_state; State m_buttons_state[BUTTONS_COUNT]; int m_x, m_y; int m_dx, m_dy; }; } #endif
BlackGround-ICG/Nitro
include/mouse_event.h
C
gpl-3.0
1,503
using AltitudeAngelWings.Extra; using GMap.NET; using GMap.NET.WindowsForms; using System; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading; using System.Windows.Forms; using Feature = GeoJSON.Net.Feature.Feature; using Unit = System.Reactive.Unit; namespace MissionPlanner.Utilities.AltitudeAngel { internal class MapAdapter : IMap, IDisposable { public MapAdapter(GMapControl mapControl) { _context = new WindowsFormsSynchronizationContext(); _mapControl = mapControl; IObservable<Unit> positionChanged = Observable .FromEvent<PositionChanged, PointLatLng>( action => point => action(point), handler => _mapControl.OnPositionChanged += handler, handler => _mapControl.OnPositionChanged -= handler) .Select(i => Unit.Default); IObservable<Unit> mapZoom = Observable .FromEvent<MapZoomChanged, Unit>( action => () => action(Unit.Default), handler => _mapControl.OnMapZoomChanged += handler, handler => _mapControl.OnMapZoomChanged -= handler); MapChanged = positionChanged .Merge(mapZoom) .ObserveOn(ThreadPoolScheduler.Instance); mapControl.OnMapDrag += MapControl_OnMapDrag; //mapControl.OnPolygonClick += Control_OnPolygonClick; mapControl.OnPolygonEnter += MapControl_OnPolygonEnter; mapControl.OnPolygonLeave += MapControl_OnPolygonLeave; //mapControl.OnRouteClick += MapControl_OnRouteClick; mapControl.OnRouteEnter += MapControl_OnRouteEnter; mapControl.OnRouteLeave += MapControl_OnRouteLeave; } private void MapControl_OnPolygonLeave(GMapPolygon item) { item.Overlay.Markers.Remove(marker); marker = null; } private void MapControl_OnPolygonEnter(GMapPolygon item) { item.Overlay.Markers.Clear(); if (marker != null) item.Overlay.Markers.Remove(marker); var point = item.Overlay.Control.PointToClient(Control.MousePosition); var pos = item.Overlay.Control.FromLocalToLatLng(point.X, point.Y); marker = new GMapMarkerRect(pos) { ToolTipMode = MarkerTooltipMode.Always, ToolTipText = createMessage(item.Tag), IsHitTestVisible = false }; item.Overlay.Markers.Add(marker); } GMapMarkerRect marker = null; private void MapControl_OnRouteLeave(GMapRoute item) { item.Overlay.Markers.Remove(marker); marker = null; } private void MapControl_OnRouteEnter(GMapRoute item) { if (marker != null) item.Overlay.Markers.Remove(marker); var point = item.Overlay.Control.PointToClient(Control.MousePosition); var pos = item.Overlay.Control.FromLocalToLatLng(point.X, point.Y); marker = new GMapMarkerRect(pos) { ToolTipMode = MarkerTooltipMode.Always, ToolTipText = createMessage(item.Tag), IsHitTestVisible = false }; item.Overlay.Markers.Add(marker); } private void MapControl_OnRouteClick(GMapRoute item, MouseEventArgs e) { CustomMessageBox.Show(createMessage(item.Tag), "Info", MessageBoxButtons.OK); } string createMessage(object item) { if (item is Feature) { var prop = ((Feature)item).Properties; var display = prop["display"] as Newtonsoft.Json.Linq.JObject; var sections = display["sections"]; string title; string text; if (sections.Count() == 0) { title = prop["detailedCategory"].ToString(); text = ""; } else { var section1 = sections.Last(); var iconURL = section1["iconUrl"].ToString(); title = display["category"].ToString(); text = section1["text"].ToString(); } var st = String.Format("{0} is categorised as a {1}\n\n{2}", display["title"], title, text); return st; } return ""; } DateTime lastmapdrag = DateTime.MinValue; private void MapControl_OnMapDrag() { lastmapdrag = DateTime.Now; } private void Control_OnPolygonClick(GMapPolygon item, MouseEventArgs e) { if (e.Button == MouseButtons.Right) return; if (item.Overlay.Control.IsDragging) return; if (_mapControl.Overlays.First(x => x.Polygons.Any(i => i.Name == item.Name)) != null) { if (item.Tag is Feature) { var st = createMessage(item.Tag); CustomMessageBox.Show(st, "Info", MessageBoxButtons.OK); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public PointLatLng GetCenter() { PointLatLng pointLatLng = default(PointLatLng); try { _context.Send(_ => pointLatLng = _mapControl.Position, null); } catch { } return pointLatLng; } public RectLatLng GetViewArea() { RectLatLng rectLatLng = default(RectLatLng); try { _context.Send(_ => rectLatLng = _mapControl.ViewArea, null); } catch { } if (rectLatLng.WidthLng < 0.03) rectLatLng.Inflate(0, (0.03 - rectLatLng.WidthLng) / 2); if (rectLatLng.HeightLat < 0.03) rectLatLng.Inflate((0.03 - rectLatLng.HeightLat) / 2, 0); return rectLatLng; } public void AddOverlay(string name) { _context.Send(state => { _mapControl.Overlays.Add(new GMapOverlay(name)); }, null); } public void DeleteOverlay(string name) { _context.Send(_ => { GMapOverlay overlay = _mapControl.Overlays.FirstOrDefault(i => i.Id == name); if (overlay != null) { _mapControl.Overlays.Remove(overlay); overlay.Dispose(); } }, null); } public IOverlay GetOverlay(string name, bool createIfNotExists = false) { IOverlay result = null; try { _context.Send(_ => { GMapOverlay overlay = _mapControl.Overlays.FirstOrDefault(i => i.Id == name); if (overlay == null) { if (createIfNotExists) { AddOverlay(name); result = GetOverlay(name); return; } throw new ArgumentException($"Overlay {name} not found."); } result = new OverlayAdapter(overlay); }, null); } catch { } return result; } private void Dispose(bool isDisposing) { if (isDisposing) { _disposer?.Dispose(); _disposer = null; } } private readonly GMapControl _mapControl; private CompositeDisposable _disposer = new CompositeDisposable(); private readonly SynchronizationContext _context; public IObservable<Unit> MapChanged { get; } public void Invalidate() { _mapControl.Invalidate(); } } }
ArduPilot/MissionPlanner
Utilities/AltitudeAngel/MapAdapter.cs
C#
gpl-3.0
8,732
using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace GitExtUtils { public sealed class GitCommandConfiguration { private readonly ConcurrentDictionary<string, GitConfigItem[]> _configByCommand = new(StringComparer.Ordinal); /// <summary> /// Gets the default configuration for git commands used by Git Extensions. /// </summary> public static GitCommandConfiguration Default { get; } static GitCommandConfiguration() { // The set of default configuration items for Git Extensions Default = new GitCommandConfiguration(); Default.Add(new GitConfigItem("rebase.autoSquash", "false"), "rebase"); Default.Add(new GitConfigItem("log.showSignature", "false"), "log", "show", "whatchanged"); Default.Add(new GitConfigItem("color.ui", "never"), "diff", "range-diff"); Default.Add(new GitConfigItem("diff.submodule", "short"), "diff"); Default.Add(new GitConfigItem("diff.noprefix", "false"), "diff"); Default.Add(new GitConfigItem("diff.mnemonicprefix", "false"), "diff"); Default.Add(new GitConfigItem("diff.ignoreSubmodules", "none"), "diff", "status"); Default.Add(new GitConfigItem("core.safecrlf", "false"), "diff"); } /// <summary> /// Registers <paramref name="configItem"/> against one or more command names. /// </summary> /// <param name="configItem">The config item to register.</param> /// <param name="commands">One or more command names to register this config item against.</param> public void Add(GitConfigItem configItem, params string[] commands) { foreach (var command in commands) { _configByCommand.AddOrUpdate( command, addValueFactory: _ => new[] { configItem }, updateValueFactory: (_, items) => items.AppendTo(configItem)); } } /// <summary> /// Retrieves the set of default config items for the given <paramref name="command"/>. /// </summary> /// <param name="command">The command to retrieve default config items for.</param> /// <returns>The default config items for <paramref name="command"/>.</returns> public IReadOnlyList<GitConfigItem> Get(string command) { return _configByCommand.TryGetValue(command, out var items) ? items : Array.Empty<GitConfigItem>(); } } }
PKRoma/gitextensions
GitExtUtils/GitCommandConfiguration.cs
C#
gpl-3.0
2,635
/* * Copyright (c) 2011 Matthew Arsenault * * This file is part of Milkway@Home. * * Milkway@Home is free software: you may copy, redistribute 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 file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include "milkyway_asprintf.h" #ifndef _WIN32 /* Random internet person says this should work but it seems to not */ #define _vscprintf(f,a) vsnprintf(NULL, (size_t) 0, f, a) #endif #if defined(_WIN32) && !HAVE_ASPRINTF /* Intended for use on windows where asprintf is missing */ int asprintf(char** bufOut, const char* format, ...) { int size, rc; char* buf; va_list args; va_start(args, format); size = _vscprintf(format, args); if (size < 0) { *bufOut = NULL; return size; } buf = (char*) malloc((size + 1) * sizeof(char)); /* Include null terminator */ if (!buf) { *bufOut = NULL; return -1; } rc = vsprintf(buf, format, args); va_end(args); *bufOut = buf; return rc; } #endif /* defined(_WIN32) && !HAVE_ASPRINTF */
MarchM4/Milkyway-home-server-expansion
milkyway/src/milkyway_asprintf.c
C
gpl-3.0
1,641
#!/bin/bash # Defining command line args. These are task-specific. To get a list of options # available for a given task, put "-h" after the task name when running BandUP. This will # print the help for the specific task requested. # Run BandUP with the "-h" option only to get a list of supported tasks # If the the task is not explicitly set, then "unfold" will be selected by default. # BandUP tries to get the Fermi energy automatically from the self-consistent calc. # If this fails, you can pass the Fermi energy by using the option "-efermi VALUE_IN_eV" unfolding_task_args="-emin -13 -emax 6 -dE 0.050" plot_task_args='-input_file unfolded_EBS_symmetry-averaged.dat --show --save' plot_task_args="${plot_task_args} -plotdir plot --round_cb 0" # Choose OMP_NUM_THREADS=1 if you do not want openmp parallelization. # I normally use OMP_NUM_THREADS=n_cores/2 export OMP_NUM_THREADS=2 # You will probably not need to change anything below this line. I do recommend, however, # that you read and understand what is happening in this whole file. Once you have fully # understood what is done here, you'll realize that this script is not needed at all, as # running BandUP directly is straightforward (particularly when you have it in your PATH) # If you compiled BandUP as recommended (using the build.sh script), then then following # line will define the variable "BANDUPDIR". If you have not done so, then you will need # to change this script so that "exe" points to the "bandup" executable. # You really should compile BandUP as recommended, though. # If the "bandup" executable is in your PATH, then you can do just exe='bandup' source ~/.bandup/config # This same executable will be used for all tasks (pre-unfolding, unfolding and plot) exe="${BANDUPDIR}/bandup" # Preparing to run BandUP's "unfold" task task='unfold' task_args=${unfolding_task_args} command_to_run="${exe} ${task} ${task_args}" # Running BandUP with the task and task-specific options requested ulimit -s unlimited eval $command_to_run # Preparing to run BandUP's "plot" task task='plot' task_args=${plot_task_args} command_to_run="${exe} ${task} ${task_args}" # Running BandUP with the task and task-specific options requested eval $command_to_run # End of script
band-unfolding/bandup
tutorial/VASP/example_3_bulk_Si_other_set_of_pcbz_directions/step_4_run_BandUP_and_plot/run_BandUP_unfold_and_plot_tasks.sh
Shell
gpl-3.0
2,252
/* Copyright 2020 Equinor ASA. This file is part of the Open Porous Media project (OPM). OPM 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. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #include <stdexcept> #include <iostream> #define BOOST_TEST_MODULE ReportConfigTest #include <boost/test/unit_test.hpp> #include <opm/parser/eclipse/EclipseState/Schedule/RPTConfig.hpp> #include <opm/parser/eclipse/EclipseState/Schedule/Schedule.hpp> #include <opm/parser/eclipse/Deck/Deck.hpp> #include <opm/parser/eclipse/Parser/Parser.hpp> #include <opm/parser/eclipse/EclipseState/EclipseState.hpp> #include <opm/parser/eclipse/Python/Python.hpp> Opm::Schedule make_schedule(const std::string& sched_string) { std::string deck_string = R"( RUNSPEC DIMENS 5 5 5 / OIL WATER TABDIMS / WELLDIMS 2 10 3 2 / GRID DXV 5*100 / DYV 5*100 / DZV 5*5 / TOPS 25*2500 / PORO 125*0.15 / PERMX 125*500 / COPY 'PERMX' 'PERMY' / 'PERMX' 'PERMZ' / / MULTIPLY 'PERMZ' 0.1 / / PROPS SWOF 0 0 1 0 1 1 0 0 / SCHEDULE )"; Opm::Parser parser; auto deck = parser.parseString(deck_string + sched_string); Opm::EclipseState ecl_state(deck); auto python = std::make_shared<Opm::Python>(); return Opm::Schedule(deck, ecl_state, python); } BOOST_AUTO_TEST_CASE(ReportConfig_INVALID) { const std::string sched_string1 = R"( RPTSCHED FIPSOL=X )"; const std::string sched_string2 = R"( RPTSCHED FIPSOL=-1 )"; const std::string sched_string3 = R"( RPTSCHED FIPSOL=2.50 )"; BOOST_CHECK_THROW(make_schedule(sched_string1), std::invalid_argument); BOOST_CHECK_THROW(make_schedule(sched_string2), std::invalid_argument); BOOST_CHECK_THROW(make_schedule(sched_string3), std::invalid_argument); } BOOST_AUTO_TEST_CASE(ReportConfig) { const std::string sched_string = R"( DATES 1 'JAN' 2000 / / RPTSCHED FIPSOL FIP=3 / DATES 1 'FEB' 2000 / / RPTSCHED FIPSOL FIP=3 NOTHING / )"; auto sched = make_schedule(sched_string); // Empty initial report configuration { auto report_config = sched[0].rpt_config.get(); BOOST_CHECK_EQUAL(report_config.size(), 0U); BOOST_CHECK(!report_config.contains("FIPFOAM")); BOOST_CHECK_THROW( report_config.at("FIPFOAM"), std::out_of_range); } // Configuration at step 1 { auto report_config = sched[1].rpt_config.get(); BOOST_CHECK_EQUAL( report_config.size() , 2U); for (const auto& p : report_config) { if (p.first == "FIPSOL") BOOST_CHECK_EQUAL(p.second, 1U); if (p.first == "FIP") BOOST_CHECK_EQUAL(p.second, 3U); } BOOST_CHECK(!report_config.contains("FIPFOAM")); BOOST_CHECK(report_config.contains("FIP")); BOOST_CHECK_EQUAL(report_config.at("FIP"), 3U); BOOST_CHECK_EQUAL(report_config.at("FIPSOL"), 1U); } // Configuration at step 2 - the special 'NOTHING' has cleared everything { auto report_config = sched[2].rpt_config.get(); BOOST_CHECK_EQUAL(report_config.size(), 0U); BOOST_CHECK(!report_config.contains("FIPFOAM")); BOOST_CHECK_THROW( report_config.at("FIPFOAM"), std::out_of_range); } }
dr-robertk/opm-common
tests/parser/test_ReportConfig.cpp
C++
gpl-3.0
3,726
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Monkeypatch initialisation functions """ try: from collections import OrderedDict except ImportError: # pragma: no-cover from ordereddict import OrderedDict # pylint:disable=import-error from rebulk.match import Match def monkeypatch_rebulk(): """Monkeypatch rebulk classes""" @property def match_advanced(self): """ Build advanced dict from match :param self: :return: """ ret = OrderedDict() ret['value'] = self.value if self.raw: ret['raw'] = self.raw ret['start'] = self.start ret['end'] = self.end return ret Match.advanced = match_advanced
clinton-hall/nzbToMedia
libs/common/guessit/monkeypatch.py
Python
gpl-3.0
729
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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/>. # ######################################################################### from django.views.generic import View from django.conf import settings from geonode.base.enumerations import LINK_TYPES as _LT # from geonode.base.models import Link from geonode.utils import json_response from geonode.geoserver import ows LINK_TYPES = [L for L in _LT if L.startswith("OGC:")] class OWSListView(View): def get(self, request): out = {'success': True} data = [] out['data'] = data # per-layer links # for link in Link.objects.filter(link_type__in=LINK_TYPES): # .distinct('url'): # data.append({'url': link.url, 'type': link.link_type}) data.append({'url': ows._wcs_get_capabilities(), 'type': 'OGC:WCS'}) data.append({'url': ows._wfs_get_capabilities(), 'type': 'OGC:WFS'}) data.append({'url': ows._wms_get_capabilities(), 'type': 'OGC:WMS'}) # catalogue from configuration for catname, catconf in settings.CATALOGUE.items(): data.append({'url': catconf['URL'], 'type': 'OGC:CSW'}) # main site url data.append({'url': settings.SITEURL, 'type': 'WWW:LINK'}) return json_response(out) ows_endpoints = OWSListView.as_view()
timlinux/geonode
geonode/contrib/ows_api/views.py
Python
gpl-3.0
2,017
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2016, British Columbia Institute of Technology * * 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. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['upload_userfile_not_set'] = 'Unable to find a post variable called userfile.'; $lang['upload_file_exceeds_limit'] = 'The uploaded file exceeds the maximum allowed size in your PHP configuration file.'; $lang['upload_file_exceeds_form_limit'] = 'The uploaded file exceeds the maximum size allowed by the submission form.'; $lang['upload_file_partial'] = 'The file was only partially uploaded.'; $lang['upload_no_temp_directory'] = 'The temporary folder is missing.'; $lang['upload_unable_to_write_file'] = 'The file could not be written to disk.'; $lang['upload_stopped_by_extension'] = 'The file upload was stopped by extension.'; $lang['upload_no_file_selected'] = 'You did not select a file to upload.'; $lang['upload_invalid_filetype'] = 'The filetype you are attempting to upload is not allowed.'; $lang['upload_invalid_filesize'] = 'The file you are attempting to upload is larger than the permitted size.'; $lang['upload_invalid_dimensions'] = 'The image you are attempting to upload doesn\'t fit into the allowed dimensions.'; $lang['upload_destination_error'] = 'A problem was encountered while attempting to move the uploaded file to the final destination.'; $lang['upload_no_filepath'] = 'The upload path does not appear to be valid.'; $lang['upload_no_file_types'] = 'You have not specified any allowed file types.'; $lang['upload_bad_filename'] = 'The file name you submitted already exists on the server.'; $lang['upload_not_writable'] = 'The upload destination folder does not appear to be writable.';
leonleslie/TastyIgniter
system/language/english/upload_lang.php
PHP
gpl-3.0
3,264
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "google_apis/drive/drive_api_requests.h" #include <stddef.h> #include "base/bind.h" #include "base/callback.h" #include "base/json/json_writer.h" #include "base/location.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/sequenced_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/task_runner_util.h" #include "base/values.h" #include "google_apis/drive/request_sender.h" #include "google_apis/drive/request_util.h" #include "google_apis/drive/time_util.h" #include "net/base/url_util.h" #include "net/http/http_response_headers.h" namespace google_apis { namespace drive { namespace { // Format of one request in batch uploading request. const char kBatchUploadRequestFormat[] = "%s %s HTTP/1.1\n" "Host: %s\n" "X-Goog-Upload-Protocol: multipart\n" "Content-Type: %s\n" "\n"; // Request header for specifying batch upload. const char kBatchUploadHeader[] = "X-Goog-Upload-Protocol: batch"; // Content type of HTTP request. const char kHttpContentType[] = "application/http"; // Break line in HTTP message. const char kHttpBr[] = "\r\n"; // Mime type of multipart mixed. const char kMultipartMixedMimeTypePrefix[] = "multipart/mixed; boundary="; // UMA names. const char kUMADriveBatchUploadResponseCode[] = "Drive.BatchUploadResponseCode"; const char kUMADriveTotalFileCountInBatchUpload[] = "Drive.TotalFileCountInBatchUpload"; const char kUMADriveTotalFileSizeInBatchUpload[] = "Drive.TotalFileSizeInBatchUpload"; // Parses the JSON value to FileResource instance and runs |callback| on the // UI thread once parsing is done. // This is customized version of ParseJsonAndRun defined above to adapt the // remaining response type. void ParseFileResourceWithUploadRangeAndRun( const UploadRangeCallback& callback, const UploadRangeResponse& response, std::unique_ptr<base::Value> value) { DCHECK(!callback.is_null()); std::unique_ptr<FileResource> file_resource; if (value) { file_resource = FileResource::CreateFrom(*value); if (!file_resource) { callback.Run(UploadRangeResponse(DRIVE_PARSE_ERROR, response.start_position_received, response.end_position_received), std::unique_ptr<FileResource>()); return; } } callback.Run(response, std::move(file_resource)); } // Attaches |properties| to the |request_body| if |properties| is not empty. // |request_body| must not be NULL. void AttachProperties(const Properties& properties, base::DictionaryValue* request_body) { DCHECK(request_body); if (properties.empty()) return; base::ListValue* const properties_value = new base::ListValue; for (const auto& property : properties) { std::unique_ptr<base::DictionaryValue> property_value( new base::DictionaryValue); std::string visibility_as_string; switch (property.visibility()) { case Property::VISIBILITY_PRIVATE: visibility_as_string = "PRIVATE"; break; case Property::VISIBILITY_PUBLIC: visibility_as_string = "PUBLIC"; break; } property_value->SetString("visibility", visibility_as_string); property_value->SetString("key", property.key()); property_value->SetString("value", property.value()); properties_value->Append(std::move(property_value)); } request_body->Set("properties", properties_value); } // Creates metadata JSON string for multipart uploading. // All the values are optional. If the value is empty or null, the value does // not appear in the metadata. std::string CreateMultipartUploadMetadataJson( const std::string& title, const std::string& parent_resource_id, const base::Time& modified_date, const base::Time& last_viewed_by_me_date, const Properties& properties) { base::DictionaryValue root; if (!title.empty()) root.SetString("title", title); // Fill parent link. if (!parent_resource_id.empty()) { std::unique_ptr<base::ListValue> parents(new base::ListValue); parents->Append(google_apis::util::CreateParentValue(parent_resource_id)); root.Set("parents", parents.release()); } if (!modified_date.is_null()) { root.SetString("modifiedDate", google_apis::util::FormatTimeAsString(modified_date)); } if (!last_viewed_by_me_date.is_null()) { root.SetString("lastViewedByMeDate", google_apis::util::FormatTimeAsString( last_viewed_by_me_date)); } AttachProperties(properties, &root); std::string json_string; base::JSONWriter::Write(root, &json_string); return json_string; } } // namespace MultipartHttpResponse::MultipartHttpResponse() : code(HTTP_SUCCESS) { } MultipartHttpResponse::~MultipartHttpResponse() { } // The |response| must be multipart/mixed format that contains child HTTP // response of drive batch request. // https://www.ietf.org/rfc/rfc2046.txt // // It looks like: // --Boundary // Content-type: application/http // // HTTP/1.1 200 OK // Header of child response // // Body of child response // --Boundary // Content-type: application/http // // HTTP/1.1 404 Not Found // Header of child response // // Body of child response // --Boundary-- bool ParseMultipartResponse(const std::string& content_type, const std::string& response, std::vector<MultipartHttpResponse>* parts) { if (response.empty()) return false; base::StringPiece content_type_piece(content_type); if (!content_type_piece.starts_with(kMultipartMixedMimeTypePrefix)) { return false; } content_type_piece.remove_prefix( base::StringPiece(kMultipartMixedMimeTypePrefix).size()); if (content_type_piece.empty()) return false; if (content_type_piece[0] == '"') { if (content_type_piece.size() <= 2 || content_type_piece.back() != '"') return false; content_type_piece = content_type_piece.substr(1, content_type_piece.size() - 2); } std::string boundary; content_type_piece.CopyToString(&boundary); const std::string header = "--" + boundary; const std::string terminator = "--" + boundary + "--"; std::vector<base::StringPiece> lines = base::SplitStringPieceUsingSubstr( response, kHttpBr, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); enum { STATE_START, STATE_PART_HEADER, STATE_PART_HTTP_STATUS_LINE, STATE_PART_HTTP_HEADER, STATE_PART_HTTP_BODY } state = STATE_START; const std::string kHttpStatusPrefix = "HTTP/1.1 "; std::vector<MultipartHttpResponse> responses; DriveApiErrorCode code = DRIVE_PARSE_ERROR; std::string body; for (const auto& line : lines) { if (state == STATE_PART_HEADER && line.empty()) { state = STATE_PART_HTTP_STATUS_LINE; continue; } if (state == STATE_PART_HTTP_STATUS_LINE) { if (line.starts_with(kHttpStatusPrefix)) { int int_code; base::StringToInt( line.substr(base::StringPiece(kHttpStatusPrefix).size()), &int_code); if (int_code > 0) code = static_cast<DriveApiErrorCode>(int_code); else code = DRIVE_PARSE_ERROR; } else { code = DRIVE_PARSE_ERROR; } state = STATE_PART_HTTP_HEADER; continue; } if (state == STATE_PART_HTTP_HEADER && line.empty()) { state = STATE_PART_HTTP_BODY; body.clear(); continue; } const base::StringPiece chopped_line = base::TrimString(line, " \t", base::TRIM_TRAILING); const bool is_new_part = chopped_line == header; const bool was_last_part = chopped_line == terminator; if (is_new_part || was_last_part) { switch (state) { case STATE_START: break; case STATE_PART_HEADER: case STATE_PART_HTTP_STATUS_LINE: responses.push_back(MultipartHttpResponse()); responses.back().code = DRIVE_PARSE_ERROR; break; case STATE_PART_HTTP_HEADER: responses.push_back(MultipartHttpResponse()); responses.back().code = code; break; case STATE_PART_HTTP_BODY: // Drop the last kHttpBr. if (!body.empty()) body.resize(body.size() - 2); responses.push_back(MultipartHttpResponse()); responses.back().code = code; responses.back().body.swap(body); break; } if (is_new_part) state = STATE_PART_HEADER; if (was_last_part) break; } else if (state == STATE_PART_HTTP_BODY) { line.AppendToString(&body); body.append(kHttpBr); } } parts->swap(responses); return true; } Property::Property() : visibility_(VISIBILITY_PRIVATE) { } Property::~Property() { } //============================ DriveApiPartialFieldRequest ==================== DriveApiPartialFieldRequest::DriveApiPartialFieldRequest( RequestSender* sender) : UrlFetchRequestBase(sender) { } DriveApiPartialFieldRequest::~DriveApiPartialFieldRequest() { } GURL DriveApiPartialFieldRequest::GetURL() const { GURL url = GetURLInternal(); if (!fields_.empty()) url = net::AppendOrReplaceQueryParameter(url, "fields", fields_); return url; } //=============================== FilesGetRequest ============================= FilesGetRequest::FilesGetRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, bool use_internal_endpoint, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator), use_internal_endpoint_(use_internal_endpoint) { DCHECK(!callback.is_null()); } FilesGetRequest::~FilesGetRequest() {} GURL FilesGetRequest::GetURLInternal() const { return url_generator_.GetFilesGetUrl(file_id_, use_internal_endpoint_, embed_origin_); } //============================ FilesAuthorizeRequest =========================== FilesAuthorizeRequest::FilesAuthorizeRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } FilesAuthorizeRequest::~FilesAuthorizeRequest() {} net::URLFetcher::RequestType FilesAuthorizeRequest::GetRequestType() const { return net::URLFetcher::POST; } GURL FilesAuthorizeRequest::GetURLInternal() const { return url_generator_.GetFilesAuthorizeUrl(file_id_, app_id_); } //============================ FilesInsertRequest ============================ FilesInsertRequest::FilesInsertRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator), visibility_(FILE_VISIBILITY_DEFAULT) { DCHECK(!callback.is_null()); } FilesInsertRequest::~FilesInsertRequest() {} net::URLFetcher::RequestType FilesInsertRequest::GetRequestType() const { return net::URLFetcher::POST; } bool FilesInsertRequest::GetContentData(std::string* upload_content_type, std::string* upload_content) { *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; if (!last_viewed_by_me_date_.is_null()) { root.SetString("lastViewedByMeDate", util::FormatTimeAsString(last_viewed_by_me_date_)); } if (!mime_type_.empty()) root.SetString("mimeType", mime_type_); if (!modified_date_.is_null()) root.SetString("modifiedDate", util::FormatTimeAsString(modified_date_)); if (!parents_.empty()) { base::ListValue* parents_value = new base::ListValue; for (size_t i = 0; i < parents_.size(); ++i) { std::unique_ptr<base::DictionaryValue> parent(new base::DictionaryValue); parent->SetString("id", parents_[i]); parents_value->Append(std::move(parent)); } root.Set("parents", parents_value); } if (!title_.empty()) root.SetString("title", title_); AttachProperties(properties_, &root); base::JSONWriter::Write(root, upload_content); DVLOG(1) << "FilesInsert data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } GURL FilesInsertRequest::GetURLInternal() const { return url_generator_.GetFilesInsertUrl( visibility_ == FILE_VISIBILITY_PRIVATE ? "PRIVATE" : ""); } //============================== FilesPatchRequest ============================ FilesPatchRequest::FilesPatchRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator), set_modified_date_(false), update_viewed_date_(true) { DCHECK(!callback.is_null()); } FilesPatchRequest::~FilesPatchRequest() {} net::URLFetcher::RequestType FilesPatchRequest::GetRequestType() const { return net::URLFetcher::PATCH; } std::vector<std::string> FilesPatchRequest::GetExtraRequestHeaders() const { std::vector<std::string> headers; headers.push_back(util::kIfMatchAllHeader); return headers; } GURL FilesPatchRequest::GetURLInternal() const { return url_generator_.GetFilesPatchUrl( file_id_, set_modified_date_, update_viewed_date_); } bool FilesPatchRequest::GetContentData(std::string* upload_content_type, std::string* upload_content) { if (title_.empty() && modified_date_.is_null() && last_viewed_by_me_date_.is_null() && parents_.empty()) return false; *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; if (!title_.empty()) root.SetString("title", title_); if (!modified_date_.is_null()) root.SetString("modifiedDate", util::FormatTimeAsString(modified_date_)); if (!last_viewed_by_me_date_.is_null()) { root.SetString("lastViewedByMeDate", util::FormatTimeAsString(last_viewed_by_me_date_)); } if (!parents_.empty()) { base::ListValue* parents_value = new base::ListValue; for (size_t i = 0; i < parents_.size(); ++i) { std::unique_ptr<base::DictionaryValue> parent(new base::DictionaryValue); parent->SetString("id", parents_[i]); parents_value->Append(std::move(parent)); } root.Set("parents", parents_value); } AttachProperties(properties_, &root); base::JSONWriter::Write(root, upload_content); DVLOG(1) << "FilesPatch data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } //============================= FilesCopyRequest ============================== FilesCopyRequest::FilesCopyRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator), visibility_(FILE_VISIBILITY_DEFAULT) { DCHECK(!callback.is_null()); } FilesCopyRequest::~FilesCopyRequest() { } net::URLFetcher::RequestType FilesCopyRequest::GetRequestType() const { return net::URLFetcher::POST; } GURL FilesCopyRequest::GetURLInternal() const { return url_generator_.GetFilesCopyUrl( file_id_, visibility_ == FILE_VISIBILITY_PRIVATE ? "PRIVATE" : ""); } bool FilesCopyRequest::GetContentData(std::string* upload_content_type, std::string* upload_content) { if (parents_.empty() && title_.empty()) return false; *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; if (!modified_date_.is_null()) root.SetString("modifiedDate", util::FormatTimeAsString(modified_date_)); if (!parents_.empty()) { base::ListValue* parents_value = new base::ListValue; for (size_t i = 0; i < parents_.size(); ++i) { std::unique_ptr<base::DictionaryValue> parent(new base::DictionaryValue); parent->SetString("id", parents_[i]); parents_value->Append(std::move(parent)); } root.Set("parents", parents_value); } if (!title_.empty()) root.SetString("title", title_); base::JSONWriter::Write(root, upload_content); DVLOG(1) << "FilesCopy data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } //============================= FilesListRequest ============================= FilesListRequest::FilesListRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileListCallback& callback) : DriveApiDataRequest<FileList>(sender, callback), url_generator_(url_generator), max_results_(100) { DCHECK(!callback.is_null()); } FilesListRequest::~FilesListRequest() {} GURL FilesListRequest::GetURLInternal() const { return url_generator_.GetFilesListUrl(max_results_, page_token_, q_); } //======================== FilesListNextPageRequest ========================= FilesListNextPageRequest::FilesListNextPageRequest( RequestSender* sender, const FileListCallback& callback) : DriveApiDataRequest<FileList>(sender, callback) { DCHECK(!callback.is_null()); } FilesListNextPageRequest::~FilesListNextPageRequest() { } GURL FilesListNextPageRequest::GetURLInternal() const { return next_link_; } //============================ FilesDeleteRequest ============================= FilesDeleteRequest::FilesDeleteRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const EntryActionCallback& callback) : EntryActionRequest(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } FilesDeleteRequest::~FilesDeleteRequest() {} net::URLFetcher::RequestType FilesDeleteRequest::GetRequestType() const { return net::URLFetcher::DELETE_REQUEST; } GURL FilesDeleteRequest::GetURL() const { return url_generator_.GetFilesDeleteUrl(file_id_); } std::vector<std::string> FilesDeleteRequest::GetExtraRequestHeaders() const { std::vector<std::string> headers( EntryActionRequest::GetExtraRequestHeaders()); headers.push_back(util::GenerateIfMatchHeader(etag_)); return headers; } //============================ FilesTrashRequest ============================= FilesTrashRequest::FilesTrashRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback) : DriveApiDataRequest<FileResource>(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } FilesTrashRequest::~FilesTrashRequest() {} net::URLFetcher::RequestType FilesTrashRequest::GetRequestType() const { return net::URLFetcher::POST; } GURL FilesTrashRequest::GetURLInternal() const { return url_generator_.GetFilesTrashUrl(file_id_); } //============================== AboutGetRequest ============================= AboutGetRequest::AboutGetRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const AboutResourceCallback& callback) : DriveApiDataRequest<AboutResource>(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } AboutGetRequest::~AboutGetRequest() {} GURL AboutGetRequest::GetURLInternal() const { return url_generator_.GetAboutGetUrl(); } //============================ ChangesListRequest =========================== ChangesListRequest::ChangesListRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const ChangeListCallback& callback) : DriveApiDataRequest<ChangeList>(sender, callback), url_generator_(url_generator), include_deleted_(true), max_results_(100), start_change_id_(0) { DCHECK(!callback.is_null()); } ChangesListRequest::~ChangesListRequest() {} GURL ChangesListRequest::GetURLInternal() const { return url_generator_.GetChangesListUrl( include_deleted_, max_results_, page_token_, start_change_id_); } //======================== ChangesListNextPageRequest ========================= ChangesListNextPageRequest::ChangesListNextPageRequest( RequestSender* sender, const ChangeListCallback& callback) : DriveApiDataRequest<ChangeList>(sender, callback) { DCHECK(!callback.is_null()); } ChangesListNextPageRequest::~ChangesListNextPageRequest() { } GURL ChangesListNextPageRequest::GetURLInternal() const { return next_link_; } //============================== AppsListRequest =========================== AppsListRequest::AppsListRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, bool use_internal_endpoint, const AppListCallback& callback) : DriveApiDataRequest<AppList>(sender, callback), url_generator_(url_generator), use_internal_endpoint_(use_internal_endpoint) { DCHECK(!callback.is_null()); } AppsListRequest::~AppsListRequest() {} GURL AppsListRequest::GetURLInternal() const { return url_generator_.GetAppsListUrl(use_internal_endpoint_); } //============================== AppsDeleteRequest =========================== AppsDeleteRequest::AppsDeleteRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, const EntryActionCallback& callback) : EntryActionRequest(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } AppsDeleteRequest::~AppsDeleteRequest() {} net::URLFetcher::RequestType AppsDeleteRequest::GetRequestType() const { return net::URLFetcher::DELETE_REQUEST; } GURL AppsDeleteRequest::GetURL() const { return url_generator_.GetAppsDeleteUrl(app_id_); } //========================== ChildrenInsertRequest ============================ ChildrenInsertRequest::ChildrenInsertRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const EntryActionCallback& callback) : EntryActionRequest(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } ChildrenInsertRequest::~ChildrenInsertRequest() {} net::URLFetcher::RequestType ChildrenInsertRequest::GetRequestType() const { return net::URLFetcher::POST; } GURL ChildrenInsertRequest::GetURL() const { return url_generator_.GetChildrenInsertUrl(folder_id_); } bool ChildrenInsertRequest::GetContentData(std::string* upload_content_type, std::string* upload_content) { *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; root.SetString("id", id_); base::JSONWriter::Write(root, upload_content); DVLOG(1) << "InsertResource data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } //========================== ChildrenDeleteRequest ============================ ChildrenDeleteRequest::ChildrenDeleteRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const EntryActionCallback& callback) : EntryActionRequest(sender, callback), url_generator_(url_generator) { DCHECK(!callback.is_null()); } ChildrenDeleteRequest::~ChildrenDeleteRequest() {} net::URLFetcher::RequestType ChildrenDeleteRequest::GetRequestType() const { return net::URLFetcher::DELETE_REQUEST; } GURL ChildrenDeleteRequest::GetURL() const { return url_generator_.GetChildrenDeleteUrl(child_id_, folder_id_); } //======================= InitiateUploadNewFileRequest ======================= InitiateUploadNewFileRequest::InitiateUploadNewFileRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& content_type, int64_t content_length, const std::string& parent_resource_id, const std::string& title, const InitiateUploadCallback& callback) : InitiateUploadRequestBase(sender, callback, content_type, content_length), url_generator_(url_generator), parent_resource_id_(parent_resource_id), title_(title) {} InitiateUploadNewFileRequest::~InitiateUploadNewFileRequest() {} GURL InitiateUploadNewFileRequest::GetURL() const { return url_generator_.GetInitiateUploadNewFileUrl(!modified_date_.is_null()); } net::URLFetcher::RequestType InitiateUploadNewFileRequest::GetRequestType() const { return net::URLFetcher::POST; } bool InitiateUploadNewFileRequest::GetContentData( std::string* upload_content_type, std::string* upload_content) { *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; root.SetString("title", title_); // Fill parent link. std::unique_ptr<base::ListValue> parents(new base::ListValue); parents->Append(util::CreateParentValue(parent_resource_id_)); root.Set("parents", parents.release()); if (!modified_date_.is_null()) root.SetString("modifiedDate", util::FormatTimeAsString(modified_date_)); if (!last_viewed_by_me_date_.is_null()) { root.SetString("lastViewedByMeDate", util::FormatTimeAsString(last_viewed_by_me_date_)); } AttachProperties(properties_, &root); base::JSONWriter::Write(root, upload_content); DVLOG(1) << "InitiateUploadNewFile data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } //===================== InitiateUploadExistingFileRequest ==================== InitiateUploadExistingFileRequest::InitiateUploadExistingFileRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& content_type, int64_t content_length, const std::string& resource_id, const std::string& etag, const InitiateUploadCallback& callback) : InitiateUploadRequestBase(sender, callback, content_type, content_length), url_generator_(url_generator), resource_id_(resource_id), etag_(etag) {} InitiateUploadExistingFileRequest::~InitiateUploadExistingFileRequest() {} GURL InitiateUploadExistingFileRequest::GetURL() const { return url_generator_.GetInitiateUploadExistingFileUrl( resource_id_, !modified_date_.is_null()); } net::URLFetcher::RequestType InitiateUploadExistingFileRequest::GetRequestType() const { return net::URLFetcher::PUT; } std::vector<std::string> InitiateUploadExistingFileRequest::GetExtraRequestHeaders() const { std::vector<std::string> headers( InitiateUploadRequestBase::GetExtraRequestHeaders()); headers.push_back(util::GenerateIfMatchHeader(etag_)); return headers; } bool InitiateUploadExistingFileRequest::GetContentData( std::string* upload_content_type, std::string* upload_content) { base::DictionaryValue root; if (!parent_resource_id_.empty()) { std::unique_ptr<base::ListValue> parents(new base::ListValue); parents->Append(util::CreateParentValue(parent_resource_id_)); root.Set("parents", parents.release()); } if (!title_.empty()) root.SetString("title", title_); if (!modified_date_.is_null()) root.SetString("modifiedDate", util::FormatTimeAsString(modified_date_)); if (!last_viewed_by_me_date_.is_null()) { root.SetString("lastViewedByMeDate", util::FormatTimeAsString(last_viewed_by_me_date_)); } AttachProperties(properties_, &root); if (root.empty()) return false; *upload_content_type = util::kContentTypeApplicationJson; base::JSONWriter::Write(root, upload_content); DVLOG(1) << "InitiateUploadExistingFile data: " << *upload_content_type << ", [" << *upload_content << "]"; return true; } //============================ ResumeUploadRequest =========================== ResumeUploadRequest::ResumeUploadRequest( RequestSender* sender, const GURL& upload_location, int64_t start_position, int64_t end_position, int64_t content_length, const std::string& content_type, const base::FilePath& local_file_path, const UploadRangeCallback& callback, const ProgressCallback& progress_callback) : ResumeUploadRequestBase(sender, upload_location, start_position, end_position, content_length, content_type, local_file_path), callback_(callback), progress_callback_(progress_callback) { DCHECK(!callback_.is_null()); } ResumeUploadRequest::~ResumeUploadRequest() {} void ResumeUploadRequest::OnRangeRequestComplete( const UploadRangeResponse& response, std::unique_ptr<base::Value> value) { DCHECK(CalledOnValidThread()); ParseFileResourceWithUploadRangeAndRun(callback_, response, std::move(value)); } void ResumeUploadRequest::OnURLFetchUploadProgress( const net::URLFetcher* source, int64_t current, int64_t total) { if (!progress_callback_.is_null()) progress_callback_.Run(current, total); } //========================== GetUploadStatusRequest ========================== GetUploadStatusRequest::GetUploadStatusRequest( RequestSender* sender, const GURL& upload_url, int64_t content_length, const UploadRangeCallback& callback) : GetUploadStatusRequestBase(sender, upload_url, content_length), callback_(callback) { DCHECK(!callback.is_null()); } GetUploadStatusRequest::~GetUploadStatusRequest() {} void GetUploadStatusRequest::OnRangeRequestComplete( const UploadRangeResponse& response, std::unique_ptr<base::Value> value) { DCHECK(CalledOnValidThread()); ParseFileResourceWithUploadRangeAndRun(callback_, response, std::move(value)); } //======================= MultipartUploadNewFileDelegate ======================= MultipartUploadNewFileDelegate::MultipartUploadNewFileDelegate( base::SequencedTaskRunner* task_runner, const std::string& title, const std::string& parent_resource_id, const std::string& content_type, int64_t content_length, const base::Time& modified_date, const base::Time& last_viewed_by_me_date, const base::FilePath& local_file_path, const Properties& properties, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback, const ProgressCallback& progress_callback) : MultipartUploadRequestBase( task_runner, CreateMultipartUploadMetadataJson(title, parent_resource_id, modified_date, last_viewed_by_me_date, properties), content_type, content_length, local_file_path, callback, progress_callback), has_modified_date_(!modified_date.is_null()), url_generator_(url_generator) {} MultipartUploadNewFileDelegate::~MultipartUploadNewFileDelegate() { } GURL MultipartUploadNewFileDelegate::GetURL() const { return url_generator_.GetMultipartUploadNewFileUrl(has_modified_date_); } net::URLFetcher::RequestType MultipartUploadNewFileDelegate::GetRequestType() const { return net::URLFetcher::POST; } //====================== MultipartUploadExistingFileDelegate =================== MultipartUploadExistingFileDelegate::MultipartUploadExistingFileDelegate( base::SequencedTaskRunner* task_runner, const std::string& title, const std::string& resource_id, const std::string& parent_resource_id, const std::string& content_type, int64_t content_length, const base::Time& modified_date, const base::Time& last_viewed_by_me_date, const base::FilePath& local_file_path, const std::string& etag, const Properties& properties, const DriveApiUrlGenerator& url_generator, const FileResourceCallback& callback, const ProgressCallback& progress_callback) : MultipartUploadRequestBase( task_runner, CreateMultipartUploadMetadataJson(title, parent_resource_id, modified_date, last_viewed_by_me_date, properties), content_type, content_length, local_file_path, callback, progress_callback), resource_id_(resource_id), etag_(etag), has_modified_date_(!modified_date.is_null()), url_generator_(url_generator) {} MultipartUploadExistingFileDelegate::~MultipartUploadExistingFileDelegate() { } std::vector<std::string> MultipartUploadExistingFileDelegate::GetExtraRequestHeaders() const { std::vector<std::string> headers( MultipartUploadRequestBase::GetExtraRequestHeaders()); headers.push_back(util::GenerateIfMatchHeader(etag_)); return headers; } GURL MultipartUploadExistingFileDelegate::GetURL() const { return url_generator_.GetMultipartUploadExistingFileUrl(resource_id_, has_modified_date_); } net::URLFetcher::RequestType MultipartUploadExistingFileDelegate::GetRequestType() const { return net::URLFetcher::PUT; } //========================== DownloadFileRequest ========================== DownloadFileRequest::DownloadFileRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& resource_id, const base::FilePath& output_file_path, const DownloadActionCallback& download_action_callback, const GetContentCallback& get_content_callback, const ProgressCallback& progress_callback) : DownloadFileRequestBase( sender, download_action_callback, get_content_callback, progress_callback, url_generator.GenerateDownloadFileUrl(resource_id), output_file_path) { } DownloadFileRequest::~DownloadFileRequest() { } //========================== PermissionsInsertRequest ========================== PermissionsInsertRequest::PermissionsInsertRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator, const EntryActionCallback& callback) : EntryActionRequest(sender, callback), url_generator_(url_generator), type_(PERMISSION_TYPE_USER), role_(PERMISSION_ROLE_READER) { } PermissionsInsertRequest::~PermissionsInsertRequest() { } GURL PermissionsInsertRequest::GetURL() const { return url_generator_.GetPermissionsInsertUrl(id_); } net::URLFetcher::RequestType PermissionsInsertRequest::GetRequestType() const { return net::URLFetcher::POST; } bool PermissionsInsertRequest::GetContentData(std::string* upload_content_type, std::string* upload_content) { *upload_content_type = util::kContentTypeApplicationJson; base::DictionaryValue root; switch (type_) { case PERMISSION_TYPE_ANYONE: root.SetString("type", "anyone"); break; case PERMISSION_TYPE_DOMAIN: root.SetString("type", "domain"); break; case PERMISSION_TYPE_GROUP: root.SetString("type", "group"); break; case PERMISSION_TYPE_USER: root.SetString("type", "user"); break; } switch (role_) { case PERMISSION_ROLE_OWNER: root.SetString("role", "owner"); break; case PERMISSION_ROLE_READER: root.SetString("role", "reader"); break; case PERMISSION_ROLE_WRITER: root.SetString("role", "writer"); break; case PERMISSION_ROLE_COMMENTER: root.SetString("role", "reader"); { base::ListValue* list = new base::ListValue; list->AppendString("commenter"); root.Set("additionalRoles", list); } break; } root.SetString("value", value_); base::JSONWriter::Write(root, upload_content); return true; } //======================= SingleBatchableDelegateRequest ======================= SingleBatchableDelegateRequest::SingleBatchableDelegateRequest( RequestSender* sender, std::unique_ptr<BatchableDelegate> delegate) : UrlFetchRequestBase(sender), delegate_(std::move(delegate)), weak_ptr_factory_(this) {} SingleBatchableDelegateRequest::~SingleBatchableDelegateRequest() { } GURL SingleBatchableDelegateRequest::GetURL() const { return delegate_->GetURL(); } net::URLFetcher::RequestType SingleBatchableDelegateRequest::GetRequestType() const { return delegate_->GetRequestType(); } std::vector<std::string> SingleBatchableDelegateRequest::GetExtraRequestHeaders() const { return delegate_->GetExtraRequestHeaders(); } void SingleBatchableDelegateRequest::Prepare(const PrepareCallback& callback) { delegate_->Prepare(callback); } bool SingleBatchableDelegateRequest::GetContentData( std::string* upload_content_type, std::string* upload_content) { return delegate_->GetContentData(upload_content_type, upload_content); } void SingleBatchableDelegateRequest::ProcessURLFetchResults( const net::URLFetcher* source) { delegate_->NotifyResult( GetErrorCode(), response_writer()->data(), base::Bind( &SingleBatchableDelegateRequest::OnProcessURLFetchResultsComplete, weak_ptr_factory_.GetWeakPtr())); } void SingleBatchableDelegateRequest::RunCallbackOnPrematureFailure( DriveApiErrorCode code) { delegate_->NotifyError(code); } void SingleBatchableDelegateRequest::OnURLFetchUploadProgress( const net::URLFetcher* source, int64_t current, int64_t total) { delegate_->NotifyUploadProgress(source, current, total); } //========================== BatchUploadRequest ========================== BatchUploadChildEntry::BatchUploadChildEntry(BatchableDelegate* request) : request(request), prepared(false), data_offset(0), data_size(0) { } BatchUploadChildEntry::~BatchUploadChildEntry() { } BatchUploadRequest::BatchUploadRequest( RequestSender* sender, const DriveApiUrlGenerator& url_generator) : UrlFetchRequestBase(sender), sender_(sender), url_generator_(url_generator), committed_(false), last_progress_value_(0), weak_ptr_factory_(this) { } BatchUploadRequest::~BatchUploadRequest() { } void BatchUploadRequest::SetBoundaryForTesting(const std::string& boundary) { boundary_ = boundary; } void BatchUploadRequest::AddRequest(BatchableDelegate* request) { DCHECK(CalledOnValidThread()); DCHECK(request); DCHECK(GetChildEntry(request) == child_requests_.end()); DCHECK(!committed_); child_requests_.push_back(new BatchUploadChildEntry(request)); request->Prepare(base::Bind(&BatchUploadRequest::OnChildRequestPrepared, weak_ptr_factory_.GetWeakPtr(), request)); } void BatchUploadRequest::OnChildRequestPrepared(RequestID request_id, DriveApiErrorCode result) { DCHECK(CalledOnValidThread()); auto const child = GetChildEntry(request_id); DCHECK(child != child_requests_.end()); if (IsSuccessfulDriveApiErrorCode(result)) { (*child)->prepared = true; } else { (*child)->request->NotifyError(result); child_requests_.erase(child); } MayCompletePrepare(); } void BatchUploadRequest::Commit() { DCHECK(CalledOnValidThread()); DCHECK(!committed_); if (child_requests_.empty()) { Cancel(); } else { committed_ = true; MayCompletePrepare(); } } void BatchUploadRequest::Prepare(const PrepareCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK(!callback.is_null()); prepare_callback_ = callback; MayCompletePrepare(); } void BatchUploadRequest::Cancel() { child_requests_.clear(); UrlFetchRequestBase::Cancel(); } // Obtains corresponding child entry of |request_id|. Returns NULL if the // entry is not found. ScopedVector<BatchUploadChildEntry>::iterator BatchUploadRequest::GetChildEntry( RequestID request_id) { for (auto it = child_requests_.begin(); it != child_requests_.end(); ++it) { if ((*it)->request.get() == request_id) return it; } return child_requests_.end(); } void BatchUploadRequest::MayCompletePrepare() { if (!committed_ || prepare_callback_.is_null()) return; for (auto* child : child_requests_) { if (!child->prepared) return; } // Build multipart body here. int64_t total_size = 0; std::vector<ContentTypeAndData> parts; for (auto* child : child_requests_) { std::string type; std::string data; const bool result = child->request->GetContentData(&type, &data); // Upload request must have content data. DCHECK(result); const GURL url = child->request->GetURL(); std::string method; switch (child->request->GetRequestType()) { case net::URLFetcher::POST: method = "POST"; break; case net::URLFetcher::PUT: method = "PUT"; break; default: NOTREACHED(); break; } const std::string header = base::StringPrintf( kBatchUploadRequestFormat, method.c_str(), url.path().c_str(), url_generator_.GetBatchUploadUrl().host().c_str(), type.c_str()); child->data_offset = header.size(); child->data_size = data.size(); total_size += data.size(); parts.push_back(ContentTypeAndData({kHttpContentType, header + data})); } UMA_HISTOGRAM_COUNTS_100(kUMADriveTotalFileCountInBatchUpload, parts.size()); UMA_HISTOGRAM_MEMORY_KB(kUMADriveTotalFileSizeInBatchUpload, total_size / 1024); std::vector<uint64_t> part_data_offset; GenerateMultipartBody(MULTIPART_MIXED, boundary_, parts, &upload_content_, &part_data_offset); DCHECK(part_data_offset.size() == child_requests_.size()); for (size_t i = 0; i < child_requests_.size(); ++i) { child_requests_[i]->data_offset += part_data_offset[i]; } prepare_callback_.Run(HTTP_SUCCESS); } bool BatchUploadRequest::GetContentData(std::string* upload_content_type, std::string* upload_content_data) { upload_content_type->assign(upload_content_.type); upload_content_data->assign(upload_content_.data); return true; } base::WeakPtr<BatchUploadRequest> BatchUploadRequest::GetWeakPtrAsBatchUploadRequest() { return weak_ptr_factory_.GetWeakPtr(); } GURL BatchUploadRequest::GetURL() const { return url_generator_.GetBatchUploadUrl(); } net::URLFetcher::RequestType BatchUploadRequest::GetRequestType() const { return net::URLFetcher::PUT; } std::vector<std::string> BatchUploadRequest::GetExtraRequestHeaders() const { std::vector<std::string> headers; headers.push_back(kBatchUploadHeader); return headers; } void BatchUploadRequest::ProcessURLFetchResults(const net::URLFetcher* source) { // Return the detailed raw HTTP code if the error code is abstracted // DRIVE_OTHER_ERROR. If HTTP connection is failed and the status code is -1, // return network status error. int histogram_error = 0; if (GetErrorCode() != DRIVE_OTHER_ERROR) { histogram_error = GetErrorCode(); } else if (source->GetResponseCode() != -1) { histogram_error = source->GetResponseCode(); } else { histogram_error = source->GetStatus().error(); } UMA_HISTOGRAM_SPARSE_SLOWLY( kUMADriveBatchUploadResponseCode, histogram_error); if (!IsSuccessfulDriveApiErrorCode(GetErrorCode())) { RunCallbackOnPrematureFailure(GetErrorCode()); sender_->RequestFinished(this); return; } std::string content_type; source->GetResponseHeaders()->EnumerateHeader( /* need only first header */ NULL, "Content-Type", &content_type); std::vector<MultipartHttpResponse> parts; if (!ParseMultipartResponse(content_type, response_writer()->data(), &parts) || child_requests_.size() != parts.size()) { RunCallbackOnPrematureFailure(DRIVE_PARSE_ERROR); sender_->RequestFinished(this); return; } for (size_t i = 0; i < parts.size(); ++i) { BatchableDelegate* delegate = child_requests_[i]->request.get(); // Pass ownership of |delegate| so that child_requests_.clear() won't // kill the delegate. It has to be deleted after the notification. delegate->NotifyResult(parts[i].code, parts[i].body, base::Bind(&base::DeletePointer<BatchableDelegate>, child_requests_[i]->request.release())); } child_requests_.clear(); sender_->RequestFinished(this); } void BatchUploadRequest::RunCallbackOnPrematureFailure(DriveApiErrorCode code) { for (auto* child : child_requests_) child->request->NotifyError(code); child_requests_.clear(); } void BatchUploadRequest::OnURLFetchUploadProgress(const net::URLFetcher* source, int64_t current, int64_t total) { for (auto* child : child_requests_) { if (child->data_offset <= current && current <= child->data_offset + child->data_size) { child->request->NotifyUploadProgress(source, current - child->data_offset, child->data_size); } else if (last_progress_value_ < child->data_offset + child->data_size && child->data_offset + child->data_size < current) { child->request->NotifyUploadProgress(source, child->data_size, child->data_size); } } last_progress_value_ = current; } } // namespace drive } // namespace google_apis
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/google_apis/drive/drive_api_requests.cc
C++
gpl-3.0
45,880
using MissionPlanner.Controls; namespace SikRadio { partial class Rssi { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.zedGraphControl1 = new ZedGraph.ZedGraphControl(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.BUT_disconnect = new MyButton(); this.BUT_connect = new MyButton(); this.SuspendLayout(); // // zedGraphControl1 // this.zedGraphControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.zedGraphControl1.Location = new System.Drawing.Point(4, 33); this.zedGraphControl1.Name = "zedGraphControl1"; this.zedGraphControl1.ScrollGrace = 0D; this.zedGraphControl1.ScrollMaxX = 0D; this.zedGraphControl1.ScrollMaxY = 0D; this.zedGraphControl1.ScrollMaxY2 = 0D; this.zedGraphControl1.ScrollMinX = 0D; this.zedGraphControl1.ScrollMinY = 0D; this.zedGraphControl1.ScrollMinY2 = 0D; this.zedGraphControl1.Size = new System.Drawing.Size(485, 353); this.zedGraphControl1.TabIndex = 0; // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // BUT_disconnect // this.BUT_disconnect.Anchor = System.Windows.Forms.AnchorStyles.Top; this.BUT_disconnect.Enabled = false; this.BUT_disconnect.Location = new System.Drawing.Point(250, 4); this.BUT_disconnect.Name = "BUT_disconnect"; this.BUT_disconnect.Size = new System.Drawing.Size(75, 23); this.BUT_disconnect.TabIndex = 2; this.BUT_disconnect.Text = "Disconnect"; this.BUT_disconnect.UseVisualStyleBackColor = true; this.BUT_disconnect.Click += new System.EventHandler(this.BUT_disconnect_Click); // // BUT_connect // this.BUT_connect.Anchor = System.Windows.Forms.AnchorStyles.Top; this.BUT_connect.Location = new System.Drawing.Point(169, 4); this.BUT_connect.Name = "BUT_connect"; this.BUT_connect.Size = new System.Drawing.Size(75, 23); this.BUT_connect.TabIndex = 1; this.BUT_connect.Text = "Connect"; this.BUT_connect.UseVisualStyleBackColor = true; this.BUT_connect.Click += new System.EventHandler(this.BUT_connect_Click); // // Rssi // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.Controls.Add(this.BUT_disconnect); this.Controls.Add(this.BUT_connect); this.Controls.Add(this.zedGraphControl1); this.Name = "Rssi"; this.Size = new System.Drawing.Size(492, 386); this.ResumeLayout(false); } #endregion private ZedGraph.ZedGraphControl zedGraphControl1; private MyButton BUT_connect; private MyButton BUT_disconnect; private System.Windows.Forms.Timer timer1; } }
GeekBoy666/VGCS
SikRadio/Rssi.Designer.cs
C#
gpl-3.0
4,321
<?php /** Copyright 2011-2015 Nick Korbel This file is part of Booked Scheduler 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 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>. */ require_once(ROOT_DIR . 'Domain/namespace.php'); require_once(ROOT_DIR . 'Domain/Access/namespace.php'); require_once(ROOT_DIR . 'lib/Application/Authorization/namespace.php'); require_once(ROOT_DIR . 'lib/Application/Schedule/namespace.php'); require_once(ROOT_DIR . 'lib/Application/Attributes/namespace.php'); require_once(ROOT_DIR . 'lib/Application/Reservation/ReservationComponentBinder.php'); require_once(ROOT_DIR . 'Pages/ReservationPage.php'); interface IReservationComponentInitializer { /** * @abstract * @return int */ public function GetResourceId(); /** * @abstract * @return int */ public function GetScheduleId(); /** * @return Date */ public function GetStartDate(); /** * @return Date */ public function GetEndDate(); /** * @return Date */ public function GetReservationDate(); /** * @abstract * @return int */ public function GetOwnerId(); /** * @abstract * @return string */ public function GetTimezone(); /** * @param Date $startDate * @param Date $endDate * @param $startPeriods array|SchedulePeriod[] * @param $endPeriods array|SchedulePeriod[] */ public function SetDates(Date $startDate, Date $endDate, $startPeriods, $endPeriods); /** * @return UserSession */ public function CurrentUser(); /** * @return ResourceDto */ public function PrimaryResource(); /** * @param $canChangeUser bool */ public function SetCanChangeUser($canChangeUser); /** * @param $reservationUser UserDto */ public function SetReservationUser($reservationUser); /** * @param $showUserDetails bool */ public function ShowUserDetails($showUserDetails); /** * @param $shouldShow bool */ public function SetShowParticipation($shouldShow); /** * @abstract * @param $showReservationDetails bool */ public function ShowReservationDetails($showReservationDetails); /** * @param $resources array|ResourceDto[] */ public function BindAvailableResources($resources); /** * @param $accessories array|AccessoryDto[] */ public function BindAvailableAccessories($accessories); /** * @param $groups ResourceGroupTree */ public function BindResourceGroups($groups); /** * @param $shouldShow bool */ public function ShowAdditionalResources($shouldShow); /** * @param $resource ResourceDto */ public function SetReservationResource($resource); /** * @abstract * @param $attribute CustomAttribute * @param $value mixed */ public function AddAttribute($attribute, $value); /** * @abstract * @param ErrorMessages|int $errorMessageId */ public function RedirectToError($errorMessageId); /** * @abstract * @param bool $isHidden */ public function HideRecurrence($isHidden); /** * @return bool */ public function IsNew(); } abstract class ReservationInitializerBase implements IReservationInitializer, IReservationComponentInitializer { /** * @var ResourceDto */ protected $primaryResource; /** * @var IReservationPage */ protected $basePage; /** * @var IReservationComponentBinder */ protected $userBinder; /** * @var IReservationComponentBinder */ protected $dateBinder; /** * @var IReservationComponentBinder */ protected $resourceBinder; /** * @var IReservationComponentBinder */ protected $attributeBinder; /** * @var int */ protected $currentUserId; /** * @var UserSession */ protected $currentUser; /** * @var array|Attribute[] */ private $customAttributes = array(); /** * @param $page IReservationPage * @param $userBinder IReservationComponentBinder * @param $dateBinder IReservationComponentBinder * @param $resourceBinder IReservationComponentBinder * @param $attributeBinder IReservationComponentBinder * @param $userSession UserSession */ public function __construct( $page, IReservationComponentBinder $userBinder, IReservationComponentBinder $dateBinder, IReservationComponentBinder $resourceBinder, IReservationComponentBinder $attributeBinder, UserSession $userSession ) { $this->basePage = $page; $this->userBinder = $userBinder; $this->dateBinder = $dateBinder; $this->resourceBinder = $resourceBinder; $this->attributeBinder = $attributeBinder; $this->currentUser = $userSession; $this->currentUserId = $this->currentUser->UserId; } public function Initialize() { $requestedScheduleId = $this->GetScheduleId(); $this->basePage->SetScheduleId($requestedScheduleId); $this->BindResourceAndAccessories(); $this->BindDates(); $this->BindUser(); $this->BindAttributes(); } protected function BindUser() { $this->userBinder->Bind($this); } protected function BindResourceAndAccessories() { $this->resourceBinder->Bind($this); } protected function BindDates() { $this->dateBinder->Bind($this); } protected function BindAttributes() { $this->attributeBinder->Bind($this); $this->basePage->SetCustomAttributes($this->customAttributes); } protected function SetSelectedDates(Date $startDate, Date $endDate, $startPeriods, $endPeriods) { $startPeriod = $this->GetStartSlotClosestTo($startPeriods, $startDate); if ($endDate->LessThanOrEqual($startDate)) { $endDate = $endDate->SetTime($startPeriod->End()); } $endPeriod = $this->GetEndSlotClosestTo($endPeriods, $endDate); $this->basePage->SetSelectedStart($startPeriod, $startDate); $this->basePage->SetSelectedEnd($endPeriod, $endDate); } /** * @param SchedulePeriod[] $periods * @param Date $date * @return SchedulePeriod */ private function GetStartSlotClosestTo($periods, $date) { for ($i = 0; $i < count($periods); $i++) { $currentPeriod = $periods[$i]; $periodBegin = $currentPeriod->BeginDate(); if ($currentPeriod->IsReservable() && $periodBegin->CompareTime($date) >= 0) { return $currentPeriod; } } $lastIndex = count($periods) - 1; return $periods[$lastIndex]; } /** * @param SchedulePeriod[] $periods * @param Date $date * @return SchedulePeriod */ private function GetEndSlotClosestTo($periods, $date) { $lastIndex = count($periods) - 1; if ($periods[$lastIndex]->EndDate()->CompareTime($date) == 0) { return $periods[$lastIndex]; } for ($i = 0; $i < count($periods); $i++) { $currentPeriod = $periods[$i]; $periodEnd = $currentPeriod->EndDate(); if ($currentPeriod->IsReservable() && $periodEnd->CompareTime($date) >= 0) { return $currentPeriod; } } return $periods[$lastIndex]; } public function SetDates(Date $startDate, Date $endDate, $startPeriods, $endPeriods) { $this->basePage->BindPeriods($startPeriods, $endPeriods); $this->SetSelectedDates($startDate, $endDate, $startPeriods, $endPeriods); } /** * @return UserSession */ public function CurrentUser() { return $this->currentUser; } /** * @return ResourceDto */ public function PrimaryResource() { return $this->primaryResource; } /** * @param $canChangeUser bool */ public function SetCanChangeUser($canChangeUser) { $this->basePage->SetCanChangeUser($canChangeUser); } /** * @param $reservationUser UserDto */ public function SetReservationUser($reservationUser) { $this->basePage->SetReservationUser($reservationUser); } /** * @param $showUserDetails bool */ public function ShowUserDetails($showUserDetails) { $this->basePage->ShowUserDetails($showUserDetails); } public function SetShowParticipation($shouldShow) { $this->basePage->SetShowParticipation($shouldShow); } /** * @param $showReservationDetails bool */ public function ShowReservationDetails($showReservationDetails) { $this->basePage->ShowReservationDetails($showReservationDetails); } /** * @param $resources array|ResourceDto[] */ public function BindAvailableResources($resources) { $this->basePage->BindAvailableResources($resources); } /** * @param $accessories array|AccessoryDto[] */ public function BindAvailableAccessories($accessories) { $this->basePage->BindAvailableAccessories($accessories); } public function BindResourceGroups($groups) { $this->basePage->BindResourceGroups($groups); } /** * @param $shouldShow bool */ public function ShowAdditionalResources($shouldShow) { $this->basePage->ShowAdditionalResources($shouldShow); } /** * @param $resource ResourceDto */ public function SetReservationResource($resource) { $this->primaryResource = $resource; $this->basePage->SetReservationResource($resource); } /** * @param $attribute CustomAttribute * @param $value mixed */ public function AddAttribute($attribute, $value) { $this->customAttributes[] = new Attribute($attribute, $value); } public function RedirectToError($errorMessageId) { $this->basePage->RedirectToError($errorMessageId); } public function HideRecurrence($isHidden) { $this->basePage->HideRecurrence($isHidden); } public function IsNew() { return true; } }
ajeshgeorge22/booked
lib/Application/Reservation/ReservationInitializerBase.php
PHP
gpl-3.0
10,075
/*========================================================================= Program: ITK-SNAP Module: $RCSfile: ColorLabel.h,v $ Language: C++ Date: $Date: 2008/11/17 19:38:23 $ Version: $Revision: 1.3 $ Copyright (c) 2007 Paul A. Yushkevich This file is part of ITK-SNAP ITK-SNAP 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/>. ----- Copyright (c) 2003 Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __ColorLabel_h_ #define __ColorLabel_h_ #include "SNAPCommon.h" #include "itkTimeStamp.h" #include <assert.h> #include <list> /** * \class ColorLabel * \brief Information about a label used for segmentation. * Color labels used to describe pixels in the segmented * image. These labels correspond to the intensities in the * segmentation image in IRISImageData class */ class ColorLabel { public: // Dummy constructor and destructor (to make gcc happy) ColorLabel() { m_TimeStamp.Modified(); } virtual ~ColorLabel() {} // Copy constructor ColorLabel(const ColorLabel &cl) : m_Label(cl.m_Label), m_Value(cl.m_Value), m_DatabaseId(cl.m_DatabaseId), m_Id(cl.m_Id), m_Visible(cl.m_Visible), m_VisibleIn3D(cl.m_VisibleIn3D), m_UpdateTime(cl.m_UpdateTime), m_Alpha(cl.m_Alpha) { m_RGB[0] = cl.m_RGB[0]; m_RGB[1] = cl.m_RGB[1]; m_RGB[2] = cl.m_RGB[2]; m_TimeStamp = cl.m_TimeStamp; } // Read the Visible attribute irisIsMacro(Visible); // Set the Visible attribute irisSetMacro(Visible,bool); // Read the Valid attribute // irisIsMacro(Valid); // Set the Valid attribute // irisSetMacro(Valid,bool); // Read the DoMesh attribute irisIsMacro(VisibleIn3D); // Set the DoMesh attribute irisSetMacro(VisibleIn3D,bool); // Read the Label attribute virtual const char *GetLabel() const { return m_Label.c_str(); } // Set the Label attribute irisSetMacro(Label,const char *); // Read the Alpha attribute irisGetMacro(Alpha,unsigned char); // Set the Alpha attribute irisSetMacro(Alpha,unsigned char); // Get the value irisGetMacro(Value, LabelType); // Check Opaqueness bool IsOpaque() const { return m_Alpha == 255; } // Read the RGB attributes unsigned char GetRGB(unsigned int index) const { assert(index < 3); return m_RGB[index]; } // Set the RGB attributes void SetRGB(unsigned int index, unsigned char in_Value) { assert(index < 3); m_RGB[index] = in_Value; } // Set all three at once void SetRGB(unsigned char in_Red,unsigned char in_Green,unsigned char in_Blue) { m_RGB[0] = in_Red; m_RGB[1] = in_Green; m_RGB[2] = in_Blue; } // Get the RGB values as a double vector (range 0-1) Vector3d GetRGBAsDoubleVector() const { return Vector3d(m_RGB[0] / 255., m_RGB[1] / 255., m_RGB[2] / 255.); } // Copy RGB into an array void GetRGBVector(unsigned char array[3]) const { array[0] = m_RGB[0]; array[1] = m_RGB[1]; array[2] = m_RGB[2]; } // Copy RGB into an array void SetRGBVector(const unsigned char array[3]) { m_RGB[0] = array[0]; m_RGB[1] = array[1]; m_RGB[2] = array[2]; } // Copy RGB into an array void GetRGBAVector(unsigned char array[4]) const { array[0] = m_RGB[0]; array[1] = m_RGB[1]; array[2] = m_RGB[2]; array[3] = m_Alpha; } // Copy RGB into an array void SetRGBAVector(const unsigned char array[4]) { m_RGB[0] = array[0]; m_RGB[1] = array[1]; m_RGB[2] = array[2]; m_Alpha = array[3]; } // Copy all properties, except for the label id and the valid flag // from one label to the other. This is used to reassign ids to labels // because the labels are in sequential order void SetPropertiesFromColorLabel(const ColorLabel &lSource) { m_VisibleIn3D = lSource.m_VisibleIn3D; m_Visible = lSource.m_Visible; m_Alpha = lSource.m_Alpha; m_Label = lSource.m_Label; m_RGB[0] = lSource.m_RGB[0]; m_RGB[1] = lSource.m_RGB[1]; m_RGB[2] = lSource.m_RGB[2]; } const itk::TimeStamp &GetTimeStamp() const { return m_TimeStamp; } itk::TimeStamp &GetTimeStamp() { return m_TimeStamp; } private: // The descriptive text of the label std::string m_Label; // The intensity assigned to the label in the segmentation image LabelType m_Value; // The ID of the label in some external database. std::string m_DatabaseId; // The internal ID of the label. By default it's equal to the value unsigned int m_Id; // Whether the label is visible in 2D views bool m_Visible; // Whether the mesh for the label is computed bool m_VisibleIn3D; // The system timestamp when the data marked with this label was last updated unsigned long m_UpdateTime; // Whether the label is valid (has been added) // bool m_Valid; // The transparency level of the label unsigned char m_Alpha; // The color of the label unsigned char m_RGB[3]; // A list of labels that contain this label std::list< unsigned int > m_Parents; // A list of labels that this label contains std::list< unsigned int > m_Children; // An itk TimeStamp, allows tracking of changes to the label appearance itk::TimeStamp m_TimeStamp; }; #endif
romangrothausmann/itksnap
Logic/Common/ColorLabel.h
C
gpl-3.0
6,143
/*! * COPYRIGHT NOTICE * Copyright (c) 2013,ɽÍâ¿Æ¼¼ * All rights reserved. * ¼¼ÊõÌÖÂÛ£ºÉ½ÍâÂÛ̳ http://www.vcan123.com * * ³ý×¢Ã÷³ö´¦Í⣬ÒÔÏÂËùÓÐÄÚÈÝ°æȨ¾ùÊôɽÍâ¿Æ¼¼ËùÓУ¬Î´¾­ÔÊÐí£¬²»µÃÓÃÓÚÉÌÒµÓÃ;£¬ * ÐÞ¸ÄÄÚÈÝʱ±ØÐë±£ÁôɽÍâ¿Æ¼¼µÄ°æȨÉùÃ÷¡£ * * @file MK60_adc.c * @brief ADCº¯Êý * @author ɽÍâ¿Æ¼¼ * @version v5.1 * @date 2014-01-16 */ #include "common.h" #include "MK60_adc.h" ADC_MemMapPtr ADCN[2] = {ADC0_BASE_PTR, ADC1_BASE_PTR}; //¶¨ÒåÁ½¸öÖ¸ÕëÊý×é±£´æ ADCN µÄµØÖ· static void adc_start (ADCn_Ch_e, ADC_nbit); //¿ªÊ¼adcת»» /*! * @brief ADC³õʼ»¯ * @param ADCn_Ch_e ADCͨµÀ * @since v5.0 * @note ´Ë³õʼ»¯½öÖ§³ÖÈí¼þ´¥·¢£¬²»ÊÇÿ¸öͨµÀ¶¼Ö§³ÖADC Èí¼þ´¥·¢£¬ ¾ßÌå˵Ã÷¼û ADCn_Ch_e µÄ×¢ÊÍ˵Ã÷ * Sample usage: adc_init (ADC0_SE10 ); //³õʼ»¯ ADC0_SE10 £¬Ê¹Óà PTA7 ¹Ü½Å */ void adc_init(ADCn_Ch_e adcn_ch) { uint8 adcn = adcn_ch >> 5 ; //uint8 ch = adcn_ch & 0x1F; switch(adcn) { case ADC0: /* ADC0 */ SIM_SCGC6 |= (SIM_SCGC6_ADC0_MASK ); //¿ªÆôADC0ʱÖÓ SIM_SOPT7 &= ~(SIM_SOPT7_ADC0ALTTRGEN_MASK | SIM_SOPT7_ADC0PRETRGSEL_MASK); SIM_SOPT7 |= SIM_SOPT7_ADC0TRGSEL(0); break; case ADC1: /* ADC1 */ SIM_SCGC3 |= (SIM_SCGC3_ADC1_MASK ); SIM_SOPT7 &= ~(SIM_SOPT7_ADC1ALTTRGEN_MASK | SIM_SOPT7_ADC1PRETRGSEL_MASK) ; SIM_SOPT7 |= SIM_SOPT7_ADC1TRGSEL(0); break; default: ASSERT(0); } switch(adcn_ch) { case ADC0_SE8: // PTB0 port_init(PTB0, ALT0); break; case ADC0_SE9: // PTB1 port_init(PTB1, ALT0); break; case ADC0_SE10: // PTA7 port_init(PTA7, ALT0); break; case ADC0_SE11: // PTA8 port_init(PTA8, ALT0); break; case ADC0_SE12: // PTB2 port_init(PTB2, ALT0); break; case ADC0_SE13: // PTB3 port_init(PTB3, ALT0); break; case ADC0_SE14: // PTC0 port_init(PTC0, ALT0); break; case ADC0_SE15: // PTC1 port_init(PTC1, ALT0); break; case ADC0_SE17: // PTE24 port_init(PTE24, ALT0); break; case ADC0_SE18: // PTE25 port_init(PTE25, ALT0); break; case ADC0_DP0: case ADC0_DP1: case ADC0_DP3: case ADC0_DM0: // ADC0_DM0 case ADC0_DM1: // ADC0_DM1 case ADC0_SE16: // ADC0_SE16 case Temp0_Sensor: // Temperature Sensor,ÄÚ²¿Î¶ȲâÁ¿£¬¿ÉÓÃADCº¯Êý case VREFH0: // ²Î¿¼¸ßµçѹ,¿ÉÓÃADCº¯Êý ,½á¹ûºãΪ 2^n-1 case VREFL0: // ²Î¿¼µÍµçѹ,¿ÉÓÃADCº¯Êý ,½á¹ûºãΪ 0 break; //Õⲿ·Ö¹Ü½Å²»ÓÃÅäÖø´Óà // ---------------------------------ADC1------------------------- case ADC1_DP0: case ADC1_DP1: case ADC1_DP3: break; case ADC1_SE4a: // PTE0 port_init(PTE0, ALT0); break; case ADC1_SE5a: // PTE1 port_init(PTE1, ALT0); break; case ADC1_SE6a: // PTE2 port_init(PTE2, ALT0); break; case ADC1_SE7a: // PTE3 port_init(PTE3, ALT0); break; case ADC1_SE8: // PTB0 port_init(PTB0, ALT0); break; case ADC1_SE9: // PTB1 port_init(PTB1, ALT0); break; case ADC1_SE10: // PTB4 port_init(PTB4, ALT0); break; case ADC1_SE11: // PTB5 port_init(PTB5, ALT0); break; case ADC1_SE12: // PTB6 port_init(PTB6, ALT0); break; case ADC1_SE13: // PTB7 port_init(PTB7, ALT0); break; case ADC1_SE14: // PTB10 port_init(PTB10, ALT0); break; case ADC1_SE15: // PTB11 port_init(PTB11, ALT0); break; case ADC1_SE17: // PTA17 port_init(PTA17, ALT0); break; case ADC1_SE16: // ADC1_SE16 case VREF_OUTPUT: // VREF Output case ADC1_DM0: // ADC1_DM0 case ADC1_DM1: // ADC1_DM1 case Temp1_Sensor: case VREFH1: // ²Î¿¼¸ßµçѹ,¿ÉÓÃADCº¯Êý ,½á¹ûºãΪ 2^n-1 case VREFL1: // ²Î¿¼µÍµçѹ,¿ÉÓÃADCº¯Êý ,½á¹ûºãΪ 0 break; default: ASSERT(0); //¶ÏÑÔ£¬´«µÝµÄ¹Ü½Å²»Ö§³Ö ADC µ¥¶ËÈí¼þ´¥·¢£¬Çë»» ÆäËû¹Ü½Å break; } } /*! * @brief »ñÈ¡ADC²ÉÑùÖµ(²»Ö§³ÖBͨµÀ) * @param ADCn_Ch_e ADCͨµÀ * @param ADC_nbit ADC¾«¶È£¨ ADC_8bit,ADC_12bit, ADC_10bit, ADC_16bit £© * @return ²ÉÑùÖµ * @since v5.0 * Sample usage: uint16 var = adc_once(ADC0_SE10, ADC_8bit); */ uint16 adc_once(ADCn_Ch_e adcn_ch, ADC_nbit bit) //²É¼¯Ä³Â·Ä£ÄâÁ¿µÄADÖµ { ADCn_e adcn = (ADCn_e)(adcn_ch >> 5) ; uint16 result = 0; adc_start(adcn_ch, bit); //Æô¶¯ADCת»» while (( ADC_SC1_REG(ADCN[adcn], 0 ) & ADC_SC1_COCO_MASK ) != ADC_SC1_COCO_MASK); //Ö»Ö§³Ö AͨµÀ result = ADC_R_REG(ADCN[adcn], 0); ADC_SC1_REG(ADCN[adcn], 0) &= ~ADC_SC1_COCO_MASK; return result; } /*! * @brief Æô¶¯ADCÈí¼þ²ÉÑù(²»Ö§³ÖBͨµÀ) * @param ADCn_Ch_e ADCͨµÀ * @param ADC_nbit ADC¾«¶È£¨ ADC_8bit,ADC_12bit, ADC_10bit, ADC_16bit £© * @since v5.0 * @note ´Ëº¯ÊýÄÚ²¿µ÷Óã¬Æô¶¯ºó¼´¿ÉµÈ´ýÊý¾Ý²É¼¯Íê³É * Sample usage: adc_start(ADC0_SE10, ADC_8bit); */ void adc_start(ADCn_Ch_e adcn_ch, ADC_nbit bit) { ADCn_e adcn = (ADCn_e)(adcn_ch >> 5) ; uint8 ch = (uint8)(adcn_ch & 0x1F); //³õʼ»¯ADCĬÈÏÅäÖà ADC_CFG1_REG(ADCN[adcn]) = (0 //| ADC_CFG1_ADLPC_MASK //ADC¹¦ºÄÅäÖã¬0ΪÕý³£¹¦ºÄ£¬1ΪµÍ¹¦ºÄ | ADC_CFG1_ADIV(2) //ʱÖÓ·ÖƵѡÔñ,·ÖƵϵÊýΪ 2^n,2bit | ADC_CFG1_ADLSMP_MASK //²ÉÑùʱ¼äÅäÖã¬0Ϊ¶Ì²ÉÑùʱ¼ä£¬1 Ϊ³¤²ÉÑùʱ¼ä | ADC_CFG1_MODE(bit) | ADC_CFG1_ADICLK(0) //0Ϊ×ÜÏßʱÖÓ,1Ϊ×ÜÏßʱÖÓ/2,2Ϊ½»ÌæʱÖÓ£¨ALTCLK£©£¬3Ϊ Ò첽ʱÖÓ£¨ADACK£©¡£ ); ADC_CFG2_REG(ADCN[adcn]) = (0 //| ADC_CFG2_MUXSEL_MASK //ADC¸´ÓÃÑ¡Ôñ,0ΪaͨµÀ£¬1ΪbͨµÀ¡£ //| ADC_CFG2_ADACKEN_MASK //Ò첽ʱÖÓÊä³öʹÄÜ,0Ϊ½ûÖ¹£¬1ΪʹÄÜ¡£ | ADC_CFG2_ADHSC_MASK //¸ßËÙÅäÖÃ,0ΪÕý³£×ª»»ÐòÁУ¬1Ϊ¸ßËÙת»»ÐòÁÐ | ADC_CFG2_ADLSTS(0) //³¤²ÉÑùʱ¼äÑ¡Ôñ£¬ADCKΪ4+n¸ö¶îÍâÑ­»·£¬¶îÍâÑ­»·£¬0Ϊ20£¬1Ϊ12£¬2Ϊ6£¬3Ϊ2 ); //дÈë SC1A Æô¶¯×ª»» ADC_SC1_REG(ADCN[adcn], 0 ) = (0 | ADC_SC1_AIEN_MASK // ת»»Íê³ÉÖжÏ,0Ϊ½ûÖ¹£¬1ΪʹÄÜ //| ADC_SC1_DIFF_MASK // ²î·ÖģʽʹÄÜ,0Ϊµ¥¶Ë£¬1Ϊ²î·Ö | ADC_SC1_ADCH( ch ) ); } /*! * @brief Í£Ö¹ADCÈí¼þ²ÉÑù * @param ADCn_e ADCÄ£¿éºÅ£¨ ADC0¡¢ ADC1£© * @since v5.0 * Sample usage: adc_stop(ADC0); */ void adc_stop(ADCn_e adcn) { ADC_SC1_REG(ADCN[adcn], 0) = (0 | ADC_SC1_AIEN_MASK // ת»»Íê³ÉÖжÏ,0Ϊ½ûÖ¹£¬1ΪʹÄÜ //| ADC_SC1_DIFF_MASK // ²î·ÖģʽʹÄÜ,0Ϊµ¥¶Ë£¬1Ϊ²î·Ö | ADC_SC1_ADCH(Module0_Dis) //ÊäÈëͨµÀÑ¡Ôñ,´Ë´¦Ñ¡Ôñ½ûֹͨµÀ ); }
zxc455052/nxp_-
黄叽公队代码/测试程序/mma8452读取测试/Chip/src/MK60_adc.c
C
gpl-3.0
7,596
# Include software raid tools grep -q blocks /proc/mdstat 2>/dev/null || return 0 Log "Software RAID detected. Including mdadm tools." PROGS=( "${PROGS[@]}" mdadm )
phracek/rear
usr/share/rear/prep/GNU/Linux/230_include_md_tools.sh
Shell
gpl-3.0
168
/* * #%~ * Integration of the ProB Solver for the VDM Interpreter * %% * Copyright (C) 2008 - 2014 Overture * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #~% */ package org.overture.interpreter.tests; import java.io.File; import org.overture.test.framework.ConditionalIgnoreMethodRule.IgnoreCondition; public class ProbNotInstalledCondition implements IgnoreCondition { @Override public boolean isIgnored() { String os = System.getProperty("os.name").toLowerCase(); String cli = null; if (os.indexOf("win") >= 0) { cli = "probcli.exe"; } else if (os.indexOf("mac") >= 0 || os.indexOf("linux") >= 0) { cli = "probcli.sh"; } else { return true; } String path = System.getProperty("prob.home"); if (path == null) { path = System.getProperty("user.home") + File.separatorChar + ".prob"; } return !new File(path, cli).exists(); } }
LasseBP/overture
core/modelcheckers/probsolverintegration/src/test/java/org/overture/interpreter/tests/ProbNotInstalledCondition.java
Java
gpl-3.0
1,517
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.daw.operaciones; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.daw.dao.ProyectoDao; import net.daw.helper.Conexion; import net.daw.helper.FilterBean; public class ProyectoGetregisters implements GenericOperation { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String data; try { ArrayList<FilterBean> alFilter = new ArrayList<>(); if (request.getParameter("filter") != null) { if (request.getParameter("filteroperator") != null) { if (request.getParameter("filtervalue") != null) { FilterBean oFilterBean = new FilterBean(); oFilterBean.setFilter(request.getParameter("filter")); oFilterBean.setFilterOperator(request.getParameter("filteroperator")); oFilterBean.setFilterValue(request.getParameter("filtervalue")); oFilterBean.setFilterOrigin("user"); alFilter.add(oFilterBean); } } } if (request.getParameter("systemfilter") != null) { if (request.getParameter("systemfilteroperator") != null) { if (request.getParameter("systemfiltervalue") != null) { FilterBean oFilterBean = new FilterBean(); oFilterBean.setFilter(request.getParameter("systemfilter")); oFilterBean.setFilterOperator(request.getParameter("systemfilteroperator")); oFilterBean.setFilterValue(request.getParameter("systemfiltervalue")); oFilterBean.setFilterOrigin("system"); alFilter.add(oFilterBean); } } } ProyectoDao oProyectoDAO = new ProyectoDao(Conexion.getConection()); int pages = oProyectoDAO.getCount(alFilter); data = "{\"data\":\"" + Integer.toString(pages) + "\"}"; return data; } catch (Exception e) { throw new ServletException("ProyectoGetregistersJson: View Error: " + e.getMessage()); } } }
jpgodesart/pruebaopenshift
src/main/java/net/daw/operaciones/ProyectoGetregisters.java
Java
gpl-3.0
2,569
<!DOCTYPE html> <meta charset="utf-8"/> <meta name="variant" content=""> <meta name="variant" content="?samesite-by-default-cookies.tentative"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/cookies/resources/cookie-helper.sub.js"></script> <script> function create_test(origin, target, expectedStatus, title) { promise_test(t => { var value = "" + Math.random(); return resetSameSiteCookies(origin, value) .then(_ => { return new Promise((resolve, reject) => { var w = window.open(origin + "/cookies/resources/postToParent.py"); var reloaded = false; var msgHandler = e => { try { getSameSiteVerifier()(expectedStatus, value, e.data); } catch (e) { reject(e); } if (reloaded) { window.removeEventListener("message", msgHandler); w.close(); resolve("Popup received the cookie."); } else { reloaded = true; w.postMessage("reload", "*"); } }; window.addEventListener("message", msgHandler); if (!w) reject("Popup could not be opened (did you whitelist the test site in your popup blocker?)."); }); }); }, title); } create_test(ORIGIN, ORIGIN, SameSiteStatus.STRICT, "Reloaded same-host auxiliary navigations are strictly same-site."); create_test(SUBDOMAIN_ORIGIN, SUBDOMAIN_ORIGIN, SameSiteStatus.STRICT, "Reloaded subdomain auxiliary navigations are strictly same-site."); create_test(CROSS_SITE_ORIGIN, CROSS_SITE_ORIGIN, SameSiteStatus.LAX, "Reloaded cross-site auxiliary navigations are laxly same-site"); </script>
ecoal95/servo
tests/wpt/web-platform-tests/cookies/samesite/window-open-reload.html
HTML
mpl-2.0
1,844
var Utils = { convertToRoute: function(str) { str = str || ""; return str.toLowerCase().replace(" ", "-"); }, parseRoute: function(route) { route = route || ""; return route.split("-").map(function(item) { return item.charAt(0).toUpperCase() + item.substr(1).toLowerCase(); }).join(" "); } }; module.exports = Utils;
mozilla/teach.webmaker.org
lib/util.js
JavaScript
mpl-2.0
352
package iso import ( "fmt" "github.com/mitchellh/multistep" parallelscommon "github.com/mitchellh/packer/builder/parallels/common" "github.com/mitchellh/packer/packer" "strconv" ) // This step creates the virtual disk that will be used as the // hard drive for the virtual machine. type stepCreateDisk struct{} func (s *stepCreateDisk) Run(state multistep.StateBag) multistep.StepAction { config := state.Get("config").(*config) driver := state.Get("driver").(parallelscommon.Driver) ui := state.Get("ui").(packer.Ui) vmName := state.Get("vmName").(string) command := []string{ "set", vmName, "--device-set", "hdd0", "--size", strconv.FormatUint(uint64(config.DiskSize), 10), "--iface", config.HardDriveInterface, } ui.Say("Creating hard drive...") err := driver.Prlctl(command...) if err != nil { err := fmt.Errorf("Error creating hard drive: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } return multistep.ActionContinue } func (s *stepCreateDisk) Cleanup(state multistep.StateBag) {}
qur/packer
builder/parallels/iso/step_create_disk.go
GO
mpl-2.0
1,065
// Copyright (C) 2014 The Syncthing Authors. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. package scanner import ( "bytes" "crypto/rand" "fmt" "io" "os" "path/filepath" "runtime" rdebug "runtime/debug" "sort" "sync" "testing" "github.com/d4l3k/messagediff" "github.com/syncthing/syncthing/lib/ignore" "github.com/syncthing/syncthing/lib/osutil" "github.com/syncthing/syncthing/lib/protocol" "github.com/syncthing/syncthing/lib/symlinks" "golang.org/x/text/unicode/norm" ) type testfile struct { name string length int64 hash string } type testfileList []testfile var testdata = testfileList{ {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"}, {"dir1", 128, ""}, {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"}, {"dir2", 128, ""}, {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"}, {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"}, {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"}, } func init() { // This test runs the risk of entering infinite recursion if it fails. // Limit the stack size to 10 megs to crash early in that case instead of // potentially taking down the box... rdebug.SetMaxStack(10 * 1 << 20) } func TestWalkSub(t *testing.T) { ignores := ignore.New(false) err := ignores.Load("testdata/.stignore") if err != nil { t.Fatal(err) } fchan, err := Walk(Config{ Dir: "testdata", Subs: []string{"dir2"}, BlockSize: 128 * 1024, Matcher: ignores, Hashers: 2, }) var files []protocol.FileInfo for f := range fchan { files = append(files, f) } if err != nil { t.Fatal(err) } // The directory contains two files, where one is ignored from a higher // level. We should see only the directory and one of the files. if len(files) != 2 { t.Fatalf("Incorrect length %d != 2", len(files)) } if files[0].Name != "dir2" { t.Errorf("Incorrect file %v != dir2", files[0]) } if files[1].Name != filepath.Join("dir2", "cfile") { t.Errorf("Incorrect file %v != dir2/cfile", files[1]) } } func TestWalk(t *testing.T) { ignores := ignore.New(false) err := ignores.Load("testdata/.stignore") if err != nil { t.Fatal(err) } t.Log(ignores) fchan, err := Walk(Config{ Dir: "testdata", BlockSize: 128 * 1024, Matcher: ignores, Hashers: 2, }) if err != nil { t.Fatal(err) } var tmp []protocol.FileInfo for f := range fchan { tmp = append(tmp, f) } sort.Sort(fileList(tmp)) files := fileList(tmp).testfiles() if diff, equal := messagediff.PrettyDiff(testdata, files); !equal { t.Errorf("Walk returned unexpected data. Diff:\n%s", diff) } } func TestWalkError(t *testing.T) { _, err := Walk(Config{ Dir: "testdata-missing", BlockSize: 128 * 1024, Hashers: 2, }) if err == nil { t.Error("no error from missing directory") } _, err = Walk(Config{ Dir: "testdata/bar", BlockSize: 128 * 1024, }) if err == nil { t.Error("no error from non-directory") } } func TestVerify(t *testing.T) { blocksize := 16 // data should be an even multiple of blocksize long data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e") buf := bytes.NewBuffer(data) progress := newByteCounter() defer progress.Close() blocks, err := Blocks(buf, blocksize, -1, progress) if err != nil { t.Fatal(err) } if exp := len(data) / blocksize; len(blocks) != exp { t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp) } if int64(len(data)) != progress.Total() { t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total()) } buf = bytes.NewBuffer(data) err = Verify(buf, blocksize, blocks) t.Log(err) if err != nil { t.Fatal("Unexpected verify failure", err) } buf = bytes.NewBuffer(append(data, '\n')) err = Verify(buf, blocksize, blocks) t.Log(err) if err == nil { t.Fatal("Unexpected verify success") } buf = bytes.NewBuffer(data[:len(data)-1]) err = Verify(buf, blocksize, blocks) t.Log(err) if err == nil { t.Fatal("Unexpected verify success") } data[42] = 42 buf = bytes.NewBuffer(data) err = Verify(buf, blocksize, blocks) t.Log(err) if err == nil { t.Fatal("Unexpected verify success") } } func TestNormalization(t *testing.T) { if runtime.GOOS == "darwin" { t.Skip("Normalization test not possible on darwin") return } os.RemoveAll("testdata/normalization") defer os.RemoveAll("testdata/normalization") tests := []string{ "0-A", // ASCII A -- accepted "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored "2-\xC3\x85", // NFC 'Å' -- accepted "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8) } numInvalid := 2 if runtime.GOOS == "windows" { // On Windows, in case 5 the character gets replaced with a // replacement character \xEF\xBF\xBD at the point it's written to disk, // which means it suddenly becomes valid (sort of). numInvalid-- } numValid := len(tests) - numInvalid for _, s1 := range tests { // Create a directory for each of the interesting strings above if err := osutil.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil { t.Fatal(err) } for _, s2 := range tests { // Within each dir, create a file with each of the interesting // file names. Ensure that the file doesn't exist when it's // created. This detects and fails if there's file name // normalization stuff at the filesystem level. if fd, err := os.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil { t.Fatal(err) } else { fd.WriteString("test") fd.Close() } } } // We can normalize a directory name, but we can't descend into it in the // same pass due to how filepath.Walk works. So we run the scan twice to // make sure it all gets done. In production, things will be correct // eventually... _, err := walkDir("testdata/normalization") if err != nil { t.Fatal(err) } tmp, err := walkDir("testdata/normalization") if err != nil { t.Fatal(err) } files := fileList(tmp).testfiles() // We should have one file per combination, plus the directories // themselves expectedNum := numValid*numValid + numValid if len(files) != expectedNum { t.Errorf("Expected %d files, got %d", expectedNum, len(files)) } // The file names should all be in NFC form. for _, f := range files { t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name)) if !norm.NFC.IsNormalString(f.name) { t.Errorf("File name %q is not NFC normalized", f.name) } } } func TestIssue1507(t *testing.T) { w := &walker{} c := make(chan protocol.FileInfo, 100) fn := w.walkAndHashFiles(c, c) fn("", nil, protocol.ErrClosed) } func TestWalkSymlink(t *testing.T) { if !symlinks.Supported { t.Skip("skipping unsupported symlink test") return } // Create a folder with a symlink in it os.RemoveAll("_symlinks") defer os.RemoveAll("_symlinks") os.Mkdir("_symlinks", 0755) symlinks.Create("_symlinks/link", "destination", symlinks.TargetUnknown) // Scan it fchan, err := Walk(Config{ Dir: "_symlinks", BlockSize: 128 * 1024, }) if err != nil { t.Fatal(err) } var files []protocol.FileInfo for f := range fchan { files = append(files, f) } // Verify that we got one symlink and with the correct attributes if len(files) != 1 { t.Errorf("expected 1 symlink, not %d", len(files)) } if len(files[0].Blocks) != 0 { t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks)) } if files[0].SymlinkTarget != "destination" { t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget) } } func walkDir(dir string) ([]protocol.FileInfo, error) { fchan, err := Walk(Config{ Dir: dir, BlockSize: 128 * 1024, AutoNormalize: true, Hashers: 2, }) if err != nil { return nil, err } var tmp []protocol.FileInfo for f := range fchan { tmp = append(tmp, f) } sort.Sort(fileList(tmp)) return tmp, nil } type fileList []protocol.FileInfo func (l fileList) Len() int { return len(l) } func (l fileList) Less(a, b int) bool { return l[a].Name < l[b].Name } func (l fileList) Swap(a, b int) { l[a], l[b] = l[b], l[a] } func (l fileList) testfiles() testfileList { testfiles := make(testfileList, len(l)) for i, f := range l { if len(f.Blocks) > 1 { panic("simple test case stuff only supports a single block per file") } testfiles[i] = testfile{name: f.Name, length: f.FileSize()} if len(f.Blocks) == 1 { testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash) } } return testfiles } func (l testfileList) String() string { var b bytes.Buffer b.WriteString("{\n") for _, f := range l { fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash) } b.WriteString("}") return b.String() } func TestSymlinkTypeEqual(t *testing.T) { testcases := []struct { onDiskType symlinks.TargetType fiType protocol.FileInfoType equal bool }{ // File is only equal to file {symlinks.TargetFile, protocol.FileInfoTypeSymlinkFile, true}, {symlinks.TargetFile, protocol.FileInfoTypeSymlinkDirectory, false}, {symlinks.TargetFile, protocol.FileInfoTypeSymlinkUnknown, false}, // Directory is only equal to directory {symlinks.TargetDirectory, protocol.FileInfoTypeSymlinkFile, false}, {symlinks.TargetDirectory, protocol.FileInfoTypeSymlinkDirectory, true}, {symlinks.TargetDirectory, protocol.FileInfoTypeSymlinkUnknown, false}, // Unknown is equal to anything {symlinks.TargetUnknown, protocol.FileInfoTypeSymlinkFile, true}, {symlinks.TargetUnknown, protocol.FileInfoTypeSymlinkDirectory, true}, {symlinks.TargetUnknown, protocol.FileInfoTypeSymlinkUnknown, true}, } for _, tc := range testcases { res := SymlinkTypeEqual(tc.onDiskType, protocol.FileInfo{Type: tc.fiType}) if res != tc.equal { t.Errorf("Incorrect result %v for %v, %v", res, tc.onDiskType, tc.fiType) } } } var initOnce sync.Once const ( testdataSize = 17 << 20 testdataName = "_random.data" ) func BenchmarkHashFile(b *testing.B) { initOnce.Do(initTestFile) b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := HashFile(testdataName, protocol.BlockSize, nil); err != nil { b.Fatal(err) } } b.ReportAllocs() } func initTestFile() { fd, err := os.Create(testdataName) if err != nil { panic(err) } lr := io.LimitReader(rand.Reader, testdataSize) if _, err := io.Copy(fd, lr); err != nil { panic(err) } if err := fd.Close(); err != nil { panic(err) } }
kamadak/syncthing
lib/scanner/walk_test.go
GO
mpl-2.0
11,136
package command import ( "context" "strings" "github.com/hashicorp/packer/packer" "github.com/posener/complete" ) type ValidateCommand struct { Meta } func (c *ValidateCommand) Run(args []string) int { ctx, cleanup := handleTermInterrupt(c.Ui) defer cleanup() cfg, ret := c.ParseArgs(args) if ret != 0 { return ret } return c.RunContext(ctx, cfg) } func (c *ValidateCommand) ParseArgs(args []string) (*ValidateArgs, int) { var cfg ValidateArgs flags := c.Meta.FlagSet("validate", FlagSetBuildFilter|FlagSetVars) flags.Usage = func() { c.Ui.Say(c.Help()) } cfg.AddFlagSets(flags) if err := flags.Parse(args); err != nil { return &cfg, 1 } args = flags.Args() if len(args) != 1 { flags.Usage() return &cfg, 1 } cfg.Path = args[0] return &cfg, 0 } func (c *ValidateCommand) RunContext(ctx context.Context, cla *ValidateArgs) int { packerStarter, ret := c.GetConfig(&cla.MetaArgs) if ret != 0 { return 1 } // If we're only checking syntax, then we're done already if cla.SyntaxOnly { c.Ui.Say("Syntax-only check passed. Everything looks okay.") return 0 } diags := packerStarter.Initialize(packer.InitializeOptions{ SkipDatasourcesExecution: true, }) ret = writeDiags(c.Ui, nil, diags) if ret != 0 { return ret } _, diags = packerStarter.GetBuilds(packer.GetBuildsOptions{ Only: cla.Only, Except: cla.Except, }) fixerDiags := packerStarter.FixConfig(packer.FixConfigOptions{ Mode: packer.Diff, }) diags = append(diags, fixerDiags...) return writeDiags(c.Ui, nil, diags) } func (*ValidateCommand) Help() string { helpText := ` Usage: packer validate [options] TEMPLATE Checks the template is valid by parsing the template and also checking the configuration with the various builders, provisioners, etc. If it is not valid, the errors will be shown and the command will exit with a non-zero exit status. If it is valid, it will exit with a zero exit status. Options: -syntax-only Only check syntax. Do not verify config of the template. -except=foo,bar,baz Validate all builds other than these. -machine-readable Produce machine-readable output. -only=foo,bar,baz Validate only these builds. -var 'key=value' Variable for templates, can be used multiple times. -var-file=path JSON or HCL2 file containing user variables. ` return strings.TrimSpace(helpText) } func (*ValidateCommand) Synopsis() string { return "check that a template is valid" } func (*ValidateCommand) AutocompleteArgs() complete.Predictor { return complete.PredictNothing } func (*ValidateCommand) AutocompleteFlags() complete.Flags { return complete.Flags{ "-syntax-only": complete.PredictNothing, "-except": complete.PredictNothing, "-only": complete.PredictNothing, "-var": complete.PredictNothing, "-machine-readable": complete.PredictNothing, "-var-file": complete.PredictNothing, } }
ricardclau/packer
command/validate.go
GO
mpl-2.0
2,969
/** * AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts **/ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } export class FilterByGroup { constructor(suite, groupPrefix) { _defineProperty(this, "suite", void 0); _defineProperty(this, "groupPrefix", void 0); this.suite = suite; this.groupPrefix = groupPrefix; } matches(spec, testcase) { throw new Error('unimplemented'); } async iterate(loader) { const specs = await loader.listing(this.suite); const entries = []; const suite = this.suite; for (const { path, description } of specs) { if (path.startsWith(this.groupPrefix)) { const isReadme = path === '' || path.endsWith('/'); const spec = isReadme ? { description } : await loader.import(`${suite}/${path}.spec.js`); entries.push({ id: { suite, path }, spec }); } } return entries; } } //# sourceMappingURL=filter_by_group.js.map
nnethercote/servo
tests/wpt/web-platform-tests/webgpu/framework/test_filter/filter_by_group.js
JavaScript
mpl-2.0
1,209
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, v. 2.0. */ function updateCommentPrivacy(checkbox, id) { var comment_elem = document.getElementById('comment_text_'+id).parentNode; if (checkbox.checked) { if (!comment_elem.className.match('bz_private')) { comment_elem.className = comment_elem.className.concat(' bz_private'); } } else { comment_elem.className = comment_elem.className.replace(/(\s*|^)bz_private(\s*|$)/, '$2'); } } /* The functions below expand and collapse comments */ function toggle_comment_display(link, comment_id) { var comment = document.getElementById('comment_text_' + comment_id); var re = new RegExp(/\bcollapsed\b/); if (comment.className.match(re)) expand_comment(link, comment); else collapse_comment(link, comment); } function toggle_all_comments(action) { // If for some given ID the comment doesn't exist, this doesn't mean // there are no more comments, but that the comment is private and // the user is not allowed to view it. var comments = YAHOO.util.Dom.getElementsByClassName('bz_comment_text'); for (var i = 0; i < comments.length; i++) { var comment = comments[i]; if (!comment) continue; var id = comments[i].id.match(/\d*$/); var link = document.getElementById('comment_link_' + id); if (action == 'collapse') collapse_comment(link, comment); else expand_comment(link, comment); } } function collapse_comment(link, comment) { link.innerHTML = "[+]"; YAHOO.util.Dom.addClass(comment, 'collapsed'); } function expand_comment(link, comment) { link.innerHTML = "[&minus;]"; YAHOO.util.Dom.removeClass(comment, 'collapsed'); } function wrapReplyText(text) { // This is -3 to account for "\n> " var maxCol = BUGZILLA.constant.COMMENT_COLS - 3; var text_lines = text.replace(/[\s\n]+$/, '').split("\n"); var wrapped_lines = new Array(); for (var i = 0; i < text_lines.length; i++) { var paragraph = text_lines[i]; // Don't wrap already-quoted text. if (paragraph.indexOf('>') == 0) { wrapped_lines.push('> ' + paragraph); continue; } var replace_lines = new Array(); while (paragraph.length > maxCol) { var testLine = paragraph.substring(0, maxCol); var pos = testLine.search(/\s\S*$/); if (pos < 1) { // Try to find some ASCII punctuation that's reasonable // to break on. var punct = '\\-\\./,!;:'; var punctRe = new RegExp('[' + punct + '][^' + punct + ']+$'); pos = testLine.search(punctRe) + 1; // Try to find some CJK Punctuation that's reasonable // to break on. if (pos == 0) pos = testLine.search(/[\u3000\u3001\u3002\u303E\u303F]/) + 1; // If we can't find any break point, we simply break long // words. This makes long, punctuation-less CJK text wrap, // even if it wraps incorrectly. if (pos == 0) pos = maxCol; } var wrapped_line = paragraph.substring(0, pos); replace_lines.push(wrapped_line); paragraph = paragraph.substring(pos); // Strip whitespace from the start of the line paragraph = paragraph.replace(/^\s+/, ''); } replace_lines.push(paragraph); wrapped_lines.push("> " + replace_lines.join("\n> ")); } return wrapped_lines.join("\n") + "\n\n"; } /* This way, we are sure that browsers which do not support JS * won't display this link */ function addCollapseLink(count, title) { document.write(' <a href="#" class="bz_collapse_comment"' + ' id="comment_link_' + count + '" onclick="toggle_comment_display(this, ' + count + '); return false;" title="' + title + '">[&minus;]<\/a> '); } function goto_add_comments( anchor ){ anchor = (anchor || "add_comment"); // we need this line to expand the comment box document.getElementById('comment').focus(); setTimeout(function(){ document.location.hash = anchor; // firefox doesn't seem to keep focus through the anchor change document.getElementById('comment').focus(); },10); return false; } if (typeof Node == 'undefined') { /* MSIE doesn't define Node, so provide a compatibility object */ window.Node = { TEXT_NODE: 3, ENTITY_REFERENCE_NODE: 5 }; } /* Concatenates all text from element's childNodes. This is used * instead of innerHTML because we want the actual text (and * innerText is non-standard). */ function getText(element) { var child, text = ""; for (var i=0; i < element.childNodes.length; i++) { child = element.childNodes[i]; var type = child.nodeType; if (type == Node.TEXT_NODE || type == Node.ENTITY_REFERENCE_NODE) { text += child.nodeValue; } else { /* recurse into nodes of other types */ text += getText(child); } } return text; }
Sabayon/bugzilla-website
js/comments.js
JavaScript
mpl-2.0
5,546
VERSION = (0, 6, 0) __version__ = '.'.join((str(x) for x in VERSION))
jicksy/oneanddone_test
vendor-local/lib/python/jingo_minify/__init__.py
Python
mpl-2.0
70
<?php /** * Copyright 2015-2017 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with osu!web. If not, see <http://www.gnu.org/licenses/>. */ namespace Tests; use App\Libraries\Payments\CentiliSignature; use Config; use TestCase; class CentiliSignatureTest extends TestCase { public function setUp() { parent::setUp(); Config::set('payments.centili.secret_key', 'magic'); } public function testStringifyInput() { // sorts params and excludes 'sign' static $expected = 'wyzv'; static $params = [ 'cde' => 'z', 'ab' => 'y', 'sign' => 'x', 'aa' => 'w', 'ce' => 'v', ]; $this->assertSame($expected, CentiliSignature::stringifyInput($params)); } public function testCalculateSignature() { static $expected = '98b26bf9ba67820abb3cc76900c0d47fac52ca4b'; static $params = [ 'clientid' => 'test-12345-123', 'country' => 'jp', 'enduserprice' => '900.000', 'event_type' => 'one_off', 'mnocode' => 'THEBEST', 'phone' => 'best@example.org', 'revenue' => '12.3456', 'revenuecurrency' => 'USD', 'service' => 'adc38aea0cf18391a31e83f0b8a88286', 'sign' => '98b26bf9ba67820abb3cc76900c0d47fac52ca4b', 'status' => 'success', 'transactionid' => '111222333444', ]; $signature = CentiliSignature::calculateSignature($params); $this->assertSame($expected, $signature); } }
Nekonyx/osu-web
tests/Libraries/Payments/CentiliSignatureTest.php
PHP
agpl-3.0
2,233
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\BackgroundJob; use OCP\ILogger; /** * Class QueuedJob * * create a background job that is to be executed at an interval * * @package OC\BackgroundJob */ abstract class TimedJob extends Job { protected $interval = 0; /** * set the interval for the job * * @param int $interval */ public function setInterval($interval) { $this->interval = $interval; } /** * run the job if * * @param JobList $jobList * @param ILogger|null $logger */ public function execute($jobList, ILogger $logger = null) { if ((time() - $this->lastRun) > $this->interval) { parent::execute($jobList, $logger); } } }
michaelletzgus/nextcloud-server
lib/private/BackgroundJob/TimedJob.php
PHP
agpl-3.0
1,487
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "UdpIODevice.h" #include <algorithm> UdpIODevice::UdpIODevice(QObject *parent) : QUdpSocket(parent) { // this might cause data to be available only after a second readyRead() signal connect(this, &QUdpSocket::readyRead, this, &UdpIODevice::_readAvailableData); } bool UdpIODevice::canReadLine() const { return _buffer.indexOf('\n') > -1; } qint64 UdpIODevice::readLineData(char *data, qint64 maxSize) { int length = _buffer.indexOf('\n') + 1; // add 1 to include the '\n' if (length == 0) { return 0; } length = std::min(length, static_cast<int>(maxSize)); // copy lines to output std::copy(_buffer.data(), _buffer.data() + length, data); // trim buffer to remove consumed line _buffer = _buffer.right(_buffer.size() - length); // return number of bytes read return length; } void UdpIODevice::_readAvailableData() { while (hasPendingDatagrams()) { int previousSize = _buffer.size(); _buffer.resize(static_cast<int>(_buffer.size() + pendingDatagramSize())); readDatagram((_buffer.data() + previousSize), pendingDatagramSize()); } }
Hunter522/qgroundcontrol
src/comm/UdpIODevice.cc
C++
agpl-3.0
1,497
# # Copyright (C) 2016 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') require_dependency "lti/membership_service/course_group_collator" module Lti::MembershipService describe CourseGroupCollator do context 'course with lots of groups' do before(:once) do course_with_teacher @group_category = @course.group_categories.create!(name: 'Membership') (0..100).each do |n| @course.groups.create!(name: "Group #{n}", group_category: @group_category) end end describe '#initialize' do it 'sets sane defaults when no options are set' do collator = CourseGroupCollator.new(@course) # expect(collator.role).to eq(IMS::LIS::ContextType::URNs::Group) expect(collator.per_page).to eq(Api.per_page) expect(collator.page).to eq(0) end it 'handles negative values for :page option' do opts = { page: -1 } collator = CourseGroupCollator.new(@course, opts) expect(collator.page).to eq(0) end it 'handles negative values for :per_page option' do opts = { per_page: -1 } collator = CourseGroupCollator.new(@course, opts) expect(collator.per_page).to eq(Api.per_page) end it 'handles values for :per_page option that exceed per page max' do opts = { per_page: Api.max_per_page + 1 } collator = CourseGroupCollator.new(@course, opts) expect(collator.per_page).to eq(Api.max_per_page) end it 'generates a list of IMS::LTI::Models::Membership objects' do collator = CourseGroupCollator.new(@course) @teacher.reload memberships = collator.memberships membership = memberships[0] expect(memberships.size).to eq(10) expect(membership.status).to eq(IMS::LIS::Statuses::SimpleNames::Active) expect(membership.role).to match_array([IMS::LIS::ContextType::URNs::Group]) expect(membership.member.name).to eq("Group 0") end end describe '#context' do it 'returns a course for the context' do collator = CourseGroupCollator.new(@course) expect(collator.context).to eq(@course) end end context 'pagination' do describe '#memberships' do it 'returns the number of memberships specified by the per_page params' do Api.stubs(:per_page).returns(1) collator = CourseGroupCollator.new(@course, per_page: 1, page: 1) expect(collator.memberships.size).to eq(1) collator = CourseGroupCollator.new(@course, per_page: 3, page: 1) expect(collator.memberships.size).to eq(3) end end describe '#next_page?' do it 'returns true when there is an additional page of results' do collator = CourseGroupCollator.new(@course, page: 1) expect(collator.next_page?).to eq(true) end it 'returns false when there are no more pages' do collator = CourseGroupCollator.new(@course, page: 11) expect(collator.next_page?).to eq(false) end end end end end end
matematikk-mooc/canvas-lms
spec/lib/lti/membership_service/course_group_collator_spec.rb
Ruby
agpl-3.0
3,984
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Rgaa30 Test.1.7.3 NA 01</title> </head> <body> <div> <h1>Rgaa30 Test.1.7.3 NA 01</h1> <div class="test-detail" lang="fr"> Chaque image embarquée (balise <code>embed</code> avec l&apos;attribut <code>type=&quot;image/...&quot;</code>) ayant une <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mDescDetaillee">description détaillée</a> vérifie-t-elle une de ces conditions ? <ul class="ssTests"> <li> La <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mDescDetaillee">description détaillée</a> adjacente à l&apos;image embarquée est pertinente</li> <li> La <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mDescDetaillee">description détaillée</a> via un <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#mLienAdj">lien adjacent</a> est pertinente</li> </ul> </div> <div class="testcase"> </div> <div class="test-explanation"> NA : The html element implied by the test is not present on the page </div> </div> </body> </html>
Asqatasun/Asqatasun
rules/rules-rgaa3.0/src/test/resources/testcases/rgaa30/Rgaa30Rule010703/Rgaa30.Test.01.07.03-4NA-01.html
HTML
agpl-3.0
1,582
// Generated by CoffeeScript 1.9.3 var Client, Device, ds, fs, ref; Client = require("request-json").JsonClient; fs = require('fs'); Device = require('../models/device'); ds = new Client("http://localhost:9101/"); if ((ref = process.env.NODE_ENV) === 'test' || ref === 'production') { ds.setBasicAuth(process.env.NAME, process.env.TOKEN); } module.exports = { devices: function(req, res, next) { return Device.all(function(err, devices) { if (err) { return next(err); } else { return res.send({ rows: devices }); } }); }, remove: function(req, res, next) { var id; id = req.params.deviceid; return Device.find(id, function(err, device) { if (err != null) { return next(err); } else { return ds.del("access/" + id + "/", function(err, response, body) { if (err) { log.error(err); } return device.destroy(function(err) { err = err || body.error; if (err != null) { return next(err); } else { return res.send(200, { success: true }); } }); }); } }); } };
Gara64/cozy-home
build/server/controllers/devices.js
JavaScript
agpl-3.0
1,244
import { useBackend, useLocalState } from '../backend'; import { Box, Button, LabeledList, NoticeBox, Section, Stack, Tabs } from '../components'; import { Window } from '../layouts'; type PaiCardData = { candidates: Candidate[]; pai: Pai; }; type Candidate = { comments: string; description: string; key: string; name: string; }; type Pai = { can_holo: number; dna: string; emagged: number; laws: string; master: string; name: string; transmit: number; receive: number; }; export const PaiCard = (_, context) => { const { data } = useBackend<PaiCardData>(context); const { pai } = data; return ( <Window width={400} height={400} title="pAI Options Menu"> <Window.Content>{!pai ? <PaiDownload /> : <PaiOptions />}</Window.Content> </Window> ); }; /** Gives a list of candidates as cards */ const PaiDownload = (_, context) => { const { act, data } = useBackend<PaiCardData>(context); const { candidates = [] } = data; return ( <Section buttons={ <Button icon="concierge-bell" onClick={() => act('request')} tooltip="Request candidates."> Request </Button> } fill scrollable title="Viewing pAI Candidates"> {!candidates.length ? ( <NoticeBox>None found!</NoticeBox> ) : ( <Stack fill vertical> {candidates.map((candidate, index) => { return ( <Stack.Item key={index}> <CandidateDisplay candidate={candidate} /> </Stack.Item> ); })} </Stack> )} </Section> ); }; /** Candidate card: Individual. Since this info is refreshing, * had to make the comments and descriptions a separate tab. * In longer entries, it is much more readable. */ const CandidateDisplay = (props, context) => { const [tab, setTab] = useLocalState(context, 'tab', 'description'); const { candidate } = props; const { comments, description, name } = candidate; const onTabClickHandler = (tab: string) => { setTab(tab); }; return ( <Box style={{ 'background': '#111111', 'border': '1px solid #4972a1', 'border-radius': '5px', 'padding': '1rem', }}> <Section buttons={ <CandidateTabs candidate={candidate} onTabClick={onTabClickHandler} tab={tab} /> } fill height={12} scrollable title="Candidate"> <Box color="green" fontSize="16px"> Name: {name || 'Randomized Name'} </Box> {tab === 'description' ? (`Description: ${description.length && description || "None"}`) : (`OOC Comments: ${comments.length && comments || "None"}`)} </Section> </Box> ); }; /** Tabs for the candidate */ const CandidateTabs = (props, context) => { const { act } = useBackend<PaiCardData>(context); const { candidate, onTabClick, tab } = props; const { key } = candidate; return ( <Stack> <Stack.Item> <Tabs> <Tabs.Tab onClick={() => { onTabClick('description'); }} selected={tab === 'description'}> Description </Tabs.Tab> <Tabs.Tab onClick={() => { onTabClick('comments'); }} selected={tab === 'comments'}> OOC </Tabs.Tab> </Tabs> </Stack.Item> <Stack.Item> <Button icon="download" onClick={() => act('download', { key })} tooltip="Accepts this pAI candidate."> Download </Button> </Stack.Item> </Stack> ); }; /** Once a pAI has been loaded, you can alter its settings here */ const PaiOptions = (_, context) => { const { act, data } = useBackend<PaiCardData>(context); const { pai } = data; const { can_holo, dna, emagged, laws, master, name, transmit, receive } = pai; return ( <Section fill scrollable title={name}> <LabeledList> <LabeledList.Item label="Master"> {master || ( <Button icon="dna" onClick={() => act('set_dna')}> Imprint </Button> )} </LabeledList.Item> {!!master && <LabeledList.Item label="DNA">{dna}</LabeledList.Item>} <LabeledList.Item label="Laws">{laws}</LabeledList.Item> <LabeledList.Item label="Holoform"> <Button icon={can_holo ? 'toggle-on' : 'toggle-off'} onClick={() => act('toggle_holo')} selected={can_holo}> Toggle </Button> </LabeledList.Item> <LabeledList.Item label="Transmit"> <Button icon={transmit ? 'toggle-on' : 'toggle-off'} onClick={() => act('toggle_radio', { option: 'transmit' })} selected={transmit}> Toggle </Button> </LabeledList.Item> <LabeledList.Item label="Receive"> <Button icon={receive ? 'toggle-on' : 'toggle-off'} onClick={() => act('toggle_radio', { option: 'receive' })} selected={receive}> Toggle </Button> </LabeledList.Item> <LabeledList.Item label="Troubleshoot"> <Button icon="comment" onClick={() => act('fix_speech')}> Fix Speech </Button> <Button icon="edit" onClick={() => act('set_laws')}> Set Laws </Button> </LabeledList.Item> <LabeledList.Item label="Personality"> <Button icon="trash" onClick={() => act('wipe_pai')}> Erase </Button> </LabeledList.Item> </LabeledList> {!!emagged && ( <Button color="bad" disabled icon="bug" mt={1}> Malicious Software Detected </Button> )} </Section> ); };
Bawhoppen/-tg-station
tgui/packages/tgui/interfaces/PaiCard.tsx
TypeScript
agpl-3.0
5,965
# # Copyright (C) 2015 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. require File.expand_path(File.dirname(__FILE__) + '/common') require File.expand_path(File.dirname(__FILE__) + '/helpers/groups_common') describe "student groups" do include_context "in-process server selenium tests" include GroupsCommon let(:group_name){ 'Windfury' } let(:group_category_name){ 'cat1' } context "As a teacher" do before(:each) do course_with_teacher_logged_in end it "if there are no student groups, there should not be a student groups tab", priority:"2", test_id: 182050 do get "/courses/#{@course.id}/users" expect(f(".ui-tabs-nav")).not_to contain_link("Student Groups") end it "if there are student groups, there should be a student groups tab", priority:"2", test_id: 182051 do create_student_group_as_a_teacher(group_name) get "/courses/#{@course.id}/users" expect(f(".ui-tabs-nav")).to contain_link("Student Groups") end context "with a student group created" do let(:students_in_group){ 4 } before(:each) do create_student_group_as_a_teacher(group_name, (students_in_group-1)) get("/courses/#{@course.id}/groups") end it "should have warning text", priority: "1", test_id: 182055 do expect(f(".alert")).to include_text("These groups are self-organized by students") end it "list student groups" do expect(f(".group-name")).to include_text(group_name.to_s) end it "have correct student count", priority: "1", test_id: 182059 do expect(f(".group")).to include_text("#{students_in_group} students") end it "teacher can delete a student group", priority: "1", test_id: 182060 do skip_if_safari(:alert) expect(f(".group-name")).to include_text(group_name.to_s) delete_group expect(f("#content")).not_to contain_css(".group-name") end it "should list all students in the student group", priority: "1", test_id: 182061 do # expand group f(".group-name").click wait_for_animations # verify each student is in the group expected_students = ["Test Student 1","Test Student 2","Test Student 3","Test Student 4"] users = f("[data-view=groupUsers]") expected_students.each do |student| expect(users).to include_text(student.to_s) end end it "should set a student as a group leader", priority: "1", test_id: 184461 do # expand group f(".group-name").click wait_for_animations # Sets user as group leader f('.group-user-actions').click wait_for_ajaximations fj('.set-as-leader:visible').click wait_for_ajaximations # Looks for student to have a group leader icon expect(f('.group-leader .icon-user')).to be_displayed # Verifies group leader silhouette and leader's name appear in the group header expect(f('.span3.ellipsis.group-leader')).to be_displayed expect(f('.span3.ellipsis.group-leader')).to include_text("Test Student 1") end end end end
djbender/canvas-lms
spec/selenium/groups_student_as_teacher_spec.rb
Ruby
agpl-3.0
3,776
# frozen_string_literal: true module Decidim module Assemblies module AdminLog module ValueTypes # This class presents the given value as a user role. Check # the `DefaultPresenter` for more info on how value # presenters work. class RolePresenter < Decidim::Log::ValueTypes::DefaultPresenter # Public: Presents the value as a user role. # # Returns an HTML-safe String. def present return if value.blank? h.t(value, scope: "decidim.admin.models.assembly_user_role.roles", default: value) end end end end end end
AjuntamentdeBarcelona/decidim
decidim-assemblies/app/presenters/decidim/assemblies/admin_log/value_types/role_presenter.rb
Ruby
agpl-3.0
653
module ImageablesHelper def can_destroy_image?(imageable) imageable.image.present? && can?(:destroy, imageable.image) end def imageable_class(imageable) imageable.class.name.parameterize('_') end def imageable_max_file_size bytes_to_megabytes(Image::MAX_IMAGE_SIZE) end def bytes_to_megabytes(bytes) bytes / Numeric::MEGABYTE end def imageable_accepted_content_types Image::ACCEPTED_CONTENT_TYPE end def imageable_accepted_content_types_extensions Image::ACCEPTED_CONTENT_TYPE .collect{ |content_type| ".#{content_type.split('/').last}" } .join(",") end def imageable_humanized_accepted_content_types Image::ACCEPTED_CONTENT_TYPE .collect{ |content_type| content_type.split("/").last } .join(", ") end def imageables_note(_imageable) t "images.form.note", accepted_content_types: imageable_humanized_accepted_content_types, max_file_size: imageable_max_file_size end end
CDJ11/CDJ
app/helpers/imageables_helper.rb
Ruby
agpl-3.0
994
<?php declare(strict_types=1); /* * This file is part of the Superdesk Web Publisher Core Bundle. * * Copyright 2019 Sourcefabric z.ú. and contributors. * * For the full copyright and license information, please see the * AUTHORS and LICENSE files distributed with this source code. * * @copyright 2019 Sourcefabric z.ú * @license http://www.superdesk.org/license */ namespace SWP\Bundle\CoreBundle\Repository; use Doctrine\ORM\QueryBuilder; use SWP\Bundle\BridgeBundle\Doctrine\ORM\PackageRepository as BasePackageRepository; use SWP\Component\Common\Criteria\Criteria; class PackageRepository extends BasePackageRepository implements PackageRepositoryInterface { public function applyCriteria(QueryBuilder $queryBuilder, Criteria $criteria, string $alias) { if ($criteria->has('authors')) { $queryBuilder->leftJoin($alias.'.authors', 'au'); $orX = $queryBuilder->expr()->orX(); foreach ((array) $criteria->get('authors') as $value) { $orX->add($queryBuilder->expr()->eq('au.name', $queryBuilder->expr()->literal($value))); } $queryBuilder->andWhere($orX); $criteria->remove('authors'); } if ($criteria->has('article-body-content')) { $value = $criteria->get('article-body-content'); $queryBuilder->leftJoin($alias.'.articles', 'a'); $orX = $queryBuilder->expr()->orX(); $orX->add($queryBuilder->expr()->like('a.body', $queryBuilder->expr()->literal('%'.$value.'%'))); $orX->add($queryBuilder->expr()->like('a.lead', $queryBuilder->expr()->literal('%'.$value.'%'))); $queryBuilder->andWhere($orX); $criteria->remove('article-body-content'); } if ($criteria->has('statuses')) { $orX = $queryBuilder->expr()->orX(); foreach ((array) $criteria->get('statuses') as $value) { $orX->add($queryBuilder->expr()->eq($alias.'.status', $queryBuilder->expr()->literal($value))); } $queryBuilder->andWhere($orX); $criteria->remove('statuses'); } parent::applyCriteria($queryBuilder, $criteria, $alias); } }
takeit/web-publisher
src/SWP/Bundle/CoreBundle/Repository/PackageRepository.php
PHP
agpl-3.0
2,235
require "rubygems" require "bundler/setup" require "minitest/unit" require "mocha/setup" require "active_record" require 'active_support/core_ext/time/conversions' if ENV["COVERAGE"] require 'simplecov' SimpleCov.start do add_filter "test/" add_filter "friendly_id/migration" end end require "friendly_id" # If you want to see the ActiveRecord log, invoke the tests using `rake test LOG=true` if ENV["LOG"] require "logger" ActiveRecord::Base.logger = Logger.new($stdout) end module FriendlyId module Test def self.included(base) MiniTest::Unit.autorun end def transaction ActiveRecord::Base.transaction { yield ; raise ActiveRecord::Rollback } end def with_instance_of(*args) model_class = args.shift args[0] ||= {:name => "a b c"} transaction { yield model_class.create!(*args) } end module Database extend self def connect version = ActiveRecord::VERSION::STRING driver = FriendlyId::Test::Database.driver engine = RUBY_ENGINE rescue "ruby" ActiveRecord::Base.establish_connection config[driver] message = "Using #{engine} #{RUBY_VERSION} AR #{version} with #{driver}" puts "-" * 72 if in_memory? ActiveRecord::Migration.verbose = false Schema.up puts "#{message} (in-memory)" else puts message end end def config @config ||= YAML::load(File.open(File.expand_path("../databases.yml", __FILE__))) end def driver (ENV["DB"] or "sqlite3").downcase end def in_memory? config[driver]["database"] == ":memory:" end end end end class Module def test(name, &block) define_method("test_#{name.gsub(/[^a-z0-9']/i, "_")}".to_sym, &block) end end require "schema" require "shared" FriendlyId::Test::Database.connect at_exit {ActiveRecord::Base.connection.disconnect!}
BibNumUMontreal/DMPonline_v4
vendor/ruby/2.1.0/gems/friendly_id-4.0.10.1/test/helper.rb
Ruby
agpl-3.0
1,960
define(['backbone', 'jquery', 'underscore', 'js/common_helpers/ajax_helpers', 'js/common_helpers/template_helpers', 'js/spec/student_account/helpers', 'js/spec/student_profile/helpers', 'js/views/fields', 'js/student_account/models/user_account_model', 'js/student_account/models/user_preferences_model', 'js/student_profile/views/learner_profile_view', 'js/student_profile/views/learner_profile_fields', 'js/student_profile/views/learner_profile_factory', 'js/views/message_banner' ], function (Backbone, $, _, AjaxHelpers, TemplateHelpers, Helpers, LearnerProfileHelpers, FieldViews, UserAccountModel, UserPreferencesModel, LearnerProfileView, LearnerProfileFields, LearnerProfilePage) { 'use strict'; describe("edx.user.LearnerProfileFactory", function () { var requests; beforeEach(function () { loadFixtures('js/fixtures/student_profile/student_profile.html'); TemplateHelpers.installTemplate('templates/fields/field_readonly'); TemplateHelpers.installTemplate('templates/fields/field_dropdown'); TemplateHelpers.installTemplate('templates/fields/field_textarea'); TemplateHelpers.installTemplate('templates/fields/field_image'); TemplateHelpers.installTemplate('templates/fields/message_banner'); TemplateHelpers.installTemplate('templates/student_profile/learner_profile'); }); var createProfilePage = function(ownProfile, options) { return new LearnerProfilePage({ 'accounts_api_url': Helpers.USER_ACCOUNTS_API_URL, 'preferences_api_url': Helpers.USER_PREFERENCES_API_URL, 'own_profile': ownProfile, 'account_settings_page_url': Helpers.USER_ACCOUNTS_API_URL, 'country_options': Helpers.FIELD_OPTIONS, 'language_options': Helpers.FIELD_OPTIONS, 'has_preferences_access': true, 'profile_image_max_bytes': Helpers.IMAGE_MAX_BYTES, 'profile_image_min_bytes': Helpers.IMAGE_MIN_BYTES, 'profile_image_upload_url': Helpers.IMAGE_UPLOAD_API_URL, 'profile_image_remove_url': Helpers.IMAGE_REMOVE_API_URL, 'default_visibility': 'all_users', 'platform_name': 'edX', 'account_settings_data': Helpers.createAccountSettingsData(options), 'preferences_data': Helpers.createUserPreferencesData() }); }; it("renders the full profile after data is successfully fetched", function() { requests = AjaxHelpers.requests(this); var context = createProfilePage(true), learnerProfileView = context.learnerProfileView; AjaxHelpers.respondWithJson(requests, Helpers.createAccountSettingsData()); AjaxHelpers.respondWithJson(requests, Helpers.createUserPreferencesData()); // sets the profile for full view. context.accountPreferencesModel.set({account_privacy: 'all_users'}); LearnerProfileHelpers.expectProfileSectionsAndFieldsToBeRendered(learnerProfileView, false); }); it("renders the limited profile for undefined 'year_of_birth'", function() { var context = createProfilePage(true, {year_of_birth: '', requires_parental_consent: true}), learnerProfileView = context.learnerProfileView; LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView); }); it("renders the limited profile for under 13 users", function() { var context = createProfilePage( true, {year_of_birth: new Date().getFullYear() - 10, requires_parental_consent: true} ); var learnerProfileView = context.learnerProfileView; LearnerProfileHelpers.expectLimitedProfileSectionsAndFieldsToBeRendered(learnerProfileView); }); }); });
antonve/s4-project-mooc
lms/static/js/spec/student_profile/learner_profile_factory_spec.js
JavaScript
agpl-3.0
4,321
#pragma once // MESSAGE BATTERY2 PACKING #define MAVLINK_MSG_ID_BATTERY2 181 typedef struct __mavlink_battery2_t { uint16_t voltage; /*< [mV] Voltage.*/ int16_t current_battery; /*< [cA] Battery current, -1: autopilot does not measure the current.*/ } mavlink_battery2_t; #define MAVLINK_MSG_ID_BATTERY2_LEN 4 #define MAVLINK_MSG_ID_BATTERY2_MIN_LEN 4 #define MAVLINK_MSG_ID_181_LEN 4 #define MAVLINK_MSG_ID_181_MIN_LEN 4 #define MAVLINK_MSG_ID_BATTERY2_CRC 174 #define MAVLINK_MSG_ID_181_CRC 174 #if MAVLINK_COMMAND_24BIT #define MAVLINK_MESSAGE_INFO_BATTERY2 { \ 181, \ "BATTERY2", \ 2, \ { { "voltage", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_battery2_t, voltage) }, \ { "current_battery", NULL, MAVLINK_TYPE_INT16_T, 0, 2, offsetof(mavlink_battery2_t, current_battery) }, \ } \ } #else #define MAVLINK_MESSAGE_INFO_BATTERY2 { \ "BATTERY2", \ 2, \ { { "voltage", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_battery2_t, voltage) }, \ { "current_battery", NULL, MAVLINK_TYPE_INT16_T, 0, 2, offsetof(mavlink_battery2_t, current_battery) }, \ } \ } #endif /** * @brief Pack a battery2 message * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * * @param voltage [mV] Voltage. * @param current_battery [cA] Battery current, -1: autopilot does not measure the current. * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_battery2_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, uint16_t voltage, int16_t current_battery) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_BATTERY2_LEN]; _mav_put_uint16_t(buf, 0, voltage); _mav_put_int16_t(buf, 2, current_battery); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_BATTERY2_LEN); #else mavlink_battery2_t packet; packet.voltage = voltage; packet.current_battery = current_battery; memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_BATTERY2_LEN); #endif msg->msgid = MAVLINK_MSG_ID_BATTERY2; return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); } /** * @brief Pack a battery2 message on a channel * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into * @param voltage [mV] Voltage. * @param current_battery [cA] Battery current, -1: autopilot does not measure the current. * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_battery2_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, uint16_t voltage,int16_t current_battery) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_BATTERY2_LEN]; _mav_put_uint16_t(buf, 0, voltage); _mav_put_int16_t(buf, 2, current_battery); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_BATTERY2_LEN); #else mavlink_battery2_t packet; packet.voltage = voltage; packet.current_battery = current_battery; memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_BATTERY2_LEN); #endif msg->msgid = MAVLINK_MSG_ID_BATTERY2; return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); } /** * @brief Encode a battery2 struct * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * @param battery2 C-struct to read the message contents from */ static inline uint16_t mavlink_msg_battery2_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_battery2_t* battery2) { return mavlink_msg_battery2_pack(system_id, component_id, msg, battery2->voltage, battery2->current_battery); } /** * @brief Encode a battery2 struct on a channel * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into * @param battery2 C-struct to read the message contents from */ static inline uint16_t mavlink_msg_battery2_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_battery2_t* battery2) { return mavlink_msg_battery2_pack_chan(system_id, component_id, chan, msg, battery2->voltage, battery2->current_battery); } /** * @brief Send a battery2 message * @param chan MAVLink channel to send the message * * @param voltage [mV] Voltage. * @param current_battery [cA] Battery current, -1: autopilot does not measure the current. */ #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS static inline void mavlink_msg_battery2_send(mavlink_channel_t chan, uint16_t voltage, int16_t current_battery) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_BATTERY2_LEN]; _mav_put_uint16_t(buf, 0, voltage); _mav_put_int16_t(buf, 2, current_battery); _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_BATTERY2, buf, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); #else mavlink_battery2_t packet; packet.voltage = voltage; packet.current_battery = current_battery; _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_BATTERY2, (const char *)&packet, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); #endif } /** * @brief Send a battery2 message * @param chan MAVLink channel to send the message * @param struct The MAVLink struct to serialize */ static inline void mavlink_msg_battery2_send_struct(mavlink_channel_t chan, const mavlink_battery2_t* battery2) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS mavlink_msg_battery2_send(chan, battery2->voltage, battery2->current_battery); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_BATTERY2, (const char *)battery2, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); #endif } #if MAVLINK_MSG_ID_BATTERY2_LEN <= MAVLINK_MAX_PAYLOAD_LEN /* This varient of _send() can be used to save stack space by re-using memory from the receive buffer. The caller provides a mavlink_message_t which is the size of a full mavlink message. This is usually the receive buffer for the channel, and allows a reply to an incoming message with minimum stack space usage. */ static inline void mavlink_msg_battery2_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint16_t voltage, int16_t current_battery) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char *buf = (char *)msgbuf; _mav_put_uint16_t(buf, 0, voltage); _mav_put_int16_t(buf, 2, current_battery); _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_BATTERY2, buf, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); #else mavlink_battery2_t *packet = (mavlink_battery2_t *)msgbuf; packet->voltage = voltage; packet->current_battery = current_battery; _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_BATTERY2, (const char *)packet, MAVLINK_MSG_ID_BATTERY2_MIN_LEN, MAVLINK_MSG_ID_BATTERY2_LEN, MAVLINK_MSG_ID_BATTERY2_CRC); #endif } #endif #endif // MESSAGE BATTERY2 UNPACKING /** * @brief Get field voltage from battery2 message * * @return [mV] Voltage. */ static inline uint16_t mavlink_msg_battery2_get_voltage(const mavlink_message_t* msg) { return _MAV_RETURN_uint16_t(msg, 0); } /** * @brief Get field current_battery from battery2 message * * @return [cA] Battery current, -1: autopilot does not measure the current. */ static inline int16_t mavlink_msg_battery2_get_current_battery(const mavlink_message_t* msg) { return _MAV_RETURN_int16_t(msg, 2); } /** * @brief Decode a battery2 message into a struct * * @param msg The message to decode * @param battery2 C-struct to decode the message contents into */ static inline void mavlink_msg_battery2_decode(const mavlink_message_t* msg, mavlink_battery2_t* battery2) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS battery2->voltage = mavlink_msg_battery2_get_voltage(msg); battery2->current_battery = mavlink_msg_battery2_get_current_battery(msg); #else uint8_t len = msg->len < MAVLINK_MSG_ID_BATTERY2_LEN? msg->len : MAVLINK_MSG_ID_BATTERY2_LEN; memset(battery2, 0, MAVLINK_MSG_ID_BATTERY2_LEN); memcpy(battery2, _MAV_PAYLOAD(msg), len); #endif }
yankailab/OpenKAI
src/Dependency/c_library_v2/ardupilotmega/mavlink_msg_battery2.h
C
agpl-3.0
9,095
<?php // Copyright (C) 2010-2012 Combodo SARL // // This file is part of iTop. // // iTop is free software; you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // iTop is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with iTop. If not, see <http://www.gnu.org/licenses/> /** * Localized data * * @author Vladimir Shilov <shilow@ukr.net> * @copyright Copyright (C) 2010-2012 Combodo SARL * @license http://opensource.org/licenses/AGPL-3.0 */ // Dictionnay conventions // Class:<class_name> // Class:<class_name>+ // Class:<class_name>/Attribute:<attribute_code> // Class:<class_name>/Attribute:<attribute_code>+ // Class:<class_name>/Attribute:<attribute_code>/Value:<value> // Class:<class_name>/Attribute:<attribute_code>/Value:<value>+ // Class:<class_name>/Stimulus:<stimulus_code> // Class:<class_name>/Stimulus:<stimulus_code>+ // // Class: Ticket // // // Class: Ticket // Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:Ticket' => 'Тикеи', 'Class:Ticket+' => '', 'Class:Ticket/Attribute:ref' => 'Ссылка', 'Class:Ticket/Attribute:ref+' => '', 'Class:Ticket/Attribute:title' => 'Название', 'Class:Ticket/Attribute:title+' => '', 'Class:Ticket/Attribute:description' => 'Описание', 'Class:Ticket/Attribute:description+' => '', 'Class:Ticket/Attribute:ticket_log' => 'Лог', 'Class:Ticket/Attribute:ticket_log+' => '', 'Class:Ticket/Attribute:start_date' => 'Начат', 'Class:Ticket/Attribute:start_date+' => '', 'Class:Ticket/Attribute:document_list' => 'Документы', 'Class:Ticket/Attribute:document_list+' => 'Документы относящиеся к тикету', 'Class:Ticket/Attribute:ci_list' => 'КЕ', 'Class:Ticket/Attribute:ci_list+' => 'КЕ затронутые инцидентом', 'Class:Ticket/Attribute:contact_list' => 'Контакты', 'Class:Ticket/Attribute:contact_list+' => 'Привлечённые команды и лица', 'Class:Ticket/Attribute:incident_list' => 'Связанные инциденты', 'Class:Ticket/Attribute:incident_list+' => '', 'Class:Ticket/Attribute:finalclass' => 'Тип', 'Class:Ticket/Attribute:finalclass+' => '', )); // // Class: lnkTicketToDoc // Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:lnkTicketToDoc' => 'Тикет/Документ', 'Class:lnkTicketToDoc+' => '', 'Class:lnkTicketToDoc/Attribute:ticket_id' => 'Тикет', 'Class:lnkTicketToDoc/Attribute:ticket_id+' => '', 'Class:lnkTicketToDoc/Attribute:ticket_ref' => '№ тикета', 'Class:lnkTicketToDoc/Attribute:ticket_ref+' => '', 'Class:lnkTicketToDoc/Attribute:document_id' => 'Документ', 'Class:lnkTicketToDoc/Attribute:document_id+' => '', 'Class:lnkTicketToDoc/Attribute:document_name' => 'Документ', 'Class:lnkTicketToDoc/Attribute:document_name+' => '', )); // // Class: lnkTicketToContact // Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:lnkTicketToContact' => 'Тикет/Контакт', 'Class:lnkTicketToContact+' => '', 'Class:lnkTicketToContact/Attribute:ticket_id' => 'Тикет', 'Class:lnkTicketToContact/Attribute:ticket_id+' => '', 'Class:lnkTicketToContact/Attribute:ticket_ref' => '№ тикета', 'Class:lnkTicketToContact/Attribute:ticket_ref+' => '', 'Class:lnkTicketToContact/Attribute:contact_id' => 'Контакт', 'Class:lnkTicketToContact/Attribute:contact_id+' => '', 'Class:lnkTicketToContact/Attribute:contact_name' => 'Контакт', 'Class:lnkTicketToContact/Attribute:contact_name+' => '', 'Class:lnkTicketToContact/Attribute:contact_email' => 'Email', 'Class:lnkTicketToContact/Attribute:contact_email+' => '', 'Class:lnkTicketToContact/Attribute:role' => 'Роль', 'Class:lnkTicketToContact/Attribute:role+' => '', )); // // Class: lnkTicketToCI // Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:lnkTicketToCI' => 'Тикет/КЕ', 'Class:lnkTicketToCI+' => '', 'Class:lnkTicketToCI/Attribute:ticket_id' => 'Тикет', 'Class:lnkTicketToCI/Attribute:ticket_id+' => '', 'Class:lnkTicketToCI/Attribute:ticket_ref' => '№ тикета', 'Class:lnkTicketToCI/Attribute:ticket_ref+' => '', 'Class:lnkTicketToCI/Attribute:ci_id' => 'КЕ', 'Class:lnkTicketToCI/Attribute:ci_id+' => '', 'Class:lnkTicketToCI/Attribute:ci_name' => 'КЕ', 'Class:lnkTicketToCI/Attribute:ci_name+' => '', 'Class:lnkTicketToCI/Attribute:ci_status' => 'КЕ Статус', 'Class:lnkTicketToCI/Attribute:ci_status+' => '', 'Class:lnkTicketToCI/Attribute:impact' => 'Воздействие', 'Class:lnkTicketToCI/Attribute:impact+' => '', )); // // Class: ResponseTicket // Dict::Add('RU RU', 'Russian', 'Русский', array( 'Class:ResponseTicket' => 'Ответный тикет', 'Class:ResponseTicket+' => '', 'Class:ResponseTicket/Attribute:status' => 'Статус', 'Class:ResponseTicket/Attribute:status+' => '', 'Class:ResponseTicket/Attribute:status/Value:new' => 'Новый', 'Class:ResponseTicket/Attribute:status/Value:new+' => 'недавно открытый', 'Class:ResponseTicket/Attribute:status/Value:escalated_tto' => 'Эскалация/TTO', 'Class:ResponseTicket/Attribute:status/Value:escalated_tto+' => '', 'Class:ResponseTicket/Attribute:status/Value:assigned' => 'Назначен', 'Class:ResponseTicket/Attribute:status/Value:assigned+' => '', 'Class:ResponseTicket/Attribute:status/Value:escalated_ttr' => 'Эскалация/TTR', 'Class:ResponseTicket/Attribute:status/Value:escalated_ttr+' => '', 'Class:ResponseTicket/Attribute:status/Value:frozen' => 'Заморожен', 'Class:ResponseTicket/Attribute:status/Value:frozen+' => '', 'Class:ResponseTicket/Attribute:status/Value:resolved' => 'Решён', 'Class:ResponseTicket/Attribute:status/Value:resolved+' => '', 'Class:ResponseTicket/Attribute:status/Value:closed' => 'Закріт', 'Class:ResponseTicket/Attribute:status/Value:closed+' => '', 'Class:ResponseTicket/Attribute:caller_id' => 'Вызывающий', 'Class:ResponseTicket/Attribute:caller_id+' => '', 'Class:ResponseTicket/Attribute:caller_email' => 'Email', 'Class:ResponseTicket/Attribute:caller_email+' => '', 'Class:ResponseTicket/Attribute:org_id' => 'Клиент', 'Class:ResponseTicket/Attribute:org_id+' => '', 'Class:ResponseTicket/Attribute:org_name' => 'Клиент', 'Class:ResponseTicket/Attribute:org_name+' => '', 'Class:ResponseTicket/Attribute:service_id' => 'Услуга', 'Class:ResponseTicket/Attribute:service_id+' => '', 'Class:ResponseTicket/Attribute:service_name' => 'Клиент', 'Class:ResponseTicket/Attribute:service_name+' => '', 'Class:ResponseTicket/Attribute:servicesubcategory_id' => 'Элемент услуги', 'Class:ResponseTicket/Attribute:servicesubcategory_id+' => '', 'Class:ResponseTicket/Attribute:servicesubcategory_name' => 'Название', 'Class:ResponseTicket/Attribute:servicesubcategory_name+' => '', 'Class:ResponseTicket/Attribute:product' => 'Продукт', 'Class:ResponseTicket/Attribute:product+' => '', 'Class:ResponseTicket/Attribute:impact' => 'Воздействие', 'Class:ResponseTicket/Attribute:impact+' => '', 'Class:ResponseTicket/Attribute:impact/Value:1' => 'Департамент', 'Class:ResponseTicket/Attribute:impact/Value:1+' => '', 'Class:ResponseTicket/Attribute:impact/Value:2' => 'Услуга', 'Class:ResponseTicket/Attribute:impact/Value:2+' => '', 'Class:ResponseTicket/Attribute:impact/Value:3' => 'Персона', 'Class:ResponseTicket/Attribute:impact/Value:3+' => '', 'Class:ResponseTicket/Attribute:urgency' => 'Срочность', 'Class:ResponseTicket/Attribute:urgency+' => '', 'Class:ResponseTicket/Attribute:urgency/Value:1' => 'Высокая', 'Class:ResponseTicket/Attribute:urgency/Value:1+' => '', 'Class:ResponseTicket/Attribute:urgency/Value:2' => 'Средняя', 'Class:ResponseTicket/Attribute:urgency/Value:2+' => '', 'Class:ResponseTicket/Attribute:urgency/Value:3' => 'Низкая', 'Class:ResponseTicket/Attribute:urgency/Value:3+' => '', 'Class:ResponseTicket/Attribute:priority' => 'Приоритет', 'Class:ResponseTicket/Attribute:priority+' => '', 'Class:ResponseTicket/Attribute:priority/Value:1' => 'Высокий', 'Class:ResponseTicket/Attribute:priority/Value:1+' => '', 'Class:ResponseTicket/Attribute:priority/Value:2' => 'Средний', 'Class:ResponseTicket/Attribute:priority/Value:2+' => '', 'Class:ResponseTicket/Attribute:priority/Value:3' => 'Низкий', 'Class:ResponseTicket/Attribute:priority/Value:3+' => '', 'Class:ResponseTicket/Attribute:workgroup_id' => 'Рабочая группа', 'Class:ResponseTicket/Attribute:workgroup_id+' => '', 'Class:ResponseTicket/Attribute:workgroup_name' => 'Рабочая группа', 'Class:ResponseTicket/Attribute:workgroup_name+' => '', 'Class:ResponseTicket/Attribute:agent_id' => 'Агент', 'Class:ResponseTicket/Attribute:agent_id+' => '', 'Class:ResponseTicket/Attribute:agent_name' => 'Агент', 'Class:ResponseTicket/Attribute:agent_name+' => '', 'Class:ResponseTicket/Attribute:agent_email' => 'email агента', 'Class:ResponseTicket/Attribute:agent_email+' => '', 'Class:ResponseTicket/Attribute:related_problem_id' => 'Связанная проблема', 'Class:ResponseTicket/Attribute:related_problem_id+' => '', 'Class:ResponseTicket/Attribute:related_problem_ref' => 'Ссылка', 'Class:ResponseTicket/Attribute:related_problem_ref+' => '', 'Class:ResponseTicket/Attribute:related_change_id' => 'Относящееся изменения', 'Class:ResponseTicket/Attribute:related_change_id+' => '', 'Class:ResponseTicket/Attribute:related_change_ref' => 'Относящееся изменения', 'Class:ResponseTicket/Attribute:related_change_ref+' => '', 'Class:ResponseTicket/Attribute:close_date' => 'Закрыто', 'Class:ResponseTicket/Attribute:close_date+' => '', 'Class:ResponseTicket/Attribute:last_update' => 'Последнее изменение', 'Class:ResponseTicket/Attribute:last_update+' => '', 'Class:ResponseTicket/Attribute:assignment_date' => 'Дата назначения', 'Class:ResponseTicket/Attribute:assignment_date+' => '', 'Class:ResponseTicket/Attribute:resolution_date' => 'Дата решения', 'Class:ResponseTicket/Attribute:resolution_date+' => '', 'Class:ResponseTicket/Attribute:tto_escalation_deadline' => 'Срок эскалации TTO', 'Class:ResponseTicket/Attribute:tto_escalation_deadline+' => '', 'Class:ResponseTicket/Attribute:ttr_escalation_deadline' => 'Срок эскалации TTR', 'Class:ResponseTicket/Attribute:ttr_escalation_deadline+' => '', 'Class:ResponseTicket/Attribute:closure_deadline' => 'Срок закрытия', 'Class:ResponseTicket/Attribute:closure_deadline+' => '', 'Class:ResponseTicket/Attribute:resolution_code' => 'Код решения', 'Class:ResponseTicket/Attribute:resolution_code+' => '', 'Class:ResponseTicket/Attribute:resolution_code/Value:couldnotreproduce' => 'Не воспроизводится', 'Class:ResponseTicket/Attribute:resolution_code/Value:couldnotreproduce+' => '', 'Class:ResponseTicket/Attribute:resolution_code/Value:duplicate' => 'Дубликатный тикет', 'Class:ResponseTicket/Attribute:resolution_code/Value:duplicate+' => '', 'Class:ResponseTicket/Attribute:resolution_code/Value:fixed' => 'Исправлен', 'Class:ResponseTicket/Attribute:resolution_code/Value:fixed+' => '', 'Class:ResponseTicket/Attribute:resolution_code/Value:irrelevant' => 'Нерелавнтный', 'Class:ResponseTicket/Attribute:resolution_code/Value:irrelevant+' => '', 'Class:ResponseTicket/Attribute:solution' => 'Решение', 'Class:ResponseTicket/Attribute:solution+' => '', 'Class:ResponseTicket/Attribute:user_satisfaction' => 'Удовлетворённость пользователя', 'Class:ResponseTicket/Attribute:user_satisfaction+' => '', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:1' => 'Польностью доволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:1+' => 'Польностью доволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:2' => 'Вполне доволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:2+' => 'Вполне доволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:3' => 'Недоволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:3+' => 'Недоволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:4' => 'Очень недоволен', 'Class:ResponseTicket/Attribute:user_satisfaction/Value:4+' => 'Очень недоволен', 'Class:ResponseTicket/Attribute:user_commment' => 'Коментарии пользователя', 'Class:ResponseTicket/Attribute:user_commment+' => '', 'Class:ResponseTicket/Stimulus:ev_assign' => 'Назначить', 'Class:ResponseTicket/Stimulus:ev_assign+' => '', 'Class:ResponseTicket/Stimulus:ev_reassign' => 'Переназначить', 'Class:ResponseTicket/Stimulus:ev_reassign+' => '', 'Class:ResponseTicket/Stimulus:ev_timeout' => 'Эскалировать', 'Class:ResponseTicket/Stimulus:ev_timeout+' => '', 'Class:ResponseTicket/Stimulus:ev_resolve' => 'Пометить как решённый', 'Class:ResponseTicket/Stimulus:ev_resolve+' => '', 'Class:ResponseTicket/Stimulus:ev_close' => 'Закрыт', 'Class:ResponseTicket/Stimulus:ev_close+' => '', )); ?>
sheyam/IncidentManagement
web/datamodels/1.x/itop-tickets-1.0.0/ru.dict.itop-tickets.php
PHP
agpl-3.0
13,986
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2014-2015 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2015 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.provision.service; import java.net.InetAddress; public interface HostnameResolver { public String getHostname(final InetAddress addr, final String location); }
aihua/opennms
opennms-provision/opennms-provisiond/src/main/java/org/opennms/netmgt/provision/service/HostnameResolver.java
Java
agpl-3.0
1,400
import random, copy def generate(data): data['correct_answers']['x'] = 3 def grade(data): raise Exception('deliberately broken grading function')
PrairieLearn/PrairieLearn
testCourse/questions/brokenGrading/server.py
Python
agpl-3.0
156
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Noncentral T Distribution</title> <link rel="stylesheet" href="../../../math.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="Math Toolkit 2.5.1"> <link rel="up" href="../dists.html" title="Distributions"> <link rel="prev" href="nc_f_dist.html" title="Noncentral F Distribution"> <link rel="next" href="normal_dist.html" title="Normal (Gaussian) Distribution"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="nc_f_dist.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../dists.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="normal_dist.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="math_toolkit.dist_ref.dists.nc_t_dist"></a><a class="link" href="nc_t_dist.html" title="Noncentral T Distribution">Noncentral T Distribution</a> </h4></div></div></div> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">math</span><span class="special">/</span><span class="identifier">distributions</span><span class="special">/</span><span class="identifier">non_central_t</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></pre> <pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">math</span><span class="special">{</span> <span class="keyword">template</span> <span class="special">&lt;</span><span class="keyword">class</span> <span class="identifier">RealType</span> <span class="special">=</span> <span class="keyword">double</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../../policy.html" title="Chapter&#160;15.&#160;Policies: Controlling Precision, Error Handling etc">Policy</a> <span class="special">=</span> <a class="link" href="../../pol_ref/pol_ref_ref.html" title="Policy Class Reference">policies::policy&lt;&gt;</a> <span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">non_central_t_distribution</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">non_central_t_distribution</span><span class="special">&lt;&gt;</span> <span class="identifier">non_central_t</span><span class="special">;</span> <span class="keyword">template</span> <span class="special">&lt;</span><span class="keyword">class</span> <span class="identifier">RealType</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../../policy.html" title="Chapter&#160;15.&#160;Policies: Controlling Precision, Error Handling etc">Policy</a><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">non_central_t_distribution</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="keyword">typedef</span> <span class="identifier">RealType</span> <span class="identifier">value_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">Policy</span> <span class="identifier">policy_type</span><span class="special">;</span> <span class="comment">// Constructor:</span> <span class="identifier">non_central_t_distribution</span><span class="special">(</span><span class="identifier">RealType</span> <span class="identifier">v</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="identifier">delta</span><span class="special">);</span> <span class="comment">// Accessor to degrees_of_freedom parameter v:</span> <span class="identifier">RealType</span> <span class="identifier">degrees_of_freedom</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> <span class="comment">// Accessor to non-centrality parameter delta:</span> <span class="identifier">RealType</span> <span class="identifier">non_centrality</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> <span class="special">};</span> <span class="special">}}</span> <span class="comment">// namespaces</span> </pre> <p> The noncentral T distribution is a generalization of the <a class="link" href="students_t_dist.html" title="Students t Distribution">Students t Distribution</a>. Let X have a normal distribution with mean &#948; and variance 1, and let &#957; S<sup>2</sup> have a chi-squared distribution with degrees of freedom &#957;. Assume that X and S<sup>2</sup> are independent. The distribution of t<sub>&#957;</sub>(&#948;)=X/S is called a noncentral t distribution with degrees of freedom &#957; and noncentrality parameter &#948;. </p> <p> This gives the following PDF: </p> <p> <span class="inlinemediaobject"><img src="../../../../equations/nc_t_ref1.svg"></span> </p> <p> where <sub>1</sub>F<sub>1</sub>(a;b;x) is a confluent hypergeometric function. </p> <p> The following graph illustrates how the distribution changes for different values of &#957; and &#948;: </p> <p> <span class="inlinemediaobject"><img src="../../../../graphs/nc_t_pdf.svg" align="middle"></span> <span class="inlinemediaobject"><img src="../../../../graphs/nc_t_cdf.svg" align="middle"></span> </p> <h5> <a name="math_toolkit.dist_ref.dists.nc_t_dist.h0"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.nc_t_dist.member_functions"></a></span><a class="link" href="nc_t_dist.html#math_toolkit.dist_ref.dists.nc_t_dist.member_functions">Member Functions</a> </h5> <pre class="programlisting"><span class="identifier">non_central_t_distribution</span><span class="special">(</span><span class="identifier">RealType</span> <span class="identifier">v</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="identifier">delta</span><span class="special">);</span> </pre> <p> Constructs a non-central t distribution with degrees of freedom parameter <span class="emphasis"><em>v</em></span> and non-centrality parameter <span class="emphasis"><em>delta</em></span>. </p> <p> Requires <span class="emphasis"><em>v</em></span> &gt; 0 (including positive infinity) and finite <span class="emphasis"><em>delta</em></span>, otherwise calls <a class="link" href="../../error_handling.html#math_toolkit.error_handling.domain_error">domain_error</a>. </p> <pre class="programlisting"><span class="identifier">RealType</span> <span class="identifier">degrees_of_freedom</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> </pre> <p> Returns the parameter <span class="emphasis"><em>v</em></span> from which this object was constructed. </p> <pre class="programlisting"><span class="identifier">RealType</span> <span class="identifier">non_centrality</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> </pre> <p> Returns the non-centrality parameter <span class="emphasis"><em>delta</em></span> from which this object was constructed. </p> <h5> <a name="math_toolkit.dist_ref.dists.nc_t_dist.h1"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.nc_t_dist.non_member_accessors"></a></span><a class="link" href="nc_t_dist.html#math_toolkit.dist_ref.dists.nc_t_dist.non_member_accessors">Non-member Accessors</a> </h5> <p> All the <a class="link" href="../nmp.html" title="Non-Member Properties">usual non-member accessor functions</a> that are generic to all distributions are supported: <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.cdf">Cumulative Distribution Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.pdf">Probability Density Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.quantile">Quantile</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.hazard">Hazard Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.chf">Cumulative Hazard Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.mean">mean</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.median">median</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.mode">mode</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.variance">variance</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.sd">standard deviation</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.skewness">skewness</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.kurtosis">kurtosis</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.kurtosis_excess">kurtosis_excess</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.range">range</a> and <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.support">support</a>. </p> <p> The domain of the random variable is [-&#8734;, +&#8734;]. </p> <h5> <a name="math_toolkit.dist_ref.dists.nc_t_dist.h2"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.nc_t_dist.accuracy"></a></span><a class="link" href="nc_t_dist.html#math_toolkit.dist_ref.dists.nc_t_dist.accuracy">Accuracy</a> </h5> <p> The following table shows the peak errors (in units of <a href="http://en.wikipedia.org/wiki/Machine_epsilon" target="_top">epsilon</a>) found on various platforms with various floating-point types. Unless otherwise specified, any floating-point type that is narrower than the one shown will have <a class="link" href="../../relative_error.html#math_toolkit.relative_error.zero_error">effectively zero error</a>. </p> <div class="table"> <a name="math_toolkit.dist_ref.dists.nc_t_dist.table_non_central_t_CDF"></a><p class="title"><b>Table&#160;5.8.&#160;Error rates for non central t CDF</b></p> <div class="table-contents"><table class="table" summary="Error rates for non central t CDF"> <colgroup> <col> <col> <col> <col> <col> </colgroup> <thead><tr> <th> </th> <th> <p> Microsoft Visual C++ version 12.0<br> Win32<br> double </p> </th> <th> <p> GNU C++ version 5.1.0<br> linux<br> double </p> </th> <th> <p> GNU C++ version 5.1.0<br> linux<br> long double </p> </th> <th> <p> Sun compiler version 0x5130<br> Sun Solaris<br> long double </p> </th> </tr></thead> <tbody> <tr> <td> <p> Non Central T </p> </td> <td> <p> <span class="blue">Max = 138&#949; (Mean = 31.5&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 0.796&#949; (Mean = 0.0691&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> <span class="red">Max = 5.28e+15&#949; (Mean = 8.49e+14&#949;) <a class="link" href="../../logs_and_tables/logs.html#errors_GNU_C_version_5_1_0_linux_double_non_central_t_CDF_Rmath_3_0_2_Non_Central_T">And other failures.</a>)</span> </p> </td> <td> <p> <span class="blue">Max = 141&#949; (Mean = 31.1&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 145&#949; (Mean = 30.2&#949;)</span> </p> </td> </tr> <tr> <td> <p> Non Central T (small non-centrality) </p> </td> <td> <p> <span class="blue">Max = 3.61&#949; (Mean = 1.03&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 0&#949; (Mean = 0&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> Max = 2.09e+03&#949; (Mean = 244&#949;)) </p> </td> <td> <p> <span class="blue">Max = 7.86&#949; (Mean = 1.69&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 9.15&#949; (Mean = 2.25&#949;)</span> </p> </td> </tr> <tr> <td> <p> Non Central T (large parameters) </p> </td> <td> <p> <span class="blue">Max = 286&#949; (Mean = 62.8&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 257&#949; (Mean = 72.1&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> Max = 2.46&#949; (Mean = 0.657&#949;)) </p> </td> <td> <p> <span class="blue">Max = 5.26e+05&#949; (Mean = 1.48e+05&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 5.24e+05&#949; (Mean = 1.47e+05&#949;)</span> </p> </td> </tr> </tbody> </table></div> </div> <br class="table-break"><div class="table"> <a name="math_toolkit.dist_ref.dists.nc_t_dist.table_non_central_t_CDF_complement"></a><p class="title"><b>Table&#160;5.9.&#160;Error rates for non central t CDF complement</b></p> <div class="table-contents"><table class="table" summary="Error rates for non central t CDF complement"> <colgroup> <col> <col> <col> <col> <col> </colgroup> <thead><tr> <th> </th> <th> <p> Microsoft Visual C++ version 12.0<br> Win32<br> double </p> </th> <th> <p> GNU C++ version 5.1.0<br> linux<br> double </p> </th> <th> <p> GNU C++ version 5.1.0<br> linux<br> long double </p> </th> <th> <p> Sun compiler version 0x5130<br> Sun Solaris<br> long double </p> </th> </tr></thead> <tbody> <tr> <td> <p> Non Central T </p> </td> <td> <p> <span class="blue">Max = 150&#949; (Mean = 32.3&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 0.707&#949; (Mean = 0.0497&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> <span class="red">Max = 6.19e+15&#949; (Mean = 6.72e+14&#949;) <a class="link" href="../../logs_and_tables/logs.html#errors_GNU_C_version_5_1_0_linux_double_non_central_t_CDF_complement_Rmath_3_0_2_Non_Central_T">And other failures.</a>)</span> </p> </td> <td> <p> <span class="blue">Max = 203&#949; (Mean = 31.8&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 340&#949; (Mean = 43.6&#949;)</span> </p> </td> </tr> <tr> <td> <p> Non Central T (small non-centrality) </p> </td> <td> <p> <span class="blue">Max = 5.21&#949; (Mean = 1.43&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 0&#949; (Mean = 0&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> Max = 1.87e+03&#949; (Mean = 263&#949;)) </p> </td> <td> <p> <span class="blue">Max = 7.48&#949; (Mean = 1.86&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 10.9&#949; (Mean = 2.43&#949;)</span> </p> </td> </tr> <tr> <td> <p> Non Central T (large parameters) </p> </td> <td> <p> <span class="blue">Max = 227&#949; (Mean = 50.4&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 478&#949; (Mean = 96.3&#949;)</span><br> <br> (<span class="emphasis"><em>Rmath 3.0.2:</em></span> Max = 2.24&#949; (Mean = 0.945&#949;)) </p> </td> <td> <p> <span class="blue">Max = 9.79e+05&#949; (Mean = 1.97e+05&#949;)</span> </p> </td> <td> <p> <span class="blue">Max = 9.79e+05&#949; (Mean = 1.97e+05&#949;)</span> </p> </td> </tr> </tbody> </table></div> </div> <br class="table-break"><div class="caution"><table border="0" summary="Caution"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Caution]" src="../../../../../../../doc/src/images/caution.png"></td> <th align="left">Caution</th> </tr> <tr><td align="left" valign="top"><p> The complexity of the current algorithm is dependent upon &#948;<sup>2</sup>: consequently the time taken to evaluate the CDF increases rapidly for &#948; &gt; 500, likewise the accuracy decreases rapidly for very large &#948;. </p></td></tr> </table></div> <p> Accuracy for the quantile and PDF functions should be broadly similar. The <span class="emphasis"><em>mode</em></span> is determined numerically and cannot in principal be more accurate than the square root of floating-point type FPT epsilon, accessed using <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">math</span><span class="special">::</span><span class="identifier">tools</span><span class="special">::</span><span class="identifier">epsilon</span><span class="special">&lt;</span><span class="identifier">FPT</span><span class="special">&gt;()</span></code>. For 64-bit <code class="computeroutput"><span class="keyword">double</span></code>, epsilon is about 1e-16, so the fractional accuracy is limited to 1e-8. </p> <h5> <a name="math_toolkit.dist_ref.dists.nc_t_dist.h3"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.nc_t_dist.tests"></a></span><a class="link" href="nc_t_dist.html#math_toolkit.dist_ref.dists.nc_t_dist.tests">Tests</a> </h5> <p> There are two sets of tests of this distribution: </p> <p> Basic sanity checks compare this implementation to the test values given in "Computing discrete mixtures of continuous distributions: noncentral chisquare, noncentral t and the distribution of the square of the sample multiple correlation coefficient." Denise Benton, K. Krishnamoorthy, Computational Statistics &amp; Data Analysis 43 (2003) 249-267. </p> <p> Accuracy checks use test data computed with this implementation and arbitary precision interval arithmetic: this test data is believed to be accurate to at least 50 decimal places. </p> <p> The cases of large (or infinite) &#957; and/or large &#948; has received special treatment to avoid catastrophic loss of accuracy. New tests have been added to confirm the improvement achieved. </p> <p> From Boost 1.52, degrees of freedom &#957; can be +&#8734; when the normal distribution located at &#948; (equivalent to the central Student's t distribution) is used in place for accuracy and speed. </p> <h5> <a name="math_toolkit.dist_ref.dists.nc_t_dist.h4"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.nc_t_dist.implementation"></a></span><a class="link" href="nc_t_dist.html#math_toolkit.dist_ref.dists.nc_t_dist.implementation">Implementation</a> </h5> <p> The CDF is computed using a modification of the method described in "Computing discrete mixtures of continuous distributions: noncentral chisquare, noncentral t and the distribution of the square of the sample multiple correlation coefficient." Denise Benton, K. Krishnamoorthy, Computational Statistics &amp; Data Analysis 43 (2003) 249-267. </p> <p> This uses the following formula for the CDF: </p> <p> <span class="inlinemediaobject"><img src="../../../../equations/nc_t_ref2.svg"></span> </p> <p> Where I<sub>x</sub>(a,b) is the incomplete beta function, and &#934;(x) is the normal CDF at x. </p> <p> Iteration starts at the largest of the Poisson weighting terms (at i = &#948;<sup>2</sup> / 2) and then proceeds in both directions as per Benton and Krishnamoorthy's paper. </p> <p> Alternatively, by considering what happens when t = &#8734;, we have x = 1, and therefore I<sub>x</sub>(a,b) = 1 and: </p> <p> <span class="inlinemediaobject"><img src="../../../../equations/nc_t_ref3.svg"></span> </p> <p> From this we can easily show that: </p> <p> <span class="inlinemediaobject"><img src="../../../../equations/nc_t_ref4.svg"></span> </p> <p> and therefore we have a means to compute either the probability or its complement directly without the risk of cancellation error. The crossover criterion for choosing whether to calculate the CDF or its complement is the same as for the <a class="link" href="nc_beta_dist.html" title="Noncentral Beta Distribution">Noncentral Beta Distribution</a>. </p> <p> The PDF can be computed by a very similar method using: </p> <p> <span class="inlinemediaobject"><img src="../../../../equations/nc_t_ref5.svg"></span> </p> <p> Where I<sub>x</sub><sup>'</sup>(a,b) is the derivative of the incomplete beta function. </p> <p> For both the PDF and CDF we switch to approximating the distribution by a Student's t distribution centred on &#948; when &#957; is very large. The crossover location appears to be when &#948;/(4&#957;) &lt; &#949;, this location was estimated by inspection of equation 2.6 in "A Comparison of Approximations To Percentiles of the Noncentral t-Distribution". H. Sahai and M. M. Ojeda, Revista Investigacion Operacional Vol 21, No 2, 2000, page 123. </p> <p> Equation 2.6 is a Fisher-Cornish expansion by Eeden and Johnson. The second term includes the ratio &#948;/(4&#957;), so when this term become negligible, this and following terms can be ignored, leaving just Student's t distribution centred on &#948;. </p> <p> This was also confirmed by experimental testing. </p> <p> See also </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> "Some Approximations to the Percentage Points of the Noncentral t-Distribution". C. van Eeden. International Statistical Review, 29, 4-31. </li> <li class="listitem"> "Continuous Univariate Distributions". N.L. Johnson, S. Kotz and N. Balkrishnan. 1995. John Wiley and Sons New York. </li> </ul></div> <p> The quantile is calculated via the usual <a class="link" href="../../roots/roots_noderiv.html" title="Root Finding Without Derivatives">root-finding without derivatives</a> method with the initial guess taken as the quantile of a normal approximation to the noncentral T. </p> <p> There is no closed form for the mode, so this is computed via functional maximisation of the PDF. </p> <p> The remaining functions (mean, variance etc) are implemented using the formulas given in Weisstein, Eric W. "Noncentral Student's t-Distribution." From MathWorld--A Wolfram Web Resource. <a href="http://mathworld.wolfram.com/NoncentralStudentst-Distribution.html" target="_top">http://mathworld.wolfram.com/NoncentralStudentst-Distribution.html</a> and in the <a href="http://reference.wolfram.com/mathematica/ref/NoncentralStudentTDistribution.html" target="_top">Mathematica documentation</a>. </p> <p> Some analytic properties of noncentral distributions (particularly unimodality, and monotonicity of their modes) are surveyed and summarized by: </p> <p> Andrea van Aubel &amp; Wolfgang Gawronski, Applied Mathematics and Computation, 141 (2003) 3-12. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2006-2010, 2012-2014 Nikhar Agrawal, Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock, Jeremy Murphy, Johan R&#229;de, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="nc_f_dist.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../dists.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="normal_dist.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
ntonjeta/iidea-Docker
examples/sobel/src/boost_1_63_0/libs/math/doc/html/math_toolkit/dist_ref/dists/nc_t_dist.html
HTML
agpl-3.0
28,547
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import res_partner
rosenvladimirov/addons
partner_vat_search/models/__init__.py
Python
agpl-3.0
120
@page styleguide2 Nitpicker's Coding Styleguide To avoid boring you to death with coding rules, we decided to not include the following in our main coding styleguide for one or more of the following reasons: - They deal with special cases. - They can, in our view, be taken for granted. - They are of lesser importance to us. - They can be easily checked for, and con-compliant code can easily be fixed. We don't really expect you to actually read the following; if you have the stamina though, and want to learn more about good coding practices, be our guest. These rules are heavily inspired by the Motor Industry Software Reliability Association's publication "MISRA C++:2008 -- Guidelines for the use of the C++ language in critical systems", an industry-wide accepted standard for writing robust C++ code. (However, if you're reading the source code of this documentation page, be aware that the HTML comments citing individual MISRA rules are included for reference only, and that our rules may differ substantially.) @note Entries in parentheses are placeholders for concerns we haven't addressed yet. Most of these correspond to rules from the MISRA C++ 2008 guidelines. @todo Flesh out the placeholders. - **Unused or useless code**: There should generally be no unreachable, orphaned, dead or pointless code, nor any unused variables or types. The following are valid exceptions: - Some feature needs to be disabled for a hotfix, and is intended to be re-enabled as soon as a proper fix has been implemented. - Helper code is already being developed (or being retained from dropped features) in anticipation of a feature that will use it. . In any case, the rationale for dragging along such unused code should be well documented in the source code. <!-- MISRA C++ 2008 **required** rules 0-1-1...0-1-6, 0-1-8...0-1-12, 14-7-1 --> - **Unused return values**: Whenever the return value of a function is ignored, it must be explicitly cast to `(void)` to indicate that this is intentional. <!-- MISRA C++ 2008 **required** rule 0-1-7 --> - **Unions**: Never use unions. Any deviation from this rule needs an exceptionally strong reason for it. <!-- MISRA C++ 2008 **required** rules 0-2-1, 9-5-1 --> - **Run-Time Checks**: When writing code, give thought to possible run-time errors, such as arithmetic errors (numeric overflow, division by zero, limits of floating-point precision, etc.), failed memory allocations, or bogus parameter values. Most notably, if a called function may indicate an error, make sure to test for that error indication and handle it appropriately. <!-- MISRA C++ 2008 document rule 0-3-1 (c), **required** rule 0-3-2 --> <!-- MISRA C++ 2008 document rule 0-4-1 (Use of scaled-integer or fixed-point arithmetic shall be documented) IGNORED: We're not using any of these... or are we? --> <!-- MISRA C++ 2008 document rule 0-4-2 (Use of floating-point arithmetic shall be documented) IGNORED: We're using floating-points virtually everywhere, and can't do without for obvious reasons. --> <!-- MISRA C++ 2008 document rule 0-4-3 (Floating-point implementations shall comply with a defined floating-point standard) IGNORED: This depends on the user's choice of compiler, and is therefore beyond the scope of any platform-independent project. --> - **Language Standard**: Source code should be written in C++ adhering to the ISO/IEC 14882:2011 standard (aka C++11). Compiler-specific language extensions may only be used in the dedicated headers intended to _hide_ compiler-specific implementation details. <!-- MISRA C++ 2008 **required** rule 1-0-1 --> <!-- MISRA C++ 2008 document rule 1-0-2 (Multiple compilers shall only be used if they have a common, defined interface) IGNORED: This depends on the user's choice of compiler, and is therefore beyond the scope of any platform-independent project. --> - **Negative Integer Division**: Source code should avoid division or modulus operations on negative integers, or should not rely on a particular rounding mode (towards negative infinity or towards zero) in such cases. <!-- MISRA C++ 2008 document rule 1-0-3 --> - **Character Encoding**: Source files should be plain vanilla ASCII, and should not use _universal character name notation_ (`\uXXXX` or `\UXXXXXXXX`). String literals should not encode any non-ASCII character by means of escape sequences. <!-- MISRA C++ 2008 document rule 2-2-1 --> - **Tri- and Digraphs**: Neither tri- nor digraphs should be used in the source code. Multiple consecutive question marks (`??`) in string literals should be escaped (`?\?`) to prevent the compiler from interpreting them as trigraphs. <!-- MISRA C++ 2008 **required** rule 2-3-1, advisory rule 2-5-1 --> - **Comments**: Do not nest block quotes; as a matter of fact, do not use `/*` in any comment (neither block nor single-line style). <!-- MISRA C++ 2008 **required** rule 2-7-1 --> - Do not use comments (neither block nor single-line style) to disable code. <!-- MISRA C++ 2008 **required** rule 2-7-2, advisory rule 2-7-3 --> - **Identifier Names**: We expect any sane developer to be using a fixed-pitch font with reasonably discernable characters, including (but not limited to) the notorious lowercase letter `l` and digit `1`. However, try to avoid cryptic identifiers with a high percentage of such problematic characters. Well, actually, better avoid _any_ cryptic identifiers. <!-- MISRA C++ 2008 **required** rule 2-10-1 --> - Avoid name collisions with identifiers in an outer scope ("shadowing"). <!-- MISRA C++ 2008 **required** rule 2-10-2 --> . - (a typedef name shall be a unique identifier) <!-- MISRA C++ 2008 **required** rule 2-10-3 --> - (a class, union or enum name shall be a unique identifier) <!-- MISRA C++ 2008 **required** rule 2-10-4 --> - (the identifier name of a non-member object or function with static storage duration shall not be reused) <!-- MISRA C++ 2008 advisory rule 2-10-5 --> - (if an identifier refers to a type, it shall not also refer to an object or a function in the same scope) <!-- MISRA C++ 2008 **required** rule 2-10-6 --> . - **Escape Sequences**: Do not use any non-standard escape sequences. <!-- MISRA C++ 2008 **required** rule 2-13-1 --> - **Octal Constants**: Do not use octal constants or octal escape sequences. <!-- MISRA C++ 2008 **required** rule 2-13-2 --> - **Hexadecimal Constants**: When using hexadecimal constants, always explicitly specify them as signed or unsigned by append either a `u` or `s` suffix. <!-- MISRA C++ 2008 **required** rule 2-13-3 --> . - (Lower case literal suffix) <!-- MISRA C++ 2008 **required** rule 2-13-4 --> . - **Wide String Literals**: Do not mix narrow and wide string literals. <!-- MISRA C++ 2008 **required** rule 2-13-5 --> . - (object/function definitions in header files) <!-- MISRA C++ 2008 **required** rule 3-1-1 --> - (function not declared at file scope) <!-- MISRA C++ 2008 **required** rule 3-1-2 --> - (zero-dimensioned array) <!-- MISRA C++ 2008 **required** rule 3-1-3 --> - (all declarations of an object or function shall have compatible types) <!-- MISRA C++ 2008 **required** rule 3-2-1 --> - (the One Definition Rule shall not be violated) <!-- MISRA C++ 2008 **required** rule 3-2-2 --> - (a type, object or function that is used in multiple translation units shall be declared in one and only one file.) <!-- MISRA C++ 2008 **required** rule 3-2-3 --> - (an identifier with external linkage shall have exactly one definition) <!-- MISRA C++ 2008 **required** rule 3-2-4 --> - (objects or functions with external linkage shall be declared in a header file) <!-- MISRA C++ 2008 **required** rule 3-3-1 --> - (if a function has internal linkage then all re-declarations shall include the static storage class specifier) <!-- MISRA C++ 2008 **required** rule 3-3-2 --> - (an identifier declared to be an object or type shall be defined in a block that minimizes its visibility) <!-- MISRA C++ 2008 **required** rule 3-4-1 --> - (The types used for an object, a function return type, or a function parameter shall be token-for-token identical in all declarations and re-declarations) <!-- MISRA C++ 2008 **required** rule 3-9-1 --> - (typedefs that indicate size and signedness should be used in place of the basic numerical types) <!-- MISRA C++ 2008 advisory rule 3-9-2 --> - (the underlying bit representations of floating-point values shall not be used) <!-- MISRA C++ 2008 **required** rule 3-9-3 --> - (Expressions with type bool shall not be used as operands to built-in operators other than the assignment operator =, the logical operators &&, ||, !, the equality operators == and !=, the unary & operator, and the conditional operator) <!-- MISRA C++ 2008 **required** rule 4-5-1 --> - (Expressions with type enum shall not be used as operands to built-in operators other than the subscript operator [], the assignment operator =, the equality operators == and !=, the unary & operator, and the relational operators <, <=, >, >=) <!-- MISRA C++ 2008 **required** rule 4-5-2 --> - (expressions with type (plain) char and wchar_t shall not be used as operands to built-in operators other than the assignment operator =, the equality operators == and !=, and the unary & operator) <!-- MISRA C++ 2008 **required** rule 4-5-3 --> - (NULL shall not be used as an integer value) <!-- MISRA C++ 2008 **required** rule 4-10-1 --> - (Literal zero (0) shall not be used as the null-pointer-constant) <!-- MISRA C++ 2008 **required** rule 4-10-2 --> - (The value of an expression shall be the same under any order of evaluation that the standard permits) <!-- MISRA C++ 2008 **required** rule 5-0-1 --> - (Limited precedence should be placed on C++ operator precedence rules in expressions) <!-- MISRA C++ 2008 advisory rule 5-0-2 --> - (A cvalue expression shall not be implicitly converted to a different underlying type) <!-- MISRA C++ 2008 **required** rule 5-0-3 --> - (An implicit integral conversion shall not change the signedness of the underlying type) <!-- MISRA C++ 2008 **required** rule 5-0-4 --> - (There shall be no implicit floating-integral conversions) <!-- MISRA C++ 2008 **required** rule 5-0-5 --> - (An implicit integral or floating-point conversion shall not reduce the size of the underlying type) <!-- MISRA C++ 2008 **required** rule 5-0-6 --> - (There shall be no explicit floating-integral conversions of a cvalue expression) <!-- MISRA C++ 2008 **required** rule 5-0-7 --> - (An explicit integral or floating-point conversion shall not increase the size of the underlying type of a cvalue expression) <!-- MISRA C++ 2008 **required** rule 5-0-8 --> - (An explicit integral conversion shall not change the signedness of the underlying type of a cvalue expression) <!-- MISRA C++ 2008 **required** rule 5-0-9 --> - (If the bitwise operators '~' and '<<' are applied to an operand with an underlying type of signed char or unsigned short, the result shall be immediately cast to the underlying type of the operand) <!-- MISRA C++ 2008 **required** rule 5-0-10 --> - (The plain char type shall only be used for the storage and use of character values) <!-- MISRA C++ 2008 **required** rule 5-0-11 --> - (signed char and unsigned char type shall only be used for the storage and use of numeric values) <!-- MISRA C++ 2008 **required** rule 5-0-12 --> - (the condition of an if-statement or iteration-statement shall have type bool) <!-- MISRA C++ 2008 **required** rule 5-0-13 --> - (the first operand of a conditional-operator shall have type bool) <!-- MISRA C++ 2008 **required** rule 5-0-14 --> - (array indexing shall be the only form of pointer arithmetic) <!-- MISRA C++ 2008 **required** rule 5-0-15 --> - (out-of-bounds pointer) <!-- MISRA C++ 2008 **required** rule 5-0-16 --> - (subtraction between pointers shall only be applied to pointers that address elements of the same array) <!-- MISRA C++ 2008 **required** rule 5-0-17 --> - (>, >=, <, <= shall not be applied to objects of pointer type, except where they point to the same array) <!-- MISRA C++ 2008 **required** rule 5-0-18 --> - (The declaration of objects shall contain no more than two levels of indirection) <!-- MISRA C++ 2008 **required** rule 5-0-19 --> - (Non-constant operands to a binary bitwise operator shall have the same underlying type) <!-- MISRA C++ 2008 **required** rule 5-0-20 --> - (Bitwise operators shall only be applied to operands of unsigned underlying type) <!-- MISRA C++ 2008 **required** rule 5-0-21 --> - ((Operands of logical operators && or || need to be parenthesized properly, except in a sequence of all-identical operators)) <!-- MISRA C++ 2008 **required** rule 5-2-1 --> - (A pointer to a virtual base class shall only be cast to a pointer to a derived class by means of dynamic_cast) <!-- MISRA C++ 2008 **required** rule 5-2-2 --> - (Casts from a base class to a derived class should not be performed on polymorphic types) <!-- MISRA C++ 2008 advisory rule 5-2-3 --> - (C-style casts (other than void casts) and functional notation casts (other than explicit constructor calls) shall not be used) <!-- MISRA C++ 2008 **required** rule 5-2-4 --> - (A cast shall not remove any const or volatile qualification from the type of a pointer or reference) <!-- MISRA C++ 2008 **required** rule 5-2-5 --> - (a cast shall not convert a pointer to a function to any other pointer type) <!-- MISRA C++ 2008 **required** rule 5-2-6 --> - (an object with pointer type shall not be converted to an unrelated type) <!-- MISRA C++ 2008 **required** rule 5-2-7 --> - (an object with integral type or pointer to void type shall not be converted to an object with pointer type) <!-- MISRA C++ 2008 advisory rule 5-2-8 --> - (a cast should not convert a pointer type to an integral type) <!-- MISRA C++ 2008 advisory rule 5-2-9 --> - (the increment (++) and decrement (--) operators should not be mixed with other operators in an expression) <!-- MISRA C++ 2008 advisory rule 5-2-10 --> - (the comma operator, && operator and the || operator shall not be overloaded) <!-- MISRA C++ 2008 **required** rule 5-2-11 --> - (An identifier with array type passed as a function argument shall not decay into a pointer) <!-- MISRA C++ 2008 **required** rule 5-2-12 --> - (Each of the ! operator, the logical && or the logical || operators shall have type bool) <!-- MISRA C++ 2008 **required** rule 5-3-1 --> - (The unary minus operator shall not be applied to an expression whose underlying type is unsigned) <!-- MISRA C++ 2008 **required** rule 5-3-2 --> - (The unary & operator shall not be overloaded) <!-- MISRA C++ 2008 **required** rule 5-3-3 --> . - **Sizeof Operator**: The parameter to the sizeof operator should always be a variable, and nothing but a variable. <!-- MISRA C++ 2008 **required** rule 5-3-4 --> . - (The right hand operand of a shift operator shall lie between zero and none less than the width in bits of the underlying type of the left operand) <!-- MISRA C++ 2008 **required** rule 5-8-1 --> - (The right hand operand of a logical && or || operator shall not contain side effects) <!-- MISRA C++ 2008 **required** rule 5-14-1 --> - (The semantic equivalence between a binary operator and its assignment operator form shall be preserved) <!-- MISRA C++ 2008 **required** rule 5-17-1 --> . - **Comma Operator**: Do not use the comma operator. <!-- MISRA C++ 2008 **required** rule 5-18-1 --> . - (Evaluation of constant unsigned integer expressions should not lead to wrap-around) <!-- MISRA C++ 2008 advisory rule 5-19-1 --> - (Assignment operators shall not be used in sub-expressions) <!-- MISRA C++ 2008 **required** rule 6-2-1 --> - (Floating-point expressions shall not be tested for equality or inequality) <!-- MISRA C++ 2008 **required** rule 6-2-2 --> - (a null statement shall only occur on a line by itself) <!-- MISRA C++ 2008 **required** rule 6-2-3 --> - (The body of a switch, while, do...while or for statement shall be a compound statement) <!-- MISRA C++ 2008 **required** rule 6-3-1 --> - (an if() shall be followed by a compound statement. an else shall be followed by either a compound statement, or another if) <!-- MISRA C++ 2008 **required** rule 6-4-1 --> - (an if...else if construct shall be terminated with an else clause) <!-- MISRA C++ 2008 **required** rule 6-4-2 --> - (a switch statement shall be _well-formed_ (no labels, jumps or declarations outside compound statements)) <!-- MISRA C++ 2008 **required** rule 6-4-3 --> - (a switch-label shall only be used when the most closely-enclosing compound statement is the body of a switch statement) <!-- MISRA C++ 2008 **required** rule 6-4-4 --> . - **Switch Fallthrough**: Intentional fall-through in a switch statement should generally be avoided. If used at all, it must be explicitly indicated with a `// FALLTHROUGH` comment. (Please use this exact spelling, to facilitate automatic code analysis.) <!-- MISRA C++ 2008 **required** rule 6-4-5 --> - **Switch Default**: Each switch statement should have a default as its last block. If it is not empty, it should end with a `break` statement. <!-- MISRA C++ 2008 **required** rule 6-4-6 --> . - (the condition of a switch statement shall not have bool type) <!-- MISRA C++ 2008 **required** rule 6-4-7 --> - (every switch statement shall have at least one case-clause) <!-- MISRA C++ 2008 **required** rule 6-4-8 --> - (a for loop shall contain a single loop-counter which shall not have floating type) <!-- MISRA C++ 2008 **required** rule 6-5-1 --> - (if loop-counter is not modified by -- or ++, then, within condition, the loop-counter shall only be used as an operand to <=, <, > or >=) <!-- MISRA C++ 2008 **required** rule 6-5-2 --> - (the loop-counter shall not be modified within condition or statement) <!-- MISRA C++ 2008 **required** rule 6-5-3 --> - (the loop-counter shall be modified by one of: --, ++, -=const, +=const) <!-- MISRA C++ 2008 **required** rule 6-5-4 --> - (other variables used for early loop termination shall not be modified within condition or expression) <!-- MISRA C++ 2008 **required** rule 6-5-5 --> - (other variables used for early loop termination shall have type bool) <!-- MISRA C++ 2008 **required** rule 6-5-6 --> . - **Goto Statements**: They are evil. Do not use them. <!-- MISRA C++ 2008 **required** rules 6-6-1, 6-6-2 --> . - (The continue statement shall only be used within a _well-formed_ for loop (i.e. that satisifies rules 6-5-1 to 6-5-6) <!-- MISRA C++ 2008 **required** rule 6-6-3 --> - (For any iteration statement there shall be no more than one break or goto statement used for loop termination) <!-- MISRA C++ 2008 **required** rule 6-6-4 --> - (A function shall have a single point of exit at the end of the function) <!-- MISRA C++ 2008 **required** rule 6-6-5 --> - (A variable which is not modified shall be const qualified) <!-- MISRA C++ 2008 **required** rule 7-1-1 --> - (A pointer or reference parameter in a function shall be declared as pointer to const or reference to const if the corresponding object is not modified) <!-- MISRA C++ 2008 **required** rule 7-1-2 --> - (An expression with enum underlying type shall only have values corresponding to the enumerators of the enumeration) <!-- MISRA C++ 2008 **required** rule 7-2-1 --> - (The global namespace shall only contain main, namespace declarations and extern "C" declarations) <!-- MISRA C++ 2008 **required** rule 7-3-1 --> - (The identifier main shall not be used for a function other than the global function main) <!-- MISRA C++ 2008 **required** rule 7-3-2 --> - (There shall be no unnamed namespaces in header files) <!-- MISRA C++ 2008 **required** rule 7-3-3 --> - (Using-directives shall not be used) <!-- MISRA C++ 2008 **required** rule 7-3-4 --> - (Multiple declarations for an identifier in the same namespace shall not straddle a using-declaration for that identifier) <!-- MISRA C++ 2008 **required** rule 7-3-5 --> - (Using-directives/declarations (excluding class scope or function scope using-declarations) shall not be used in header file) <!-- MISRA C++ 2008 **required** rule 7-3-6 --> - (All usage of assembler shall be documented) <!-- MISRA C++ 2008 document rule 7-4-1 --> - (Assembler instructions shall only be introduced using the asm directive) <!-- MISRA C++ 2008 **required** rule 7-4-2 --> - (Assembly language shall be encapsulated and isolated) <!-- MISRA C++ 2008 **required** rule 7-4-3 --> - (a function shall not return a reference or pointer to an automatic variable (i.e. non-static local or non-reference parameter)) <!-- MISRA C++ 2008 **required** rule 7-5-1 --> - (the address of an object with automatic storage shall not be assigned to another object that may persist after the first object has ceased to exist) <!-- MISRA C++ 2008 **required** rule 7-5-2 --> - (a function shall not return a reference or a pointer to a parameter that is passed by reference or const reference) <!-- MISRA C++ 2008 **required** rule 7-5-3 --> - (Functions shall not call themselves, either directly or indirectly) <!-- MISRA C++ 2008 advisory rule 7-5-4 --> - (An init-declarator-list or a member-declarator-list shall consist of a single init-declarator or member-declarator respectively) <!-- MISRA C++ 2008 **required** rule 8-0-1 --> - (Parameters in an overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default parameters) <!-- MISRA C++ 2008 **required** rule 8-3-1 --> - (Functions shall not be defined using the ellipsis notation) <!-- MISRA C++ 2008 **required** rule 8-4-1 --> - (The identifiers used for the parameters in a re-declaration of a function shall be identical to those in the declaration) <!-- MISRA C++ 2008 **required** rule 8-4-2 --> - (All exit paths from a function with non-void return type shall have an explicit return statement with an expression) <!-- MISRA C++ 2008 **required** rule 8-4-3 --> - (A function identifier shall either be used to call the function or it shall be preceded wby &) <!-- MISRA C++ 2008 **required** rule 8-4-4 --> - (All variables shall have a defined value before they are used) <!-- MISRA C++ 2008 **required** rule 8-5-1 --> - (Braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures) <!-- MISRA C++ 2008 **required** rule 8-5-2 --> - (In enumerator lists, the = construct shall not be used to explicitly initialize members other than the first, unless all items are explicitly initialized) <!-- MISRA C++ 2008 **required** rule 8-5-3 --> - (const member functions shall not return non-const pointers or reference to class-data) <!-- MISRA C++ 2008 **required** rule 9-3-1 --> - (member functions shall not return non-const handles to class-data) <!-- MISRA C++ 2008 **required** rule 9-3-2 --> - (If a member function can be made static then it shall be made static, otherwise if it can be made const then it shall be made const) <!-- MISRA C++ 2008 **required** rule 9-3-3 --> - (When the absolute positioning of bits representing a bit-field is required, then the behaviour and packing of bit-fields shall be documented) <!-- MISRA C++ 2008 document rule 9-6-1 --> - (bit-fields shall be either bool type or an explicitly unsigned or signed integral type) <!-- MISRA C++ 2008 **required** rule 9-6-2 --> - (bit fields shall not have enum type) <!-- MISRA C++ 2008 **required** rule 9-6-3 --> - (named bit-fields with signed integer type shall have a length of more than one bit) <!-- MISRA C++ 2008 **required** rule 9-6-4 --> - (Classes should not be derived from virtual bases (i.e., `class B: public virtual A`)) <!-- MISRA C++ 2008 advisory rule 10-1-1 --> - (A base class shall only be declared virtual (i.e., `class B: public virtual A`) if it is used in a diamond hierarchy.) <!-- MISRA C++ 2008 **required** rule 10-1-2 --> - (An accessible base class shall not be both virtual (i.e., `class B: public virtual A`) and non-virtual in the same hierarchy) <!-- MISRA C++ 2008 **required** rule 10-1-3 --> - (All accessible entity names within a multiple inheritance hierarchy should be unique) <!-- MISRA C++ 2008 advisory rule 10-2-1 --> - (There shall be no more than one definition of each virtual function on each path through the inheritance hierarchy) <!-- MISRA C++ 2008 **required** rule 10-3-1 --> - (Each overriding virtual function shall be declared with the 'virtual' keyword) <!-- MISRA C++ 2008 **required** rule 10-3-2 --> - (A virtual function shall only be overridden by a pure virtual function if it is itself declared as pure virtual) <!-- MISRA C++ 2008 **required** rule 10-3-3 --> - (Member data in non-POD class types shall be private) <!-- MISRA C++ 2008 **required** rule 11-0-1 --> - (An object's dynamic type shall not be used from the body of its constructor or destructor (i.e. no virtual function calls, no use of typeid or dynamic_cast)) <!-- MISRA C++ 2008 **required** rule 12-1-1 --> - (All constructors of a class should explicitly call a constructor of all of its immediate base classes and all virtual base classes) <!-- MISRA C++ 2008 advisory rule 12-1-2 --> - (All constructors that are callable with a single argument of fundamental type shall be declared `explicit`) <!-- MISRA C++ 2008 **required** rule 12-1-3 --> - (A copy constructor shall only initialize its base classes and the non-static members of the class of which it is a member) <!-- MISRA C++ 2008 **required** rule 12-8-1 --> - (The copy assignment operator shall be declared protective or private in an abstract class) <!-- MISRA C++ 2008 **required** rule 12-8-2 --> - [!] (A non-member generic function shall only be declared in a template that is not an associated namespace) <!-- MISRA C++ 2008 **required** rule 14-5-1 --> - [!] (A copy constructor shall be declared when there is a template constructor with a single parameter that is a generic parameter) <!-- MISRA C++ 2008 **required** rule 14-5-2 --> - [!] (A copy assignment operator shall be declared when there is a template assignment operator with a parameter that is a generic parameter) <!-- MISRA C++ 2008 **required** rule 14-5-3 --> - [!] (In a class template with a dependent base, any name that may be found in that dependent base shall be referred to using a qualified-id or `this->`) <!-- MISRA C++ 2008 **required** rule 14-6-1 --> - [!] (The function chosen by overload resolution shall resolve to a function declared previously in the translation unit) <!-- MISRA C++ 2008 **required** rule 14-6-2 --> - (For any given template specialization, an explicit instantiation of the template with the template-arguments used in the specialization shall not render the program ill-formed) <!-- MISRA C++ 2008 **required** rule 14-7-2 --> - (all partial and explicit specializations for a template shall be declared in the same file as the declaration of their primary template) <!-- MISRA C++ 2008 **required** rule 14-7-3 --> - (Overloaded function templates shall not be explicitly specialized) <!-- MISRA C++ 2008 **required** rule 14-8-1 --> - (The viable function set for a function call should either contain no function specializations, or only contain function specializations) <!-- MISRA C++ 2008 advisory rule 14-8-2 --> - (Exceptions shall only be used for error handling) <!-- MISRA C++ 2008 document rule 15-0-1 --> - (An exception object should not have pointer type) <!-- MISRA C++ 2008 advisory rule 15-0-2 --> - (Control shall not be transferred into a try or catch block using a goto or a switch statement) <!-- MISRA C++ 2008 **required** rule 15-0-3 --> - (The assignment-expression of a throw statement shall not itself cause an exception to be thrown) <!-- MISRA C++ 2008 **required** rule 15-1-1 --> - (`NULL` shall not be thrown explicit) <!-- MISRA C++ 2008 **required** rule 15-1-2 --> - (An empty throw shall only be used in the compound-statement of a catch handler) <!-- MISRA C++ 2008 **required** rule 15-1-3 --> - (Exceptions shall be raised only after start-up and before termination of the program (i.e., exceptions shall not be thrown in static constructors/destructors)) <!-- MISRA C++ 2008 **required** rule 15-3-1 --> - (There should be at least one exception handler to catch all otherwise unhandled exceptions) <!-- MISRA C++ 2008 advisory rule 15-3-2 --> - (Handlers of a function-try-block implementation of a class constructor or destructor shall not reference any non-static members from this class or its bases) <!-- MISRA C++ 2008 **required** rule 15-3-3 --> - (Each exception explicitly thrown in the code shall have a handler of compatible type in all call paths that could lead to that point) <!-- MISRA C++ 2008 **required** rule 15-3-4 --> - (A class type exception shall always be caught by reference) <!-- MISRA C++ 2008 **required** rule 15-3-5 --> - (Where multiple handlers are provided in a single try-catch statement or function-try-block for a derived class and some or all of its bases, the handlers shall be ordered most-derived to base class) <!-- MISRA C++ 2008 **required** rule 15-3-6 --> - (Where multiple handlers are provided in a single try-catch statement or function-try-block, any ellipsis handler shall occur last) <!-- MISRA C++ 2008 **required** rule 15-3-7 --> - (If a function is declared with an exception specification, then all declarations of the same function (in other translation units) shall be declared with the same set of type-ids) <!-- MISRA C++ 2008 **required** rule 15-4-1 --> - (A destructor shall not exit with an exception) <!-- MISRA C++ 2008 **required** rule 15-5-1 --> - (Where a function's declaration includes an exception specification, the function shall only be capable of throwing exceptions of the indicated types) <!-- MISRA C++ 2008 **required** rule 15-5-2 --> - (The terminate() function shall not be called implicitly (see earlier rules)) <!-- MISRA C++ 2008 **required** rule 15-5-3 --> - (`#``include` directives in a file shall only be preceded by other preprocessor directives or comments) <!-- MISRA C++ 2008 **required** rule 16-0-1 --> - (Macros shall only be defined or undefined in the global namespace) <!-- MISRA C++ 2008 **required** rule 16-0-2 --> - (`#``undef` shall not be used) <!-- MISRA C++ 2008 **required** rule 16-0-3 --> - (function-like macros shall not be defined) <!-- MISRA C++ 2008 **required** rule 16-0-4 --> - (Arguments to a function-like macro shall not contain tokens that look like preprocessing directives) <!-- MISRA C++ 2008 **required** rule 16-0-5 --> - (in the definition of a function-like macro, each instance of a parameter shall be enclosed in parentheses, unless it is used as the operand of `#` or `##`) <!-- MISRA C++ 2008 **required** rule 16-0-6 --> - (undefined macro identifiers shall not be used in `#``if` or `#``elif` preprocessor directives, except as operands to the `defined` operator) <!-- MISRA C++ 2008 **required** rule 16-0-7 --> - (if the `#` token appears as the first token on a line, then it shall be immediately followed by a preprocessing token) <!-- MISRA C++ 2008 **required** rule 16-0-8 --> - (The `defined` operator shall only be used in the form `defined ( identifier )` or `defined identifier`) <!-- MISRA C++ 2008 **required** rule 16-1-1 --> - (All `#``else`, `#``elif` and `#``endif` preprocessor directives shall reside in the same file as the `#``if` or `#``ifdef` directive to which they are related) <!-- MISRA C++ 2008 **required** rule 16-1-2 --> - (The preprocessor shall only be used for file inclusion and include guards) <!-- MISRA C++ 2008 **required** rule 16-2-1 --> - (macros shall only be used for include guards, type qualifiers, or storage class specifiers) <!-- MISRA C++ 2008 **required** rule 16-2-2 --> - (include guards shall be provided) <!-- MISRA C++ 2008 **required** rule 16-2-3 --> - (the ', ", /* or // character sequences shall not occur in a header file name) <!-- MISRA C++ 2008 **required** rule 16-2-4 --> - (the \ character should not occur in a header file name) <!-- MISRA C++ 2008 advisory rule 16-2-5 --> - (the `#``include` directive shall be followed by either a <filename> or "filename" sequence) <!-- MISRA C++ 2008 **required** rule 16-2-6 --> - (There shall be at most one occurrence of the `#` or `##` operators in a single macro definition) <!-- MISRA C++ 2008 **required** rule 16-3-1 --> - (The `#` and `##` operators should not be used) <!-- MISRA C++ 2008 advisory rule 16-3-2 --> - (All uses of the `#``pragma` directive shall be documented) <!-- MISRA C++ 2008 document rule 16-6-1 --> - (Reserved identifiers, macros and functions in the standard library shall not be defined, redefined or undefined) <!-- MISRA C++ 2008 **required** rule 17-0-1 --> - (The names of standard library macros and objects shall not be reused) <!-- MISRA C++ 2008 **required** rule 17-0-2 --> - (The names of standard library functions shall not be overridden) <!-- MISRA C++ 2008 **required** rule 17-0-3 --> . <!-- MISRA C++ 2008 **required** rule 17-0-4 (All library code shall conform to MISRA C++) IGNORED: We're using MISRA C++ only as a guideline for our own code, presuming that authors of well-established 3rd party libraries take their own reasonable measures to assure good code quality. --> - **longjmp**: The `setjmp` macro and `longjmp` function are evil. Do not use them. <!-- MISRA C++ 2008 **required** rule 17-0-5 --> - **Standard Libraries**: Do not use the C libraries (e.g. `<stdio.h>`); use the corresponding C++ libraries instead (e.g. `<cstdio>`). <!-- MISRA C++ 2008 **required** rule 18-0-1 --> - Do not use `atof`, `atoi`, or `atol`. <!-- MISRA C++ 2008 **required** rule 18-0-2 --> . - (The library functions abort, exit, getenv and system from <cstdlib> shall not be used) <!-- MISRA C++ 2008 **required** rule 18-0-3 --> - (The time handling functions of <ctime> shall not be used) <!-- MISRA C++ 2008 **required** rule 18-0-4 --> . - **Strings**: Do not use C-style strings, except as literals to initialize `std::string` objects. <!-- MISRA C++ 2008 MISRA C++ **required** rule 18-0-5 --> . - (The macro offsetof shall not be used) <!-- MISRA C++ 2008 **required** rule 18-2-1 --> . <!-- MISRA C++ 2008 **required** rule 18-4-1 (Dynamic heap memory allocation shall not be used) IGNORED: We're making heavy use of dynamic heap memory allocation and can't reasonably do without. --> . - (The signal handling facilities of <csignal> shall not be used) <!-- MISRA C++ 2008 **required** rule 18-7-1 --> - (The error indicator errno shall not be used) <!-- MISRA C++ 2008 **required** rule 19-3-1 --> - (The stream input/output library <cstdio> shall not be used) <!-- MISRA C++ 2008 **required** rule 27-0-1 --> .
POV-Ray/povray
source-doc/styleguide2.md
Markdown
agpl-3.0
35,552
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.configuration; import org.geomajas.annotation.Api; /** * A synthetic attribute has its value calculated and not stored in the database. It is typically built from the normal * attribute values. The value can be built using Spring expression language or in code. * <p/> * A synthetic attribute cannot be edited. * * @author Joachim Van der Auwera * @since 1.10.0 */ @Api(allMethods = true) public class SyntheticAttributeInfo extends AbstractReadOnlyAttributeInfo { private static final long serialVersionUID = 1100L; private String expression; /** * Expression (using Spring Expression Language) to build the attribute value). * <p/> * This will always result in a String attribute value. It is only used if no {@link #attributeBuilder} is given. * * @return expression for building the attribute */ public String getExpression() { return expression; } /** * Expression (using Spring Expression Language) to build the attribute value). * <p/> * This will always result in a String attribute value. It is only used if no {@link #attributeBuilder} is given. * * @param expression attribute expression in Spring Expression Language */ public void setExpression(String expression) { this.expression = expression; } }
olivermay/geomajas
face/geomajas-face-common-gwt/common-gwt/src/main/resources/org/geomajas/emul/org/geomajas/configuration/SyntheticAttributeInfo.java
Java
agpl-3.0
1,705
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 15:48:31 2015 @author: thomas.douenne """ # L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993 # Import de fonctions spécifiques à Openfisca Indirect Taxation from openfisca_france_indirect_taxation.examples.utils_example import graph_builder_bar_list from openfisca_france_indirect_taxation.examples.dataframes_from_legislation.get_accises import \ get_accise_ticpe_majoree # Recherche des paramètres de la législation liste = ['ticpe_gazole', 'ticpe_super9598', 'super_plombe_ticpe'] df_accises = get_accise_ticpe_majoree() # Réalisation des graphiques graph_builder_bar_list(df_accises['accise majoree sans plomb'], 1, 1) graph_builder_bar_list(df_accises['accise majoree diesel'], 1, 1) graph_builder_bar_list(df_accises['accise majoree super plombe'], 1, 1)
benjello/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/transports/plot_legislation/plot_ticpe_accises.py
Python
agpl-3.0
865
#!/usr/bin/env bash set -e set -x env if [ "$PYTHON" == "" ] then # python26 is required for RedHat/CentOS 5 if [ -x /usr/bin/python26 ] then PYTHON=python26 else PYTHON=python fi fi GENERATOR="$1" if [ "$GENERATOR" == "" ] then if [ -f /etc/debian_version ]; then GENERATOR=DEB fi if [ -f /etc/redhat-release ]; then GENERATOR=RPM fi fi if [ "$GENERATOR" != "DEB" -a "$GENERATOR" != "RPM" ] then echo "Usage: make-package.sh [DEB|RPM]" exit 1 fi if [ "$CMAKE" == "" ] then CMAKE="cmake" if which cmake28 then CMAKE="cmake28" fi fi if [ "$CPACK" == "" ] then CPACK="cpack" if which cpack28 then CPACK="cpack28" fi fi DIR=`dirname $0` cd "$DIR" DIR=`pwd` # Add node, etc. to the path PATH=$DIR/../bin:$PATH mkdir -p build cd build "$CMAKE" -DCMAKE_INSTALL_PREFIX=/opt -DPYTHON="$PYTHON" ../.. make # START: building in project root -------------------------- pushd ../.. ./bin/npm --python="${PYTHON}" rebuild # Need to rebuild ourselves since 'npm install' won't run gyp for us. ./bin/node ./ext/node/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js --python="$PYTHON" rebuild popd # END: building in project root ---------------------------- "$CPACK" -G "$GENERATOR"
sneumann/shiny-server
packaging/make-package.sh
Shell
agpl-3.0
1,222
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Implementation for VectorFileSensor class */ #include <stdexcept> #include <string> #include <iostream> #include <sstream> #include <list> #include <cstring> // strlen #include <capnp/any.h> #include <nupic/engine/Region.hpp> #include <nupic/engine/Spec.hpp> #include <nupic/proto/VectorFileSensorProto.capnp.h> #include <nupic/regions/VectorFileSensor.hpp> #include <nupic/utils/Log.hpp> #include <nupic/utils/StringUtils.hpp> //#include <nupic/os/FStream.hpp> #include <nupic/ntypes/Value.hpp> #include <nupic/ntypes/BundleIO.hpp> using namespace std; namespace nupic { //---------------------------------------------------------------------------- VectorFileSensor::VectorFileSensor(const ValueMap& params, Region* region) : RegionImpl(region), repeatCount_(1), iterations_(0), curVector_(0), activeOutputCount_(0), hasCategoryOut_(false), hasResetOut_(false), dataOut_(NTA_BasicType_Real32), categoryOut_(NTA_BasicType_Real32), resetOut_(NTA_BasicType_Real32), filename_(""), scalingMode_("none"), recentFile_("") { activeOutputCount_ = params.getScalar("activeOutputCount")->getValue<NTA_UInt32>(); if (params.contains("hasCategoryOut")) hasCategoryOut_ = params.getScalar("hasCategoryOut")->getValue<NTA_UInt32>() == 1; if (params.contains("hasResetOut")) hasResetOut_ = params.getScalar("hasResetOut")->getValue<NTA_UInt32>() == 1; if (params.contains("inputFile")) filename_ = *params.getString("inputFile"); if (params.contains("repeatCount")) repeatCount_ = params.getScalar("repeatCount")->getValue<NTA_UInt32>(); } VectorFileSensor::VectorFileSensor(BundleIO& bundle, Region* region) : RegionImpl(region), repeatCount_(1), iterations_(0), curVector_(0), activeOutputCount_(0), hasCategoryOut_(false), hasResetOut_(false), dataOut_(NTA_BasicType_Real32), categoryOut_(NTA_BasicType_Real32), resetOut_(NTA_BasicType_Real32), filename_(""), scalingMode_("none"), recentFile_("") { deserialize(bundle); } VectorFileSensor::VectorFileSensor( capnp::AnyPointer::Reader& proto, Region* region) : RegionImpl(region), repeatCount_(1), iterations_(0), curVector_(0), activeOutputCount_(0), hasCategoryOut_(false), hasResetOut_(false), dataOut_(NTA_BasicType_Real32), categoryOut_(NTA_BasicType_Real32), resetOut_(NTA_BasicType_Real32), filename_(""), scalingMode_("none"), recentFile_("") { read(proto); } void VectorFileSensor::initialize() { NTA_CHECK(region_ != nullptr); dataOut_ = region_->getOutputData("dataOut"); categoryOut_ = region_->getOutputData("categoryOut"); resetOut_ = region_->getOutputData("resetOut"); if (dataOut_.getCount() != activeOutputCount_) { NTA_THROW << "VectorFileSensor::init - wrong output size: " << dataOut_.getCount() << " should be: " << activeOutputCount_; } } VectorFileSensor::~VectorFileSensor() { } //---------------------------------------------------------------------------- void VectorFileSensor::compute() { // It's not necessarily an error to have no outputs. In this case we just return if (dataOut_.getCount() == 0) return; // Don't write if there is no open file. if (recentFile_ == "") { NTA_WARN << "VectorFileSesnsor compute() called, but there is no open file"; return; } NTA_CHECK(vectorFile_.vectorCount() > 0) << "VectorFileSensor::compute - no data vectors in memory." << "Perhaps no data file has been loaded using the 'loadFile'" << " execute command."; if (iterations_ % repeatCount_ == 0) { // Get index to next vector and copy scaled vector to our output curVector_++; curVector_ %= vectorFile_.vectorCount(); } Real *out = (Real *) dataOut_.getBuffer(); Size count = dataOut_.getCount(); UInt offset = 0; if (hasCategoryOut_) { Real * categoryOut = reinterpret_cast<Real *>(categoryOut_.getBuffer()); vectorFile_.getRawVector((nupic::UInt)curVector_, categoryOut, offset, 1); offset++; } if (hasResetOut_) { Real * resetOut = reinterpret_cast<Real *>(resetOut_.getBuffer()); vectorFile_.getRawVector((nupic::UInt)curVector_, resetOut, offset, 1); offset++; } vectorFile_.getScaledVector((nupic::UInt)curVector_, out, offset, count); iterations_++; } //-------------------------------------------------------------------------------- inline const char *checkExtensions(const std::string &filename, const char *const *extensions) { while(*extensions) { const char *ext = *extensions; if(filename.rfind(ext) == (filename.size() - ::strlen(ext))) return ext; ++extensions; } return nullptr; } //-------------------------------------------------------------------------------- /// Execute a VectorFilesensor specific command std::string VectorFileSensor::executeCommand(const std::vector<std::string>& args, Int64 index) { UInt32 argCount = args.size(); // Get the first argument (command string) NTA_CHECK(argCount > 0) << "VectorFileSensor: No command name"; string command = args[0]; // Process each command if ((command == "loadFile") || (command == "appendFile")) { NTA_CHECK(argCount > 1) << "VectorFileSensor: no filename specified for " << command; UInt32 labeled = 2; // Default format is 2 // string filename = ReadStringFromBuffer(*buf2); string filename(args[1]); cout << "In VectorFileSensor " << filename << endl; if (argCount == 3) { labeled = StringUtils::toUInt32(args[2]); } else { // Check for some common extensions. const char *csvExtensions[] = { ".csv", ".CSV", nullptr }; if(checkExtensions(filename, csvExtensions)) { cout << "Reading CSV file" << endl; labeled = 3; // CSV format. } } // Detect binary file format and set labeled flag to read little endian // binary file if (filename.substr(filename.size() - 3, 3) == "bin") { cout << "Reading binary file" << endl; labeled = 4; } if (labeled > (UInt32) VectorFile::maxFormat()) NTA_THROW << "VectorFileSensor: unknown file format '" << labeled << "'"; // Read in new set of vectors // If the command is loadFile, we clear the list first and reset the position // to the beginning if (command == "loadFile") vectorFile_.clear(false); //Timer t(true); UInt32 elementCount = activeOutputCount_; if (hasCategoryOut_) elementCount ++; if (hasResetOut_) elementCount ++; vectorFile_.appendFile(filename, elementCount, labeled); cout << "Read " << vectorFile_.vectorCount() << " vectors" << endl; //in " << t.getValue() << " seconds" << endl; if (command == "loadFile") seek(0); recentFile_ = filename; } else if (command == "dump") { nupic::Byte message[256]; Size n = ::sprintf(message, "VectorFileSensor isLabeled = %d repeatCount = %d vectorCount = %d iterations = %d\n", vectorFile_.isLabeled(), (int) repeatCount_, (int) vectorFile_.vectorCount(), (int) iterations_); //out.write(message, n); return string(message, n); } else if (command == "saveFile") { NTA_CHECK(argCount > 1) << "VectorFileSensor: no filename specified for " << command; Int32 format = 2; // Default format is 2 Int64 begin = 0, end = 0; bool hasEnd = false; string filename(args[1]); if (argCount > 2) { format = StringUtils::toUInt32(args[2]); if ((format < 0) || (format > VectorFile::maxFormat())) NTA_THROW << "VectorFileSensor: unknown file format '" << format << "'"; } if (argCount > 3) { begin = StringUtils::toUInt32(args[3]); } if (argCount > 4) { end = StringUtils::toUInt32(args[4]); hasEnd = true; } NTA_CHECK(argCount <= 5) << "VectorFileSensor: too many arguments"; OFStream f(filename.c_str()); if (hasEnd) vectorFile_.saveVectors(f, dataOut_.getCount(), format, begin, end); else vectorFile_.saveVectors(f, dataOut_.getCount(), format, begin, end); } else { NTA_THROW << "VectorFileSensor: Unknown execute command: '" << command << "' sent!"; } return ""; } //-------------------------------------------------------------------------------- void VectorFileSensor::setParameterFromBuffer(const std::string& name, Int64 index, IReadBuffer& value) { const char* where = "VectorFileSensor, while setting parameter: "; UInt32 int_param = 0; if (name == "repeatCount") { NTA_CHECK(value.read(int_param) == 0) << where << "Unable to read repeatCount: " << int_param << " - Should be a positive integer"; if (int_param >= 1) { repeatCount_ = int_param; } } else if (name == "position") { NTA_CHECK(value.read(int_param) == 0) << where << "Unable to read position: " << int_param << " - Should be a positive integer"; if ( int_param < vectorFile_.vectorCount() ) { seek(int_param); } else { NTA_THROW << "VectorFileSensor: invalid position " << " to seek to: " << int_param; } } else if (name == "scalingMode") { // string mode = ReadStringFromvaluefer(value); string mode(value.getData(), value.getSize()); if (mode == "none") vectorFile_.resetScaling(); else if (mode == "standardForm") vectorFile_.setStandardScaling(); else if (mode != "custom") // Do nothing if set to custom NTA_THROW << where << " Unknown scaling mode: " << mode; scalingMode_ = mode; } else if (name == "hasCategoryOut") { NTA_CHECK(value.read(int_param) == 0) << where << "Unable to read hasCategoryOut: " << int_param << " - Should be a positive integer"; hasCategoryOut_ = int_param == 1; } else if (name == "hasResetOut") { NTA_CHECK(value.read(int_param) == 0) << where << "Unable to read hasResetOut: " << int_param << " - Should be a positive integer"; hasResetOut_ = int_param == 1; } else { NTA_THROW << where << "couldn't set '" << name << "'"; } } //-------------------------------------------------------------------------------- void VectorFileSensor::getParameterFromBuffer(const std::string& name, Int64 index, IWriteBuffer& value) { const char* where = "VectorFileSensor, while getting parameter: "; Int32 res = 0; if (name == "vectorCount") { res = value.write((UInt32)vectorFile_.vectorCount()); } else if (name == "position") { res = value.write(UInt32(curVector_+1)); } else if (name == "repeatCount") { res = value.write(UInt32(repeatCount_)); } else if (name == "scalingMode") { // res = value.writeString(scalingMode_.data(), (Size)scalingMode_.size()); res = value.write(scalingMode_.data(), (Size)scalingMode_.size()); } else if (name == "recentFile") { // res = value.writeString(recentFile_.data(), (Size)recentFile_.size()); if (recentFile_.empty()) { res = value.write("", 1); } else { res = value.write(recentFile_.data(), (Size)recentFile_.size()); } } else if (name == "scaleVector") { stringstream buf; Real s = 0, o = 0; for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.getScaling(i, s, o); buf << s << " "; } string bufstr = buf.str(); res = value.write(bufstr.c_str(), (Size)bufstr.size()); } else if (name == "activeOutputCount") { res = value.write(UInt32(activeOutputCount_)); } else if (name == "maxOutputVectorCount") { res = value.write(UInt32(vectorFile_.vectorCount() * repeatCount_)); } else if (name == "offsetVector") { stringstream buf; Real s = 0, o = 0; for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.getScaling(i, s, o); buf << o << " "; } string bufstr = buf.str(); res = value.write(bufstr.c_str(), (Size)bufstr.size()); } else if (name == "hasCategoryOut") { res = value.write(UInt32(hasCategoryOut_)); } else if (name == "hasResetOut") { res = value.write(UInt32(hasResetOut_)); } NTA_CHECK(res >= 0) << where << "couldn't retrieve '" << name << "'"; } //---------------------------------------------------------------------- void VectorFileSensor::seek(int n) { NTA_CHECK( (n >= 0) && ((unsigned int) n < vectorFile_.vectorCount()) ); // Set curVector_ to be one before the vector we want and reset iterations iterations_ = 0; curVector_ = n - 1; //circular-buffer, reached one end of vector/line, continue fro the other if (n - 1 <= 0) curVector_ = (NTA_Size)vectorFile_.vectorCount() - 1; } size_t VectorFileSensor::getNodeOutputElementCount(const std::string& outputName) { NTA_CHECK(outputName == "dataOut") << "Invalid output name: " << outputName; return activeOutputCount_; } void VectorFileSensor::serialize(BundleIO& bundle) { std::ofstream & f = bundle.getOutputStream("vfs"); f << repeatCount_ << " " << activeOutputCount_ << " " << filename_ << " " << scalingMode_ << " "; f.close(); } void VectorFileSensor::deserialize(BundleIO& bundle) { std::ifstream& f = bundle.getInputStream("vfs"); f >> repeatCount_ >> activeOutputCount_ >> filename_ >> scalingMode_; f.close(); } void VectorFileSensor::write(capnp::AnyPointer::Builder& anyProto) const { auto proto = anyProto.getAs<VectorFileSensorProto>(); proto.setRepeatCount(repeatCount_); proto.setActiveOutputCount(activeOutputCount_); proto.setFilename(filename_.c_str()); proto.setScalingMode(scalingMode_.c_str()); } void VectorFileSensor::read(capnp::AnyPointer::Reader& anyProto) { auto proto = anyProto.getAs<VectorFileSensorProto>(); repeatCount_ = proto.getRepeatCount(); activeOutputCount_ = proto.getActiveOutputCount(); filename_ = proto.getFilename().cStr(); scalingMode_ = proto.getScalingMode().cStr(); } Spec* VectorFileSensor::createSpec() { auto ns = new Spec; ns->description = "VectorFileSensor is a basic sensor for reading files containing vectors.\n" "\n" "VectorFileSensor reads in a text file containing lists of numbers\n" "and outputs these vectors in sequence. The output is updated\n" "each time the sensor's compute() method is called. If\n" "repeatCount is > 1, then each vector is repeated that many times\n" "before moving to the next one. The sensor loops when the end of\n" "the vector list is reached. The default file format\n" "is as follows (assuming the sensor is configured with N outputs):\n" "\n" " e11 e12 e13 ... e1N\n" " e21 e22 e23 ... e2N\n" " : \n" " eM1 eM2 eM3 ... eMN\n" "\n" "In this format the sensor ignores all whitespace in the file, including newlines\n" "If the file contains an incorrect number of floats, the sensor has no way\n" "of checking and will silently ignore the extra numbers at the end of the file.\n" "\n" "The sensor can also read in comma-separated (CSV) files following the format:\n" "\n" " e11, e12, e13, ... ,e1N\n" " e21, e22, e23, ... ,e2N\n" " : \n" " eM1, eM2, eM3, ... ,eMN\n" "\n" "When reading CSV files the sensor expects that each line contains a new vector\n" "Any line containing too few elements or any text will be ignored. If there are\n" "more than N numbers on a line, the sensor retains only the first N.\n"; ns->outputs.add( "dataOut", OutputSpec("Data read from file", NTA_BasicType_Real32, 0, // count true, // isRegionLevel true // isDefaultOutput )); ns->outputs.add( "categoryOut", OutputSpec("The current category encoded as a float (represent a whole number)", NTA_BasicType_Real32, 1, // count true, // isRegionLevel false // isDefaultOutput )); ns->outputs.add( "resetOut", OutputSpec("Sequence reset signal: 0 - do nothing, otherwise start a new sequence", NTA_BasicType_Real32, 1, // count true, // isRegionLevel false // isDefaultOutput )); ns->parameters.add( "vectorCount", ParameterSpec( "The number of vectors currently loaded in memory.", NTA_BasicType_UInt32, 1, // elementCount "interval: [0, ...]", // constraints "0", // defaultValue ParameterSpec::ReadOnlyAccess )); ns->parameters.add( "position", ParameterSpec( "Set or get the current position within the list of vectors in memory.", NTA_BasicType_UInt32, 1, // elementCount "interval: [0, ...]", // constraints "0", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "repeatCount", ParameterSpec( "Set or get the current repeatCount. Each vector is repeated\n" "repeatCount times before moving to the next one.", NTA_BasicType_UInt32, 1, // elementCount "interval: [1, ...]", // constraints "1", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "recentFile", ParameterSpec( "Writes output vectors to this file on each compute. Will append to any\n" "existing data in the file. This parameter must be set at runtime before\n" "the first compute is called. Throws an exception if it is not set or\n" "the file cannot be written to.\n", NTA_BasicType_Byte, 0, // elementCount "", // constraints "", // defaultValue ParameterSpec::ReadOnlyAccess )); ns->parameters.add( "scalingMode", ParameterSpec( "During compute, each vector is adjusted as follows. If X is the data vector,\n" "S the scaling vector and O the offset vector, then the node's output\n" " Y[i] = S[i]*(X[i] + O[i]).\n" "\n" "Scaling is applied according to scalingMode as follows:\n" "\n" " If 'none', the vectors are unchanged, i.e. S[i]=1 and O[i]=0.\n" " If 'standardForm', S[i] is 1/standard deviation(i) and O[i] = - mean(i)\n" " If 'custom', each component is adjusted according to the vectors specified by the\n" "setScale and setOffset commands.\n", NTA_BasicType_Byte, 0, // elementCount "", // constraints "none", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "scaleVector", ParameterSpec( "Set or return the current scale vector S.\n", NTA_BasicType_Real32, 0, // elementCount "", // constraints "", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "offsetVector", ParameterSpec( "Set or return the current offset vector 0.\n", NTA_BasicType_Real32, 0, // elementCount "", // constraints "", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "activeOutputCount", ParameterSpec( "The number of active outputs of the node.", NTA_BasicType_UInt32, 1, // elementCount "interval: [0, ...]", // constraints "", // default Value ParameterSpec::CreateAccess )); ns->parameters.add( "maxOutputVectorCount", ParameterSpec( "The number of output vectors that can be generated by this sensor\n" "under the current configuration.", NTA_BasicType_UInt32, 1, // elementCount "interval: [0, ...]", // constraints "0", // defaultValue ParameterSpec::ReadOnlyAccess )); ns->parameters.add( "hasCategoryOut", ParameterSpec( "Category info is present in data file.", NTA_BasicType_UInt32, 1, // elementCount "enum: [0, 1]", // constraints "0", // defaultValue ParameterSpec::ReadWriteAccess )); ns->parameters.add( "hasResetOut", ParameterSpec( "New sequence reset signal is present in data file.", NTA_BasicType_UInt32, 1, // elementCount "enum: [0, 1]", // constraints "0", // defaultValue ParameterSpec::ReadWriteAccess )); ns->commands.add( "loadFile", CommandSpec( "loadFile <filename> [file_format]\n" "Reads vectors from the specified file, replacing any vectors\n" "currently in the list. Position is set to zero. \n" "Available file formats are: \n" " 0 # Reads in unlabeled file with first number = element count\n" " 1 # Reads in a labeled file with first number = element count (deprecated)\n" " 2 # Reads in unlabeled file without element count (default)\n" " 3 # Reads in a csv file\n" )); ns->commands.add( "appendFile", CommandSpec( "appendFile <filename> [file_format]\n" "Reads vectors from the specified file, appending to current vector list.\n" "Position remains unchanged. Available file formats are: \n" " 0 # Reads in unlabeled file with first number = element count\n" " 1 # Reads in a labeled file with first number = element count (deprecated)\n" " 2 # Reads in unlabeled file without element count (default)\n" " 3 # Reads in a csv file\n")); ns->commands.add( "saveFile", CommandSpec( "saveFile filename [format [begin [end]]]\n" "Save the currently loaded vectors to a file. Typically used for debugging\n" "but may be used to convert between formats.\n")); ns->commands.add("dump", CommandSpec("Displays some debugging info.")); return ns; } void VectorFileSensor::getParameterArray(const std::string& name, Int64 index, Array & a) { if (a.getCount() != dataOut_.getCount()) NTA_THROW << "getParameterArray(), array size is: " << a.getCount() << "instead of : " << dataOut_.getCount(); Real * buf = (Real *)a.getBuffer(); Real dummy; if (name == "scaleVector") { Real * buf = (Real *)a.getBuffer(); for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.getScaling(i, buf[i], dummy); } } else if (name == "offsetVector") { for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.getScaling(i, dummy, buf[i]); } } else { NTA_THROW << "VectorfileSensor::getParameterArray(), unknown parameter: " << name; } } void VectorFileSensor::setParameterArray(const std::string& name, Int64 index, const Array & a) { if (a.getCount() != dataOut_.getCount()) NTA_THROW << "setParameterArray(), array size is: " << a.getCount() << "instead of : " << dataOut_.getCount(); Real * buf = (Real *)a.getBuffer(); if (name == "scaleVector") { for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.setScale(i, buf[i]); } } else if (name == "offsetVector") { for (UInt i = 0; i < vectorFile_.getElementCount(); i++) { vectorFile_.setOffset(i, buf[i]); } } else { NTA_THROW << "VectorfileSensor::setParameterArray(), unknown parameter: " << name; } scalingMode_ = "custom"; } size_t VectorFileSensor::getParameterArrayCount(const std::string& name, Int64 index) { if (name != "scaleVector" && name != "offsetVector") NTA_THROW << "VectorFileSensor::getParameterArrayCount(), unknown array parameter: " << name; return dataOut_.getCount(); } } // end namespace nupic
scottpurdy/nupic.core
src/nupic/regions/VectorFileSensor.cpp
C++
agpl-3.0
24,587
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** 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 GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QVariant> #include <QStringList> #include "qanyuri_p.h" #include "qatomicstring_p.h" #include "qbuiltintypes_p.h" #include "qcommonsequencetypes_p.h" #include "qgenericsequencetype_p.h" #include "qinteger_p.h" #include "qitem_p.h" #include "qsequencetype_p.h" #include "qvariableloader_p.h" #include "qxmlquery_p.h" QT_BEGIN_NAMESPACE namespace QPatternist { class VariantListIterator : public ListIteratorPlatform<QVariant, Item, VariantListIterator> { public: inline VariantListIterator(const QVariantList &list) : ListIteratorPlatform<QVariant, Item, VariantListIterator>(list) { } private: friend class ListIteratorPlatform<QVariant, Item, VariantListIterator>; inline Item inputToOutputItem(const QVariant &inputType) const { return AtomicValue::toXDM(inputType); } }; class StringListIterator : public ListIteratorPlatform<QString, Item, StringListIterator> { public: inline StringListIterator(const QStringList &list) : ListIteratorPlatform<QString, Item, StringListIterator>(list) { } private: friend class ListIteratorPlatform<QString, Item, StringListIterator>; static inline Item inputToOutputItem(const QString &inputType) { return AtomicString::fromValue(inputType); } }; /** * Takes two DynamicContext instances, and redirects the storage of temporary trees * to one of them. * * @since 4.5 */ class TemporaryTreesRedirectingContext : public DelegatingDynamicContext { public: TemporaryTreesRedirectingContext(const DynamicContext::Ptr &other, const DynamicContext::Ptr &modelStorage) : DelegatingDynamicContext(other) , m_modelStorage(modelStorage) { Q_ASSERT(m_modelStorage); } virtual void addNodeModel(const QAbstractXmlNodeModel::Ptr &nodeModel) { m_modelStorage->addNodeModel(nodeModel); } private: const DynamicContext::Ptr m_modelStorage; }; } using namespace QPatternist; SequenceType::Ptr VariableLoader::announceExternalVariable(const QXmlName name, const SequenceType::Ptr &declaredType) { Q_UNUSED(declaredType); const QVariant &variant = m_bindingHash.value(name); if(variant.isNull()) return SequenceType::Ptr(); else if(variant.userType() == qMetaTypeId<QIODevice *>()) return CommonSequenceTypes::ExactlyOneAnyURI; else if(variant.userType() == qMetaTypeId<QXmlQuery>()) { const QXmlQuery variableQuery(qvariant_cast<QXmlQuery>(variant)); return variableQuery.d->expression()->staticType(); } else { return makeGenericSequenceType(AtomicValue::qtToXDMType(qvariant_cast<QXmlItem>(variant)), Cardinality::exactlyOne()); } } Item::Iterator::Ptr VariableLoader::evaluateSequence(const QXmlName name, const DynamicContext::Ptr &context) { const QVariant &variant = m_bindingHash.value(name); Q_ASSERT_X(!variant.isNull(), Q_FUNC_INFO, "We assume that we have a binding."); /* Same code as in the default clause below. */ if(variant.userType() == qMetaTypeId<QIODevice *>()) return makeSingletonIterator(itemForName(name)); else if(variant.userType() == qMetaTypeId<QXmlQuery>()) { const QXmlQuery variableQuery(qvariant_cast<QXmlQuery>(variant)); return variableQuery.d->expression()->evaluateSequence(DynamicContext::Ptr(new TemporaryTreesRedirectingContext(variableQuery.d->dynamicContext(), context))); } const QVariant v(qvariant_cast<QXmlItem>(variant).toAtomicValue()); switch(v.type()) { case QVariant::StringList: return Item::Iterator::Ptr(new StringListIterator(v.toStringList())); case QVariant::List: return Item::Iterator::Ptr(new VariantListIterator(v.toList())); default: return makeSingletonIterator(itemForName(name)); } } Item VariableLoader::itemForName(const QXmlName &name) const { const QVariant &variant = m_bindingHash.value(name); if(variant.userType() == qMetaTypeId<QIODevice *>()) return Item(AnyURI::fromValue(QLatin1String("tag:trolltech.com,2007:QtXmlPatterns:QIODeviceVariable:") + m_namePool->stringForLocalName(name.localName()))); const QXmlItem item(qvariant_cast<QXmlItem>(variant)); if(item.isNode()) return Item::fromPublic(item); else { const QVariant atomicValue(item.toAtomicValue()); /* If the atomicValue is null it means it doesn't exist in m_bindingHash, and therefore it must * be a QIODevice, since Patternist guarantees to only ask for variables that announceExternalVariable() * has accepted. */ if(atomicValue.isNull()) return Item(AnyURI::fromValue(QLatin1String("tag:trolltech.com,2007:QtXmlPatterns:QIODeviceVariable:") + m_namePool->stringForLocalName(name.localName()))); else return AtomicValue::toXDM(atomicValue); } } Item VariableLoader::evaluateSingleton(const QXmlName name, const DynamicContext::Ptr &) { return itemForName(name); } bool VariableLoader::isSameType(const QVariant &v1, const QVariant &v2) const { /* Are both of type QIODevice *? */ if(v1.userType() == qMetaTypeId<QIODevice *>() && v1.userType() == v2.userType()) return true; /* Ok, we have two QXmlItems. */ const QXmlItem i1(qvariant_cast<QXmlItem>(v1)); const QXmlItem i2(qvariant_cast<QXmlItem>(v2)); if(i1.isNode()) { Q_ASSERT(false); return false; } else if(i2.isAtomicValue()) return i1.toAtomicValue().type() == i2.toAtomicValue().type(); else { /* One is an atomic, the other is a node or they are null. */ return false; } } void VariableLoader::removeBinding(const QXmlName &name) { m_bindingHash.remove(name); } bool VariableLoader::hasBinding(const QXmlName &name) const { return m_bindingHash.contains(name) || (m_previousLoader && m_previousLoader->hasBinding(name)); } QVariant VariableLoader::valueFor(const QXmlName &name) const { if(m_bindingHash.contains(name)) return m_bindingHash.value(name); else if(m_previousLoader) return m_previousLoader->valueFor(name); else return QVariant(); } void VariableLoader::addBinding(const QXmlName &name, const QVariant &value) { m_bindingHash.insert(name, value); } bool VariableLoader::invalidationRequired(const QXmlName &name, const QVariant &variant) const { return hasBinding(name) && !isSameType(valueFor(name), variant); } QT_END_NAMESPACE
CodeDJ/qt5-hidpi
qt/qtxmlpatterns/src/xmlpatterns/api/qvariableloader.cpp
C++
lgpl-2.1
9,111
/* * JOSSO: Java Open Single Sign-On * * Copyright 2004-2009, Atricore, Inc. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.josso.gateway.session.exceptions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author <a href="mailto:sgonzalez@josso.org">Sebastian Gonzalez Oyuela</a> * @version $Id: TooManyOpenSessionsException.java 543 2008-03-18 21:34:58Z sgonzalez $ */ public class TooManyOpenSessionsException extends SSOSessionException { private static final Log logger = LogFactory.getLog(TooManyOpenSessionsException.class); public TooManyOpenSessionsException(int openSessions) { super("Too many open sessions : " + openSessions); } }
webbfontaine/josso1
core/josso-core/src/main/java/org/josso/gateway/session/exceptions/TooManyOpenSessionsException.java
Java
lgpl-2.1
1,467
/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org> * * 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 */ #include "qtcamflickerreduction.h" #include "qtcamcapability_p.h" QtCamFlickerReduction::QtCamFlickerReduction(QtCamDevice *dev, QObject *parent) : QtCamCapability(new QtCamCapabilityPrivate(dev, QtCamCapability::FlickerReduction, "flicker-mode"), parent) { } QtCamFlickerReduction::~QtCamFlickerReduction() { } QtCamFlickerReduction::FlickerReductionMode QtCamFlickerReduction::value() { int val = 0; if (!d_ptr->intValue(&val)) { return QtCamFlickerReduction::Auto; } switch (val) { case QtCamFlickerReduction::Off: case QtCamFlickerReduction::FiftyHz: case QtCamFlickerReduction::SixtyHz: return (QtCamFlickerReduction::FlickerReductionMode)val; default: return QtCamFlickerReduction::Auto; } } bool QtCamFlickerReduction::setValue(const QtCamFlickerReduction::FlickerReductionMode& mode) { return d_ptr->setIntValue(mode, false); }
foolab/cameraplus
lib/qtcamflickerreduction.cpp
C++
lgpl-2.1
1,744
/** * This is a simple mechanism to bind Inkscape to Java, and thence * to all of the nice things that can be layered upon that. * * Authors: * Bob Jamison * * Copyright (c) 2007-2008 Inkscape.org * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * Note that these DOM files are implementations of the Java * interface package found here: * http://www.w3.org/TR/DOM-Level-2-Style/ */ package org.inkscape.dom.stylesheets; import org.w3c.dom.Node; import org.w3c.dom.stylesheets.StyleSheet; import org.w3c.dom.stylesheets.MediaList; public class StyleSheetImpl implements org.w3c.dom.stylesheets.StyleSheet { public native String getType(); public native boolean getDisabled(); public native void setDisabled(boolean disabled); public native Node getOwnerNode(); public native StyleSheet getParentStyleSheet(); public native String getHref(); public native String getTitle(); public native MediaList getMedia(); }
step21/inkscape-osx-packaging-native
src/bind/java/org/inkscape/dom/stylesheets/StyleSheetImpl.java
Java
lgpl-2.1
1,655
/** * Copyright (c) 2010-present Abixen Systems. 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.abixen.platform.core.configuration; import com.abixen.platform.core.configuration.properties.AbstractPlatformMailConfigurationProperties; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Properties; @Configuration public class PlatformMailConfiguration { private static Logger log = Logger.getLogger(PlatformMailConfiguration.class.getName()); @Autowired private AbstractPlatformMailConfigurationProperties platformMailConfigurationProperties; @Bean public JavaMailSender javaMailService() { log.debug("javaMailService()"); JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(platformMailConfigurationProperties.getHost()); javaMailSender.setPort(platformMailConfigurationProperties.getPort()); javaMailSender.setUsername(platformMailConfigurationProperties.getUser().getUsername()); javaMailSender.setPassword(platformMailConfigurationProperties.getUser().getPassword()); javaMailSender.setJavaMailProperties(getMailProperties()); return javaMailSender; } private Properties getMailProperties() { Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", platformMailConfigurationProperties.getTransport().getProtocol()); properties.setProperty("mail.smtp.auth", platformMailConfigurationProperties.getSmtp().getAuth() ? "true" : "false"); properties.setProperty("mail.smtp.starttls.enable", platformMailConfigurationProperties.getSmtp().getStarttls().getEnable() ? "true" : "false"); properties.setProperty("mail.debug", platformMailConfigurationProperties.getDebug() ? "true" : "false"); return properties; } }
alvin-reyes/abixen-platform
abixen-platform-core/src/main/java/com/abixen/platform/core/configuration/PlatformMailConfiguration.java
Java
lgpl-2.1
2,638
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.workplace.tools.accounts; import org.opencms.file.CmsUser; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; /** * Dialog to edit new or existing system user in the administration view.<p> * * @since 6.0.0 */ public class CmsEditUserDialog extends A_CmsEditUserDialog { /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsEditUserDialog(CmsJspActionElement jsp) { super(jsp); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsEditUserDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * @see org.opencms.workplace.tools.accounts.A_CmsEditUserDialog#createUser(java.lang.String, java.lang.String, java.lang.String, java.util.Map) */ @Override protected CmsUser createUser(String name, String pwd, String desc, Map<String, Object> info) throws CmsException { return getCms().createUser(name, pwd, desc, info); } /** * @see org.opencms.workplace.tools.accounts.A_CmsEditUserDialog#getListClass() */ @Override protected String getListClass() { return CmsUsersList.class.getName(); } /** * @see org.opencms.workplace.tools.accounts.A_CmsEditUserDialog#getListRootPath() */ @Override protected String getListRootPath() { return "/accounts/orgunit/users"; } /** * @see org.opencms.workplace.tools.accounts.A_CmsEditUserDialog#isEditable(org.opencms.file.CmsUser) */ @Override protected boolean isEditable(CmsUser user) { return true; } /** * @see org.opencms.workplace.tools.accounts.A_CmsEditUserDialog#writeUser(org.opencms.file.CmsUser) */ @Override protected void writeUser(CmsUser user) throws CmsException { getCms().writeUser(user); } }
it-tavis/opencms-core
src-modules/org/opencms/workplace/tools/accounts/CmsEditUserDialog.java
Java
lgpl-2.1
3,402
/******************************************************************************* * This file is part of the Polyglot extensible compiler framework. * * Copyright (c) 2000-2012 Polyglot project group, Cornell University * Copyright (c) 2006-2012 IBM Corporation * All rights reserved. * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This program and the accompanying materials are made available under * the terms of the Lesser GNU Public License v2.0 which accompanies this * distribution. * * The development of the Polyglot project has been supported by a * number of funding sources, including DARPA Contract F30602-99-1-0533, * monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and * N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302, * and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan * Research Fellowship, and an Intel Research Ph.D. Fellowship. * * See README for contributors. ******************************************************************************/ package ppg.code; public class ActionCode extends Code { public ActionCode(String actionCode) { value = actionCode; } @Override public Object clone() { return new ActionCode(value.toString()); } @Override public String toString() { return "action code {:\n" + value + "\n:}\n"; } }
liujed/polyglot-eclipse
tools/ppg/src/ppg/code/ActionCode.java
Java
lgpl-2.1
1,561
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "DiscreteNucleationMarker.h" #include "DiscreteNucleationMap.h" registerMooseObject("PhaseFieldApp", DiscreteNucleationMarker); InputParameters DiscreteNucleationMarker::validParams() { InputParameters params = Marker::validParams(); params.addClassDescription("Mark new nucleation sites for refinement"); params.addRequiredParam<UserObjectName>("map", "DiscreteNucleationMap user object"); return params; } DiscreteNucleationMarker::DiscreteNucleationMarker(const InputParameters & parameters) : Marker(parameters), _map(getUserObject<DiscreteNucleationMap>("map")), _periodic(_map.getPeriodic()), _inserter(_map.getInserter()), _int_width(_map.getWidth()), _nucleus_list(_inserter.getNucleusList()) { } Marker::MarkerValue DiscreteNucleationMarker::computeElementMarker() { const RealVectorValue centroid = _current_elem->centroid(); const Real size = 0.5 * _current_elem->hmax(); // check if the surface of a nucleus might touch the element for (unsigned i = 0; i < _nucleus_list.size(); ++i) { // get the radius of the current nucleus const Real radius = _nucleus_list[i].radius; // use a non-periodic or periodic distance const Real r = _periodic < 0 ? (centroid - _nucleus_list[i].center).norm() : _mesh.minPeriodicDistance(_periodic, centroid, _nucleus_list[i].center); if (r < radius + size && r > radius - size && size > _int_width) return REFINE; } // We return don't mark to allow coarsening when used in a ComboMarker return DONT_MARK; }
harterj/moose
modules/phase_field/src/markers/DiscreteNucleationMarker.C
C++
lgpl-2.1
1,901
\hypertarget{classCqrs_1_1EventStore_1_1Bus_1_1EventConverter}{}\section{Cqrs.\+Event\+Store.\+Bus.\+Event\+Converter Class Reference} \label{classCqrs_1_1EventStore_1_1Bus_1_1EventConverter}\index{Cqrs.\+Event\+Store.\+Bus.\+Event\+Converter@{Cqrs.\+Event\+Store.\+Bus.\+Event\+Converter}} \subsection*{Static Public Member Functions} \begin{DoxyCompactItemize} \item static T\+Event \hyperlink{classCqrs_1_1EventStore_1_1Bus_1_1EventConverter_a22d7d8455731564574dc9684c272e6d2_a22d7d8455731564574dc9684c272e6d2}{Get\+Event\+From\+Data$<$ T\+Event $>$} (byte\mbox{[}$\,$\mbox{]} event\+Data, string type\+Name) \end{DoxyCompactItemize} \subsection{Member Function Documentation} \mbox{\Hypertarget{classCqrs_1_1EventStore_1_1Bus_1_1EventConverter_a22d7d8455731564574dc9684c272e6d2_a22d7d8455731564574dc9684c272e6d2}\label{classCqrs_1_1EventStore_1_1Bus_1_1EventConverter_a22d7d8455731564574dc9684c272e6d2_a22d7d8455731564574dc9684c272e6d2}} \index{Cqrs\+::\+Event\+Store\+::\+Bus\+::\+Event\+Converter@{Cqrs\+::\+Event\+Store\+::\+Bus\+::\+Event\+Converter}!Get\+Event\+From\+Data$<$ T\+Event $>$@{Get\+Event\+From\+Data$<$ T\+Event $>$}} \index{Get\+Event\+From\+Data$<$ T\+Event $>$@{Get\+Event\+From\+Data$<$ T\+Event $>$}!Cqrs\+::\+Event\+Store\+::\+Bus\+::\+Event\+Converter@{Cqrs\+::\+Event\+Store\+::\+Bus\+::\+Event\+Converter}} \subsubsection{\texorpdfstring{Get\+Event\+From\+Data$<$ T\+Event $>$()}{GetEventFromData< TEvent >()}} {\footnotesize\ttfamily static T\+Event Cqrs.\+Event\+Store.\+Bus.\+Event\+Converter.\+Get\+Event\+From\+Data$<$ T\+Event $>$ (\begin{DoxyParamCaption}\item[{byte \mbox{[}$\,$\mbox{]}}]{event\+Data, }\item[{string}]{type\+Name }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [static]}}
Chinchilla-Software-Com/CQRS
wiki/docs/2.1/latex/classCqrs_1_1EventStore_1_1Bus_1_1EventConverter.tex
TeX
lgpl-2.1
1,735
// @(#)root/tree:$Id$ // Author: Rene Brun 14/01/2001 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TBranchElement #define ROOT_TBranchElement ////////////////////////////////////////////////////////////////////////// // // // TBranchElement // // // // A Branch for the case of an object. // ////////////////////////////////////////////////////////////////////////// #ifndef ROOT_TBranch #include "TBranch.h" #endif #ifndef ROOT_TClassRef #include "TClassRef.h" #endif #ifndef ROOT_TTree #include "TTree.h" #endif #ifndef ROOT_TError #include "TError.h" #endif #include <vector> class TFolder; class TStreamerInfo; class TVirtualCollectionProxy; class TVirtualCollectionIterators; class TVirtualCollectionPtrIterators; class TVirtualArray; namespace TStreamerInfoActions { class TActionSequence; } class TBranchElement : public TBranch { // Friends friend class TTreeCloner; // Types protected: enum { kBranchFolder = BIT(14), kDeleteObject = BIT(16), // We are the owner of fObject. kCache = BIT(18), // Need to pushd/pop fOnfileObject. kOwnOnfileObj = BIT(19), // We are the owner of fOnfileObject. kAddressSet = BIT(20), // The addressing set have been called for this branch kMakeClass = BIT(21), // This branch has been switched to using the MakeClass Mode kDecomposedObj= BIT(21) // More explicit alias for kMakeClass. }; // Data Members protected: TString fClassName; // Class name of referenced object TString fParentName; // Name of parent class TString fClonesName; // Name of class in TClonesArray (if any) TVirtualCollectionProxy *fCollProxy; //! collection interface (if any) UInt_t fCheckSum; // CheckSum of class Int_t fClassVersion; // Version number of class Int_t fID; // element serial number in fInfo Int_t fType; // branch type Int_t fStreamerType; // branch streamer type Int_t fMaximum; // Maximum entries for a TClonesArray or variable array Int_t fSTLtype; //! STL container type Int_t fNdata; //! Number of data in this branch TBranchElement *fBranchCount; // pointer to primary branchcount branch TBranchElement *fBranchCount2; // pointer to secondary branchcount branch TStreamerInfo *fInfo; //! Pointer to StreamerInfo char *fObject; //! Pointer to object at *fAddress TVirtualArray *fOnfileObject; //! Place holder for the onfile representation of data members. Bool_t fInit; //! Initialization flag for branch assignment Bool_t fInitOffsets; //! Initialization flag to not endlessly recalculate offsets TClassRef fTargetClass; //! Reference to the target in-memory class TClassRef fCurrentClass; //! Reference to current (transient) class definition TClassRef fParentClass; //! Reference to class definition in fParentName TClassRef fBranchClass; //! Reference to class definition in fClassName TClassRef fClonesClass; //! Reference to class definition in fClonesName Int_t *fBranchOffset; //! Sub-Branch offsets with respect to current transient class Int_t fBranchID; //! ID number assigned by a TRefTable. std::vector<Int_t> fIDs; //! List of the serial number of all the StreamerInfo to be used. TStreamerInfoActions::TActionSequence *fReadActionSequence; //! Set of actions to be executed to extract the data from the basket. TStreamerInfoActions::TActionSequence *fFillActionSequence; //! Set of actions to be executed to write the data to the basket. TVirtualCollectionIterators *fIterators; //! holds the iterators when the branch is of fType==4. TVirtualCollectionPtrIterators *fPtrIterators; //! holds the iterators when the branch is of fType==4 and it is a split collection of pointers. // Not implemented private: TBranchElement(const TBranchElement&); // not implemented TBranchElement& operator=(const TBranchElement&); // not implemented static void SwitchContainer(TObjArray *); // Implementation use only functions. protected: void BuildTitle(const char* name); virtual void InitializeOffsets(); virtual void InitInfo(); Bool_t IsMissingCollection() const; TClass *GetCurrentClass(); // Class referenced by transient description TClass *GetParentClass(); // Class referenced by fParentName TStreamerInfo *GetInfoImp() const; void ReleaseObject(); void SetBranchCount(TBranchElement* bre); void SetBranchCount2(TBranchElement* bre) { fBranchCount2 = bre; } Int_t Unroll(const char* name, TClass* cltop, TClass* cl, char* ptr, Int_t basketsize, Int_t splitlevel, Int_t btype); inline void ValidateAddress() const; void Init(TTree *tree, TBranch *parent, const char* name, TStreamerInfo* sinfo, Int_t id, char* pointer, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t btype = 0); void Init(TTree *tree, TBranch *parent, const char* name, TClonesArray* clones, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); void Init(TTree *tree, TBranch *parent, const char* name, TVirtualCollectionProxy* cont, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); void ReadLeavesImpl(TBuffer& b); void ReadLeavesMakeClass(TBuffer& b); void ReadLeavesCollection(TBuffer& b); void ReadLeavesCollectionSplitPtrMember(TBuffer& b); void ReadLeavesCollectionSplitVectorPtrMember(TBuffer& b); void ReadLeavesCollectionMember(TBuffer& b); void ReadLeavesClones(TBuffer& b); void ReadLeavesClonesMember(TBuffer& b); void ReadLeavesCustomStreamer(TBuffer& b); void ReadLeavesMember(TBuffer& b); void ReadLeavesMemberBranchCount(TBuffer& b); void ReadLeavesMemberCounter(TBuffer& b); void SetReadLeavesPtr(); void SetReadActionSequence(); void SetupAddressesImpl(); void FillLeavesImpl(TBuffer& b); void FillLeavesMakeClass(TBuffer& b); void FillLeavesCollection(TBuffer& b); void FillLeavesCollectionSplitVectorPtrMember(TBuffer& b); void FillLeavesCollectionSplitPtrMember(TBuffer& b); void FillLeavesCollectionMember(TBuffer& b); void FillLeavesClones(TBuffer& b); void FillLeavesClonesMember(TBuffer& b); void FillLeavesCustomStreamer(TBuffer& b); void FillLeavesMemberBranchCount(TBuffer& b); void FillLeavesMemberCounter(TBuffer& b); void FillLeavesMember(TBuffer& b); void SetFillLeavesPtr(); void SetFillActionSequence(); // Public Interface. public: TBranchElement(); TBranchElement(TTree *tree, const char* name, TStreamerInfo* sinfo, Int_t id, char* pointer, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t btype = 0); TBranchElement(TTree *tree, const char* name, TClonesArray* clones, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); TBranchElement(TTree *tree, const char* name, TVirtualCollectionProxy* cont, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); TBranchElement(TBranch *parent, const char* name, TStreamerInfo* sinfo, Int_t id, char* pointer, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t btype = 0); TBranchElement(TBranch *parent, const char* name, TClonesArray* clones, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); TBranchElement(TBranch *parent, const char* name, TVirtualCollectionProxy* cont, Int_t basketsize = 32000, Int_t splitlevel = 0, Int_t compress = -1); virtual ~TBranchElement(); virtual void Browse(TBrowser* b); virtual Int_t Fill(); virtual TBranch *FindBranch(const char *name); virtual TLeaf *FindLeaf(const char *name); virtual char *GetAddress() const; TBranchElement *GetBranchCount() const { return fBranchCount; } TBranchElement *GetBranchCount2() const { return fBranchCount2; } Int_t *GetBranchOffset() const { return fBranchOffset; } UInt_t GetCheckSum() { return fCheckSum; } virtual const char *GetClassName() const { return fClassName.Data(); } virtual TClass *GetClass() const { return fBranchClass; } virtual const char *GetClonesName() const { return fClonesName.Data(); } TVirtualCollectionProxy *GetCollectionProxy(); virtual Int_t GetEntry(Long64_t entry = 0, Int_t getall = 0); virtual Int_t GetExpectedType(TClass *&clptr,EDataType &type); const char *GetIconName() const; Int_t GetID() const { return fID; } TStreamerInfo *GetInfo() const; Bool_t GetMakeClass() const; char *GetObject() const; virtual const char *GetParentName() const { return fParentName.Data(); } virtual Int_t GetMaximum() const; Int_t GetNdata() const { return fNdata; } Int_t GetType() const { return fType; } Int_t GetStreamerType() const { return fStreamerType; } virtual TClass *GetTargetClass() { return fTargetClass; } virtual const char *GetTypeName() const; Double_t GetValue(Int_t i, Int_t len, Bool_t subarr = kFALSE) const; virtual void *GetValuePointer() const; Int_t GetClassVersion() { return fClassVersion; } Bool_t IsBranchFolder() const { return TestBit(kBranchFolder); } Bool_t IsFolder() const; virtual Bool_t IsObjectOwner() const { return TestBit(kDeleteObject); } virtual Bool_t Notify() { if (fAddress) { ResetAddress(); } return 1; } virtual void Print(Option_t* option = "") const; void PrintValue(Int_t i) const; virtual void Reset(Option_t* option = ""); virtual void ResetAfterMerge(TFileMergeInfo *); virtual void ResetAddress(); virtual void ResetDeleteObject(); virtual void SetAddress(void* addobj); virtual Bool_t SetMakeClass(Bool_t decomposeObj = kTRUE); virtual void SetObject(void *objadd); virtual void SetBasketSize(Int_t buffsize); virtual void SetBranchFolder() { SetBit(kBranchFolder); } virtual void SetClassName(const char* name) { fClassName = name; } virtual void SetOffset(Int_t offset); inline void SetParentClass(TClass* clparent); virtual void SetParentName(const char* name) { fParentName = name; } virtual void SetTargetClass(const char *name); virtual void SetupAddresses(); virtual void SetType(Int_t btype) { fType = btype; } virtual void UpdateFile(); ClassDef(TBranchElement,9) // Branch in case of an object }; inline void TBranchElement::SetParentClass(TClass* clparent) { fParentClass = clparent; fParentName = clparent ? clparent->GetName() : ""; } inline void TBranchElement::ValidateAddress() const { // Check to see if the user changed the object pointer without telling us. if (fID < 0) { // We are a top-level branch. if (!fTree->GetMakeClass() && fAddress && (*((char**) fAddress) != fObject)) { // The semantics of fAddress and fObject are violated. // Assume the user changed the pointer on us. // Note: The cast is here because we want to be able to // be called from the constant get functions. // FIXME: Disable the check/warning TTree until we add a missing interface. if (TestBit(kDeleteObject)) { // This should never happen! Error("ValidateAddress", "We owned an object whose address changed! our ptr: %p new ptr: %p", fObject, *((char**) fAddress)); const_cast<TBranchElement*>(this)->ResetBit(kDeleteObject); } const_cast<TBranchElement*>(this)->SetAddress(fAddress); } } } #endif // ROOT_TBranchElement
dawehner/root
tree/tree/inc/TBranchElement.h
C
lgpl-2.1
13,410
package edu.ncsu.csc.itrust.beans.loaders; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.beans.MessageBean; /** * A loader for MessageBeans. * * Loads in information to/from beans using ResultSets and PreparedStatements. Use the superclass to enforce consistency. * For details on the paradigm for a loader (and what its methods do), see {@link BeanLoader} */ public class MessageBeanLoader implements BeanLoader<MessageBean> { public List<MessageBean> loadList(ResultSet rs) throws SQLException { List<MessageBean> list = new ArrayList<MessageBean>(); while (rs.next()) list.add(loadSingle(rs)); return list; } public PreparedStatement loadParameters(PreparedStatement ps, MessageBean message) throws SQLException { ps.setLong(1, message.getFrom()); ps.setLong(2, message.getTo()); ps.setString(3, message.getBody()); ps.setString(4, message.getSubject()); ps.setInt(5, message.getRead()); if (message.getParentMessageId() != 0L) { ps.setLong(6, message.getParentMessageId()); } return ps; } public MessageBean loadSingle(ResultSet rs) throws SQLException { MessageBean message = new MessageBean(); message.setMessageId(rs.getLong("message_id")); message.setFrom(rs.getLong("from_id")); message.setTo(rs.getLong("to_id")); message.setSubject(rs.getString("subject")); message.setBody(rs.getString("message")); message.setSentDate(rs.getTimestamp("sent_date")); message.setRead(rs.getInt("been_read")); message.setParentMessageId(rs.getLong("parent_msg_id")); return message; } }
qynnine/JDiffOriginDemo
examples/iTrust_v11/edu/ncsu/csc/itrust/beans/loaders/MessageBeanLoader.java
Java
lgpl-2.1
1,722
\hypertarget{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension}{}\section{Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension Class Reference} \label{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension}\index{Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension@{Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension}} \subsection*{Static Public Member Functions} \begin{DoxyCompactItemize} \item static Index\+Keys\+Builder \hyperlink{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a7c8f1f6e1477161509f8e9ac3ba1d8d9_a7c8f1f6e1477161509f8e9ac3ba1d8d9}{Ascending$<$ T $>$} (this Index\+Keys\+Builder mongo\+Index\+Keys, params Expression$<$ Func$<$ T, object $>$$>$\mbox{[}$\,$\mbox{]} selectors) \item static Index\+Keys\+Builder \hyperlink{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a9b2a712a921c4b5aea720a56eecb7643_a9b2a712a921c4b5aea720a56eecb7643}{Descending$<$ T $>$} (this Index\+Keys\+Builder mongo\+Index\+Keys, params Expression$<$ Func$<$ T, object $>$$>$\mbox{[}$\,$\mbox{]} selectors) \item static string \hyperlink{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_ab380ab44ca3970fb1e5a4c40e429b444_ab380ab44ca3970fb1e5a4c40e429b444}{Check\+For\+Child\+Property} (Member\+Expression selector\+Member\+Expression) \end{DoxyCompactItemize} \subsection{Member Function Documentation} \mbox{\Hypertarget{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a7c8f1f6e1477161509f8e9ac3ba1d8d9_a7c8f1f6e1477161509f8e9ac3ba1d8d9}\label{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a7c8f1f6e1477161509f8e9ac3ba1d8d9_a7c8f1f6e1477161509f8e9ac3ba1d8d9}} \index{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}!Ascending$<$ T $>$@{Ascending$<$ T $>$}} \index{Ascending$<$ T $>$@{Ascending$<$ T $>$}!Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}} \subsubsection{\texorpdfstring{Ascending$<$ T $>$()}{Ascending< T >()}} {\footnotesize\ttfamily static Index\+Keys\+Builder Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension.\+Ascending$<$ T $>$ (\begin{DoxyParamCaption}\item[{this Index\+Keys\+Builder}]{mongo\+Index\+Keys, }\item[{params Expression$<$ Func$<$ T, object $>$$>$ \mbox{[}$\,$\mbox{]}}]{selectors }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [static]}} \mbox{\Hypertarget{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_ab380ab44ca3970fb1e5a4c40e429b444_ab380ab44ca3970fb1e5a4c40e429b444}\label{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_ab380ab44ca3970fb1e5a4c40e429b444_ab380ab44ca3970fb1e5a4c40e429b444}} \index{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}!Check\+For\+Child\+Property@{Check\+For\+Child\+Property}} \index{Check\+For\+Child\+Property@{Check\+For\+Child\+Property}!Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}} \subsubsection{\texorpdfstring{Check\+For\+Child\+Property()}{CheckForChildProperty()}} {\footnotesize\ttfamily static string Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension.\+Check\+For\+Child\+Property (\begin{DoxyParamCaption}\item[{Member\+Expression}]{selector\+Member\+Expression }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [static]}} \mbox{\Hypertarget{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a9b2a712a921c4b5aea720a56eecb7643_a9b2a712a921c4b5aea720a56eecb7643}\label{classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension_a9b2a712a921c4b5aea720a56eecb7643_a9b2a712a921c4b5aea720a56eecb7643}} \index{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}!Descending$<$ T $>$@{Descending$<$ T $>$}} \index{Descending$<$ T $>$@{Descending$<$ T $>$}!Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension@{Cqrs\+::\+Mongo\+::\+Factories\+::\+Index\+Keys\+Builder\+Extension}} \subsubsection{\texorpdfstring{Descending$<$ T $>$()}{Descending< T >()}} {\footnotesize\ttfamily static Index\+Keys\+Builder Cqrs.\+Mongo.\+Factories.\+Index\+Keys\+Builder\+Extension.\+Descending$<$ T $>$ (\begin{DoxyParamCaption}\item[{this Index\+Keys\+Builder}]{mongo\+Index\+Keys, }\item[{params Expression$<$ Func$<$ T, object $>$$>$ \mbox{[}$\,$\mbox{]}}]{selectors }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [static]}}
Chinchilla-Software-Com/CQRS
wiki/docs/2.1/latex/classCqrs_1_1Mongo_1_1Factories_1_1IndexKeysBuilderExtension.tex
TeX
lgpl-2.1
4,625
<?php /* * Limb PHP Framework * * @link http://limb-project.com * @copyright Copyright &copy; 2004-2009 BIT(http://bit-creative.com) * @license LGPL http://www.gnu.org/copyleft/lesser.html */ lmb_require('limb/toolkit/src/lmbToolkit.class.php'); lmb_require('limb/fs/src/lmbFs.class.php'); lmb_require('limb/js/src/lmbJsDirectiveHandlers.class.php'); lmb_env_setor('LIMB_JS_INCLUDE_PATH', 'www/js;limb/*/shared/js'); /** * class lmbJsPreprocessor. * * @package js * @version $Id$ */ class lmbJsPreprocessor { protected $processed = array(); protected $directives = array(); protected $error = false; function __construct() { $this->toolkit = lmbToolkit :: instance(); $this->addDirective('include', array(&$this, '_processInclude')); } function addDirective($directive, $handler) { $this->handlers[$directive] = $handler; } function processFiles($files) { $contents = ''; foreach($files as $file) { if(!$processed_file_contents = $this->processFile($file)) continue; $contents .= $processed_file_contents . "\n"; } return $contents; } function processFile($file) { $file = lmbFs :: normalizePath($file); if($this->_isProcessed($file)) return ''; $contents = file_get_contents($file); $this->_markAsProcessed($file); $result = $this->_processDirectives($contents); return $result; } protected function _processDirectives(&$contents) { $processed_contents = preg_replace_callback('~^//#([a-z_\\-0-9]+)\s+(.*)$~m', array(&$this, '_processDirective'), $contents); // repeatedly throw saved exception to prevent preg_replace_callback warning if($this->error) throw $this->error; return $processed_contents; } protected function _processDirective($matches) { $params = $this->_parseDirectiveParams($matches[2]); if(!isset($this->handlers[$matches[1]])) return ''; return call_user_func_array($this->handlers[$matches[1]], $params); } protected function _parseDirectiveParams($params_string) { if(!$params_string) return array(); $params = explode(' ', $params_string); foreach($params as $key => $param) { if(!$param) unset($params[$key]); } return $params; } protected function _markAsProcessed($file) { $this->processed[$file] = 1; } protected function _isProcessed($file) { return isset($this->processed[$file]); } protected function _locateFiles($name) { $locator = $this->toolkit->getFileLocator(lmb_env_get('LIMB_JS_INCLUDE_PATH'), 'js'); return $locator->locateAll($name); } protected function _processInclude($filename) { try { $files = $this->_locateFiles(trim($filename, " \" '\r ")); } catch(lmbException $e) { // temporarily stop and save exception to prevent preg_replace_callback warning if(!$this->error) $this->error = $e; return ''; } return trim($this->processFiles($files)); } }
limb-php-framework/limb-cms
lib/limb-cms/js/src/lmbJsPreprocessor.class.php
PHP
lgpl-2.1
3,148
"""SCons.Tool.gcc Tool-specific initialization for gcc. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2017 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/gcc.py 74b2c53bc42290e911b334a6b44f187da698a668 2017/11/14 13:16:53 bdbaddog" from . import cc import os import re import subprocess import SCons.Util compilers = ['gcc', 'cc'] def generate(env): """Add Builders and construction variables for gcc to an Environment.""" if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] cc.generate(env) if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version version = detect_version(env, env['CC']) if version: env['CCVERSION'] = version def exists(env): # is executable, and is a GNU compiler (or accepts '--version' at least) return detect_version(env, env.Detect(env.get('CC', compilers))) def detect_version(env, cc): """Return the version of the GNU compiler, or None if it is not a GNU compiler.""" cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # version = line line = SCons.Util.to_str(pipe.stdout.readline()) match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: version = match.group(0) # Non-GNU compiler's output (like AIX xlc's) may exceed the stdout buffer: # So continue with reading to let the child process actually terminate. while SCons.Util.to_str(pipe.stdout.readline()): pass ret = pipe.wait() if ret != 0: return None return version # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
mapycz/mapnik
scons/scons-local-3.0.1/SCons/Tool/gcc.py
Python
lgpl-2.1
3,530
<?php /* * This file is part of phpMorphy project * * Copyright (c) 2007-2012 Kamaev Vladimir <heromantor@users.sourceforge.net> * * 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, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ class phpMorphy_Generator_Decorator_HandlerDefault implements phpMorphy_Generator_Decorator_HandlerInterface { const INDENT_SIZE = 4; const INDENT_CHAR = ' '; /** * @return string */ function generateHeaderDocComment($decorateeClass, $decoratorClass) { return $this->indentText( phpMorphy_Generator_Decorator_PhpDocHelper::generateHeaderPhpDoc( $decorateeClass, $decoratorClass, true ), 0 ); } /** * @param string $docComment * @param string $class * @param string[]|null $extends * @param string[]|null $implements * @return string */ function generateClassDeclaration($docComment, $class, $extends, $implements) { $docComment = $this->unindentText($docComment); $text = $docComment . PHP_EOL . 'abstract class ' . $class; $implements = false === $implements ? array() : $implements; $implements[] = 'phpMorphy_DecoratorInterface'; if(null !== $extends) { $text .= ' extends ' . implode(', ', $extends); } if(null !== $implements) { $text .= ' implements ' . implode(', ', $implements); } return $this->indentText($text, 0); } /** * @param string $decoratorClass * @param string $decorateeClass * @return string */ function generateCommonMethods($decoratorClass, $decorateeClass) { $ctor = <<<EOF /** @var $decorateeClass */ private \$object; /** @var Closure|null */ private \$on_instantiate; /** * @param \$object $decorateeClass */ function __construct($decorateeClass \$object) { \$this->setDecorateeObject(\$object); } /** * Set current decorator behaviour to proxy model * @param Closure|null \$onInstantiate */ protected function actAsProxy(/*TODO: uncomment for php >= 5.3 Closure */\$onInstantiate = null) { unset(\$this->object); \$this->on_instantiate = \$onInstantiate; } /** * @param \$object $decorateeClass * @return $decoratorClass */ protected function setDecorateeObject($decorateeClass \$object) { \$this->object = \$object; return \$this; } /** * @return $decorateeClass */ public function getDecorateeObject() { return \$this->object; } /** * @param string \$class * @param array \$ctorArgs * @return $decorateeClass */ static protected function instantiateClass(\$class, \$ctorArgs) { \$ref = new ReflectionClass(\$class); return \$ref->newInstanceArgs(\$ctorArgs); } /** * @param string \$propName * @return $decorateeClass */ public function __get(\$propName) { if('object' === \$propName) { \$obj = \$this->proxyInstantiate(); \$this->setDecorateeObject(\$obj); return \$obj; } throw new phpMorphy_Exception("Unknown property '\$propName'"); } /** * This method invoked by __get() at first time access to proxy object * Must return instance of '$decorateeClass' * @abstract * @return object */ protected function proxyInstantiate() { if(!isset(\$this->on_instantiate)) { throw new phpMorphy_Exception('You must implement $decoratorClass::proxyInstantiate or pass \\\$onInstantiate to actAsProxy() method'); } \$fn = \$this->on_instantiate; unset(\$this->on_instantiate); return \$fn(); } /** * Implement deep copy paradigm */ function __clone() { if(isset(\$this->object)) { \$this->object = clone \$this->object; } } EOF; return $this->indentText($ctor, 1); } /** * @param string $docComment * @param string $modifiers * @param bool $isReturnRef * @param string $name * @param string $args * @param string $passArgs * @return string */ function generateMethod($docComment, $modifiers, $isReturnRef, $name, $args, $passArgs) { $ref = $isReturnRef ? '&' : ''; $docComment = $this->unindentText($docComment); $args = $this->unindentText($args); $text = <<<EOF $docComment $modifiers function {$ref}$name($args) { \$result = \$this->object->$name($passArgs); return \$result === \$this->object ? \$this : \$result; } EOF; return $this->indentText($text, 1); } /** * @param string $text * @param int $level * @return string */ protected function indentText($text, $level) { $indent = str_repeat(self::INDENT_CHAR, self::INDENT_SIZE * $level); return implode( PHP_EOL, array_map( function ($line) use ($indent) { return $indent . rtrim($line); }, explode(PHP_EOL, ltrim($text)) ) ); } /** * @param string $text * @return string */ protected function unindentText($text) { $lines = array_values( array_filter( array_map( 'rtrim', explode("\n", $text) ), 'strlen' ) ); $min_indent_length = $this->getMinIndentLength($lines); if(count($lines) > 1) { // try min indent without first line $old_first_line = array_shift($lines); $min_indent_length_new = $this->getMinIndentLength($lines); if($min_indent_length_new > $min_indent_length) { array_unshift( $lines, str_repeat(' ', $min_indent_length_new) . ltrim($old_first_line) ); $min_indent_length = $min_indent_length_new; } } foreach($lines as &$line) { $line = substr($line, $min_indent_length); } return implode(PHP_EOL, $lines); } protected function getMinIndentLength(array $lines) { $min_indent_length = PHP_INT_MAX; foreach($lines as $line) { $diff = strlen($line) - strlen(ltrim($line)); $min_indent_length = min($diff, $min_indent_length); } return $min_indent_length; } }
heromantor/phpmorphy
src/phpMorphy/Generator/Decorator/HandlerDefault.php
PHP
lgpl-2.1
6,997
/************************************************************************** ** ** Copyright (C) 2014 BlackBerry Limited. All rights reserved. ** ** Contact: BlackBerry (qt@blackberry.com) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qnxsettingswidget.h" #include "ui_qnxsettingswidget.h" #include "qnxconfiguration.h" #include "qnxconfigurationmanager.h" #include <qtsupport/qtversionmanager.h> #include <coreplugin/icore.h> #include <QFileDialog> #include <QMessageBox> #include <qdebug.h> namespace Qnx { namespace Internal { QnxSettingsWidget::QnxSettingsWidget(QWidget *parent) : QWidget(parent), m_ui(new Ui_QnxSettingsWidget), m_qnxConfigManager(QnxConfigurationManager::instance()) { m_ui->setupUi(this); populateConfigsCombo(); connect(m_ui->addButton, SIGNAL(clicked()), this, SLOT(addConfiguration())); connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(removeConfiguration())); connect(m_ui->configsCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateInformation())); connect(m_ui->generateKitsCheckBox, SIGNAL(toggled(bool)), this, SLOT(generateKits(bool))); connect(m_qnxConfigManager, SIGNAL(configurationsListUpdated()), this, SLOT(populateConfigsCombo())); connect(QtSupport::QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)), this, SLOT(updateInformation())); } QnxSettingsWidget::~QnxSettingsWidget() { delete m_ui; } QList<QnxSettingsWidget::ConfigState> QnxSettingsWidget::changedConfigs() { return m_changedConfigs; } void QnxSettingsWidget::addConfiguration() { QString filter; if (Utils::HostOsInfo::isWindowsHost()) filter = QLatin1String("*.bat file"); else filter = QLatin1String("*.sh file"); const QString envFile = QFileDialog::getOpenFileName(this, tr("Select QNX Environment File"), QString(), filter); if (envFile.isEmpty()) return; QnxConfiguration *config = new QnxConfiguration(Utils::FileName::fromString(envFile)); if (m_qnxConfigManager->configurations().contains(config) || !config->isValid()) { QMessageBox::warning(Core::ICore::mainWindow(), tr("Warning"), tr("Configuration already exists or is invalid.")); delete config; return; } setConfigState(config, Added); m_ui->configsCombo->addItem(config->displayName(), QVariant::fromValue(static_cast<void*>(config))); } void QnxSettingsWidget::removeConfiguration() { const int currentIndex = m_ui->configsCombo->currentIndex(); QnxConfiguration *config = static_cast<QnxConfiguration*>( m_ui->configsCombo->itemData(currentIndex).value<void*>()); if (!config) return; QMessageBox::StandardButton button = QMessageBox::question(Core::ICore::mainWindow(), tr("Remove QNX Configuration"), tr("Are you sure you want to remove:\n %1?").arg(config->displayName()), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { setConfigState(config, Removed); m_ui->configsCombo->removeItem(currentIndex); } } void QnxSettingsWidget::generateKits(bool checked) { const int currentIndex = m_ui->configsCombo->currentIndex(); QnxConfiguration *config = static_cast<QnxConfiguration*>( m_ui->configsCombo->itemData(currentIndex).value<void*>()); if (!config) return; setConfigState(config, checked ? Activated : Deactivated); } void QnxSettingsWidget::updateInformation() { const int currentIndex = m_ui->configsCombo->currentIndex(); QnxConfiguration *config = static_cast<QnxConfiguration*>( m_ui->configsCombo->itemData(currentIndex).value<void*>()); // update the checkbox m_ui->generateKitsCheckBox->setEnabled(config ? config->canCreateKits() : false); m_ui->generateKitsCheckBox->setChecked(config ? config->isActive() : false); // update information m_ui->configName->setText(config? config->displayName() : QString()); m_ui->configVersion->setText(config ? config->version().toString() : QString()); m_ui->configHost->setText(config ? config->qnxHost().toString() : QString()); m_ui->configTarget->setText(config ? config->qnxTarget().toString() : QString()); } void QnxSettingsWidget::populateConfigsCombo() { m_ui->configsCombo->clear(); foreach (QnxConfiguration *config, m_qnxConfigManager->configurations()) { m_ui->configsCombo->addItem(config->displayName(), QVariant::fromValue(static_cast<void*>(config))); } updateInformation(); } void QnxSettingsWidget::setConfigState(QnxConfiguration *config, QnxSettingsWidget::State state) { QnxSettingsWidget::State stateToRemove; switch (state) { case QnxSettingsWidget::Added : stateToRemove = QnxSettingsWidget::Removed; break; case QnxSettingsWidget::Removed: stateToRemove = QnxSettingsWidget::Added; break; case QnxSettingsWidget::Activated: stateToRemove = QnxSettingsWidget::Deactivated; break; case QnxSettingsWidget::Deactivated: stateToRemove = QnxSettingsWidget::Activated; } foreach (const ConfigState &configState, m_changedConfigs) { if (configState.config == config && configState.state == stateToRemove) m_changedConfigs.removeAll(configState); } m_changedConfigs.append(ConfigState(config, state)); } void QnxSettingsWidget::applyChanges() { foreach (const ConfigState &configState, m_changedConfigs) { switch (configState.state) { case Activated : configState.config->activate(); break; case Deactivated: configState.config->deactivate(); break; case Added: m_qnxConfigManager->addConfiguration(configState.config); break; case Removed: configState.config->deactivate(); m_qnxConfigManager->removeConfiguration(configState.config); break; } } m_changedConfigs.clear(); } } }
farseerri/git_code
src/plugins/qnx/qnxsettingswidget.cpp
C++
lgpl-2.1
7,765
/* * Copyright (C) 2014 Freie Universität Berlin * Copyright (C) 2014 Lotte Steenbrink <lotte.steenbrink@fu-berlin.de> * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup aodvv2 * @{ * * @file * @brief aodvv2 routing protocol * * @author Lotte Steenbrink <lotte.steenbrink@fu-berlin.de> */ #include "aodv.h" #include "aodvv2/aodvv2.h" #include "aodv_debug.h" #define ENABLE_DEBUG (0) #include "debug.h" #define UDP_BUFFER_SIZE (128) /** with respect to IEEE 802.15.4's MTU */ #define RCV_MSG_Q_SIZE (32) /* TODO: check if smaller values work, too */ static void _init_addresses(void); static void _init_sock_snd(void); static void *_aodv_receiver_thread(void *arg); static void *_aodv_sender_thread(void *arg); static void _deep_free_msg_container(struct msg_container *msg_container); static void _write_packet(struct rfc5444_writer *wr __attribute__ ((unused)), struct rfc5444_writer_target *iface __attribute__((unused)), void *buffer, size_t length); #if ENABLE_DEBUG char addr_str[IPV6_MAX_ADDR_STR_LEN]; static struct netaddr_str nbuf; #endif static char aodv_rcv_stack_buf[THREAD_STACKSIZE_MAIN]; static char aodv_snd_stack_buf[THREAD_STACKSIZE_MAIN]; static aodvv2_metric_t _metric_type; static int sender_thread; static int _sock_snd; static struct autobuf _hexbuf; static sockaddr6_t sa_wp; static ipv6_addr_t _v6_addr_local, _v6_addr_mcast, _v6_addr_loopback; static struct netaddr na_local; /* the same as _v6_addr_local, but to save us * constant calls to ipv6_addr_t_to_netaddr()... */ static struct writer_target *wt; static mutex_t rreq_mutex; static mutex_t rrep_mutex; static mutex_t rerr_mutex; struct netaddr na_mcast; void aodv_init(void) { AODV_DEBUG("%s()\n", __func__); /* TODO: set if_id properly */ int if_id = 0; net_if_set_src_address_mode(if_id, NET_IF_TRANS_ADDR_M_SHORT); mutex_init(&rreq_mutex); mutex_init(&rrep_mutex); mutex_init(&rerr_mutex); aodv_set_metric_type(AODVV2_DEFAULT_METRIC_TYPE); _init_addresses(); _init_sock_snd(); /* init ALL the things! \o, */ seqnum_init(); routingtable_init(); clienttable_init(); /* every node is its own client. */ clienttable_add_client(&na_local); rreqtable_init(); /* init reader and writer */ aodv_packet_reader_init(); aodv_packet_writer_init(_write_packet); /* start listening & enable sending */ thread_create(aodv_rcv_stack_buf, sizeof(aodv_rcv_stack_buf), THREAD_PRIORITY_MAIN, CREATE_STACKTEST, _aodv_receiver_thread, NULL, "_aodv_receiver_thread"); AODV_DEBUG("listening on port %d\n", HTONS(MANET_PORT)); sender_thread = thread_create(aodv_snd_stack_buf, sizeof(aodv_snd_stack_buf), THREAD_PRIORITY_MAIN, CREATE_STACKTEST, _aodv_sender_thread, NULL, "_aodv_sender_thread"); /* register aodv for routing */ ipv6_iface_set_routing_provider(aodv_get_next_hop); } void aodv_set_metric_type(aodvv2_metric_t metric_type) { if (metric_type != AODVV2_DEFAULT_METRIC_TYPE) { return; } _metric_type = metric_type; } void aodv_send_rreq(struct aodvv2_packet_data *packet_data) { /* Make sure only one thread is dispatching a RREQ at a time */ mutex_lock(&rreq_mutex); AODV_DEBUG("%s()\n", __func__); struct aodvv2_packet_data *pd = malloc(sizeof(struct aodvv2_packet_data)); memcpy(pd, packet_data, sizeof(struct aodvv2_packet_data)); struct rreq_rrep_data *rd = malloc(sizeof(struct rreq_rrep_data)); *rd = (struct rreq_rrep_data) { .next_hop = &na_mcast, .packet_data = pd, }; struct msg_container *mc = malloc(sizeof(struct msg_container)); *mc = (struct msg_container) { .type = RFC5444_MSGTYPE_RREQ, .data = rd }; msg_t msg; msg.content.ptr = (char *) mc; msg_try_send(&msg, sender_thread); mutex_unlock(&rreq_mutex); } void aodv_send_rrep(struct aodvv2_packet_data *packet_data, struct netaddr *next_hop) { /* Make sure only one thread is dispatching a RREP at a time */ mutex_lock(&rrep_mutex); AODV_DEBUG("%s()\n", __func__); struct aodvv2_packet_data *pd = malloc(sizeof(struct aodvv2_packet_data)); memcpy(pd, packet_data, sizeof(struct aodvv2_packet_data)); struct netaddr *nh = malloc(sizeof(struct netaddr)); memcpy(nh, next_hop, sizeof(struct netaddr)); struct rreq_rrep_data *rd = malloc(sizeof(struct rreq_rrep_data)); *rd = (struct rreq_rrep_data) { .next_hop = nh, .packet_data = pd, }; struct msg_container *mc = malloc(sizeof(struct msg_container)); *mc = (struct msg_container) { .type = RFC5444_MSGTYPE_RREP, .data = rd }; msg_t msg; msg.content.ptr = (char *) mc; msg_try_send(&msg, sender_thread); mutex_unlock(&rrep_mutex); } void aodv_send_rerr(struct unreachable_node unreachable_nodes[], size_t len, struct netaddr *next_hop) { /* Make sure only one thread is dispatching a RERR at a time */ mutex_lock(&rerr_mutex); AODV_DEBUG("%s()\n", __func__); struct rerr_data *rerrd = malloc(sizeof(struct rerr_data)); *rerrd = (struct rerr_data) { .unreachable_nodes = unreachable_nodes, .len = len, .hoplimit = AODVV2_MAX_HOPCOUNT, .next_hop = next_hop }; struct msg_container *mc2 = malloc(sizeof(struct msg_container)); *mc2 = (struct msg_container) { .type = RFC5444_MSGTYPE_RERR, .data = rerrd }; msg_t msg2; msg2.content.ptr = (char *) mc2; msg_try_send(&msg2, sender_thread); mutex_unlock(&rerr_mutex); } /* * init the multicast address all RREQ and RERRS are sent to * and the local address (source address) of this node */ static void _init_addresses(void) { /* init multicast address: set to to a link-local all nodes multicast address */ ipv6_addr_set_all_nodes_addr(&_v6_addr_mcast); AODV_DEBUG("my multicast address is: %s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &_v6_addr_mcast)); /* get best IP for sending */ ipv6_net_if_get_best_src_addr(&_v6_addr_local, &_v6_addr_mcast); AODV_DEBUG("my src address is: %s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &_v6_addr_local)); /* store src & multicast address as netaddr as well for easy interaction * with oonf based stuff */ ipv6_addr_t_to_netaddr(&_v6_addr_local, &na_local); ipv6_addr_t_to_netaddr(&_v6_addr_mcast, &na_mcast); ipv6_addr_set_loopback_addr(&_v6_addr_loopback); /* init sockaddr that write_packet will use to send data */ sa_wp.sin6_family = AF_INET6; sa_wp.sin6_port = HTONS(MANET_PORT); } /* init socket communication for sender */ static void _init_sock_snd(void) { _sock_snd = socket_base_socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP); if (-1 == _sock_snd) { AODV_DEBUG("Error Creating Socket!\n"); } } /* Build RREQs, RREPs and RERRs from the information contained in the thread's * message queue and send them */ static void *_aodv_sender_thread(void *arg) { (void) arg; msg_t msgq[RCV_MSG_Q_SIZE]; msg_init_queue(msgq, sizeof msgq); AODV_DEBUG("_aodv_sender_thread initialized.\n"); while (true) { AODV_DEBUG("%s()\n", __func__); msg_t msg; msg_receive(&msg); struct msg_container *mc = (struct msg_container *) msg.content.ptr; if (mc->type == RFC5444_MSGTYPE_RREQ) { struct rreq_rrep_data *rreq_data = (struct rreq_rrep_data *) mc->data; aodv_packet_writer_send_rreq(rreq_data->packet_data, rreq_data->next_hop); } else if (mc->type == RFC5444_MSGTYPE_RREP) { struct rreq_rrep_data *rrep_data = (struct rreq_rrep_data *) mc->data; aodv_packet_writer_send_rrep(rrep_data->packet_data, rrep_data->next_hop); } else if (mc->type == RFC5444_MSGTYPE_RERR) { struct rerr_data *rerr_data = (struct rerr_data *) mc->data; aodv_packet_writer_send_rerr(rerr_data->unreachable_nodes, rerr_data->len, rerr_data->hoplimit, rerr_data->next_hop); } else { DEBUG("ERROR: Couldn't identify Message\n"); } _deep_free_msg_container(mc); } return NULL; } /* receive RREQs, RREPs and RERRs and handle them */ static void *_aodv_receiver_thread(void *arg) { (void) arg; AODV_DEBUG("%s()\n", __func__); uint32_t fromlen; char buf_rcv[UDP_BUFFER_SIZE]; msg_t msg_q[RCV_MSG_Q_SIZE]; msg_init_queue(msg_q, RCV_MSG_Q_SIZE); sockaddr6_t sa_rcv = { .sin6_family = AF_INET6, .sin6_port = HTONS(MANET_PORT) }; int sock_rcv = socket_base_socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP); if (-1 == socket_base_bind(sock_rcv, &sa_rcv, sizeof(sa_rcv))) { DEBUG("Error: bind to receive socket failed!\n"); socket_base_close(sock_rcv); return NULL; } AODV_DEBUG("ready to receive data\n"); while (true) { int32_t rcv_size = socket_base_recvfrom(sock_rcv, (void *)buf_rcv, UDP_BUFFER_SIZE, 0, &sa_rcv, &fromlen); if (rcv_size < 0) { AODV_DEBUG("ERROR receiving data!\n"); } AODV_DEBUG("_aodv_receiver_thread() %s:", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &_v6_addr_local)); DEBUG(" UDP packet received from %s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &sa_rcv.sin6_addr)); struct netaddr _sender; ipv6_addr_t_to_netaddr(&sa_rcv.sin6_addr, &_sender); /* We sometimes get passed our own packets. Drop them. */ if (netaddr_cmp(&_sender, &na_local) == 0) { AODV_DEBUG("received our own packet, dropping it.\n"); } else { aodv_packet_reader_handle_packet((void *) buf_rcv, rcv_size, &_sender); } } socket_base_close(sock_rcv); return NULL; } ipv6_addr_t *aodv_get_next_hop(ipv6_addr_t *dest) { AODV_DEBUG("aodv_get_next_hop() %s:", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &_v6_addr_local)); DEBUG(" getting next hop for %s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, dest)); struct netaddr _tmp_dest; ipv6_addr_t_to_netaddr(dest, &_tmp_dest); timex_t now; struct unreachable_node unreachable_nodes[AODVV2_MAX_UNREACHABLE_NODES]; size_t len; /* The network stack sometimes asks us for the next hop towards our own IP */ if (memcmp(dest, &_v6_addr_local, sizeof(ipv6_addr_t)) == 0) { AODV_DEBUG("That's me, returning loopback\n"); return &_v6_addr_loopback; } /* * TODO use ndp_neighbor_get_ll_address() as soon as it's available. * note: delete check for active/stale/delayed entries, get_ll_address * does that for us then */ ndp_neighbor_cache_t *ndp_nc_entry = ndp_neighbor_cache_search(dest); struct aodvv2_routing_entry_t *rt_entry = routingtable_get_entry(&_tmp_dest, _metric_type); if (ndp_nc_entry != NULL) { /* Case 2: Broken Link (detected by lower layer) */ int link_broken = (ndp_nc_entry->state == NDP_NCE_STATUS_INCOMPLETE || ndp_nc_entry->state == NDP_NCE_STATUS_PROBE) && (rt_entry != NULL && rt_entry->state != ROUTE_STATE_INVALID); if (link_broken) { DEBUG("\tNeighbor Cache entry found, but invalid (state: %i). Sending RERR.\n", ndp_nc_entry->state); /* mark all routes (active, idle, expired) that use next_hop as broken * and add all *Active* routes to the list of unreachable nodes */ routingtable_break_and_get_all_hopping_over(&_tmp_dest, unreachable_nodes, &len); aodv_send_rerr(unreachable_nodes, len, &na_mcast); return NULL; } DEBUG("[aodvv2][ndp] found NC entry. Returning dest addr.\n"); return dest; } DEBUG("\t[ndp] no entry for addr %s found\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, dest)); if (rt_entry) { /* Case 1: Undeliverable Packet */ int packet_indeliverable = rt_entry->state == ROUTE_STATE_INVALID; if (packet_indeliverable) { DEBUG("\tRouting table entry found, but invalid (state %i). Sending RERR.\n", rt_entry->state); unreachable_nodes[0].addr = _tmp_dest; unreachable_nodes[0].seqnum = rt_entry->seqnum; aodv_send_rerr(unreachable_nodes, 1, &na_mcast); return NULL; } DEBUG("\tfound dest %s in routing table\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, dest)); vtimer_now(&now); rt_entry->lastUsed = now; if (rt_entry->state == ROUTE_STATE_IDLE) { rt_entry->state = ROUTE_STATE_ACTIVE; } /* Currently, there is no way to do this, so I'm doing it the worst * possible, but safe way: I can't make sure that the current call to * aodv_get_next_hop() is overridden by another call to aodv_get_next_hop() * by a thread with higher priority, thus messing up return values if I just * use a static ipv6_addr_t. * The following malloc will never be free()'d. TODO: FIX THIS ASAP. */ ipv6_addr_t *next_hop = (ipv6_addr_t *) malloc(sizeof(ipv6_addr_t)); netaddr_to_ipv6_addr_t(&rt_entry->nextHopAddr, next_hop); return next_hop; } aodvv2_seqnum_t seqnum = seqnum_get(); seqnum_inc(); struct aodvv2_packet_data rreq_data = (struct aodvv2_packet_data) { .hoplimit = AODVV2_MAX_HOPCOUNT, .metricType = _metric_type, .origNode = (struct node_data) { .addr = na_local, .metric = 0, .seqnum = seqnum, }, .targNode = (struct node_data) { .addr = _tmp_dest, }, .timestamp = (timex_t) {0,0} /* this timestamp is never used, it exists * merely to make the compiler shut up */ }; DEBUG("\tNo route found towards %s, starting route discovery... \n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, dest)); aodv_send_rreq(&rreq_data); return NULL; } /** * Handle the output of the RFC5444 packet creation process. This callback is * called by every writer_send_* function. */ static void _write_packet(struct rfc5444_writer *wr __attribute__ ((unused)), struct rfc5444_writer_target *iface __attribute__((unused)), void *buffer, size_t length) { AODV_DEBUG("%s()\n", __func__); /* generate hexdump and human readable representation of packet * and print to console */ abuf_hexdump(&_hexbuf, "\t", buffer, length); rfc5444_print_direct(&_hexbuf, buffer, length); DEBUG("%s", abuf_getptr(&_hexbuf)); abuf_clear(&_hexbuf); /* fetch the address the packet is supposed to be sent to (i.e. to a * specific node or the multicast address) from the writer_target struct * iface* is stored in. This is a bit hacky, but it does the trick. */ wt = container_of(iface, struct writer_target, interface); netaddr_to_ipv6_addr_t(&wt->target_addr, &sa_wp.sin6_addr); /* When originating a RREQ, add it to our RREQ table/update its predecessor */ if (wt->type == RFC5444_MSGTYPE_RREQ && netaddr_cmp(&wt->packet_data.origNode.addr, &na_local) == 0) { AODV_DEBUG("originating RREQ with SeqNum %d towards %s via %s; updating RREQ table...\n", wt->packet_data.origNode.seqnum, netaddr_to_string(&nbuf, &wt->packet_data.targNode.addr), ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &sa_wp.sin6_addr)); rreqtable_is_redundant(&wt->packet_data); } int bytes_sent = socket_base_sendto(_sock_snd, buffer, length, 0, &sa_wp, sizeof sa_wp); (void) bytes_sent; AODV_DEBUG("%d bytes sent.\n", bytes_sent); } /* free the matryoshka doll of cobbled-together structs that the sender_thread receives */ static void _deep_free_msg_container(struct msg_container *mc) { int type = mc->type; if ((type == RFC5444_MSGTYPE_RREQ) || (type == RFC5444_MSGTYPE_RREP)) { struct rreq_rrep_data *rreq_rrep_data = (struct rreq_rrep_data *) mc->data; free(rreq_rrep_data->packet_data); if (netaddr_cmp(rreq_rrep_data->next_hop, &na_mcast) != 0) { free(rreq_rrep_data->next_hop); } } else if (type == RFC5444_MSGTYPE_RERR) { struct rerr_data *rerr_data = (struct rerr_data *) mc->data; if (netaddr_cmp(rerr_data->next_hop, &na_mcast) != 0) { free(rerr_data->next_hop); } } free(mc->data); free(mc); }
phiros/RIOT
sys/net/routing/aodvv2/aodv.c
C
lgpl-2.1
17,254
/* * Copyright (c) 2008 Los Alamos National Security, LLC. * * Los Alamos National Laboratory * Research Library * Digital Library Research & Prototyping Team * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ package gov.lanl.adore.djatoka.util; import ij.ImagePlus; import ij.io.Opener; import ij.process.ImageProcessor; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; /** * Image Information Utility used to obtain width and height information. * This util is useful when processing images using external compression * applications, such as Kakadu JPEG 2000 kdu_compress. The image to be * compressed is opened by either ImageJ or JAI and determines dimensions. * JAI is better with TIFF files and and file extensions are used to * determine which API will be used to resolve dimensions. * @author Ryan Chute * */ public class ImageRecordUtils { /** * Return an ImageRecord containing the images pixel dimensions. * @param file absolute file path to image * @return ImageRecord containing the images pixel dimensions */ public static ImageRecord getImageDimensions(String file) { ImageRecord dim = null; // try JAI dim = setUsingJAI(file); // if that fails, try ImageJ if (dim == null) dim = setUsingImageJ(file); return dim; } private static ImageRecord setUsingImageJ(String file) { ImageRecord dim = new ImageRecord(file); Opener o = new Opener(); ImagePlus imp = o.openImage(file); if (imp == null) return null; ImageProcessor ip = imp.getProcessor(); dim.setWidth(ip.getWidth()); dim.setHeight(ip.getHeight()); ip = null; return dim; } private static ImageRecord setUsingJAI(String file) { ImageRecord dim = new ImageRecord(file); PlanarImage pi = JAI.create("fileload", file); dim.setWidth(pi.getWidth()); dim.setHeight(pi.getHeight()); pi.dispose(); pi = null; return dim; } }
cbeer/adore-djatoka-mirror
src/gov/lanl/adore/djatoka/util/ImageRecordUtils.java
Java
lgpl-2.1
2,589
package npe; // From java.net.InterfaceAddress public class InterfaceAddress { String address, broadcast; int maskLength; public InterfaceAddress(String address, String broadcast, int maskLength) { this.address = address; this.broadcast = broadcast; this.maskLength = maskLength; } @Override public int hashCode() { int result = 0; if (address != null) result ^= address.hashCode(); if (broadcast != null) result ^= broadcast.hashCode(); result ^= maskLength; return result; } @Override public boolean equals(Object obj) { if (!(obj instanceof InterfaceAddress)) { return false; } InterfaceAddress cmp = (InterfaceAddress) obj; if ((address != null & cmp.address == null) || (!address.equals(cmp.address))) return false; if ((broadcast != null & cmp.broadcast == null) || (!broadcast.equals(cmp.broadcast))) return false; if (maskLength != cmp.maskLength) return false; return true; } }
sewe/spotbugs
spotbugsTestCases/src/java/npe/InterfaceAddress.java
Java
lgpl-2.1
1,125
/* * Electronic Arts TGV Video Decoder * Copyright (c) 2007-2008 Peter Ross * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Electronic Arts TGV Video Decoder * by Peter Ross (pross@xvid.org) * * Technical details here: * http://wiki.multimedia.cx/index.php?title=Electronic_Arts_TGV */ #include "avcodec.h" #define BITSTREAM_READER_LE #include "get_bits.h" #include "internal.h" #include "libavutil/imgutils.h" #include "libavutil/mem.h" #define EA_PREAMBLE_SIZE 8 #define kVGT_TAG MKTAG('k', 'V', 'G', 'T') typedef struct TgvContext { AVCodecContext *avctx; AVFrame last_frame; uint8_t *frame_buffer; int width,height; uint32_t palette[AVPALETTE_COUNT]; int (*mv_codebook)[2]; uint8_t (*block_codebook)[16]; int num_mvs; ///< current length of mv_codebook int num_blocks_packed; ///< current length of block_codebook } TgvContext; static av_cold int tgv_decode_init(AVCodecContext *avctx) { TgvContext *s = avctx->priv_data; s->avctx = avctx; avctx->time_base = (AVRational){1, 15}; avctx->pix_fmt = AV_PIX_FMT_PAL8; avcodec_get_frame_defaults(&s->last_frame); return 0; } /** * Unpack buffer * @return 0 on success, -1 on critical buffer underflow */ static int unpack(const uint8_t *src, const uint8_t *src_end, uint8_t *dst, int width, int height) { uint8_t *dst_end = dst + width*height; int size, size1, size2, offset, run; uint8_t *dst_start = dst; if (src[0] & 0x01) src += 5; else src += 2; if (src_end - src < 3) return AVERROR_INVALIDDATA; size = AV_RB24(src); src += 3; while (size > 0 && src < src_end) { /* determine size1 and size2 */ size1 = (src[0] & 3); if (src[0] & 0x80) { // 1 if (src[0] & 0x40 ) { // 11 if (src[0] & 0x20) { // 111 if (src[0] < 0xFC) // !(111111) size1 = (((src[0] & 31) + 1) << 2); src++; size2 = 0; } else { // 110 offset = ((src[0] & 0x10) << 12) + AV_RB16(&src[1]) + 1; size2 = ((src[0] & 0xC) << 6) + src[3] + 5; src += 4; } } else { // 10 size1 = ((src[1] & 0xC0) >> 6); offset = (AV_RB16(&src[1]) & 0x3FFF) + 1; size2 = (src[0] & 0x3F) + 4; src += 3; } } else { // 0 offset = ((src[0] & 0x60) << 3) + src[1] + 1; size2 = ((src[0] & 0x1C) >> 2) + 3; src += 2; } /* fetch strip from src */ if (size1 > src_end - src) break; if (size1 > 0) { size -= size1; run = FFMIN(size1, dst_end - dst); memcpy(dst, src, run); dst += run; src += run; } if (size2 > 0) { if (dst - dst_start < offset) return 0; size -= size2; run = FFMIN(size2, dst_end - dst); av_memcpy_backptr(dst, offset, run); dst += run; } } return 0; } /** * Decode inter-frame * @return 0 on success, -1 on critical buffer underflow */ static int tgv_decode_inter(TgvContext *s, AVFrame *frame, const uint8_t *buf, const uint8_t *buf_end) { int num_mvs; int num_blocks_raw; int num_blocks_packed; int vector_bits; int i,j,x,y; GetBitContext gb; int mvbits; const uint8_t *blocks_raw; if(buf_end - buf < 12) return AVERROR_INVALIDDATA; num_mvs = AV_RL16(&buf[0]); num_blocks_raw = AV_RL16(&buf[2]); num_blocks_packed = AV_RL16(&buf[4]); vector_bits = AV_RL16(&buf[6]); buf += 12; if (vector_bits > MIN_CACHE_BITS || !vector_bits) { av_log(s->avctx, AV_LOG_ERROR, "Invalid value for motion vector bits: %d\n", vector_bits); return AVERROR_INVALIDDATA; } /* allocate codebook buffers as necessary */ if (num_mvs > s->num_mvs) { if (av_reallocp_array(&s->mv_codebook, num_mvs, sizeof(*s->mv_codebook))) { s->num_mvs = 0; return AVERROR(ENOMEM); } s->num_mvs = num_mvs; } if (num_blocks_packed > s->num_blocks_packed) { if (av_reallocp_array(&s->block_codebook, num_blocks_packed, sizeof(*s->block_codebook))) { s->num_blocks_packed = 0; return AVERROR(ENOMEM); } s->num_blocks_packed = num_blocks_packed; } /* read motion vectors */ mvbits = (num_mvs * 2 * 10 + 31) & ~31; if (buf_end - buf < (mvbits>>3) + 16*num_blocks_raw + 8*num_blocks_packed) return AVERROR_INVALIDDATA; init_get_bits(&gb, buf, mvbits); for (i = 0; i < num_mvs; i++) { s->mv_codebook[i][0] = get_sbits(&gb, 10); s->mv_codebook[i][1] = get_sbits(&gb, 10); } buf += mvbits >> 3; /* note ptr to uncompressed blocks */ blocks_raw = buf; buf += num_blocks_raw * 16; /* read compressed blocks */ init_get_bits(&gb, buf, (buf_end - buf) << 3); for (i = 0; i < num_blocks_packed; i++) { int tmp[4]; for (j = 0; j < 4; j++) tmp[j] = get_bits(&gb, 8); for (j = 0; j < 16; j++) s->block_codebook[i][15-j] = tmp[get_bits(&gb, 2)]; } if (get_bits_left(&gb) < vector_bits * (s->avctx->height / 4) * (s->avctx->width / 4)) return AVERROR_INVALIDDATA; /* read vectors and build frame */ for (y = 0; y < s->avctx->height / 4; y++) for (x = 0; x < s->avctx->width / 4; x++) { unsigned int vector = get_bits(&gb, vector_bits); const uint8_t *src; int src_stride; if (vector < num_mvs) { int mx = x * 4 + s->mv_codebook[vector][0]; int my = y * 4 + s->mv_codebook[vector][1]; if (mx < 0 || mx + 4 > s->avctx->width || my < 0 || my + 4 > s->avctx->height) { av_log(s->avctx, AV_LOG_ERROR, "MV %d %d out of picture\n", mx, my); continue; } src = s->last_frame.data[0] + mx + my * s->last_frame.linesize[0]; src_stride = s->last_frame.linesize[0]; } else { int offset = vector - num_mvs; if (offset < num_blocks_raw) src = blocks_raw + 16*offset; else if (offset - num_blocks_raw < num_blocks_packed) src = s->block_codebook[offset - num_blocks_raw]; else continue; src_stride = 4; } for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) frame->data[0][(y * 4 + j) * frame->linesize[0] + (x * 4 + i)] = src[j * src_stride + i]; } return 0; } static int tgv_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; TgvContext *s = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; AVFrame *frame = data; int chunk_type, ret; if (buf_end - buf < EA_PREAMBLE_SIZE) return AVERROR_INVALIDDATA; chunk_type = AV_RL32(&buf[0]); buf += EA_PREAMBLE_SIZE; if (chunk_type == kVGT_TAG) { int pal_count, i; if(buf_end - buf < 12) { av_log(avctx, AV_LOG_WARNING, "truncated header\n"); return AVERROR_INVALIDDATA; } s->width = AV_RL16(&buf[0]); s->height = AV_RL16(&buf[2]); if (s->avctx->width != s->width || s->avctx->height != s->height) { avcodec_set_dimensions(s->avctx, s->width, s->height); av_freep(&s->frame_buffer); av_frame_unref(&s->last_frame); } pal_count = AV_RL16(&buf[6]); buf += 12; for(i = 0; i < pal_count && i < AVPALETTE_COUNT && buf_end - buf >= 3; i++) { s->palette[i] = 0xFFU << 24 | AV_RB24(buf); buf += 3; } } if ((ret = av_image_check_size(s->width, s->height, 0, avctx)) < 0) return ret; if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; memcpy(frame->data[1], s->palette, AVPALETTE_SIZE); if (chunk_type == kVGT_TAG) { int y; frame->key_frame = 1; frame->pict_type = AV_PICTURE_TYPE_I; if (!s->frame_buffer && !(s->frame_buffer = av_malloc(s->width * s->height))) return AVERROR(ENOMEM); if (unpack(buf, buf_end, s->frame_buffer, s->avctx->width, s->avctx->height) < 0) { av_log(avctx, AV_LOG_WARNING, "truncated intra frame\n"); return AVERROR_INVALIDDATA; } for (y = 0; y < s->height; y++) memcpy(frame->data[0] + y * frame->linesize[0], s->frame_buffer + y * s->width, s->width); } else { if (!s->last_frame.data[0]) { av_log(avctx, AV_LOG_WARNING, "inter frame without corresponding intra frame\n"); return buf_size; } frame->key_frame = 0; frame->pict_type = AV_PICTURE_TYPE_P; if (tgv_decode_inter(s, frame, buf, buf_end) < 0) { av_log(avctx, AV_LOG_WARNING, "truncated inter frame\n"); return AVERROR_INVALIDDATA; } } av_frame_unref(&s->last_frame); if ((ret = av_frame_ref(&s->last_frame, frame)) < 0) return ret; *got_frame = 1; return buf_size; } static av_cold int tgv_decode_end(AVCodecContext *avctx) { TgvContext *s = avctx->priv_data; av_frame_unref(&s->last_frame); av_freep(&s->frame_buffer); av_free(s->mv_codebook); av_free(s->block_codebook); return 0; } AVCodec ff_eatgv_decoder = { .name = "eatgv", .long_name = NULL_IF_CONFIG_SMALL("Electronic Arts TGV video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_TGV, .priv_data_size = sizeof(TgvContext), .init = tgv_decode_init, .close = tgv_decode_end, .decode = tgv_decode_frame, .capabilities = CODEC_CAP_DR1, };
instarcam/InstarVision-Android
ffmpeg/libavcodec/eatgv.c
C
lgpl-2.1
11,263
package dr.evomodel.antigenic.phyloclustering; import java.util.LinkedList; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; public class TreeClusteringSharedRoutines { public static int[] setMembershipTreeToVirusIndexes(int numdata, MatrixParameter virusLocations, int numNodes, TreeModel treeModel ){ //I suspect this is an expensive operation, so I don't want to do it many times, //which is also unnecessary - MAY have to update whenever a different tree is used. int[] correspondingTreeIndexForVirus = new int[numdata]; for(int i=0; i < numdata; i++){ Parameter v = virusLocations.getParameter(i); String curName = v.getParameterName(); // System.out.println(curName); int isFound = 0; for(int j=0; j < numNodes; j++){ String treeId = treeModel.getTaxonId(j); if(curName.equals(treeId) ){ // System.out.println(" isFound at j=" + j); correspondingTreeIndexForVirus[i] = j; isFound=1; break; } } if(isFound ==0){ System.out.println("not found. Exit now."); System.exit(0); } } return(correspondingTreeIndexForVirus); } public static void updateUndriftedVirusLocations(int numNodes, int numdata, TreeModel treeModel, MatrixParameter virusLocationsTreeNode, Parameter indicators, MatrixParameter mu, MatrixParameter virusLocations, int[] correspondingTreeIndexForVirus){ double[][] nodeloc = new double[numNodes][2]; //process the tree and get the vLoc of the viruses.. //breadth first depth first.. NodeRef cNode = treeModel.getRoot(); LinkedList<NodeRef> visitlist = new LinkedList<NodeRef>(); visitlist.add(cNode); int countProcessed=0; while(visitlist.size() > 0){ countProcessed++; //assign value to the current node... if(treeModel.getParent(cNode) == null){ //this means it is a root node Parameter curMu = mu.getParameter( cNode.getNumber() ); //Parameter curMu = mu.getParameter(0); nodeloc[cNode.getNumber()][0] = curMu.getParameterValue(0); nodeloc[cNode.getNumber() ][1] = curMu.getParameterValue(1); Parameter curVirusLoc = virusLocationsTreeNode.getParameter(cNode.getNumber()); curVirusLoc.setParameterValue(0, curMu.getParameterValue(0) ); curVirusLoc.setParameterValue(1, curMu.getParameterValue(1) ); } else{ nodeloc[cNode.getNumber()][0] = nodeloc[treeModel.getParent(cNode).getNumber()][0]; nodeloc[cNode.getNumber()][1] = nodeloc[treeModel.getParent(cNode).getNumber()][1]; if( (int) indicators.getParameterValue(cNode.getNumber()) == 1){ Parameter curMu = mu.getParameter(cNode.getNumber() ); // no +1 because I don't need another mu- the root's mu takes care of the first cluster's mu //Parameter curMu = mu.getParameter(cNode.getNumber() +1); //+1 because mu0 is reserved for the root. nodeloc[cNode.getNumber()][0] += curMu.getParameterValue(0); nodeloc[cNode.getNumber()][1] += curMu.getParameterValue(1); } Parameter curVirusLoc = virusLocationsTreeNode.getParameter(cNode.getNumber()); curVirusLoc.setParameterValue(0, nodeloc[cNode.getNumber()][0] ); curVirusLoc.setParameterValue(1,nodeloc[cNode.getNumber()][1] ); } //add all the children to the queue for(int childNum=0; childNum < treeModel.getChildCount(cNode); childNum++){ NodeRef node= treeModel.getChild(cNode,childNum); visitlist.add(node); } visitlist.pop(); //now that we have finished visiting this node, pops it out of the queue if(visitlist.size() > 0){ cNode = visitlist.getFirst(); //set the new first node in the queue to visit } } //write the virus locations for(int i=0; i < numdata; i++){ Parameter vLocParameter = virusLocations.getParameter(i); vLocParameter.setParameterValue(0, nodeloc[correspondingTreeIndexForVirus[i]][0]); vLocParameter.setParameterValue(1, nodeloc[correspondingTreeIndexForVirus[i]][1]); } //for(int i=0; i < numdata; i++){ //Parameter vLocP= virusLocations.getParameter(i); //System.out.println("virus " + vLocP.getId() + "\t" + vLocP.getParameterValue(0) + "," + vLocP.getParameterValue(1) ); //} } //may be very inefficient public static int findAnOnNodeIncludingRootRandomly(int numNodes, Parameter indicators) { int isOn= 0; int I_selected = -1; while(isOn ==0){ I_selected = (int) (Math.floor(Math.random()*numNodes)); isOn = (int) indicators.getParameterValue(I_selected); } return I_selected; } //Copied from TreeClusterAlgorithm - should have put into the shared class... public static LinkedList<Integer> findActiveBreakpointsChildren(int selectedNodeNumber, int numNodes, TreeModel treeModel, Parameter indicators) { //a list of breakpoints... LinkedList<Integer> linkedList = new LinkedList<Integer>(); int[] nodeBreakpointNumber = new int[numNodes]; //int[] nodeStatus = new int[numNodes]; //for(int i=0; i < numNodes; i ++){ // nodeStatus[i] = -1; //} //convert to easy process format. //for(int i=0; i < (binSize ); i++){ // if((int) indicators.getParameterValue(i) ==1){ // nodeStatus[(int)breakPoints.getParameterValue(i)] = i; // } //} //process the tree and get the vLoc of the viruses.. //breadth first depth first.. NodeRef cNode = treeModel.getRoot(); LinkedList<NodeRef> visitlist = new LinkedList<NodeRef>(); visitlist.add(cNode); //I am not sure if it still works...... int countProcessed=0; while(visitlist.size() > 0){ countProcessed++; //assign value to the current node... if(treeModel.getParent(cNode) == null){ //Parameter curMu = mu.getParameter(0); nodeBreakpointNumber[cNode.getNumber()] = cNode.getNumber(); } else{ nodeBreakpointNumber[cNode.getNumber()] = nodeBreakpointNumber[treeModel.getParent(cNode).getNumber()]; //System.out.println("node#" + cNode.getNumber() + " is " + nodeBreakpointNumber[cNode.getNumber()]); if( (int) indicators.getParameterValue(cNode.getNumber()) == 1){ //System.out.println(cNode.getNumber() + " is a break point"); //Parameter curMu = mu.getParameter(cNode.getNumber() +1); //+1 because mu0 is reserved for the root. //Parameter curMu = mu.getParameter(cNode.getNumber() ); //+1 because mu0 is reserved for the root. //see if parent's status is the same as the selectedIndex if( nodeBreakpointNumber[cNode.getNumber()] == selectedNodeNumber ){ //System.out.println("hihi"); linkedList.add( cNode.getNumber() ); } //now, replace this nodeBreakpointNumber with its own node number nodeBreakpointNumber[cNode.getNumber()] = cNode.getNumber(); } } //add all the children to the queue for(int childNum=0; childNum < treeModel.getChildCount(cNode); childNum++){ NodeRef node= treeModel.getChild(cNode,childNum); visitlist.add(node); } visitlist.pop(); //now that we have finished visiting this node, pops it out of the queue if(visitlist.size() > 0){ cNode = visitlist.getFirst(); //set the new first node in the queue to visit } } //System.out.println("Now printing children of " + selectedNodeNumber+":"); //for(int i=0; i < linkedList.size(); i++){ // System.out.println( linkedList.get(i) ); //} return linkedList; } }
adamallo/beast-mcmc
src/dr/evomodel/antigenic/phyloclustering/TreeClusteringSharedRoutines.java
Java
lgpl-2.1
8,209
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QACCESSIBLEQUICKITEM_H #define QACCESSIBLEQUICKITEM_H #include <QtQuick/QQuickItem> #include <QtQuick/QQuickView> #include <QtQuick/private/qqmlaccessible_p.h> QT_BEGIN_NAMESPACE #ifndef QT_NO_ACCESSIBILITY class QTextDocument; class QAccessibleQuickItem : public QQmlAccessible, public QAccessibleValueInterface, public QAccessibleTextInterface { public: QAccessibleQuickItem(QQuickItem *item); QRect rect() const; QRect viewRect() const; bool clipsChildren() const; QAccessibleInterface *childAt(int x, int y) const; QAccessibleInterface *parent() const; QAccessibleInterface *child(int index) const; int childCount() const; int indexOfChild(const QAccessibleInterface *iface) const; QList<QQuickItem *> childItems() const; QAccessible::State state() const; QAccessible::Role role() const; QString text(QAccessible::Text) const; bool isAccessible() const; // Action Interface QStringList actionNames() const; void doAction(const QString &actionName); QStringList keyBindingsForAction(const QString &actionName) const; // Value Interface QVariant currentValue() const; void setCurrentValue(const QVariant &value); QVariant maximumValue() const; QVariant minimumValue() const; QVariant minimumStepSize() const; // Text Interface void selection(int selectionIndex, int *startOffset, int *endOffset) const; int selectionCount() const; void addSelection(int startOffset, int endOffset); void removeSelection(int selectionIndex); void setSelection(int selectionIndex, int startOffset, int endOffset); // cursor int cursorPosition() const; void setCursorPosition(int position); // text QString text(int startOffset, int endOffset) const; QString textBeforeOffset(int offset, QAccessible::TextBoundaryType boundaryType, int *startOffset, int *endOffset) const; QString textAfterOffset(int offset, QAccessible::TextBoundaryType boundaryType, int *startOffset, int *endOffset) const; QString textAtOffset(int offset, QAccessible::TextBoundaryType boundaryType, int *startOffset, int *endOffset) const; int characterCount() const; // character <-> geometry QRect characterRect(int /* offset */) const { return QRect(); } int offsetAtPoint(const QPoint & /* point */) const { return -1; } void scrollToSubstring(int /* startIndex */, int /* endIndex */) {} QString attributes(int /* offset */, int *startOffset, int *endOffset) const { *startOffset = 0; *endOffset = 0; return QString(); } QTextDocument *textDocument() const; protected: QQuickItem *item() const { return static_cast<QQuickItem*>(object()); } void *interface_cast(QAccessible::InterfaceType t); private: QTextDocument *m_doc; }; QRect itemScreenRect(QQuickItem *item); QList<QQuickItem *> accessibleUnignoredChildren(QQuickItem *item, bool paintOrder = false); #endif // QT_NO_ACCESSIBILITY QT_END_NAMESPACE #endif // QACCESSIBLEQUICKITEM_H
Distrotech/qtdeclarative
src/quick/accessible/qaccessiblequickitem_p.h
C
lgpl-3.0
4,726
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:59:45 CET 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Interface org.openbase.bco.manager.user.lib.User (BCO Manager 1.5-SNAPSHOT API)</title> <meta name="date" content="2018-01-16"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.openbase.bco.manager.user.lib.User (BCO Manager 1.5-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/openbase/bco/manager/user/lib/class-use/User.html" target="_top">Frames</a></li> <li><a href="User.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.openbase.bco.manager.user.lib.User" class="title">Uses of Interface<br>org.openbase.bco.manager.user.lib.User</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">User</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.openbase.bco.manager.user.core">org.openbase.bco.manager.user.core</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.openbase.bco.manager.user.lib">org.openbase.bco.manager.user.lib</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.openbase.bco.manager.user.core"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">User</a> in <a href="../../../../../../../org/openbase/bco/manager/user/core/package-summary.html">org.openbase.bco.manager.user.core</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../org/openbase/bco/manager/user/core/package-summary.html">org.openbase.bco.manager.user.core</a> that implement <a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">User</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/openbase/bco/manager/user/core/UserControllerImpl.html" title="class in org.openbase.bco.manager.user.core">UserControllerImpl</a></span></code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.openbase.bco.manager.user.lib"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">User</a> in <a href="../../../../../../../org/openbase/bco/manager/user/lib/package-summary.html">org.openbase.bco.manager.user.lib</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation"> <caption><span>Subinterfaces of <a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">User</a> in <a href="../../../../../../../org/openbase/bco/manager/user/lib/package-summary.html">org.openbase.bco.manager.user.lib</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/openbase/bco/manager/user/lib/UserController.html" title="interface in org.openbase.bco.manager.user.lib">UserController</a></span></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/openbase/bco/manager/user/lib/User.html" title="interface in org.openbase.bco.manager.user.lib">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/openbase/bco/manager/user/lib/class-use/User.html" target="_top">Frames</a></li> <li><a href="User.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015&#x2013;2018 <a href="https://github.com/openbase">openbase.org</a>. All rights reserved.</small></p> </body> </html>
DivineThreepwood/bco.core-manager
docs/apidocs/org/openbase/bco/manager/user/lib/class-use/User.html
HTML
lgpl-3.0
8,337
package com.googlecode.lanterna.examples; import java.io.IOException; import com.googlecode.lanterna.graphics.TextGraphics; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.screen.TerminalScreen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import com.googlecode.lanterna.terminal.Terminal; public class OutputString { public static void main(String[] args) throws IOException { Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); String s = "Hello World!"; TextGraphics tGraphics = screen.newTextGraphics(); screen.startScreen(); screen.clear(); tGraphics.putString(10, 10, s); screen.refresh(); screen.readInput(); screen.stopScreen(); } }
LTI2000/lanterna
src/examples/java/com/googlecode/lanterna/examples/OutputString.java
Java
lgpl-3.0
782
/* * Copyright (C) 2006-2011, SRI International (R) * * 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/>. */ #pragma once #ifndef __OpenKarto_StringHelper_h__ #define __OpenKarto_StringHelper_h__ #include <stdio.h> #include <ostream> #include <sstream> #include <OpenKarto/String.h> namespace karto { ///** \addtogroup OpenKarto */ //@{ //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// class Color; class Pose2; class Pose3; class Quaternion; template<typename T> class Size2; template<typename T> class Vector2; template<typename T> class Vector3; template<typename T> class Vector4; /** * Class to convert to and from Karto strings */ class KARTO_EXPORT StringHelper { public: /** * Converts the given C-string to a string * @param value value to be converted * @return string representation of the C-string */ static String ToString(const char* value); /** * Converts the given boolean to a string * @param value value to be converted * @return string representation of the boolean */ static String ToString(kt_bool value); /** * Converts the given 16-bit signed integer to a string * @param value value to be converted * @return string representation of the 16-bit signed integer */ static String ToString(kt_int16s value); /** * Converts the given 16-bit unsigned integer to a string * @param value value to be converted * @return string representation of the 16-bit unsigned integer */ static String ToString(kt_int16u value); /** * Converts the given 32-bit signed integer to a string * @param value value to be converted * @return string representation of the 32-bit signed integer */ static String ToString(kt_int32s value); /** * Converts the given 32-bit unsigned integer to a string * @param value value to be converted * @return string representation of the 32-bit unsigned integer */ static String ToString(kt_int32u value); /** * Converts the given 64-bit signed integer to a string * @param value value to be converted * @return string representation of the 64-bit signed integer */ static String ToString(kt_int64s value); /** * Converts the given 64-bit unsigned integer to a string * @param value value to be converted * @return string representation of the 64-bit unsigned integer */ static String ToString(kt_int64u value); #if defined(__APPLE__) && !defined(__LP64__) static String ToString(kt_size_t value); #endif /** * Converts the given float to a string * @param value value to be converted * @return string representation of the float */ static String ToString(kt_float value); /** * Converts the given double to a string * @param value value to be converted * @return string representation of the double */ static String ToString(kt_double value); /** * Converts the given float to a string with the given precision * @param value value to be converted * @param precision precision * @return string representation of the float */ static String ToString(kt_float value, kt_int32u precision); /** * Converts the given double to a string with the given precision * @param value value to be converted * @param precision precision * @return string representation of the double */ static String ToString(kt_double value, kt_int32u precision); /** * Copies the string argument * @param rValue string value * @return copy of the string argument */ static String ToString(const String& rValue); /** * Converts the given size to a string * @param rValue value to be converted * @return string representation of the size */ template<typename T> inline static String ToString(const Size2<T>& rValue); /** * Converts the given vector to a string * @param rValue value to be converted * @return string representation of the vector */ template<typename T> inline static String ToString(const Vector2<T>& rValue); /** * Converts the given vector to a string * @param rValue value to be converted * @return string representation of the vector */ template<typename T> inline static String ToString(const Vector3<T>& rValue); /** * Converts the given vector to a string * @param rValue value to be converted * @return string representation of the vector */ template<typename T> inline static String ToString(const Vector4<T>& rValue); /** * Converts the given quaternion to a string * @param rValue value to be converted * @return string representation of the quaternion */ static String ToString(const Quaternion& rValue); /** * Converts the given color to a string * @param rValue value to be converted * @return string representation of the color */ static String ToString(const Color& rValue); /** * Converts the given pose to a string * @param rValue value to be converted * @return string representation of the pose */ static String ToString(const Pose2& rValue); /** * Converts the given pose to a string * @param rValue value to be converted * @return string representation of the pose */ static String ToString(const Pose3& rValue); /** * Converts the given string to a boolean * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_bool& rValue); /** * Converts the given string to a 16-bit signed integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int16s& rValue); /** * Converts the given string to a 16-bit unsigned integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int16u& rValue); /** * Converts the given string to a 32-bit signed integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int32s& rValue); /** * Converts the given string to a 32-bit unsigned integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int32u& rValue); /** * Converts the given string to a 64-bit signed integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int64s& rValue); /** * Converts the given string to a 64-bit unsigned integer * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_int64u& rValue); /** * Converts the given string to a float * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_float& rValue); /** * Converts the given string to a double * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, kt_double& rValue); /** * Converts the given String to a String * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, String& rValue); /** * Converts the given String to a Size2<T> * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ template<typename T> static kt_bool FromString(const String& rStringValue, Size2<T>& rValue) { kt_size_t index = rStringValue.FindFirstOf(" "); if (index != -1) { karto::String stringValue; T value; stringValue = rStringValue.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetWidth(value); stringValue = rStringValue.SubString(index + 1, rStringValue.Size()); value = 0; FromString(stringValue, value); rValue.SetHeight(value); return true; } return false; } /** * Converts the given String to a Vector2<T> * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ template<typename T> static kt_bool FromString(const String& rStringValue, Vector2<T>& rValue) { kt_size_t index = rStringValue.FindFirstOf(" "); if (index != -1) { karto::String stringValue; T value; stringValue = rStringValue.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetX(value); stringValue = rStringValue.SubString(index + 1, rStringValue.Size()); value = 0; FromString(stringValue, value); rValue.SetY(value); return true; } return false; } /** * Converts the given String to a Vector3<T> * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ template<typename T> inline static kt_bool FromString(const String& rStringValue, Vector3<T>& rValue) { karto::String tempString = rStringValue; kt_size_t index = tempString.FindFirstOf(" "); if (index != -1) { karto::String stringValue; T value; // Get X stringValue = tempString.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetX(value); // Get Y tempString = rStringValue.SubString(index + 1, rStringValue.Size()); index = tempString.FindFirstOf(" "); stringValue = tempString.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetY(value); // Get Z tempString = tempString.SubString(index + 1, rStringValue.Size()); index = tempString.FindFirstOf(" "); stringValue = tempString.SubString(index + 1, rStringValue.Size()); value = 0; FromString(stringValue, value); rValue.SetZ(value); return true; } return false; } /** * Converts the given String to a Vector4<T> * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ template<typename T> static kt_bool FromString(const String& rStringValue, Vector4<T>& rValue) { karto::String tempString = rStringValue; kt_size_t index = tempString.FindFirstOf(" "); if (index != -1) { karto::String stringValue; T value; // Get X stringValue = tempString.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetX(value); // Get Y tempString = rStringValue.SubString(index + 1, rStringValue.Size()); index = tempString.FindFirstOf(" "); stringValue = tempString.SubString(0, index); value = 0; FromString(stringValue, value); rValue.SetY(value); // Get Z tempString = tempString.SubString(index + 1, rStringValue.Size()); index = tempString.FindFirstOf(" "); stringValue = tempString.SubString(index + 1, rStringValue.Size()); value = 0; FromString(stringValue, value); rValue.SetZ(value); // Get W tempString = tempString.SubString(index + 1, rStringValue.Size()); index = tempString.FindFirstOf(" "); stringValue = tempString.SubString(index + 1, rStringValue.Size()); value = 0; FromString(stringValue, value); rValue.SetW(value); return true; } return false; } /** * Converts the given String to a Quaternion * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, Quaternion& rValue); /** * Converts the given String to a Color * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, Color& rValue); /** * Converts the given String to a Pose2 * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, Pose2& rValue); /** * Converts the given String to a Pose3 * @param rStringValue string representation of value * @param rValue value to set from string * @return true if conversion was success, false otherwise */ static kt_bool FromString(const String& rStringValue, Pose3& rValue); /** * Returns a trimmed version of the given string * @param rValue string * @return trimmed version of the given string */ static String Trim(const String& rValue); /** * Replace all instances of string pattern in source string with replacement pattern * @param rSource source string * @param rFind string pattern * @param rReplace replacement pattern * @return replaced string */ static String Replace(const String& rSource, const String& rFind, const String& rReplace); /** * Checks if given character is a letter * @param ch character * @return true if given character is a letter */ static kt_bool IsLetter(char ch); /** * Returns a lowercase version of the given string * @param rValue string * @return lowercase version of the given string */ static String ToLowerCase(const String &rValue); /** * Returns a uppercase version of the given string * @param rValue string * @return uppercase version of the given string */ static String ToUpperCase(const String &rValue); }; // class StringHelper //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// /** * Class to build strings */ class KARTO_EXPORT StringBuilder { public: /** * Convert contents to string * @return string of contents */ const String& ToString() const; /** * Erase contents of string builder */ void Clear(); public: /** * Add char to this string builder * @param value char value */ // StringBuilder& operator << (char value); /** * Add kt_int8u to this string builder * @param value kt_int8u value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int8u value); /** * Add kt_int16s to this string builder * @param value kt_int16s value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int16s value); /** * Add kt_int16u to this string builder * @param value kt_int16u value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int16u value); /** * Add kt_int32s to this string builder * @param value kt_int32s value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int32s value); /** * Add kt_int32u to this string builder * @param value kt_int32u value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int32u value); /** * Add kt_int64s to this string builder * @param value kt_int64s value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int64s value); /** * Add kt_int64u to this string builder * @param value kt_int64u value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_int64u value); #if defined(__APPLE__) && !defined(__LP64__) /** * Add kt_size_t to this string builder * @param value kt_size_t value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_size_t value); #endif /** * Add kt_float to this string builder * @param value kt_float value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_float value); /** * Add kt_double to this string builder * @param value kt_double value * @return this StringBuilder with given value added */ StringBuilder& operator << (kt_double value); /** * Add string to this string builder * @param rValue string value * @return this StringBuilder with given value added */ StringBuilder& operator << (const String& rValue); /** * Add string builder to this string builder * @param rValue string builder value * @return this StringBuilder with given value added */ StringBuilder& operator << (const StringBuilder& rValue); /** * Write string to output stream * @param rStream output stream * @param rStringBuilder StringBuilder to write * @return rStream */ friend KARTO_FORCEINLINE std::ostream& operator << (std::ostream& rStream, const StringBuilder& rStringBuilder) { rStream << rStringBuilder.ToString(); return rStream; } private: String m_String; }; // class StringBuilder //@} } #endif // __OpenKarto_StringHelper_h__
skasperski/OpenKarto
source/OpenKarto/StringHelper.h
C
lgpl-3.0
20,975
/* * #%L * Alfresco Solr Client * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.solr.client; import javax.servlet.http.HttpServletResponse; import org.springframework.extensions.surf.util.I18NUtil; /** * Status code constants for SOLR. * * @since 4.0 */ public class Status { /* Status code constants */ public static final int STATUS_CONTINUE = HttpServletResponse.SC_CONTINUE; public static final int STATUS_SWITCHING_PROTOCOLS = HttpServletResponse.SC_SWITCHING_PROTOCOLS; public static final int STATUS_OK = HttpServletResponse.SC_OK; public static final int STATUS_CREATED = HttpServletResponse.SC_CREATED; public static final int STATUS_ACCEPTED = HttpServletResponse.SC_ACCEPTED; public static final int STATUS_NON_AUTHORITATIVE_INFORMATION = HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION; public static final int STATUS_NO_CONTENT = HttpServletResponse.SC_NO_CONTENT; public static final int STATUS_RESET_CONTENT = HttpServletResponse.SC_RESET_CONTENT; public static final int STATUS_PARTIAL_CONTENT = HttpServletResponse.SC_PARTIAL_CONTENT; public static final int STATUS_MULTIPLE_CHOICES = HttpServletResponse.SC_MULTIPLE_CHOICES; public static final int STATUS_MOVED_PERMANENTLY = HttpServletResponse.SC_MOVED_PERMANENTLY; public static final int STATUS_MOVED_TEMPORARILY = HttpServletResponse.SC_MOVED_TEMPORARILY; public static final int STATUS_FOUND = HttpServletResponse.SC_FOUND; public static final int STATUS_SEE_OTHER = HttpServletResponse.SC_SEE_OTHER; public static final int STATUS_NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED; public static final int STATUS_USE_PROXY = HttpServletResponse.SC_USE_PROXY; public static final int STATUS_TEMPORARY_REDIRECT = HttpServletResponse.SC_TEMPORARY_REDIRECT; public static final int STATUS_BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST; public static final int STATUS_UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED; public static final int STATUS_PAYMENT_REQUIRED = HttpServletResponse.SC_PAYMENT_REQUIRED; public static final int STATUS_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN; public static final int STATUS_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND; public static final int STATUS_METHOD_NOT_ALLOWED = HttpServletResponse.SC_METHOD_NOT_ALLOWED; public static final int STATUS_NOT_ACCEPTABLE = HttpServletResponse.SC_NOT_ACCEPTABLE; public static final int STATUS_PROXY_AUTHENTICATION_REQUIRED = HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED; public static final int STATUS_REQUEST_TIMEOUT = HttpServletResponse.SC_REQUEST_TIMEOUT; public static final int STATUS_CONFLICT = HttpServletResponse.SC_CONFLICT; public static final int STATUS_GONE = HttpServletResponse.SC_GONE; public static final int STATUS_LENGTH_REQUIRED = HttpServletResponse.SC_LENGTH_REQUIRED; public static final int STATUS_PRECONDITION_FAILED = HttpServletResponse.SC_PRECONDITION_FAILED; public static final int STATUS_REQUEST_ENTITY_TOO_LARGE = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; public static final int STATUS_REQUEST_URI_TOO_LONG = HttpServletResponse.SC_REQUEST_URI_TOO_LONG; public static final int STATUS_UNSUPPORTED_MEDIA_TYPE = HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE; public static final int STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE; public static final int STATUS_EXPECTATION_FAILED = HttpServletResponse.SC_EXPECTATION_FAILED; public static final int STATUS_INTERNAL_SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; public static final int STATUS_NOT_IMPLEMENTED = HttpServletResponse.SC_NOT_IMPLEMENTED; public static final int STATUS_BAD_GATEWAY = HttpServletResponse.SC_BAD_GATEWAY; public static final int STATUS_SERVICE_UNAVAILABLE = HttpServletResponse.SC_SERVICE_UNAVAILABLE; public static final int STATUS_GATEWAY_TIMEOUT = HttpServletResponse.SC_GATEWAY_TIMEOUT; public static final int STATUS_HTTP_VERSION_NOT_SUPPORTED = HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED; private Throwable exception = null; private String location = ""; private int code = HttpServletResponse.SC_OK; private String message = ""; private boolean redirect = false; /** * Helper method to set the code and message. * <p> * Redirect is set to true. * * @param code code * @param message message */ public void setCode(int code, String message) { this.code = code; this.message = message; this.redirect = true; } /** * @param exception Throwable */ public void setException(Throwable exception) { this.exception = exception; } /** * @return exception */ public Throwable getException() { return exception; } /** * @param message String */ public void setMessage(String message) { this.message = message; } /** * @return message */ public String getMessage() { return message; } /** * @param redirect redirect to status code response */ public void setRedirect(boolean redirect) { this.redirect = redirect; } /** * @return redirect to status code response */ public boolean getRedirect() { return redirect; } /** * @see javax.servlet.http.HTTPServletResponse * * @param code status code */ public void setCode(int code) { this.code = code; } /** * @return status code */ public int getCode() { return code; } /** * Gets the short name of the status code * * @return status code name */ public String getCodeName() { String codeName = I18NUtil.getMessage("webscript.code." + code + ".name"); return codeName == null ? "" : codeName; } /** * @see javax.servlet.http.HTTPServletResponse * * @param location location response-header */ public void setLocation(String location) { this.location = location; } /** * @return location */ public String getLocation() { return location; } /** * Gets the description of the status code * * @return status code description */ public String getCodeDescription() { String codeDescription = I18NUtil.getMessage("webscript.code." + code + ".description"); return codeDescription == null ? "" : codeDescription; } @Override public String toString() { return Integer.toString(code); } }
Alfresco/community-edition
projects/solr-client/source/java/org/alfresco/solr/client/Status.java
Java
lgpl-3.0
7,961
package com.marginallyclever.makelangeloRobot.loadAndSave; import java.io.InputStream; import java.io.OutputStream; import javax.swing.filechooser.FileNameExtensionFilter; import com.marginallyclever.makelangeloRobot.MakelangeloRobot; /** * Interface for the service handler * @author Admin * */ public interface LoadAndSaveFileType { /** * Just what it sounds like. * @return */ public FileNameExtensionFilter getFileNameFilter(); /** * @return true if this plugin can load data from a stream. */ public boolean canLoad(); /** * @return true if this plugin can save data to a stream. */ public boolean canSave(); /** * Checks a string's filename, which includes the file extension, (e.g. foo.jpg). * * @param filename absolute path of file to load. * @return true if this plugin can load this file. */ public boolean canLoad(String filename); /** * Checks a string's filename, which includes the file extension, (e.g. foo.jpg). * * @param filename absolute path of file to save. * @return true if this plugin can save this file. */ public boolean canSave(String filename); /** * attempt to load a file into the system from a given stream * @param filename * @return true if load successful. */ public boolean load(InputStream inputStream,MakelangeloRobot robot); /** * attempt to save makelangelo instructions to a given stream * @param filename * @return true if save successful. */ public boolean save(OutputStream outputStream,MakelangeloRobot robot); }
rossonet/RAM
modelli/progetti/plotter_a_corde/Makelangelo-software-master/java/src/main/java/com/marginallyclever/makelangeloRobot/loadAndSave/LoadAndSaveFileType.java
Java
lgpl-3.0
1,540
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto 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 Yusuke Yamamoto ``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 Yusuke Yamamoto 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 com.fitbit.api.client.http; import com.fitbit.api.FitbitAPIException; /** * Representing authorized Access Token which is passed to the service provider in order to access protected resources.<br> * the token and token secret can be stored into some persistent stores such as file system or RDBMS for the further accesses. * @author Yusuke Yamamoto - yusuke at mac.com */ public class AccessToken extends OAuthToken { private static final long serialVersionUID = -8344528374458826291L; public static final String PN_ENCODED_USER_ID = "encoded_user_id"; private String encodedUserId; AccessToken(Response res) throws FitbitAPIException { this(res.asString()); } // for test unit AccessToken(String str) { super(str); encodedUserId = getParameter(PN_ENCODED_USER_ID); } public AccessToken(String token, String tokenSecret) { super(token, tokenSecret); } public AccessToken(String token, String tokenSecret, String encodedUserId) { this(token, tokenSecret); this.encodedUserId = encodedUserId; } /** * Encoded id of user who authorized access. * @return Encoded id of user who authorized access. * @since Fitbit4J 1 */ public String getEncodedUserId() { return encodedUserId; } }
jordancheah/fitbit4j
fitbit4j/src/main/java/com/fitbit/api/client/http/AccessToken.java
Java
lgpl-3.0
2,812
package org.molgenis.data.rsql; import org.molgenis.data.meta.AttributeType; import org.molgenis.data.meta.model.Attribute; import org.molgenis.data.meta.model.EntityType; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Iterator; import static com.google.common.collect.Lists.newArrayList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.molgenis.data.meta.AttributeType.*; import static org.testng.Assert.assertEquals; public class RSQLValueParserTest { private RSQLValueParser rSqlValueParser; @BeforeMethod public void setUpBeforeMethod() { rSqlValueParser = new RSQLValueParser(); } @DataProvider(name = "parseProvider") public static Iterator<Object[]> parseProvider() { return newArrayList(new Object[] { ONE_TO_MANY, INT, 1 }, new Object[] { ONE_TO_MANY, STRING, "1" }, new Object[] { XREF, INT, 1 }, new Object[] { XREF, STRING, "1" }).iterator(); } @Test(dataProvider = "parseProvider") public void parse(AttributeType attrType, AttributeType refIdAttrType, Object parsedValue) { Attribute oneToManyAttr = mock(Attribute.class); when(oneToManyAttr.getDataType()).thenReturn(attrType); EntityType refEntity = mock(EntityType.class); Attribute refIdAttr = mock(Attribute.class); when(refIdAttr.getDataType()).thenReturn(refIdAttrType); when(refEntity.getIdAttribute()).thenReturn(refIdAttr); when(oneToManyAttr.getRefEntity()).thenReturn(refEntity); assertEquals(parsedValue, rSqlValueParser.parse("1", oneToManyAttr)); } }
jjettenn/molgenis
molgenis-data/src/test/java/org/molgenis/data/rsql/RSQLValueParserTest.java
Java
lgpl-3.0
1,617
/* * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. 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. */ #include "config.h" #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) #include "NotificationCenter.h" #include "Document.h" #include "NotificationClient.h" #include "SecurityOrigin.h" #include "WorkerContext.h" namespace WebCore { PassRefPtr<NotificationCenter> NotificationCenter::create(ScriptExecutionContext* context, NotificationClient* client) { RefPtr<NotificationCenter> notificationCenter(adoptRef(new NotificationCenter(context, client))); notificationCenter->suspendIfNeeded(); return notificationCenter.release(); } NotificationCenter::NotificationCenter(ScriptExecutionContext* context, NotificationClient* client) : ActiveDOMObject(context, this) , m_client(client) { } #if ENABLE(LEGACY_NOTIFICATIONS) int NotificationCenter::checkPermission() { if (!client() || !scriptExecutionContext()) return NotificationClient::PermissionDenied; switch (scriptExecutionContext()->securityOrigin()->canShowNotifications()) { case SecurityOrigin::AlwaysAllow: return NotificationClient::PermissionAllowed; case SecurityOrigin::AlwaysDeny: return NotificationClient::PermissionDenied; case SecurityOrigin::Ask: return m_client->checkPermission(scriptExecutionContext()); } ASSERT_NOT_REACHED(); return m_client->checkPermission(scriptExecutionContext()); } #endif #if ENABLE(LEGACY_NOTIFICATIONS) void NotificationCenter::requestPermission(PassRefPtr<VoidCallback> callback) { if (!client() || !scriptExecutionContext()) return; switch (scriptExecutionContext()->securityOrigin()->canShowNotifications()) { case SecurityOrigin::AlwaysAllow: case SecurityOrigin::AlwaysDeny: { m_callbacks.add(NotificationRequestCallback::createAndStartTimer(this, callback)); return; } case SecurityOrigin::Ask: return m_client->requestPermission(scriptExecutionContext(), callback); } ASSERT_NOT_REACHED(); m_client->requestPermission(scriptExecutionContext(), callback); } #endif void NotificationCenter::stop() { if (!m_client) return; m_client->cancelRequestsForPermission(scriptExecutionContext()); m_client->clearNotifications(scriptExecutionContext()); m_client = 0; } void NotificationCenter::requestTimedOut(NotificationCenter::NotificationRequestCallback* request) { m_callbacks.remove(request); } PassRefPtr<NotificationCenter::NotificationRequestCallback> NotificationCenter::NotificationRequestCallback::createAndStartTimer(NotificationCenter* center, PassRefPtr<VoidCallback> callback) { RefPtr<NotificationCenter::NotificationRequestCallback> requestCallback = adoptRef(new NotificationCenter::NotificationRequestCallback(center, callback)); requestCallback->startTimer(); return requestCallback.release(); } NotificationCenter::NotificationRequestCallback::NotificationRequestCallback(NotificationCenter* center, PassRefPtr<VoidCallback> callback) : m_notificationCenter(center) , m_timer(this, &NotificationCenter::NotificationRequestCallback::timerFired) , m_callback(callback) { } void NotificationCenter::NotificationRequestCallback::startTimer() { m_timer.startOneShot(0); } void NotificationCenter::NotificationRequestCallback::timerFired(Timer<NotificationCenter::NotificationRequestCallback>*) { m_callback->handleEvent(); m_notificationCenter->requestTimedOut(this); } } // namespace WebCore #endif // ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
nawawi/wkhtmltopdf
webkit/Source/WebCore/Modules/notifications/NotificationCenter.cpp
C++
lgpl-3.0
5,127
/* * #%L * Alfresco Remote API * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.web.scripts.dictionary.prefixed; import org.alfresco.repo.web.scripts.dictionary.AbstractPropertyGet; import org.alfresco.service.namespace.QName; import org.springframework.extensions.webscripts.Status; import org.springframework.extensions.webscripts.WebScriptException; import org.springframework.extensions.webscripts.WebScriptRequest; /** * Webscript to get the Propertydefinition for a given classname and propname * * @author Saravanan Sellathurai, Viachaslau Tsikhanovich */ public class PropertyGet extends AbstractPropertyGet { private static final String DICTIONARY_PREFIX = "prefix"; private static final String DICTIONARY_SHORT_CLASS_NAME = "shortClassName"; private static final String DICTIONARY_SHORTPROPERTY_NAME = "propname"; private static final String DICTIONARY_PROPERTY_FREFIX = "proppref"; @Override protected QName getPropertyQname(WebScriptRequest req) { String propertyName = req.getServiceMatch().getTemplateVars().get(DICTIONARY_SHORTPROPERTY_NAME); String propertyPrefix = req.getServiceMatch().getTemplateVars().get(DICTIONARY_PROPERTY_FREFIX); //validate the presence of property name if(propertyName == null) { throw new WebScriptException(Status.STATUS_NOT_FOUND, "Missing parameter short propertyname in the URL"); } //validate the presence of property prefix if(propertyPrefix == null) { throw new WebScriptException(Status.STATUS_NOT_FOUND, "Missing parameter propertyprefix in the URL"); } return QName.createQName(getFullNamespaceURI(propertyPrefix, propertyName)); } @Override protected QName getClassQname(WebScriptRequest req) { String prefix = req.getServiceMatch().getTemplateVars().get(DICTIONARY_PREFIX); String shortClassName = req.getServiceMatch().getTemplateVars().get(DICTIONARY_SHORT_CLASS_NAME); // validate the classname if (isValidClassname(prefix, shortClassName) == false) { throw new WebScriptException(Status.STATUS_NOT_FOUND, "Check the classname - " + prefix + ":" + shortClassName + " - parameter in the URL"); } return QName.createQName(getFullNamespaceURI(prefix, shortClassName)); } }
Alfresco/community-edition
projects/remote-api/source/java/org/alfresco/repo/web/scripts/dictionary/prefixed/PropertyGet.java
Java
lgpl-3.0
3,382
/* s390.h -- Header file for S390 opcode table Copyright (C) 2000-2021 Free Software Foundation, Inc. Contributed by Martin Schwidefsky (schwidefsky@de.ibm.com). This file is part of BFD, the Binary File Descriptor library. 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, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef S390_H #define S390_H /* List of instruction sets variations. */ enum s390_opcode_mode_val { S390_OPCODE_ESA = 0, S390_OPCODE_ZARCH }; enum s390_opcode_cpu_val { S390_OPCODE_G5 = 0, S390_OPCODE_G6, S390_OPCODE_Z900, S390_OPCODE_Z990, S390_OPCODE_Z9_109, S390_OPCODE_Z9_EC, S390_OPCODE_Z10, S390_OPCODE_Z196, S390_OPCODE_ZEC12, S390_OPCODE_Z13, S390_OPCODE_ARCH12, S390_OPCODE_ARCH13, S390_OPCODE_MAXCPU }; /* Instruction specific flags. */ #define S390_INSTR_FLAG_OPTPARM 0x1 #define S390_INSTR_FLAG_OPTPARM2 0x2 #define S390_INSTR_FLAG_HTM 0x4 #define S390_INSTR_FLAG_VX 0x8 #define S390_INSTR_FLAG_FACILITY_MASK 0xc /* The opcode table is an array of struct s390_opcode. */ struct s390_opcode { /* The opcode name. */ const char * name; /* The opcode itself. Those bits which will be filled in with operands are zeroes. */ unsigned char opcode[6]; /* The opcode mask. This is used by the disassembler. This is a mask containing ones indicating those bits which must match the opcode field, and zeroes indicating those bits which need not match (and are presumably filled in by operands). */ unsigned char mask[6]; /* The opcode length in bytes. */ int oplen; /* An array of operand codes. Each code is an index into the operand table. They appear in the order which the operands must appear in assembly code, and are terminated by a zero. */ unsigned char operands[6]; /* Bitmask of execution modes this opcode is available for. */ unsigned int modes; /* First cpu this opcode is available for. */ enum s390_opcode_cpu_val min_cpu; /* Instruction specific flags. */ unsigned int flags; }; /* The table itself is sorted by major opcode number, and is otherwise in the order in which the disassembler should consider instructions. */ extern const struct s390_opcode s390_opcodes[]; extern const int s390_num_opcodes; /* A opcode format table for the .insn pseudo mnemonic. */ extern const struct s390_opcode s390_opformats[]; extern const int s390_num_opformats; /* Values defined for the flags field of a struct s390_opcode. */ /* The operands table is an array of struct s390_operand. */ struct s390_operand { /* The number of bits in the operand. */ int bits; /* How far the operand is left shifted in the instruction. */ int shift; /* One bit syntax flags. */ unsigned long flags; }; /* Elements in the table are retrieved by indexing with values from the operands field of the s390_opcodes table. */ extern const struct s390_operand s390_operands[]; /* Values defined for the flags field of a struct s390_operand. */ /* This operand names a register. The disassembler uses this to print register names with a leading 'r'. */ #define S390_OPERAND_GPR 0x1 /* This operand names a floating point register. The disassembler prints these with a leading 'f'. */ #define S390_OPERAND_FPR 0x2 /* This operand names an access register. The disassembler prints these with a leading 'a'. */ #define S390_OPERAND_AR 0x4 /* This operand names a control register. The disassembler prints these with a leading 'c'. */ #define S390_OPERAND_CR 0x8 /* This operand is a displacement. */ #define S390_OPERAND_DISP 0x10 /* This operand names a base register. */ #define S390_OPERAND_BASE 0x20 /* This operand names an index register, it can be skipped. */ #define S390_OPERAND_INDEX 0x40 /* This operand is a relative branch displacement. The disassembler prints these symbolically if possible. */ #define S390_OPERAND_PCREL 0x80 /* This operand takes signed values. */ #define S390_OPERAND_SIGNED 0x100 /* This operand is a length. */ #define S390_OPERAND_LENGTH 0x200 /* The operand needs to be a valid GP or FP register pair. */ #define S390_OPERAND_REG_PAIR 0x400 /* This operand names a vector register. The disassembler uses this to print register names with a leading 'v'. */ #define S390_OPERAND_VR 0x800 #define S390_OPERAND_CP16 0x1000 #define S390_OPERAND_OR1 0x2000 #define S390_OPERAND_OR2 0x4000 #define S390_OPERAND_OR8 0x8000 #endif /* S390_H */
condret/radare2
libr/asm/arch/include/opcode/s390.h
C
lgpl-3.0
5,255
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.IO; using System.Linq; using System.Reflection; // Tip: If you are looking for more Roslyn samples, // look at https://github.com/dotnet/roslyn/tree/master/src/Samples namespace RoslynDemos.SemanticModel { class Program { static void Main(string[] args) { var greeting = "Hello World!" + 5; // Let's self-inspect this program and find out the type of 'greeting' var sourcePath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", // debug "..", // bin "Program.cs"); // Get the syntax tree from this source file var syntaxTree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourcePath)); // Run the compiler and get the semantic model var semanticModel = CSharpCompilation.Create("selfInspection") .AddSyntaxTrees(syntaxTree) .AddReferences( // Add reference to mscorlib MetadataReference.CreateFromAssembly(typeof(object).Assembly)) .GetSemanticModel(syntaxTree); // Look for variable declarator of 'greeting' var varNode = syntaxTree.GetRoot() .DescendantNodes() .OfType<LocalDeclarationStatementSyntax>() .Select(d => d.Declaration) .First(d => d.ChildNodes() .OfType<VariableDeclaratorSyntax>() .First() .Identifier .ValueText == "greeting") .Type; // Get the semantic information for variable declarator and print its type var semanticInfo = semanticModel.GetTypeInfo(varNode); Console.WriteLine(semanticInfo.Type.Name); // Here is an alternative: Find symbol by name based on cursor position // Find span of body of main method var mainStart = syntaxTree.GetRoot() .DescendantNodes() .OfType<MethodDeclarationSyntax>() .Single(m => m.Identifier.ValueText == "Main") .ChildNodes() .OfType<BlockSyntax>() .Single() .Span .Start; // Look for symbol 'greeting' based on location inside source var symbol = semanticModel .LookupSymbols(mainStart, name: "greeting") .First() as ILocalSymbol; Console.WriteLine(symbol.Type.Name); } } }
cicorias/Samples
RoslynDemos/RoslynDemos.SemanticModel/Program.cs
C#
lgpl-3.0
2,197
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Authorization Library * * Used to check if a user must enter a password before viewing a page. * Has automatic expiration of requests (called in Bw_session) * Handles redirection to /authorize and to desired page. * * Successful auth requests are stored in the users session. * This may be a mitigating factor in the choice of session data in a cookie * * Will eventually look after post data if there happens to be any. * Same functions would treat visiting /admin for the first time, and the * reaction to the eventual expiration, if it happens as a user is typing out a form. * The result should be the post data is kept also. Functions like Admin/Account/PGP * would need to check an as yet undesigned session identifier - if the user has just come from * an auth request. Then, it would check for session data. (this bit of data is a counter. * it will be deleted once it is incremented twice, and forgotten. * * @package BitWasp * @subpackage Libraries * @category Authorization * @author BitWasp */ class Bw_auth { /** * Message Password Timeout * * This sets the default amount of time to hold the message password * in the session before expiring. */ protected $message_password_timeout = 1200; /** * CI */ protected $CI; /** * URI * * Store the Current_user/URI here. */ public $URI; /** * Auth Req's * * Store the current users auth requests here. */ public $auth_reqs; /** * Construct * * Load the codeigniter framework, the current URI, and auth_requests. */ public function __construct() { $this->CI = & get_instance(); $this->URI = explode("/", uri_string()); $this->auth_reqs = (array)json_decode($this->CI->session->userdata('auth_reqs')); } /** * Auth Timeout * * Remove any expired authorization for a page. */ public function auth_timeout() { // Clear auth req data if the user isn't on the authorize page. if ($this->URI[0] !== 'authorize') $this->CI->session->unset_userdata('current_auth_req'); if (count($this->auth_reqs) > 0) { $auth_reqs = $this->auth_reqs; $new = array(); // Purge any expired ones. foreach ($auth_reqs as $key => $req) { if (($req->time + $req->timeout) > time()) { $new[$key] = array('timeout' => $req->timeout, 'time' => $req->time); } } $this->set_data($new); } } /** * New Auth * * Generate a new authorization request. Record the current URI * so we can redirect the user later on, and direct them to the * authorize page. * * @return void */ public function new_auth() { $config = array('current_auth_req' => uri_string()); $this->CI->session->set_userdata($config); redirect('authorize'); } /** * Check Current * * Check if the current URI has already been authorized by the user. * * @return bool */ public function check_current() { foreach ($this->auth_reqs as $key => $req) { if ($key == $this->URI[0]) return TRUE; } return FALSE; } /** * Has Request * * Check if the user has made an attempt to authorize a request. * @return bool */ public function has_request() { return (is_string($this->CI->session->userdata('current_auth_req'))) ? TRUE : FALSE; } /** * Set Data * * A general function to store the authorization requests in the session. * * @param array $array * @return void */ public function set_data(array $auth_reqs = array()) { $this->CI->session->set_userdata('auth_reqs', json_encode($auth_reqs)); } /** * Setup Authorization * * This function records the new authorized request for the URI, along * with the current time, and the timeout for this request. * * @param string $URI * @param int $timeout * @return void */ public function setup_auth($URI, $timeout) { if ($timeout > 0) { $new_auth = $this->auth_reqs; $new_auth[$URI[0]] = array('timeout' => $timeout, 'time' => time()); $this->set_data($new_auth); } } /** * Successful Auth * * Record the successful authorization request, how long until it expires, * and then provide the requested URI so the user can be redirected. * * @return string */ public function successful_auth() { // $this->CI->load->model('auth_model'); $attempted_uri = $this->CI->current_user->current_auth_req; $URI = explode('/', $attempted_uri); // Lookup timeout. $timeout = $this->CI->auth_model->check_auth_timeout($URI[0]); $this->CI->session->unset_userdata('current_auth_req'); $this->setup_auth($URI, $timeout); return $attempted_uri; } /** * Message Password Timeout * * This function will check if the message password is expired, and * should be forgotten. * * @return void */ public function message_password_timeout() { $grant_time = $this->CI->session->userdata('message_password_granted'); if ($grant_time !== NULL && $grant_time < (time() - $this->message_password_timeout)) { $this->CI->session->unset_userdata('message_password'); $this->CI->session->unset_userdata('message_password_granted'); } } /** * Generate Two Factor Token * * This function will generate and store a new two-factor token. * If the challenge is successfully generated, then the challenge is * returned. On failure, the function returns FALSE. * * @return string / FALSE */ public function generate_two_factor_token() { $this->CI->load->model('accounts_model'); // Load the users PGP key. $key = $this->CI->accounts_model->get_pgp_key($this->CI->current_user->user_id); if ($key == FALSE) // Abort if it's not set. return FALSE; // Generate a solution. $solution = $this->CI->general->generate_salt(); // Encrypt the challenge. $challenge = $this->CI->gpg->encrypt($key['fingerprint'], "Login Token: $solution\n"); if ($challenge == FALSE) // Abort if unsuccessful. return FALSE; // If we successfully stored the solution, return the challenge. return ($this->CI->auth_model->add_two_factor_token($solution) == TRUE) ? $challenge : FALSE; } } ; /* End of file Bw_auth.php */
geopayme/btcMarketPlace
application/libraries/Bw_auth.php
PHP
unlicense
7,088
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is built by mktables from e.g. UnicodeData.txt. # Any changes made here will be lost! # # This file supports: # \p{InGlagolitic} (and fuzzy permutations) # # Meaning: Block 'Glagolitic' # return <<'END'; 2C00 2C5F Glagolitic END
caplin/qa-browsers
git/lib/perl5/5.8.8/unicore/lib/gc_sc/InGlagol.pl
Perl
unlicense
302
// +build linux darwin /* Copyright 2013 The Perkeep 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 fs import ( "context" "errors" "os" "path/filepath" "strings" "sync" "time" "bazil.org/fuse" "bazil.org/fuse/fs" "go4.org/types" "perkeep.org/pkg/blob" "perkeep.org/pkg/schema" "perkeep.org/pkg/search" ) // roDir is a read-only directory. // Its permanode is the permanode with camliPath:entname attributes. type roDir struct { fs *CamliFileSystem permanode blob.Ref parent *roDir // or nil, if the root within its roots.go root. name string // ent name (base name within parent) at time.Time mu sync.Mutex children map[string]roFileOrDir xattrs map[string][]byte } var _ fs.Node = (*roDir)(nil) var _ fs.HandleReadDirAller = (*roDir)(nil) var _ fs.NodeGetxattrer = (*roDir)(nil) var _ fs.NodeListxattrer = (*roDir)(nil) func newRODir(fs *CamliFileSystem, permanode blob.Ref, name string, at time.Time) *roDir { return &roDir{ fs: fs, permanode: permanode, name: name, at: at, } } // for debugging func (n *roDir) fullPath() string { if n == nil { return "" } return filepath.Join(n.parent.fullPath(), n.name) } func (n *roDir) Attr(ctx context.Context, a *fuse.Attr) error { *a = fuse.Attr{ Inode: n.permanode.Sum64(), Mode: os.ModeDir | 0500, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } return nil } // populate hits the blobstore to populate map of child nodes. func (n *roDir) populate() error { n.mu.Lock() defer n.mu.Unlock() ctx := context.TODO() // Things never change here, so if we've ever populated, we're // populated. if n.children != nil { return nil } Logger.Printf("roDir.populate(%q) - Sending request At %v", n.fullPath(), n.at) res, err := n.fs.client.Describe(ctx, &search.DescribeRequest{ BlobRef: n.permanode, Depth: 3, At: types.Time3339(n.at), }) if err != nil { Logger.Println("roDir.paths:", err) return nil } db := res.Meta[n.permanode.String()] if db == nil { return errors.New("dir blobref not described") } // Find all child permanodes and stick them in n.children n.children = make(map[string]roFileOrDir) for k, v := range db.Permanode.Attr { const p = "camliPath:" if !strings.HasPrefix(k, p) || len(v) < 1 { continue } name := k[len(p):] childRef := v[0] child := res.Meta[childRef] if child == nil { Logger.Printf("child not described: %v", childRef) continue } if target := child.Permanode.Attr.Get("camliSymlinkTarget"); target != "" { // This is a symlink. n.children[name] = &roFile{ fs: n.fs, permanode: blob.ParseOrZero(childRef), parent: n, name: name, symLink: true, target: target, } } else if isDir(child.Permanode) { // This is a directory. n.children[name] = &roDir{ fs: n.fs, permanode: blob.ParseOrZero(childRef), parent: n, name: name, at: n.at, } } else if contentRef := child.Permanode.Attr.Get("camliContent"); contentRef != "" { // This is a file. content := res.Meta[contentRef] if content == nil { Logger.Printf("child content not described: %v", childRef) continue } if content.CamliType != "file" { Logger.Printf("child not a file: %v", childRef) continue } n.children[name] = &roFile{ fs: n.fs, permanode: blob.ParseOrZero(childRef), parent: n, name: name, content: blob.ParseOrZero(contentRef), size: content.File.Size, } } else { // unknown type continue } n.children[name].xattr().load(child.Permanode) } return nil } func (n *roDir) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { if err := n.populate(); err != nil { Logger.Println("populate:", err) return nil, fuse.EIO } n.mu.Lock() defer n.mu.Unlock() var ents []fuse.Dirent for name, childNode := range n.children { var ino uint64 switch v := childNode.(type) { case *roDir: ino = v.permanode.Sum64() case *roFile: ino = v.permanode.Sum64() default: Logger.Printf("roDir.ReadDirAll: unknown child type %T", childNode) } // TODO: figure out what Dirent.Type means. // fuse.go says "Type uint32 // ?" dirent := fuse.Dirent{ Name: name, Inode: ino, } Logger.Printf("roDir(%q) appending inode %x, %+v", n.fullPath(), dirent.Inode, dirent) ents = append(ents, dirent) } return ents, nil } var _ fs.NodeStringLookuper = (*roDir)(nil) func (n *roDir) Lookup(ctx context.Context, name string) (ret fs.Node, err error) { defer func() { Logger.Printf("roDir(%q).Lookup(%q) = %#v, %v", n.fullPath(), name, ret, err) }() if err := n.populate(); err != nil { Logger.Println("populate:", err) return nil, fuse.EIO } n.mu.Lock() defer n.mu.Unlock() if n2 := n.children[name]; n2 != nil { return n2, nil } return nil, fuse.ENOENT } // roFile is a read-only file, or symlink. type roFile struct { fs *CamliFileSystem permanode blob.Ref parent *roDir name string // ent name (base name within parent) mu sync.Mutex // protects all following fields symLink bool // if true, is a symlink target string // if a symlink content blob.Ref // if a regular file size int64 mtime, atime time.Time // if zero, use serverStart xattrs map[string][]byte } var _ fs.Node = (*roFile)(nil) var _ fs.NodeGetxattrer = (*roFile)(nil) var _ fs.NodeListxattrer = (*roFile)(nil) var _ fs.NodeSetxattrer = (*roFile)(nil) var _ fs.NodeRemovexattrer = (*roFile)(nil) var _ fs.NodeOpener = (*roFile)(nil) var _ fs.NodeFsyncer = (*roFile)(nil) var _ fs.NodeReadlinker = (*roFile)(nil) func (n *roDir) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, res *fuse.GetxattrResponse) error { return n.xattr().get(req, res) } func (n *roDir) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, res *fuse.ListxattrResponse) error { return n.xattr().list(req, res) } func (n *roFile) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, res *fuse.GetxattrResponse) error { return n.xattr().get(req, res) } func (n *roFile) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, res *fuse.ListxattrResponse) error { return n.xattr().list(req, res) } func (n *roFile) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error { return fuse.EPERM } func (n *roFile) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error { return fuse.EPERM } // for debugging func (n *roFile) fullPath() string { if n == nil { return "" } return filepath.Join(n.parent.fullPath(), n.name) } func (n *roFile) Attr(ctx context.Context, a *fuse.Attr) error { // TODO: don't grab n.mu three+ times in here. var mode os.FileMode = 0400 // read-only n.mu.Lock() size := n.size var blocks uint64 if size > 0 { blocks = uint64(size)/512 + 1 } inode := n.permanode.Sum64() if n.symLink { mode |= os.ModeSymlink } n.mu.Unlock() *a = fuse.Attr{ Inode: inode, Mode: mode, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), Size: uint64(size), Blocks: blocks, Mtime: n.modTime(), Atime: n.accessTime(), Ctime: serverStart, Crtime: serverStart, } return nil } func (n *roFile) accessTime() time.Time { n.mu.Lock() if !n.atime.IsZero() { defer n.mu.Unlock() return n.atime } n.mu.Unlock() return n.modTime() } func (n *roFile) modTime() time.Time { n.mu.Lock() defer n.mu.Unlock() if !n.mtime.IsZero() { return n.mtime } return serverStart } // Empirically: // open for read: req.Flags == 0 // open for append: req.Flags == 1 // open for write: req.Flags == 1 // open for read/write (+<) == 2 (bitmask? of?) // // open flags are O_WRONLY (1), O_RDONLY (0), or O_RDWR (2). and also // bitmaks of O_SYMLINK (0x200000) maybe. (from // fuse_filehandle_xlate_to_oflags in macosx/kext/fuse_file.h) func (n *roFile) Open(ctx context.Context, req *fuse.OpenRequest, res *fuse.OpenResponse) (fs.Handle, error) { roFileOpen.Incr() if isWriteFlags(req.Flags) { return nil, fuse.EPERM } Logger.Printf("roFile.Open: %v: content: %v dir=%v flags=%v", n.permanode, n.content, req.Dir, req.Flags) r, err := schema.NewFileReader(ctx, n.fs.fetcher, n.content) if err != nil { roFileOpenError.Incr() Logger.Printf("roFile.Open: %v", err) return nil, fuse.EIO } // Turn off the OpenDirectIO bit (on by default in rsc fuse server.go), // else append operations don't work for some reason. res.Flags &= ^fuse.OpenDirectIO // Read-only. nod := &node{ fs: n.fs, blobref: n.content, } return &nodeReader{n: nod, fr: r}, nil } func (n *roFile) Fsync(ctx context.Context, r *fuse.FsyncRequest) error { // noop return nil } func (n *roFile) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) { Logger.Printf("roFile.Readlink(%q)", n.fullPath()) n.mu.Lock() defer n.mu.Unlock() if !n.symLink { Logger.Printf("roFile.Readlink on node that's not a symlink?") return "", fuse.EIO } return n.target, nil } // roFileOrDir is a *roFile or *roDir type roFileOrDir interface { fs.Node permanodeString() string xattr() *xattr } func (n *roFile) permanodeString() string { return n.permanode.String() } func (n *roDir) permanodeString() string { return n.permanode.String() } func (n *roFile) xattr() *xattr { return &xattr{"roFile", n.fs, n.permanode, &n.mu, &n.xattrs} } func (n *roDir) xattr() *xattr { return &xattr{"roDir", n.fs, n.permanode, &n.mu, &n.xattrs} }
angelcabo/camlistore
pkg/fs/ro.go
GO
apache-2.0
10,046
#!/bin/bash if [ ${CIRCLE_BRANCH} = "preview" ] then echo "server: https://forms.preview.developer.concur.com" > src/_data/forms.yml elif [ ${CIRCLE_BRANCH} = "livesite" ] then echo "server: https://forms.developer.concur.com" > src/_data/forms.yml else echo "Branch ${CIRCLE_BRANCH} does not have a known forms server" fi cat src/_data/forms.yml
bhague1281/developer.concur.com
build/write_forms.sh
Shell
apache-2.0
357
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 com.facebook.buck.features.go; import com.facebook.buck.core.build.buildable.context.BuildableContext; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.impl.BuildTargetPaths; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rules.BuildRuleParams; import com.facebook.buck.core.rules.impl.AbstractBuildRuleWithDeclaredAndExtraDeps; import com.facebook.buck.core.rules.impl.SymlinkTree; import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter; import com.facebook.buck.core.toolchain.tool.Tool; import com.facebook.buck.features.go.GoListStep.ListType; import com.facebook.buck.io.BuildCellRelativePath; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.step.Step; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.facebook.buck.step.fs.MkdirStep; import com.facebook.buck.step.fs.SymlinkFileStep; import com.facebook.buck.step.fs.TouchStep; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; public class GoCompile extends AbstractBuildRuleWithDeclaredAndExtraDeps { @AddToRuleKey private final Tool compiler; @AddToRuleKey private final Tool assembler; @AddToRuleKey private final Tool packer; @AddToRuleKey(stringify = true) private final Path packageName; @AddToRuleKey private final ImmutableSet<SourcePath> srcs; @AddToRuleKey private final ImmutableSet<SourcePath> generatedSrcs; @AddToRuleKey private final ImmutableList<String> compilerFlags; @AddToRuleKey private final ImmutableList<String> assemblerFlags; @AddToRuleKey private final ImmutableList<SourcePath> extraAsmOutputs; @AddToRuleKey private final GoPlatform platform; @AddToRuleKey private final boolean gensymabis; // TODO(mikekap): Make these part of the rule key. private final ImmutableList<Path> assemblerIncludeDirs; private final ImmutableMap<Path, Path> importPathMap; private final SymlinkTree symlinkTree; private final Path output; private final List<ListType> goListTypes; public GoCompile( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, SymlinkTree symlinkTree, Path packageName, ImmutableMap<Path, Path> importPathMap, ImmutableSet<SourcePath> srcs, ImmutableSet<SourcePath> generatedSrcs, ImmutableList<String> compilerFlags, ImmutableList<String> assemblerFlags, GoPlatform platform, boolean gensymabis, ImmutableList<SourcePath> extraAsmOutputs, List<ListType> goListTypes) { super(buildTarget, projectFilesystem, params); this.importPathMap = importPathMap; this.srcs = srcs; this.generatedSrcs = generatedSrcs; this.symlinkTree = symlinkTree; this.packageName = packageName; this.compilerFlags = compilerFlags; this.compiler = platform.getCompiler(); this.assemblerFlags = assemblerFlags; this.assemblerIncludeDirs = platform.getAssemblerIncludeDirs(); this.assembler = platform.getAssembler(); this.packer = platform.getPacker(); this.platform = platform; this.gensymabis = gensymabis; this.output = BuildTargetPaths.getGenPath( getProjectFilesystem(), getBuildTarget(), "%s/" + getBuildTarget().getShortName() + ".a"); this.extraAsmOutputs = extraAsmOutputs; this.goListTypes = goListTypes; } @Override public ImmutableList<Step> getBuildSteps( BuildContext context, BuildableContext buildableContext) { buildableContext.recordArtifact(output); List<Path> srcFiles = getSourceFiles(srcs, context); ImmutableMap<String, ImmutableList<Path>> groupedSrcs = getGroupedSrcs(srcFiles); ImmutableList.Builder<Step> steps = ImmutableList.builder(); Optional<Path> asmHeaderPath = Optional.empty(); boolean allowExternalReferences = !getAsmSources(groupedSrcs).isEmpty() || !extraAsmOutputs.isEmpty(); FilteredSourceFiles filteredAsmSrcs = new FilteredSourceFiles( getAsmSources(groupedSrcs), platform, Collections.singletonList(ListType.SFiles)); steps.addAll(filteredAsmSrcs.getFilterSteps()); steps.add( MkdirStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), getProjectFilesystem(), output.getParent()))); Path asmOutputDir = BuildTargetPaths.getScratchPath( getProjectFilesystem(), getBuildTarget(), "%s/" + getBuildTarget().getShortName() + "__asm_compile"); Path asmIncludeDir = BuildTargetPaths.getScratchPath( getProjectFilesystem(), getBuildTarget(), "%s/" + getBuildTarget().getShortName() + "__asm_includes"); steps.addAll( MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), getProjectFilesystem(), asmOutputDir))); steps.addAll( MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), getProjectFilesystem(), asmIncludeDir))); if (!getAsmSources(groupedSrcs).isEmpty()) { asmHeaderPath = Optional.of( BuildTargetPaths.getScratchPath( getProjectFilesystem(), getBuildTarget(), "%s/" + getBuildTarget().getShortName() + "__asm_hdr") .resolve("go_asm.h")); steps.add( MkdirStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), getProjectFilesystem(), asmHeaderPath.get().getParent()))); } SourcePathResolverAdapter resolver = context.getSourcePathResolver(); if (getGoSources(groupedSrcs).isEmpty()) { steps.add(new TouchStep(getProjectFilesystem(), output)); } else { Optional<Path> asmSymabisPath = Optional.empty(); if (gensymabis && !getAsmSources(groupedSrcs).isEmpty()) { asmSymabisPath = Optional.of(asmOutputDir.resolve("symabis")); steps.add(new TouchStep(getProjectFilesystem(), asmHeaderPath.get())); steps.add( new GoAssembleStep( getProjectFilesystem().getRootPath(), assembler.getEnvironment(resolver), assembler.getCommandPrefix(resolver), ImmutableList.<String>builder().addAll(assemblerFlags).add("-gensymabis").build(), filteredAsmSrcs, ImmutableList.<Path>builder() .addAll(assemblerIncludeDirs) .add(asmHeaderPath.get().getParent()) .add(asmIncludeDir) .build(), platform, asmSymabisPath.get())); } FilteredSourceFiles filteredCompileSrcs = new FilteredSourceFiles( getGoSources(groupedSrcs), getSourceFiles(generatedSrcs, context), platform, goListTypes); steps.addAll(filteredCompileSrcs.getFilterSteps()); steps.add( new GoCompileStep( getProjectFilesystem().getRootPath().getPath(), compiler.getEnvironment(resolver), compiler.getCommandPrefix(resolver), compilerFlags, packageName, filteredCompileSrcs, filteredAsmSrcs, importPathMap, ImmutableList.of(symlinkTree.getRoot()), asmHeaderPath, allowExternalReferences, platform, asmSymabisPath, output)); } ImmutableList.Builder<Path> asmOutputs = ImmutableList.builder(); if (!getAsmSources(groupedSrcs).isEmpty()) { Path asmOutputPath = asmOutputDir.resolve(getBuildTarget().getShortName() + ".o"); if (!getHeaderSources(groupedSrcs).isEmpty()) { // TODO(mikekap): Allow header-map style input. for (Path header : Stream.of(getHeaderSources(groupedSrcs), getAsmSources(groupedSrcs)) .flatMap(ImmutableList::stream) .collect(ImmutableList.toImmutableList())) { steps.add( SymlinkFileStep.of( getProjectFilesystem(), header, asmIncludeDir.resolve(header.getFileName()))); } } steps.add( new GoAssembleStep( getProjectFilesystem().getRootPath(), assembler.getEnvironment(resolver), assembler.getCommandPrefix(resolver), assemblerFlags, filteredAsmSrcs, ImmutableList.<Path>builder() .addAll(assemblerIncludeDirs) .add(asmHeaderPath.get().getParent()) .add(asmIncludeDir) .build(), platform, asmOutputPath)); asmOutputs.add(asmOutputPath); } if (!getAsmSources(groupedSrcs).isEmpty() || !extraAsmOutputs.isEmpty()) { steps.add( new GoPackStep( getProjectFilesystem().getRootPath().getPath(), packer.getEnvironment(resolver), packer.getCommandPrefix(resolver), GoPackStep.Operation.APPEND, asmOutputs .addAll(extraAsmOutputs.stream().map(x -> resolver.getAbsolutePath(x)).iterator()) .build(), filteredAsmSrcs, output)); } return steps.build(); } static List<Path> getSourceFiles(ImmutableSet<SourcePath> srcPaths, BuildContext context) { List<Path> srcFiles = new ArrayList<>(); for (SourcePath path : srcPaths) { Path srcPath = context.getSourcePathResolver().getAbsolutePath(path); if (Files.isDirectory(srcPath)) { try (Stream<Path> sourcePaths = Files.list(srcPath)) { srcFiles.addAll(sourcePaths.filter(Files::isRegularFile).collect(Collectors.toList())); } catch (IOException e) { throw new RuntimeException("An error occur when listing the files under " + srcPath, e); } } else { srcFiles.add(srcPath); } } return srcFiles; } @Nullable private ImmutableList<Path> getAsmSources(ImmutableMap<String, ImmutableList<Path>> groupedSrcs) { return groupedSrcs.get("s"); } @Nullable private ImmutableList<Path> getGoSources(ImmutableMap<String, ImmutableList<Path>> groupedSrcs) { return groupedSrcs.get("go"); } @Nullable private ImmutableList<Path> getHeaderSources( ImmutableMap<String, ImmutableList<Path>> groupedSrcs) { return groupedSrcs.get("h"); } private ImmutableMap<String, ImmutableList<Path>> getGroupedSrcs(List<Path> srcFiles) { ImmutableList.Builder<Path> compileSrcListBuilder = ImmutableList.builder(); ImmutableList.Builder<Path> headerSrcListBuilder = ImmutableList.builder(); ImmutableList.Builder<Path> asmSrcListBuilder = ImmutableList.builder(); for (Path sourceFile : srcFiles) { String extension = MorePaths.getFileExtension(sourceFile).toLowerCase(); if (extension.equals("s")) { asmSrcListBuilder.add(sourceFile); } else if (extension.equals("go")) { compileSrcListBuilder.add(sourceFile); } else { headerSrcListBuilder.add(sourceFile); } } return ImmutableMap.of( "s", asmSrcListBuilder.build(), "go", compileSrcListBuilder.build(), "h", headerSrcListBuilder.build()); } @Override public SourcePath getSourcePathToOutput() { return ExplicitBuildTargetSourcePath.of(getBuildTarget(), output); } }
facebook/buck
src/com/facebook/buck/features/go/GoCompile.java
Java
apache-2.0
12,963
/* * Copyright (c) 2005-2011 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.customers.personnel.business.service; import java.util.ArrayList; import java.util.Date; import org.joda.time.LocalDateTime; import org.mifos.accounts.util.helpers.AccountExceptionConstants; import org.mifos.config.PasswordRules; import org.mifos.core.MifosRuntimeException; import org.mifos.customers.personnel.business.PersonnelBO; import org.mifos.customers.personnel.business.PersonnelUsedPasswordEntity; import org.mifos.customers.personnel.persistence.PersonnelDao; import org.mifos.framework.hibernate.helper.HibernateTransactionHelper; import org.mifos.framework.hibernate.helper.HibernateTransactionHelperForStaticHibernateUtil; import org.mifos.security.authentication.EncryptionService; import org.mifos.security.util.UserContext; import org.mifos.service.BusinessRuleException; import org.springframework.beans.factory.annotation.Autowired; public class PersonnelServiceImpl implements PersonnelService { private final PersonnelDao personnelDao; private final HibernateTransactionHelper hibernateTransactionHelper = new HibernateTransactionHelperForStaticHibernateUtil(); @Autowired public PersonnelServiceImpl(PersonnelDao personnelDao) { this.personnelDao = personnelDao; } @Override public void changePassword(PersonnelBO user, String newPassword, boolean setPasswordChanged) { UserContext userContext = new UserContext(); userContext.setId(user.getPersonnelId()); userContext.setName(user.getUserName()); user.updateDetails(userContext); validateIfPasswordIsRecentlyUsed(user, newPassword); byte[] newEncPass = EncryptionService.getInstance().createEncryptedPassword(newPassword); PersonnelUsedPasswordEntity personnelUsedPassword; int passwordHistoryCount = PasswordRules.getPasswordHistoryCount(); if (user.getPersonnelUsedPasswords().size() >= passwordHistoryCount) { personnelUsedPassword = new ArrayList<PersonnelUsedPasswordEntity>(user.getPersonnelUsedPasswords()).get(0); personnelUsedPassword.setUsedPassword(newEncPass); personnelUsedPassword.setDateChanged(new LocalDateTime().toDateTime().toDate()); } else { personnelUsedPassword = new PersonnelUsedPasswordEntity(); personnelUsedPassword.setPersonnel(user); personnelUsedPassword.setUsedPassword(newEncPass); personnelUsedPassword.setDateChanged(new LocalDateTime().toDateTime().toDate()); user.getPersonnelUsedPasswords().add(personnelUsedPassword); } try { hibernateTransactionHelper.startTransaction(); hibernateTransactionHelper.beginAuditLoggingFor(user); user.changePasswordTo(newPassword, user.getPersonnelId(), setPasswordChanged); this.personnelDao.save(user); hibernateTransactionHelper.commitTransaction(); } catch (Exception e) { hibernateTransactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { hibernateTransactionHelper.closeSession(); } } private void validateIfPasswordIsRecentlyUsed(PersonnelBO user, String newPassword) { for (PersonnelUsedPasswordEntity usedPass: user.getPersonnelUsedPasswords()) { if (EncryptionService.getInstance().verifyPassword(newPassword, usedPass.getUsedPassword())) { throw new BusinessRuleException(AccountExceptionConstants.PASSWORD_USED_EXCEPTION); } } } @Override public void changePasswordExpirationDate(PersonnelBO user, Date passwordExpirationDate) { UserContext userContext = new UserContext(); userContext.setId(user.getPersonnelId()); userContext.setName(user.getUserName()); user.updateDetails(userContext); try { hibernateTransactionHelper.startTransaction(); hibernateTransactionHelper.beginAuditLoggingFor(user); user.setPasswordExpirationDate(passwordExpirationDate); this.personnelDao.save(user); hibernateTransactionHelper.commitTransaction(); } catch (Exception e) { hibernateTransactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { hibernateTransactionHelper.closeSession(); } } }
madhav123/gkmaster
appdomain/src/main/java/org/mifos/customers/personnel/business/service/PersonnelServiceImpl.java
Java
apache-2.0
5,048
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.ml; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksAction; import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.persistent.PersistentTasksCustomMetadata; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.tasks.TaskInfo; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.action.util.QueryPage; import org.elasticsearch.xpack.core.ml.MlMetadata; import org.elasticsearch.xpack.core.ml.action.DeleteExpiredDataAction; import org.elasticsearch.xpack.core.ml.action.DeleteJobAction; import org.elasticsearch.xpack.core.ml.action.GetJobsAction; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.junit.After; import org.junit.Before; import org.mockito.stubbing.Answer; import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.elasticsearch.mock.orig.Mockito.verify; import static org.mockito.Matchers.any; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class MlDailyMaintenanceServiceTests extends ESTestCase { private ThreadPool threadPool; private Client client; private ClusterService clusterService; private MlAssignmentNotifier mlAssignmentNotifier; @Before public void setUpTests() { threadPool = new TestThreadPool("MlDailyMaintenanceServiceTests"); client = mock(Client.class); when(client.threadPool()).thenReturn(threadPool); clusterService = mock(ClusterService.class); mlAssignmentNotifier = mock(MlAssignmentNotifier.class); } @After public void stop() { terminate(threadPool); } public void testScheduledTriggering() throws InterruptedException { when(clusterService.state()).thenReturn(createClusterState(false)); doAnswer(withResponse(new DeleteExpiredDataAction.Response(true))) .when(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); doAnswer(withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.emptyList(), 0, new ParseField(""))))) .when(client).execute(same(GetJobsAction.INSTANCE), any(), any()); int triggerCount = randomIntBetween(2, 4); CountDownLatch latch = new CountDownLatch(triggerCount); try (MlDailyMaintenanceService service = createService(latch, client)) { service.start(); latch.await(5, TimeUnit.SECONDS); } verify(client, times(triggerCount - 1)).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); verify(client, times(triggerCount - 1)).execute(same(GetJobsAction.INSTANCE), any(), any()); verify(mlAssignmentNotifier, times(triggerCount - 1)).auditUnassignedMlTasks(any(), any()); } public void testScheduledTriggeringWhileUpgradeModeIsEnabled() throws InterruptedException { when(clusterService.state()).thenReturn(createClusterState(true)); int triggerCount = randomIntBetween(2, 4); CountDownLatch latch = new CountDownLatch(triggerCount); try (MlDailyMaintenanceService service = createService(latch, client)) { service.start(); latch.await(5, TimeUnit.SECONDS); } verify(clusterService, times(triggerCount - 1)).state(); verifyNoMoreInteractions(client, clusterService, mlAssignmentNotifier); } public void testBothTasksAreTriggered_BothTasksSucceed() throws InterruptedException { assertThatBothTasksAreTriggered( withResponse(new DeleteExpiredDataAction.Response(true)), withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.emptyList(), 0, new ParseField(""))))); } public void testBothTasksAreTriggered_DeleteExpiredDataTaskFails() throws InterruptedException { assertThatBothTasksAreTriggered( withResponse(new DeleteExpiredDataAction.Response(false)), withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.emptyList(), 0, new ParseField(""))))); } public void testBothTasksAreTriggered_DeleteExpiredDataTaskFailsWithException() throws InterruptedException { assertThatBothTasksAreTriggered( withException(new ElasticsearchException("exception thrown by DeleteExpiredDataAction")), withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.emptyList(), 0, new ParseField(""))))); } public void testBothTasksAreTriggered_DeleteJobsTaskFails() throws InterruptedException { assertThatBothTasksAreTriggered( withResponse(new DeleteExpiredDataAction.Response(true)), withException(new ElasticsearchException("exception thrown by GetJobsAction"))); } public void testBothTasksAreTriggered_BothTasksFail() throws InterruptedException { assertThatBothTasksAreTriggered( withException(new ElasticsearchException("exception thrown by DeleteExpiredDataAction")), withException(new ElasticsearchException("exception thrown by GetJobsAction"))); } private void assertThatBothTasksAreTriggered(Answer<?> deleteExpiredDataAnswer, Answer<?> getJobsAnswer) throws InterruptedException { when(clusterService.state()).thenReturn(createClusterState(false)); doAnswer(deleteExpiredDataAnswer).when(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); doAnswer(getJobsAnswer).when(client).execute(same(GetJobsAction.INSTANCE), any(), any()); CountDownLatch latch = new CountDownLatch(2); try (MlDailyMaintenanceService service = createService(latch, client)) { service.start(); latch.await(5, TimeUnit.SECONDS); } verify(client, times(2)).threadPool(); verify(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); verify(client).execute(same(GetJobsAction.INSTANCE), any(), any()); verify(mlAssignmentNotifier).auditUnassignedMlTasks(any(), any()); verifyNoMoreInteractions(client, mlAssignmentNotifier); } public void testJobInDeletingStateAlreadyHasDeletionTask() throws InterruptedException { String jobId = "job-in-state-deleting"; TaskInfo taskInfo = new TaskInfo( new TaskId("test", 123), "test", DeleteJobAction.NAME, "delete-job-" + jobId, null, 0, 0, true, false, new TaskId("test", 456), Collections.emptyMap()); when(clusterService.state()).thenReturn(createClusterState(false)); doAnswer(withResponse(new DeleteExpiredDataAction.Response(true))) .when(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); Job job = mock(Job.class); when(job.getId()).thenReturn(jobId); when(job.isDeleting()).thenReturn(true); doAnswer(withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.singletonList(job), 1, new ParseField(""))))) .when(client).execute(same(GetJobsAction.INSTANCE), any(), any()); doAnswer(withResponse(new ListTasksResponse(Collections.singletonList(taskInfo), Collections.emptyList(), Collections.emptyList()))) .when(client).execute(same(ListTasksAction.INSTANCE), any(), any()); CountDownLatch latch = new CountDownLatch(2); try (MlDailyMaintenanceService service = createService(latch, client)) { service.start(); latch.await(5, TimeUnit.SECONDS); } verify(client, times(3)).threadPool(); verify(client).execute(same(GetJobsAction.INSTANCE), any(), any()); verify(client).execute(same(ListTasksAction.INSTANCE), any(), any()); verify(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); verify(mlAssignmentNotifier).auditUnassignedMlTasks(any(), any()); verifyNoMoreInteractions(client, mlAssignmentNotifier); } public void testJobGetsDeleted() throws InterruptedException { testJobInDeletingStateDoesNotHaveDeletionTask(true); } public void testJobDoesNotGetDeleted() throws InterruptedException { testJobInDeletingStateDoesNotHaveDeletionTask(false); } private void testJobInDeletingStateDoesNotHaveDeletionTask(boolean deleted) throws InterruptedException { String jobId = "job-in-state-deleting"; when(clusterService.state()).thenReturn(createClusterState(false)); doAnswer(withResponse(new DeleteExpiredDataAction.Response(true))) .when(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); Job job = mock(Job.class); when(job.getId()).thenReturn(jobId); when(job.isDeleting()).thenReturn(true); doAnswer(withResponse(new GetJobsAction.Response(new QueryPage<>(Collections.singletonList(job), 1, new ParseField(""))))) .when(client).execute(same(GetJobsAction.INSTANCE), any(), any()); doAnswer(withResponse(new ListTasksResponse(Collections.emptyList(), Collections.emptyList(), Collections.emptyList()))) .when(client).execute(same(ListTasksAction.INSTANCE), any(), any()); doAnswer(withResponse(AcknowledgedResponse.of(deleted))) .when(client).execute(same(DeleteJobAction.INSTANCE), any(), any()); CountDownLatch latch = new CountDownLatch(2); try (MlDailyMaintenanceService service = createService(latch, client)) { service.start(); latch.await(5, TimeUnit.SECONDS); } verify(client, times(4)).threadPool(); verify(client).execute(same(GetJobsAction.INSTANCE), any(), any()); verify(client).execute(same(ListTasksAction.INSTANCE), any(), any()); verify(client).execute(same(DeleteJobAction.INSTANCE), any(), any()); verify(client).execute(same(DeleteExpiredDataAction.INSTANCE), any(), any()); verify(mlAssignmentNotifier).auditUnassignedMlTasks(any(), any()); verifyNoMoreInteractions(client, mlAssignmentNotifier); } private MlDailyMaintenanceService createService(CountDownLatch latch, Client client) { return new MlDailyMaintenanceService(Settings.EMPTY, threadPool, client, clusterService, mlAssignmentNotifier, () -> { // We need to be careful that an unexpected iteration doesn't get squeezed in by the maintenance threadpool in // between the latch getting counted down to zero and the main test thread stopping the maintenance service. // This could happen if the main test thread happens to be waiting for a CPU for the whole 100ms after the // latch counts down to zero. if (latch.getCount() > 0) { latch.countDown(); return TimeValue.timeValueMillis(100); } else { return TimeValue.timeValueHours(1); } }); } private static ClusterState createClusterState(boolean isUpgradeMode) { return ClusterState.builder(new ClusterName("MlDailyMaintenanceServiceTests")) .metadata(Metadata.builder() .putCustom(PersistentTasksCustomMetadata.TYPE, PersistentTasksCustomMetadata.builder().build()) .putCustom(MlMetadata.TYPE, new MlMetadata.Builder().isUpgradeMode(isUpgradeMode).build())) .nodes(DiscoveryNodes.builder().build()) .build(); } @SuppressWarnings("unchecked") private static <Response> Answer<Response> withResponse(Response response) { return invocationOnMock -> { ActionListener<Response> listener = (ActionListener<Response>) invocationOnMock.getArguments()[2]; listener.onResponse(response); return null; }; } @SuppressWarnings("unchecked") private static <Response> Answer<Response> withException(Exception e) { return invocationOnMock -> { ActionListener<Response> listener = (ActionListener<Response>) invocationOnMock.getArguments()[2]; listener.onFailure(e); return null; }; } }
robin13/elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlDailyMaintenanceServiceTests.java
Java
apache-2.0
13,511
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.api.model.dmn; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.kie.dmn.api.core.DMNContext; import org.kie.dmn.api.core.DMNDecisionResult.DecisionEvaluationStatus; import org.kie.dmn.core.impl.DMNContextImpl; import org.kie.dmn.core.impl.DMNDecisionResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.server.api.marshalling.Marshaller; import org.kie.server.api.marshalling.MarshallerFactory; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.api.model.KieServiceResponse.ResponseType; import org.kie.server.api.model.ServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JSONAPIRoundTripTest { private static final Logger LOG = LoggerFactory.getLogger(JSONAPIRoundTripTest.class); private Marshaller marshaller; @Before public void init() { Set<Class<?>> extraClasses = new HashSet<Class<?>>(); extraClasses.add(Applicant.class); marshaller = MarshallerFactory.getMarshaller(extraClasses, MarshallingFormat.JSON, this.getClass().getClassLoader()); } @Test public void test() { Applicant applicant = new Applicant("John Doe", 47); Applicant applicant2 = roundTrip(applicant); Assertions.assertThat(applicant2).isEqualTo(applicant); DMNContext ctx = new DMNContextImpl(); ctx.set("Applicant", applicant); // VERY IMPORTANT that the map key is "Applicant" with the capital-A to clash with Application.class simple name. DMNContextKS contextKS = new DMNContextKS("ns1", "model1", ctx.getAll()); DMNContextKS contextKS2 = roundTrip(contextKS); Assertions.assertThat(contextKS2.getDmnContext()).isEqualTo(contextKS.getDmnContext()); Assertions.assertThat(contextKS2.toString()).isEqualTo(contextKS.toString()); DMNResultImpl dmnResults = new DMNResultImpl(null); dmnResults.setContext(ctx); dmnResults.addDecisionResult(new DMNDecisionResultImpl("decision", "decision", DecisionEvaluationStatus.SUCCEEDED, applicant, Collections.emptyList())); DMNResultKS resultsKS = new DMNResultKS(dmnResults); DMNResultKS resultsKS2 = roundTrip(resultsKS); Assertions.assertThat(resultsKS2.getContext().getAll()).isEqualTo(resultsKS.getContext().getAll()); ServiceResponse<DMNResultKS> sr = new ServiceResponse<DMNResultKS>(ResponseType.SUCCESS, "ok", resultsKS); ServiceResponse<DMNResultKS> sr2 = roundTrip(sr); Assertions.assertThat(sr2.getResult().getContext().getAll()).isEqualTo(sr.getResult().getContext().getAll()); } private <T> T roundTrip(T input) { String asJSON = marshaller.marshall(input); LOG.debug("{}", asJSON); @SuppressWarnings("unchecked") // intentional due to type-erasure. T unmarshall = (T) marshaller.unmarshall(asJSON, input.getClass()); LOG.debug("{}", unmarshall); return unmarshall; } public static class Applicant { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Applicant() { } public Applicant(String name, int age) { super(); this.name = name; this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Applicant other = (Applicant) obj; if (age != other.age) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return "Applicant [name=" + name + ", age=" + age + "]"; } } }
winklerm/droolsjbpm-integration
kie-server-parent/kie-server-api/src/test/java/org/kie/server/api/model/dmn/JSONAPIRoundTripTest.java
Java
apache-2.0
5,387
/*========================================================================= * * Copyright Insight Software Consortium * * 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.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. * *=========================================================================*/ #ifndef itkMatchCardinalityImageToImageMetric_h #define itkMatchCardinalityImageToImageMetric_h /** * TODO: This class needs to be more tightly integrated with the new * multi-threaded ImageToImageMetric. */ #include "itkImageToImageMetric.h" #include "itkPoint.h" #include <vector> namespace itk { /** \class MatchCardinalityImageToImageMetric * \brief Computes similarity between two objects to be registered * * This Class is templated over the type of the fixed and moving * images to be compared. * * This metric computes cardinality of the set of pixels that match * exactly between the moving and fixed images. The spatial * correspondance between both images is established through a * Transform. Pixel values are taken from the Moving image. Their * positions are mapped to the Fixed image and result in general in * non-grid position on it. Values at these non-grid position of the * Fixed image are interpolated using a user-selected Interpolator. * * This metric is designed for matching label maps. All pixel * mismatches are considered equal whether they are between label 1 * and label 2 or between label 1 and label 500. In other words, the * magnitude of an individual label mismatch is not relevant, or the * occurrence of a label mismatch is important. * * Given the nature of label maps, a nearest neighbor interpolator is * the preferred interpolator. * * The metric measure can measure the number of pixel matches (pixels * with exactly the same label) or pixel mismatches (pixels with * different labels). The returned metric value is the number of pixel * matches (or mismatches) normalized by the number of pixels * considered. The number of pixel considered is a function of the * number of pixels in the overlap of the fixed and moving image * buffers conditional on any assigned masks. * * \ingroup RegistrationMetrics * \ingroup ITKRegistrationCommon */ template< typename TFixedImage, typename TMovingImage > class ITK_TEMPLATE_EXPORT MatchCardinalityImageToImageMetric: public ImageToImageMetric< TFixedImage, TMovingImage > { public: ITK_DISALLOW_COPY_AND_ASSIGN(MatchCardinalityImageToImageMetric); /** Standard class type aliases. */ using Self = MatchCardinalityImageToImageMetric; using Superclass = ImageToImageMetric< TFixedImage, TMovingImage >; using Pointer = SmartPointer< Self >; using ConstPointer = SmartPointer< const Self >; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(MatchCardinalityImageToImageMetric, ImageToImageMetric); /** Types transferred from the base class */ using RealType = typename Superclass::RealType; using TransformType = typename Superclass::TransformType; using TransformPointer = typename Superclass::TransformPointer; using TransformParametersType = typename Superclass::TransformParametersType; using TransformJacobianType = typename Superclass::TransformJacobianType; using GradientPixelType = typename Superclass::GradientPixelType; using MeasureType = typename Superclass::MeasureType; using DerivativeType = typename Superclass::DerivativeType; using FixedImageType = typename Superclass::FixedImageType; using MovingImageType = typename Superclass::MovingImageType; using FixedImageConstPointer = typename Superclass::FixedImageConstPointer; using MovingImageConstPointer = typename Superclass::MovingImageConstPointer; using FixedImageRegionType = typename Superclass::FixedImageRegionType; /** Get the derivatives of the match measure. */ void GetDerivative(const TransformParametersType &, DerivativeType & derivative) const override { itkWarningMacro(<< "This metric does not provide metric derivatives."); derivative.Fill(NumericTraits< typename DerivativeType::ValueType >::ZeroValue()); } /** Get the value of the metric at a particular parameter * setting. The metric value is the number of pixel matches (or * mis-matches, see SetMeasureMatches()) normalized by the number * of pixels under consideration (within the buffer and if * specified within a mask). In other words, the metric measure the * percentage of pixel matches or mismatches. */ MeasureType GetValue(const TransformParametersType & parameters) const override; /** Set/Get whether this metric measures pixel matches or pixel * mismatches. Note the GetValue() returns the number of matches (or * mismatches) normalized by the number of pixels considered. In * other words, the metric measures the percentage of pixel matches * or mismatches. The default is to measure matches * (MeasureMatchesOn). */ itkSetMacro(MeasureMatches, bool); itkBooleanMacro(MeasureMatches); itkGetConstMacro(MeasureMatches, bool); /** Return the multithreader used by this class. */ MultiThreaderBase * GetMultiThreader() { return m_Threader; } protected: MatchCardinalityImageToImageMetric(); ~MatchCardinalityImageToImageMetric() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; /** * Non-const version of GetValue(). This is a hack around various * const issues with trying to spawn threads from the const version * of GetValue(). */ MeasureType GetNonconstValue(const TransformParametersType & parameters); /** * Thread worker routine to calculate the contribution of the a * subregion to the overall metric. Can only be called from * GetValue(). */ virtual void ThreadedGetValue(const FixedImageRegionType & outputRegionForThread, ThreadIdType threadId); /** Split the FixedImageRegion into "num" pieces, returning * region "i" as "splitRegion". This method is called "num" times. The * regions must not overlap. The method returns the number of pieces that * the routine is capable of splitting the FixedImageRegion, * i.e. return value is less than or equal to "num". */ virtual ThreadIdType SplitFixedRegion(ThreadIdType i, int num, FixedImageRegionType & splitRegion); /** Static function used as a "callback" by the MultiThreaderBase. The threading * library will call this routine for each thread, which will delegate the * control to ThreadedGetValue(). */ static ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION ThreaderCallback(void *arg); /** Internal structure used for passing image data into the threading library */ struct ThreadStruct { Pointer Metric; }; private: bool m_MeasureMatches; std::vector< MeasureType > m_ThreadMatches; std::vector< SizeValueType > m_ThreadCounts; /** Support processing data in multiple threads. Used by subclasses * (e.g., ImageSource). */ MultiThreaderBase::Pointer m_Threader; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkMatchCardinalityImageToImageMetric.hxx" #endif #endif
blowekamp/ITK
Modules/Registration/Common/include/itkMatchCardinalityImageToImageMetric.h
C
apache-2.0
7,736
import {ListWrapper, List} from 'angular2/src/facade/collection'; import {stringify, BaseException, isBlank} from 'angular2/src/facade/lang'; function findFirstClosedCycle(keys: List<any>): List<any> { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys: List<any>): string { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = ListWrapper.map(reversed, (k) => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured bindings. * * @exportedAs angular2/di_errors */ export class AbstractBindingError extends BaseException { name: string; message: string; keys: List<any>; constructResolvingMessage: Function; // TODO(tbosch): Can't do key:Key as this results in a circular dependency! constructor(key, constructResolvingMessage: Function, originalException?, originalStack?) { super(null, originalException, originalStack); this.keys = [key]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } // TODO(tbosch): Can't do key:Key as this results in a circular dependency! addKey(key): void { this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } toString(): string { return this.message; } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Binding} for {@link Key}. * * @exportedAs angular2/di_errors */ export class NoBindingError extends AbstractBindingError { // TODO(tbosch): Can't do key:Key as this results in a circular dependency! constructor(key) { super(key, function(keys: List<any>) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when trying to retrieve an async {@link Binding} using the sync API. * * ## Example * * ```javascript * var injector = Injector.resolveAndCreate([ * bind(Number).toAsyncFactory(() => { * return new Promise((resolve) => resolve(1 + 2)); * }), * bind(String).toFactory((v) => { return "Value: " + v; }, [String]) * ]); * * injector.asyncGet(String).then((v) => expect(v).toBe('Value: 3')); * expect(() => { * injector.get(String); * }).toThrowError(AsycBindingError); * ``` * * The above example throws because `String` depends on `Number` which is async. If any binding in * the dependency graph is async then the graph can only be retrieved using the `asyncGet` API. * * @exportedAs angular2/di_errors */ export class AsyncBindingError extends AbstractBindingError { // TODO(tbosch): Can't do key:Key as this results in a circular dependency! constructor(key) { super(key, function(keys: List<any>) { var first = stringify(ListWrapper.first(keys).token); return `Cannot instantiate ${first} synchronously. It is provided as a promise!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ## Example: * * ```javascript * class A { * constructor(b:B) {} * } * class B { * constructor(a:A) {} * } * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. * * @exportedAs angular2/di_errors */ export class CyclicDependencyError extends AbstractBindingError { // TODO(tbosch): Can't do key:Key as this results in a circular dependency! constructor(key) { super(key, function(keys: List<any>) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * @exportedAs angular2/di_errors */ export class InstantiationError extends AbstractBindingError { causeKey; // TODO(tbosch): Can't do key:Key as this results in a circular dependency! constructor(originalException, originalStack, key) { super(key, function(keys: List<any>) { var first = stringify(ListWrapper.first(keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(keys)}.` + ` ORIGINAL ERROR: ${originalException}` + `\n\n ORIGINAL STACK: ${originalStack}`; }, originalException, originalStack); this.causeKey = key; } } /** * Thrown when an object other then {@link Binding} (or `Type`) is passed to {@link Injector} * creation. * * @exportedAs angular2/di_errors */ export class InvalidBindingError extends BaseException { message: string; constructor(binding) { super(); this.message = "Invalid binding - only instances of Binding and Type are allowed, got: " + binding.toString(); } toString(): string { return this.message; } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * @exportedAs angular2/di_errors */ export class NoAnnotationError extends BaseException { name: string; message: string; constructor(typeOrFunc, params: List<List<any>>) { super(); var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(ListWrapper.map(parameter, stringify).join(' ')); } } this.message = "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } toString(): string { return this.message; } } /** * Thrown when getting an object by index. * * @exportedAs angular2/di_errors */ export class OutOfBoundsError extends BaseException { message: string; constructor(index) { super(); this.message = `Index ${index} is out-of-bounds.`; } toString(): string { return this.message; } }
MyoungJin/angular
modules/angular2/src/di/exceptions.ts
TypeScript
apache-2.0
6,490
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template result&lt;This(Expr)&gt;</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../child.html#idp381445968" title="Description"> <link rel="prev" href="../child.html" title="Struct template child"> <link rel="next" href="../value.html" title="Struct value"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../child.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../child.html#idp381445968"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../value.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.proto.functional.child.result_This(E_idp203592768"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template result&lt;This(Expr)&gt;</span></h2> <p>boost::proto::functional::child::result&lt;This(Expr)&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../../proto/reference.html#header.boost.proto.traits_hpp" title="Header &lt;boost/proto/traits.hpp&gt;">boost/proto/traits.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> This<span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="../../../../Expr.html" title="Concept Expr">Expr</a><span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="result_This_E_idp203592768.html" title="Struct template result&lt;This(Expr)&gt;">result</a><span class="special">&lt;</span><span class="identifier">This</span><span class="special">(</span><span class="identifier">Expr</span><span class="special">)</span><span class="special">&gt;</span> <span class="special">:</span> <span class="keyword"></span> <a class="link" href="../../result_of/child.html" title="Struct template child">proto::result_of::child</a>&lt; Expr, N &gt; <span class="special">{</span> <span class="special">}</span><span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2008 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../child.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../child.html#idp381445968"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../value.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
biospi/seamass-windeps
src/boost_1_57_0/doc/html/boost/proto/functional/child/result_This_E_idp203592768.html
HTML
apache-2.0
4,383
/* * Autopsy Forensic Browser * * Copyright 2012-2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.corecomponents; import java.awt.Color; import java.awt.Cursor; import java.awt.Dialog; import java.awt.EventQueue; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.logging.Level; import java.util.prefs.Preferences; import java.util.stream.Collectors; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.SortOrder; import javax.swing.SwingWorker; import org.apache.commons.lang3.StringUtils; import org.netbeans.api.progress.ProgressHandle; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.explorer.ExplorerManager; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.NodeEvent; import org.openide.nodes.NodeListener; import org.openide.nodes.NodeMemberEvent; import org.openide.nodes.NodeReorderEvent; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.util.lookup.ServiceProvider; import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer; import static org.sleuthkit.autopsy.corecomponents.Bundle.*; import org.sleuthkit.autopsy.corecomponents.ResultViewerPersistence.SortCriterion; import org.sleuthkit.autopsy.coreutils.ImageUtils; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.guiutils.WrapLayout; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.TskCoreException; /** * A thumbnail result viewer, with paging support, that displays the children of * the given root node using an IconView. The paging is intended to reduce * memory footprint by loading no more than two humdred images at a time. * * Instances of this class should use the explorer manager of an ancestor top * component to connect the lookups of the nodes displayed in the IconView to * the actions global context. The explorer manager can be supplied during * construction, but the typical use case is for the result viewer to find the * ancestor top component's explorer manager at runtime. */ @ServiceProvider(service = DataResultViewer.class) @SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives public final class DataResultViewerThumbnail extends AbstractDataResultViewer { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName()); private final PageUpdater pageUpdater = new PageUpdater(); private TableFilterNode rootNode; private ThumbnailViewChildren rootNodeChildren; private NodeSelectionListener selectionListener; private int currentPage; private int totalPages; private int currentPageImages; private int thumbSize = ImageUtils.ICON_SIZE_MEDIUM; /** * Constructs a thumbnail result viewer, with paging support, that displays * the children of the given root node using an IconView. The viewer should * have an ancestor top component to connect the lookups of the nodes * displayed in the IconView to the actions global context. The explorer * manager will be discovered at runtime. */ public DataResultViewerThumbnail() { this(null); } /** * Constructs a thumbnail result viewer, with paging support, that displays * the children of the given root node using an IconView. The viewer should * have an ancestor top component to connect the lookups of the nodes * displayed in the IconView to the actions global context. * * @param explorerManager The explorer manager of the ancestor top * component. */ @NbBundle.Messages({ "DataResultViewerThumbnail.thumbnailSizeComboBox.small=Small Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.medium=Medium Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.large=Large Thumbnails" }) public DataResultViewerThumbnail(ExplorerManager explorerManager) { super(explorerManager); initComponents(); iconView.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); thumbnailSizeComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{ Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_small(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_medium(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_large()})); thumbnailSizeComboBox.setSelectedIndex(1); currentPage = -1; totalPages = 0; currentPageImages = 0; // The GUI builder is using FlowLayout therefore this change so have no // impact on the initally designed layout. This change will just effect // how the components are laid out as size of the window changes. buttonBarPanel.setLayout(new WrapLayout()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonBarPanel = new javax.swing.JPanel(); pagesPanel = new javax.swing.JPanel(); pageNumberPane = new javax.swing.JPanel(); pageLabel = new javax.swing.JLabel(); pageNumLabel = new javax.swing.JLabel(); pageButtonPanel = new javax.swing.JPanel(); pagesLabel = new javax.swing.JLabel(); pagePrevButton = new javax.swing.JButton(); pageNextButton = new javax.swing.JButton(); pageGotoPane = new javax.swing.JPanel(); goToPageLabel = new javax.swing.JLabel(); goToPageField = new javax.swing.JTextField(); imagePane = new javax.swing.JPanel(); imagesLabel = new javax.swing.JLabel(); imagesRangeLabel = new javax.swing.JLabel(); thumbnailSizeComboBox = new javax.swing.JComboBox<>(); sortPane = new javax.swing.JPanel(); sortLabel = new javax.swing.JLabel(); sortButton = new javax.swing.JButton(); filePathLabel = new javax.swing.JLabel(); iconView = new org.openide.explorer.view.IconView(); setLayout(new java.awt.BorderLayout()); buttonBarPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); pagesPanel.setLayout(new java.awt.GridBagLayout()); pageNumberPane.setLayout(new java.awt.GridBagLayout()); pageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 9); pageNumberPane.add(pageLabel, gridBagConstraints); pageNumLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNumLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 15); pageNumberPane.add(pageNumLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; pagesPanel.add(pageNumberPane, gridBagConstraints); buttonBarPanel.add(pagesPanel); pageButtonPanel.setLayout(new java.awt.GridBagLayout()); pagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagesLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 9); pageButtonPanel.add(pagesLabel, gridBagConstraints); pagePrevButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back.png"))); // NOI18N pagePrevButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagePrevButton.text")); // NOI18N pagePrevButton.setBorder(null); pagePrevButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_disabled.png"))); // NOI18N pagePrevButton.setFocusable(false); pagePrevButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); pagePrevButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); pagePrevButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_hover.png"))); // NOI18N pagePrevButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); pagePrevButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pagePrevButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; pageButtonPanel.add(pagePrevButton, gridBagConstraints); pageNextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward.png"))); // NOI18N pageNextButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNextButton.text")); // NOI18N pageNextButton.setBorder(null); pageNextButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_disabled.png"))); // NOI18N pageNextButton.setFocusable(false); pageNextButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); pageNextButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); pageNextButton.setMaximumSize(new java.awt.Dimension(27, 23)); pageNextButton.setMinimumSize(new java.awt.Dimension(27, 23)); pageNextButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_hover.png"))); // NOI18N pageNextButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); pageNextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pageNextButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 15); pageButtonPanel.add(pageNextButton, gridBagConstraints); buttonBarPanel.add(pageButtonPanel); pageGotoPane.setLayout(new java.awt.GridBagLayout()); goToPageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 9); pageGotoPane.add(goToPageLabel, gridBagConstraints); goToPageField.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageField.text")); // NOI18N goToPageField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goToPageFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; gridBagConstraints.ipadx = 75; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 15); pageGotoPane.add(goToPageField, gridBagConstraints); buttonBarPanel.add(pageGotoPane); imagePane.setLayout(new java.awt.GridBagLayout()); imagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 9); imagePane.add(imagesLabel, gridBagConstraints); imagesRangeLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesRangeLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 15); imagePane.add(imagesRangeLabel, gridBagConstraints); buttonBarPanel.add(imagePane); thumbnailSizeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { thumbnailSizeComboBoxActionPerformed(evt); } }); buttonBarPanel.add(thumbnailSizeComboBox); sortPane.setLayout(new java.awt.GridBagLayout()); sortLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.sortLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.weighty = 1.0; sortPane.add(sortLabel, gridBagConstraints); sortButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.sortButton.text")); // NOI18N sortButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sortButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 15, 0, 9); sortPane.add(sortButton, gridBagConstraints); buttonBarPanel.add(sortPane); add(buttonBarPanel, java.awt.BorderLayout.NORTH); filePathLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.filePathLabel.text")); // NOI18N add(filePathLabel, java.awt.BorderLayout.SOUTH); add(iconView, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void pagePrevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagePrevButtonActionPerformed previousPage(); }//GEN-LAST:event_pagePrevButtonActionPerformed private void pageNextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pageNextButtonActionPerformed nextPage(); }//GEN-LAST:event_pageNextButtonActionPerformed private void goToPageFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goToPageFieldActionPerformed goToPage(goToPageField.getText()); }//GEN-LAST:event_goToPageFieldActionPerformed private void thumbnailSizeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_thumbnailSizeComboBoxActionPerformed int newIconSize; switch (thumbnailSizeComboBox.getSelectedIndex()) { case 0: newIconSize = ImageUtils.ICON_SIZE_SMALL; break; case 2: newIconSize = ImageUtils.ICON_SIZE_LARGE; break; case 1: default: newIconSize = ImageUtils.ICON_SIZE_MEDIUM; //default size break; } if (thumbSize != newIconSize) { thumbSize = newIconSize; Node root = this.getExplorerManager().getRootContext(); ((ThumbnailViewChildren) root.getChildren()).setThumbsSize(thumbSize); // Temporarily set the explored context to the root, instead of a child node. // This is a workaround hack to convince org.openide.explorer.ExplorerManager to // update even though the new and old Node values are identical. This in turn // will cause the entire view to update completely. After this we // immediately set the node back to the current child by calling switchPage(). this.getExplorerManager().setExploredContext(root); switchPage(); } }//GEN-LAST:event_thumbnailSizeComboBoxActionPerformed private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortButtonActionPerformed List<Node.Property<?>> childProperties = ResultViewerPersistence.getAllChildProperties(this.getExplorerManager().getRootContext(), 100); SortChooser sortChooser = new SortChooser(childProperties, ResultViewerPersistence.loadSortCriteria(rootNode)); DialogDescriptor dialogDescriptor = new DialogDescriptor(sortChooser, sortChooser.getDialogTitle()); Dialog createDialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor); createDialog.setVisible(true); final Object dialogReturnValue = dialogDescriptor.getValue(); if (DialogDescriptor.OK_OPTION == dialogReturnValue) { //apply new sort List<SortCriterion> criteria = sortChooser.getCriteria(); final Preferences preferences = NbPreferences.forModule(DataResultViewerThumbnail.class); Map<Node.Property<?>, SortCriterion> criteriaMap = criteria.stream() .collect(Collectors.toMap(SortCriterion::getProperty, Function.identity(), (u, v) -> u)); //keep first criteria if property is selected multiple times. //store the sorting information int numProperties = childProperties.size(); for (int i = 0; i < numProperties; i++) { Node.Property<?> prop = childProperties.get(i); String propName = prop.getName(); SortCriterion criterion = criteriaMap.get(prop); final String columnSortOrderKey = ResultViewerPersistence.getColumnSortOrderKey(rootNode, propName); final String columnSortRankKey = ResultViewerPersistence.getColumnSortRankKey(rootNode, propName); if (criterion != null) { preferences.putBoolean(columnSortOrderKey, criterion.getSortOrder() == SortOrder.ASCENDING); preferences.putInt(columnSortRankKey, criterion.getSortRank() + 1); } else { preferences.remove(columnSortOrderKey); preferences.remove(columnSortRankKey); } } setNode(rootNode); //this is just to force a refresh } }//GEN-LAST:event_sortButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonBarPanel; private javax.swing.JLabel filePathLabel; private javax.swing.JTextField goToPageField; private javax.swing.JLabel goToPageLabel; private org.openide.explorer.view.IconView iconView; private javax.swing.JPanel imagePane; private javax.swing.JLabel imagesLabel; private javax.swing.JLabel imagesRangeLabel; private javax.swing.JPanel pageButtonPanel; private javax.swing.JPanel pageGotoPane; private javax.swing.JLabel pageLabel; private javax.swing.JButton pageNextButton; private javax.swing.JLabel pageNumLabel; private javax.swing.JPanel pageNumberPane; private javax.swing.JButton pagePrevButton; private javax.swing.JLabel pagesLabel; private javax.swing.JPanel pagesPanel; private javax.swing.JButton sortButton; private javax.swing.JLabel sortLabel; private javax.swing.JPanel sortPane; private javax.swing.JComboBox<String> thumbnailSizeComboBox; // End of variables declaration//GEN-END:variables @Override public boolean isSupported(Node selectedNode) { return (selectedNode != null); } @Override public void setNode(Node givenNode) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (selectionListener == null) { this.getExplorerManager().addPropertyChangeListener(new NodeSelectionListener()); } if (rootNodeChildren != null) { rootNodeChildren.cancelLoadingThumbnails(); } try { // There is an issue with ThumbnailViewChildren // addNotify, that it's call to getChildren.getNodes() does not cause the // children nodes to be created. Adding a call to getChildren.getNodesCount() // here will assure that the children nodes are created particularly in the // case where the DataResultViewerThumbnail stands along from the // DataResultViewer. See DataResultViewer setNode for more information. if (givenNode != null && givenNode.getChildren().getNodesCount() > 0) { rootNode = (TableFilterNode) givenNode; /* * Wrap the given node in a ThumbnailViewChildren that will * produce ThumbnailPageNodes with ThumbnailViewNode children * from the child nodes of the given node. */ rootNodeChildren = new ThumbnailViewChildren(givenNode, thumbSize); final Node root = new AbstractNode(rootNodeChildren); pageUpdater.setRoot(root); root.addNodeListener(pageUpdater); this.getExplorerManager().setRootContext(root); } else { rootNode = null; rootNodeChildren = null; Node emptyNode = new AbstractNode(Children.LEAF); this.getExplorerManager().setRootContext(emptyNode); iconView.setBackground(Color.BLACK); } } finally { this.setCursor(null); } } @Override public String getTitle() { return NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.title"); } @Override public DataResultViewer createInstance() { return new DataResultViewerThumbnail(); } @Override public void resetComponent() { super.resetComponent(); this.totalPages = 0; this.currentPage = -1; currentPageImages = 0; updateControls(); } @Override public void clearComponent() { this.iconView.removeAll(); this.iconView = null; super.clearComponent(); } private void nextPage() { if (currentPage < totalPages) { currentPage++; switchPage(); } } private void previousPage() { if (currentPage > 1) { currentPage--; switchPage(); } } private void goToPage(String pageNumText) { int newPage; try { newPage = Integer.parseInt(pageNumText); } catch (NumberFormatException e) { //ignore input return; } if (newPage > totalPages || newPage < 1) { JOptionPane.showMessageDialog(this, NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.msgDlg", totalPages), NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.err"), JOptionPane.WARNING_MESSAGE); return; } currentPage = newPage; switchPage(); } private void switchPage() { EventQueue.invokeLater(() -> { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); }); //Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps new SwingWorker<Object, Void>() { private ProgressHandle progress; @Override protected Object doInBackground() throws Exception { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); progress = ProgressHandle.createHandle( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.genThumbs")); progress.start(); progress.switchToIndeterminate(); ExplorerManager explorerManager = DataResultViewerThumbnail.this.getExplorerManager(); Node root = explorerManager.getRootContext(); Node pageNode = root.getChildren().getNodeAt(currentPage - 1); explorerManager.setExploredContext(pageNode); currentPageImages = pageNode.getChildren().getNodesCount(); return null; } @Override protected void done() { progress.finish(); setCursor(null); updateControls(); // see if any exceptions were thrown try { get(); } catch (InterruptedException | ExecutionException ex) { NotifyDescriptor d = new NotifyDescriptor.Message( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.switchPage.done.errMsg", ex.getMessage()), NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(d); logger.log(Level.SEVERE, "Error making thumbnails: {0}", ex.getMessage()); //NON-NLS } catch (java.util.concurrent.CancellationException ex) { // catch and ignore if we were cancelled } } }.execute(); } @NbBundle.Messages({ "# {0} - sort criteria", "DataResultViewerThumbnail.sortLabel.textTemplate=Sorted by: {0}", "DataResultViewerThumbnail.sortLabel.text=Sorted by: ---"}) private void updateControls() { if (totalPages == 0) { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); pageNumLabel.setText(""); imagesRangeLabel.setText(""); thumbnailSizeComboBox.setEnabled(false); sortButton.setEnabled(false); sortLabel.setText(DataResultViewerThumbnail_sortLabel_text()); } else { pageNumLabel.setText(NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.pageNumbers.curOfTotal", Integer.toString(currentPage), Integer.toString(totalPages))); final int imagesFrom = (currentPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE + 1; final int imagesTo = currentPageImages + (currentPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE; imagesRangeLabel.setText(imagesFrom + "-" + imagesTo); pageNextButton.setEnabled(!(currentPage == totalPages)); pagePrevButton.setEnabled(!(currentPage == 1)); goToPageField.setEnabled(totalPages > 1); sortButton.setEnabled(true); thumbnailSizeComboBox.setEnabled(true); if (rootNode != null) { String sortString = ResultViewerPersistence.loadSortCriteria(rootNode).stream() .map(SortCriterion::toString) .collect(Collectors.joining(" ")); sortString = StringUtils.defaultIfBlank(sortString, "---"); sortLabel.setText(Bundle.DataResultViewerThumbnail_sortLabel_textTemplate(sortString)); } else { sortLabel.setText(DataResultViewerThumbnail_sortLabel_text()); } } } /** * Listens for root change updates and updates the paging controls */ private class PageUpdater implements NodeListener { private Node root; void setRoot(Node root) { this.root = root; } @Override public void propertyChange(PropertyChangeEvent evt) { } @Override public void childrenAdded(NodeMemberEvent nme) { totalPages = root.getChildren().getNodesCount(); if (totalPages == 0) { currentPage = -1; updateControls(); return; } if (currentPage == -1 || currentPage > totalPages) { currentPage = 1; } //force load the curPage node final Node pageNode = root.getChildren().getNodeAt(currentPage - 1); //em.setSelectedNodes(new Node[]{pageNode}); if (pageNode != null) { pageNode.addNodeListener(new NodeListener() { @Override public void childrenAdded(NodeMemberEvent nme) { currentPageImages = pageNode.getChildren().getNodesCount(); updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { currentPageImages = 0; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } @Override public void propertyChange(PropertyChangeEvent evt) { } }); DataResultViewerThumbnail.this.getExplorerManager().setExploredContext(pageNode); } updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { totalPages = 0; currentPage = -1; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } } private class NodeSelectionListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(ExplorerManager.PROP_SELECTED_NODES)) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Node[] selectedNodes = DataResultViewerThumbnail.this.getExplorerManager().getSelectedNodes(); if (selectedNodes.length == 1) { AbstractFile af = selectedNodes[0].getLookup().lookup(AbstractFile.class); if (af == null) { filePathLabel.setText(""); } else { try { String uPath = af.getUniquePath(); filePathLabel.setText(uPath); filePathLabel.setToolTipText(uPath); } catch (TskCoreException e) { logger.log(Level.WARNING, "Could not get unique path for content: {0}", af.getName()); //NON-NLS } } } else { filePathLabel.setText(""); } } finally { setCursor(null); } } } } }
esaunders/autopsy
Core/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java
Java
apache-2.0
34,868
package com.google.api.ads.dfp.jaxws.v201405; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for BillingCap. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="BillingCap"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="NO_CAP"/> * &lt;enumeration value="CAPPED_CUMULATIVE"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "BillingCap") @XmlEnum public enum BillingCap { /** * * There is no cap for each billing month. * * */ NO_CAP, /** * * Use a billing source of capped actuals with a billing cap of cumulative to bill your * advertiser up to a campaign's capped amount, regardless of the number of impressions that * are served each month. * * */ CAPPED_CUMULATIVE, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static BillingCap fromValue(String v) { return valueOf(v); } }
stoksey69/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/BillingCap.java
Java
apache-2.0
1,448
/* SPDX-License-Identifier: GPL-2.0 */ /* Copyright (C) 2018-2020 Authors of Cilium */ #ifndef SOCK_OPS_MAP #define SOCK_OPS_MAP cilium_sock_ops #endif #define SOCKOPS_MAP_SIZE 65535 #ifndef CALLS_MAP #define CALLS_MAP test_cilium_calls #endif
tklauser/cilium
bpf/sockops/sockops_config.h
C
apache-2.0
245
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <ztest.h> #include "tests_thread_apis.h" static ZTEST_BMEM int execute_flag; K_SEM_DEFINE(sync_sema, 0, 1); #define BLOCK_SIZE 64 static void thread_entry(void *p1, void *p2, void *p3) { execute_flag = 1; k_msleep(100); execute_flag = 2; } static void thread_entry_abort(void *p1, void *p2, void *p3) { /**TESTPOINT: abort current thread*/ execute_flag = 1; k_thread_abort(k_current_get()); /*unreachable*/ execute_flag = 2; zassert_true(1 == 0, NULL); } /** * @ingroup kernel_thread_tests * @brief Validate k_thread_abort() when called by current thread * * @details Create a user thread and let the thread execute. * Then call k_thread_abort() and check if the thread is terminated. * Here the main thread is also a user thread. * * @see k_thread_abort() */ void test_threads_abort_self(void) { execute_flag = 0; k_thread_create(&tdata, tstack, STACK_SIZE, thread_entry_abort, NULL, NULL, NULL, 0, K_USER, K_NO_WAIT); k_msleep(100); /**TESTPOINT: spawned thread executed but abort itself*/ zassert_true(execute_flag == 1, NULL); } /** * @ingroup kernel_thread_tests * @brief Validate k_thread_abort() when called by other thread * * @details Create a user thread and abort the thread before its * execution. Create a another user thread and abort the thread * after it has started. * * @see k_thread_abort() */ void test_threads_abort_others(void) { execute_flag = 0; k_tid_t tid = k_thread_create(&tdata, tstack, STACK_SIZE, thread_entry, NULL, NULL, NULL, 0, K_USER, K_NO_WAIT); k_thread_abort(tid); k_msleep(100); /**TESTPOINT: check not-started thread is aborted*/ zassert_true(execute_flag == 0, NULL); tid = k_thread_create(&tdata, tstack, STACK_SIZE, thread_entry, NULL, NULL, NULL, 0, K_USER, K_NO_WAIT); k_msleep(50); k_thread_abort(tid); /**TESTPOINT: check running thread is aborted*/ zassert_true(execute_flag == 1, NULL); k_msleep(1000); zassert_true(execute_flag == 1, NULL); } /** * @ingroup kernel_thread_tests * @brief Test abort on a terminated thread * * @see k_thread_abort() */ void test_threads_abort_repeat(void) { execute_flag = 0; k_tid_t tid = k_thread_create(&tdata, tstack, STACK_SIZE, thread_entry, NULL, NULL, NULL, 0, K_USER, K_NO_WAIT); k_thread_abort(tid); k_msleep(100); k_thread_abort(tid); k_msleep(100); k_thread_abort(tid); /* If no fault occurred till now. The test case passed. */ ztest_test_pass(); } bool abort_called; void *block; static void delayed_thread_entry(void *p1, void *p2, void *p3) { execute_flag = 1; zassert_unreachable("Delayed thread shouldn't be executed"); } /** * @ingroup kernel_thread_tests * @brief Test abort on delayed thread before it has started * execution * * @see k_thread_abort() */ void test_delayed_thread_abort(void) { int current_prio = k_thread_priority_get(k_current_get()); execute_flag = 0; /* Make current thread preemptive */ k_thread_priority_set(k_current_get(), K_PRIO_PREEMPT(2)); /* Create a preemptive thread of higher priority than * current thread */ k_tid_t tid = k_thread_create(&tdata, tstack, STACK_SIZE, (k_thread_entry_t)delayed_thread_entry, NULL, NULL, NULL, K_PRIO_PREEMPT(1), 0, K_MSEC(100)); /* Give up CPU */ k_msleep(50); /* Test point: check if thread delayed for 100ms has not started*/ zassert_true(execute_flag == 0, "Delayed thread created is not" " put to wait queue"); k_thread_abort(tid); /* Test point: Test abort of thread before its execution*/ zassert_false(execute_flag == 1, "Delayed thread is has executed" " before cancellation"); /* Restore the priority */ k_thread_priority_set(k_current_get(), current_prio); } static volatile bool isr_finished; static void offload_func(const void *param) { struct k_thread *t = (struct k_thread *)param; k_thread_abort(t); /* k_thread_abort() in an isr shouldn't affect the ISR's execution */ isr_finished = true; } static void entry_abort_isr(void *p1, void *p2, void *p3) { /* Simulate taking an interrupt which kills this thread */ irq_offload(offload_func, k_current_get()); printk("shouldn't see this, thread should have been killed"); ztest_test_fail(); } extern struct k_sem offload_sem; /** * @ingroup kernel_thread_tests * * @brief Show that threads can be aborted from interrupt context by itself * * @details Spwan a thread, then enter ISR context in child thread and abort * the child thread. Check if ISR completed and target thread was aborted. * * @see k_thread_abort() */ void test_abort_from_isr(void) { isr_finished = false; k_thread_create(&tdata, tstack, STACK_SIZE, entry_abort_isr, NULL, NULL, NULL, 0, 0, K_NO_WAIT); k_thread_join(&tdata, K_FOREVER); zassert_true(isr_finished, "ISR did not complete"); /* Notice: Recover back the offload_sem: This is use for releasing * offload_sem which might be held when thread aborts itself in ISR * context, it will cause irq_offload cannot be used again. */ k_sem_give(&offload_sem); } /* use for sync thread start */ static struct k_sem sem_abort; static void entry_aborted_thread(void *p1, void *p2, void *p3) { k_sem_give(&sem_abort); /* wait for being aborted */ while (1) { k_sleep(K_MSEC(1)); } zassert_unreachable("should not reach here"); } /** * @ingroup kernel_thread_tests * * @brief Show that threads can be aborted from interrupt context * * @details Spwan a thread, then enter ISR context in main thread and abort * the child thread. Check if ISR completed and target thread was aborted. * * @see k_thread_abort() */ void test_abort_from_isr_not_self(void) { k_tid_t tid; isr_finished = false; k_sem_init(&sem_abort, 0, 1); tid = k_thread_create(&tdata, tstack, STACK_SIZE, entry_aborted_thread, NULL, NULL, NULL, 0, 0, K_NO_WAIT); /* wait for thread started */ k_sem_take(&sem_abort, K_FOREVER); /* Simulate taking an interrupt which kills spwan thread */ irq_offload(offload_func, (void *)tid); k_thread_join(&tdata, K_FOREVER); zassert_true(isr_finished, "ISR did not complete"); }
galak/zephyr
tests/kernel/threads/thread_apis/src/test_threads_cancel_abort.c
C
apache-2.0
6,206
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Copyright (c) 2015 Samsung Electronics Co., Ltd. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_EXTENSIONS_XWALK_EXTENSION_INSTANCE_H_ #define XWALK_EXTENSIONS_XWALK_EXTENSION_INSTANCE_H_ #include <functional> #include <string> #include "extensions/public/XW_Extension.h" namespace extensions { class XWalkExtension; class XWalkExtensionInstance { public: typedef std::function<void(const std::string&)> MessageCallback; XWalkExtensionInstance(XWalkExtension* extension, XW_Instance xw_instance); virtual ~XWalkExtensionInstance(); void HandleMessage(const std::string& msg); void HandleSyncMessage(const std::string& msg); void SetPostMessageCallback(MessageCallback callback); void SetSendSyncReplyCallback(MessageCallback callback); private: friend class XWalkExtensionAdapter; void PostMessageToJS(const std::string& msg); void SyncReplyToJS(const std::string& reply); XWalkExtension* extension_; XW_Instance xw_instance_; void* instance_data_; MessageCallback post_message_callback_; MessageCallback send_sync_reply_callback_; }; } // namespace extensions #endif // XWALK_EXTENSIONS_XWALK_EXTENSION_INSTANCE_H_
psikorski/crosswalk-tizen
extensions/extension/xwalk_extension_instance.h
C
apache-2.0
1,322
require 'puppet/provider/netscaler' require 'json' Puppet::Type.type(:netscaler_route).provide(:rest, {:parent => Puppet::Provider::Netscaler}) do def netscaler_api_type "route" end def self.instances instances = [] #look for files at a certain location routes = Puppet::Provider::Netscaler.call('/config/route') return [] if routes.nil? routes.each do |route| instances << new({ :ensure => :present, :name => "#{route['network']}/#{route['netmask']}:#{route['gateway']}", :td => route['td'], :advertise => route['advertise'], :distance => route['distance'], :cost1 => route['cost1'], :weight => route['weight'], :protocol => route['protocol'], :msr => route['msr'], :monitor => route['monitor'], }) end instances end mk_resource_methods # Map for conversion in the message. def property_to_rest_mapping { } end def immutable_properties [ ] end def destroy network, netmask_gateway = resource.name.split('/') netmask, gateway = netmask_gateway.split(':') result = Puppet::Provider::Netscaler.delete("/config/#{netscaler_api_type}/#{network}", {'args'=>"netmask:#{netmask},gateway:#{gateway}"}) @property_hash.clear return result end def per_provider_munge(message) message[:network], netmask_gateway = message[:name].split('/') message[:netmask], message[:gateway] = netmask_gateway.split(':') message.delete(:name) message end end
mhaskel/puppetlabs-netscaler
lib/puppet/provider/netscaler_route/rest.rb
Ruby
apache-2.0
1,578
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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 com.intellij.openapi.fileEditor.impl; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.ArrayUtilRt; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; @State(name = "editorHistoryManager", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) public final class EditorHistoryManager implements PersistentStateComponent<Element>, ProjectComponent { private static final Logger LOG = Logger.getInstance(EditorHistoryManager.class); private final Project myProject; public static EditorHistoryManager getInstance(@NotNull Project project){ return project.getComponent(EditorHistoryManager.class); } /** * State corresponding to the most recent file is the last */ private final List<HistoryEntry> myEntriesList = new ArrayList<HistoryEntry>(); EditorHistoryManager(@NotNull Project project, @NotNull UISettings uiSettings) { myProject = project; uiSettings.addUISettingsListener(new UISettingsListener() { @Override public void uiSettingsChanged(UISettings source) { trimToSize(); } }, project); MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, new FileEditorManagerListener.Before.Adapter() { @Override public void beforeFileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { updateHistoryEntry(file, false); } }); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyEditorManagerListener()); } private synchronized void addEntry(HistoryEntry entry) { myEntriesList.add(entry); } private synchronized void removeEntry(HistoryEntry entry) { boolean removed = myEntriesList.remove(entry); if (removed) entry.destroy(); } private synchronized void moveOnTop(HistoryEntry entry) { myEntriesList.remove(entry); myEntriesList.add(entry); } /** * Makes file most recent one */ private void fileOpenedImpl(@NotNull final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider) { ApplicationManager.getApplication().assertIsDispatchThread(); // don't add files that cannot be found via VFM (light & etc.) if (VirtualFileManager.getInstance().findFileByUrl(file.getUrl()) == null) return; final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] { fallbackEditor }; } if (oldProviders.length <= 0 && fallbackProvider != null) { oldProviders = new FileEditorProvider[] { fallbackProvider }; } if (editors.length <= 0) { LOG.error("No editors for file " + file.getPresentableUrl()); } FileEditor selectedEditor = editorManager.getSelectedEditor(file); if (selectedEditor == null) { selectedEditor = fallbackEditor; } LOG.assertTrue(selectedEditor != null); final int selectedProviderIndex = ArrayUtilRt.find(editors, selectedEditor); LOG.assertTrue(selectedProviderIndex != -1, "Can't find " + selectedEditor + " among " + Arrays.asList(editors)); final HistoryEntry entry = getEntry(file); if(entry != null){ moveOnTop(entry); } else { final FileEditorState[] states=new FileEditorState[editors.length]; final FileEditorProvider[] providers=new FileEditorProvider[editors.length]; for (int i = states.length - 1; i >= 0; i--) { final FileEditorProvider provider = oldProviders [i]; LOG.assertTrue(provider != null); providers[i] = provider; states[i] = editors[i].getState(FileEditorStateLevel.FULL); } addEntry(HistoryEntry.createHeavy(myProject, file, providers, states, providers[selectedProviderIndex])); trimToSize(); } } public void updateHistoryEntry(@Nullable final VirtualFile file, final boolean changeEntryOrderOnly) { updateHistoryEntry(file, null, null, changeEntryOrderOnly); } private void updateHistoryEntry(@Nullable final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider, final boolean changeEntryOrderOnly) { if (file == null) { return; } final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file); FileEditor[] editors = editorsWithProviders.getFirst(); FileEditorProvider[] providers = editorsWithProviders.getSecond(); if (editors.length <= 0 && fallbackEditor != null) { editors = new FileEditor[] {fallbackEditor}; providers = new FileEditorProvider[] {fallbackProvider}; } if (editors.length == 0) { // obviously not opened in any editor at the moment, // makes no sense to put the file in the history return; } final HistoryEntry entry = getEntry(file); if(entry == null){ // Size of entry list can be less than number of opened editors (some entries can be removed) if (file.isValid()) { // the file could have been deleted, so the isValid() check is essential fileOpenedImpl(file, fallbackEditor, fallbackProvider); } return; } if (!changeEntryOrderOnly) { // update entry state //LOG.assertTrue(editors.length > 0); for (int i = editors.length - 1; i >= 0; i--) { final FileEditor editor = editors [i]; final FileEditorProvider provider = providers [i]; if (!editor.isValid()) { // this can happen for example if file extension was changed // and this method was called during corresponding myEditor close up continue; } final FileEditorState oldState = entry.getState(provider); final FileEditorState newState = editor.getState(FileEditorStateLevel.FULL); if (!newState.equals(oldState)) { entry.putState(provider, newState); } } } final Pair <FileEditor, FileEditorProvider> selectedEditorWithProvider = editorManager.getSelectedEditorWithProvider(file); if (selectedEditorWithProvider != null) { //LOG.assertTrue(selectedEditorWithProvider != null); entry.setSelectedProvider(selectedEditorWithProvider.getSecond()); LOG.assertTrue(entry.getSelectedProvider() != null); if(changeEntryOrderOnly){ moveOnTop(entry); } } } /** * @return array of valid files that are in the history, oldest first. May contain duplicates. */ public synchronized VirtualFile[] getFiles(){ final List<VirtualFile> result = new ArrayList<VirtualFile>(myEntriesList.size()); for (HistoryEntry entry : myEntriesList) { VirtualFile file = entry.getFile(); if (file != null) result.add(file); } return VfsUtilCore.toVirtualFileArray(result); } /** * @return a set of valid files that are in the history, oldest first. */ public LinkedHashSet<VirtualFile> getFileSet() { LinkedHashSet<VirtualFile> result = ContainerUtil.newLinkedHashSet(); for (VirtualFile file : getFiles()) { // if the file occurs several times in the history, only its last occurrence counts result.remove(file); result.add(file); } return result; } public synchronized boolean hasBeenOpen(@NotNull VirtualFile f) { for (HistoryEntry each : myEntriesList) { if (Comparing.equal(each.getFile(), f)) return true; } return false; } /** * Removes specified <code>file</code> from history. The method does * nothing if <code>file</code> is not in the history. * * @exception IllegalArgumentException if <code>file</code> * is <code>null</code> */ public synchronized void removeFile(@NotNull final VirtualFile file){ final HistoryEntry entry = getEntry(file); if(entry != null){ removeEntry(entry); } } public FileEditorState getState(@NotNull VirtualFile file, final FileEditorProvider provider) { final HistoryEntry entry = getEntry(file); return entry != null ? entry.getState(provider) : null; } /** * @return may be null */ public FileEditorProvider getSelectedProvider(final VirtualFile file) { final HistoryEntry entry = getEntry(file); return entry != null ? entry.getSelectedProvider() : null; } private synchronized HistoryEntry getEntry(@NotNull VirtualFile file) { for (int i = myEntriesList.size() - 1; i >= 0; i--) { final HistoryEntry entry = myEntriesList.get(i); VirtualFile entryFile = entry.getFile(); if (file.equals(entryFile)) { return entry; } } return null; } /** * If total number of files in history more then <code>UISettings.RECENT_FILES_LIMIT</code> * then removes the oldest ones to fit the history to new size. */ private synchronized void trimToSize(){ final int limit = UISettings.getInstance().RECENT_FILES_LIMIT + 1; while(myEntriesList.size()>limit){ HistoryEntry removed = myEntriesList.remove(0); removed.destroy(); } } @Override public void loadState(@NotNull Element element) { // we have to delay xml processing because history entries require EditorStates to be created // which is done via corresponding EditorProviders, those are not accessible before their // is initComponent() called final Element state = element.clone(); StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new DumbAwareRunnable() { @Override public void run() { for (Element e : state.getChildren(HistoryEntry.TAG)) { try { addEntry(HistoryEntry.createHeavy(myProject, e)); } catch (InvalidDataException e1) { // OK here } catch (ProcessCanceledException e1) { // OK here } catch (Exception anyException) { LOG.error(anyException); } } trimToSize(); } }); } @Override public synchronized Element getState() { Element element = new Element("state"); // update history before saving final VirtualFile[] openFiles = FileEditorManager.getInstance(myProject).getOpenFiles(); for (int i = openFiles.length - 1; i >= 0; i--) { final VirtualFile file = openFiles[i]; // we have to update only files that are in history if (getEntry(file) != null) { updateHistoryEntry(file, false); } } for (final HistoryEntry entry : myEntriesList) { entry.writeExternal(element, myProject); } return element; } @Override public void projectOpened() { } @Override public void projectClosed() { } @Override public void initComponent() { } @Override public synchronized void disposeComponent() { for (HistoryEntry entry : myEntriesList) { entry.destroy(); } myEntriesList.clear(); } @NotNull @Override public String getComponentName() { return "editorHistoryManager"; } /** * Updates history */ private final class MyEditorManagerListener extends FileEditorManagerAdapter{ @Override public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file){ fileOpenedImpl(file, null, null); } @Override public void selectionChanged(@NotNull final FileEditorManagerEvent event){ // updateHistoryEntry does commitDocument which is 1) very expensive and 2) cannot be performed from within PSI change listener // so defer updating history entry until documents committed to improve responsiveness PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(new Runnable() { @Override public void run() { updateHistoryEntry(event.getOldFile(), event.getOldEditor(), event.getOldProvider(), false); updateHistoryEntry(event.getNewFile(), true); } }); } } }
Soya93/Extract-Refactoring
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java
Java
apache-2.0
14,211