code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#region Copyright and License Information
// Fluent Ribbon Control Suite
// http://fluent.codeplex.com/
// Copyright © Degtyarev Daniel, Rikker Serg. 2009-2010. All rights reserved.
//
// Distributed under the terms of the Microsoft Public License (Ms-PL).
// The license is available online http://fluent.codeplex.com/license
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
namespace Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Threading;
using Fluent.Extensions;
using Fluent.Internal;
/// <summary>
/// Represents backstage button
/// </summary>
[ContentProperty("Content")]
public class Backstage : RibbonControl
{
private static readonly object syncIsOpen = new object();
#region Events
/// <summary>
/// Occurs when IsOpen has been changed
/// </summary>
public event DependencyPropertyChangedEventHandler IsOpenChanged;
#endregion
#region Fields
// Adorner for backstage
BackstageAdorner adorner;
#endregion
#region Properties
#region IsOpen
/// <summary>
/// Gets or sets whether backstage is shown
/// </summary>
public bool IsOpen
{
get { return (bool)this.GetValue(IsOpenProperty); }
set { this.SetValue(IsOpenProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for IsOpen.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool),
typeof(Backstage), new UIPropertyMetadata(false, OnIsOpenChanged));
/// <summary>
/// Gets or sets the duration for the hide animation
/// </summary>
public Duration HideAnimationDuration
{
get { return (Duration)this.GetValue(HideAnimationDurationProperty); }
set { this.SetValue(HideAnimationDurationProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for HideAnimationDuration.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty HideAnimationDurationProperty = DependencyProperty.Register("HideAnimationDuration", typeof(Duration), typeof(Backstage), new PropertyMetadata(null));
/// <summary>
/// Gets or sets whether context tabs on the titlebar should be hidden when backstage is open
/// </summary>
public bool HideContextTabsOnOpen
{
get { return (bool)this.GetValue(HideContextTabsOnOpenProperty); }
set { this.SetValue(HideContextTabsOnOpenProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for HideContextTabsOnOpen.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty HideContextTabsOnOpenProperty = DependencyProperty.Register("HideContextTabsOnOpen", typeof(bool), typeof(Backstage), new PropertyMetadata(false));
private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var backstage = (Backstage)d;
lock (syncIsOpen)
{
if ((bool)e.NewValue)
{
backstage.Show();
}
else
{
if (backstage.HideAnimationDuration.HasTimeSpan)
{
var timespan = backstage.HideAnimationDuration.TimeSpan;
Task.Factory.StartNew(() =>
{
Thread.Sleep(timespan);
backstage.Dispatcher.RunInDispatcher(backstage.Hide);
});
}
else
{
backstage.Hide();
}
}
// Invoke the event
if (backstage.IsOpenChanged != null)
{
backstage.IsOpenChanged(backstage, e);
}
}
}
#endregion
#region Content
/// <summary>
/// Gets or sets content of the backstage
/// </summary>
public UIElement Content
{
get { return (UIElement)this.GetValue(ContentProperty); }
set { this.SetValue(ContentProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for Content.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(UIElement), typeof(Backstage),
new UIPropertyMetadata(null, OnContentChanged));
static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var backstage = (Backstage)d;
if (e.OldValue != null)
{
backstage.RemoveLogicalChild(e.OldValue);
}
if (e.NewValue != null)
{
backstage.AddLogicalChild(e.NewValue);
}
}
#endregion
#region LogicalChildren
/// <summary>
/// Gets an enumerator for logical child elements of this element.
/// </summary>
protected override IEnumerator LogicalChildren
{
get
{
if (this.Content != null)
{
yield return this.Content;
}
}
}
#endregion
#endregion
#region Initialization
/// <summary>
/// Static constructor
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810")]
static Backstage()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(typeof(Backstage)));
// Disable QAT for this control
CanAddToQuickAccessToolBarProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(false));
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(Backstage), new FrameworkPropertyMetadata(KeyboardNavigationMode.Cycle));
}
/// <summary>
/// Default constructor
/// </summary>
public Backstage()
{
this.Loaded += this.OnBackstageLoaded;
this.Unloaded += this.OnBackstageUnloaded;
}
private void OnPopupDismiss(object sender, DismissPopupEventArgs e)
{
this.IsOpen = false;
}
#endregion
#region Methods
// Handles click event
private void Click()
{
this.IsOpen = !this.IsOpen;
}
#region Show / Hide
// We have to collapse WindowsFormsHost while Backstate is open
private readonly Dictionary<FrameworkElement, Visibility> collapsedElements = new Dictionary<FrameworkElement, Visibility>();
// Saved window sizes
private double savedWindowMinWidth = double.NaN;
private double savedWindowMinHeight = double.NaN;
private double savedWindowWidth = double.NaN;
private double savedWindowHeight = double.NaN;
// Opens backstage on an Adorner layer
private void Show()
{
// don't open the backstage while in design mode
if (DesignerProperties.GetIsInDesignMode(this))
{
return;
}
if (this.IsLoaded == false)
{
this.Loaded += this.OnDelayedShow;
return;
}
if (this.Content == null)
{
return;
}
this.CreateAndAttachBackstageAdorner();
this.ShowAdorner();
var ribbon = this.FindRibbon();
if (ribbon != null)
{
ribbon.TabControl.IsDropDownOpen = false;
ribbon.TabControl.HighlightSelectedItem = false;
ribbon.TabControl.RequestBackstageClose += this.OnTabControlRequestBackstageClose;
// Disable QAT & title bar
if (ribbon.QuickAccessToolBar != null)
{
ribbon.QuickAccessToolBar.IsEnabled = false;
}
if (ribbon.TitleBar != null)
{
ribbon.TitleBar.IsEnabled = false;
ribbon.TitleBar.HideContextTabs = this.HideContextTabsOnOpen;
}
}
var window = Window.GetWindow(this);
this.SaveWindowSize(window);
this.SaveWindowMinSize(window);
if (window != null)
{
window.KeyDown += this.HandleWindowKeyDown;
if (this.savedWindowMinWidth < 500)
{
window.MinWidth = 500;
}
if (this.savedWindowMinHeight < 400)
{
window.MinHeight = 400;
}
window.SizeChanged += this.OnWindowSizeChanged;
// We have to collapse WindowsFormsHost while Backstage is open
this.CollapseWindowsFormsHosts(window);
}
var content = this.Content as IInputElement;
if (content != null)
{
content.Focus();
}
}
private void ShowAdorner()
{
if (this.adorner == null)
{
return;
}
this.adorner.Visibility = Visibility.Visible;
}
private void HideAdorner()
{
if (this.adorner == null)
{
return;
}
this.adorner.Visibility = Visibility.Collapsed;
}
private void CreateAndAttachBackstageAdorner()
{
if (this.adorner != null)
{
return;
}
FrameworkElement topLevelElement = null;
if (DesignerProperties.GetIsInDesignMode(this))
{
// TODO: in design mode it is required to use design time adorner
topLevelElement = (FrameworkElement)VisualTreeHelper.GetParent(this);
}
else
{
var mainWindow = Window.GetWindow(this);
if (mainWindow == null)
{
return;
}
var content = mainWindow.Content;
var fe = content as FrameworkElement; // Content may be an arbitrary .NET object when set using a databinding and using data templates.
if (fe != null)
{
topLevelElement = fe;
}
else
{
// If Content is not a FrameworkElement we try to find the ContentPresenter
// containing the template to display the content.
var contentPresenter = UIHelper.FindVisualChild<ContentPresenter>(mainWindow);
if (contentPresenter != null && contentPresenter.Content == content)
{
// set the root element of the template as the top level element.
topLevelElement = (FrameworkElement)VisualTreeHelper.GetChild(contentPresenter, 0);
}
}
}
if (topLevelElement == null)
{
return;
}
this.adorner = new BackstageAdorner(topLevelElement, this);
var layer = AdornerLayer.GetAdornerLayer(this);
layer.Add(this.adorner);
layer.CommandBindings.Add(new CommandBinding(RibbonCommands.OpenBackstage,
(sender, args) =>
{
this.IsOpen = !this.IsOpen;
}));
}
private void DestroyAdorner()
{
if (this.adorner == null)
{
return;
}
var layer = AdornerLayer.GetAdornerLayer(this);
layer.Remove(this.adorner);
this.adorner.Clear();
this.adorner = null;
}
private void OnDelayedShow(object sender, EventArgs args)
{
this.Loaded -= this.OnDelayedShow;
// Delaying show so everthing can load properly.
// If we don't run this in the background setting IsOpen=true on application start we don't have access to the Bastage from the BackstageTabControl.
this.RunInDispatcherAsync(this.Show, DispatcherPriority.Background);
}
// Hide backstage
private void Hide()
{
this.Loaded -= this.OnDelayedShow;
if (this.Content == null)
{
return;
}
if (!this.IsLoaded
|| this.adorner == null)
{
return;
}
this.HideAdorner();
var ribbon = this.FindRibbon();
if (ribbon != null)
{
ribbon.TabControl.HighlightSelectedItem = true;
ribbon.TabControl.RequestBackstageClose -= this.OnTabControlRequestBackstageClose;
// Restore enable under QAT & title bar
if (ribbon.QuickAccessToolBar != null)
{
ribbon.QuickAccessToolBar.IsEnabled = true;
ribbon.QuickAccessToolBar.Refresh();
}
if (ribbon.TitleBar != null)
{
ribbon.TitleBar.IsEnabled = true;
ribbon.TitleBar.HideContextTabs = false;
}
}
var window = Window.GetWindow(this);
if (window != null)
{
window.PreviewKeyDown -= this.HandleWindowKeyDown;
window.SizeChanged -= this.OnWindowSizeChanged;
if (double.IsNaN(this.savedWindowMinWidth) == false
&& double.IsNaN(this.savedWindowMinHeight) == false)
{
window.MinWidth = this.savedWindowMinWidth;
window.MinHeight = this.savedWindowMinHeight;
}
if (double.IsNaN(this.savedWindowWidth) == false
&& double.IsNaN(this.savedWindowHeight) == false)
{
window.Width = this.savedWindowWidth;
window.Height = this.savedWindowHeight;
}
}
// Uncollapse elements
foreach (var element in this.collapsedElements)
{
element.Key.Visibility = element.Value;
}
this.collapsedElements.Clear();
}
// Finds underlying ribbon control
private Ribbon FindRibbon()
{
DependencyObject item = this;
while (item != null
&& !(item is Ribbon))
{
item = VisualTreeHelper.GetParent(item);
}
return (Ribbon)item;
}
private void SaveWindowMinSize(Window window)
{
if (window == null)
{
this.savedWindowMinWidth = double.NaN;
this.savedWindowMinHeight = double.NaN;
return;
}
this.savedWindowMinWidth = window.MinWidth;
this.savedWindowMinHeight = window.MinHeight;
}
private void SaveWindowSize(Window window)
{
if (window == null)
{
this.savedWindowWidth = double.NaN;
this.savedWindowHeight = double.NaN;
return;
}
this.savedWindowWidth = window.ActualWidth;
this.savedWindowHeight = window.ActualHeight;
}
private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
this.SaveWindowSize(Window.GetWindow(this));
}
private void OnTabControlRequestBackstageClose(object sender, EventArgs e)
{
this.IsOpen = false;
}
// We have to collapse WindowsFormsHost while Backstage is open
private void CollapseWindowsFormsHosts(DependencyObject parent)
{
if (parent == null)
{
return;
}
var frameworkElement = parent as FrameworkElement;
// Do not hide contents in the backstage area
if (parent is BackstageAdorner) return;
if (frameworkElement != null)
{
if ((parent is HwndHost) &&
frameworkElement.Visibility != Visibility.Collapsed)
{
this.collapsedElements.Add(frameworkElement, frameworkElement.Visibility);
frameworkElement.Visibility = Visibility.Collapsed;
return;
}
}
// Traverse visual tree
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
this.CollapseWindowsFormsHosts(VisualTreeHelper.GetChild(parent, i));
}
}
/// <summary>
/// Invoked when an unhandled <see cref="E:System.Windows.Input.Keyboard.KeyDown"/> attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
/// </summary>
/// <param name="e">The <see cref="T:System.Windows.Input.KeyEventArgs"/> that contains the event data.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Handled)
{
return;
}
switch (e.Key)
{
case Key.Enter:
case Key.Space:
if (this.IsFocused)
{
this.IsOpen = !this.IsOpen;
e.Handled = true;
}
break;
}
base.OnKeyDown(e);
}
// Handles backstage Esc key keydown
private void HandleWindowKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
// only handle ESC when the backstage is open
e.Handled = this.IsOpen;
this.IsOpen = false;
}
}
private void OnBackstageLoaded(object sender, RoutedEventArgs e)
{
this.AddHandler(PopupService.DismissPopupEvent, (DismissPopupEventHandler)this.OnPopupDismiss);
}
private void OnBackstageUnloaded(object sender, RoutedEventArgs e)
{
this.RemoveHandler(PopupService.DismissPopupEvent, (DismissPopupEventHandler)this.OnPopupDismiss);
}
#endregion
#endregion
#region Overrides
/// <summary>
/// Invoked when an unhandled System.Windows.UIElement.PreviewMouseLeftButtonDown routed event reaches an element
/// in its route that is derived from this class. Implement this method to add class handling for this event.
/// </summary>
/// <param name="e">The System.Windows.Input.MouseButtonEventArgs that contains the event data.
/// The event data reports that the left mouse button was pressed.</param>
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
this.Click();
}
/// <summary>
/// Handles key tip pressed
/// </summary>
public override void OnKeyTipPressed()
{
this.IsOpen = true;
base.OnKeyTipPressed();
}
/// <summary>
/// Handles back navigation with KeyTips
/// </summary>
public override void OnKeyTipBack()
{
this.IsOpen = false;
base.OnKeyTipBack();
}
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate"/>.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (this.IsOpen)
{
this.Hide();
}
this.DestroyAdorner();
if (this.IsOpen)
{
this.Show();
}
}
#endregion
#region Quick Access Toolbar
/// <summary>
/// Gets control which represents shortcut item.
/// This item MUST be syncronized with the original
/// and send command to original one control.
/// </summary>
/// <returns>Control which represents shortcut item</returns>
public override FrameworkElement CreateQuickAccessItem()
{
throw new NotImplementedException();
}
#endregion
}
} | wskplho/Fluent.Ribbon | Fluent/Controls/Backstage.cs | C# | mit | 22,640 |
import logging
import os
import ftplib
from urlparse import urlparse
from flexget import plugin
from flexget.event import event
log = logging.getLogger('ftp')
class OutputFtp(object):
"""
Ftp Download plugin
input-url: ftp://<user>:<password>@<host>:<port>/<path to file>
Example: ftp://anonymous:anon@my-ftp-server.com:21/torrent-files-dir
config:
ftp_download:
tls: False
ftp_tmp_path: /tmp
TODO:
- Resume downloads
- create banlists files
- validate connection parameters
"""
schema = {
'type': 'object',
'properties': {
'use-ssl': {'type': 'boolean', 'default': False},
'ftp_tmp_path': {'type': 'string', 'format': 'path'},
'delete_origin': {'type': 'boolean', 'default': False}
},
'additionalProperties': False
}
def prepare_config(self, config, task):
config.setdefault('use-ssl', False)
config.setdefault('delete_origin', False)
config.setdefault('ftp_tmp_path', os.path.join(task.manager.config_base, 'temp'))
return config
def ftp_connect(self, config, ftp_url, current_path):
if config['use-ssl']:
ftp = ftplib.FTP_TLS()
else:
ftp = ftplib.FTP()
log.debug("Connecting to " + ftp_url.hostname)
ftp.connect(ftp_url.hostname, ftp_url.port)
ftp.login(ftp_url.username, ftp_url.password)
ftp.sendcmd('TYPE I')
ftp.set_pasv(True)
ftp.cwd(current_path)
return ftp
def check_connection(self, ftp, config, ftp_url, current_path):
try:
ftp.voidcmd("NOOP")
except:
ftp = self.ftp_connect(config, ftp_url, current_path)
return ftp
def on_task_download(self, task, config):
config = self.prepare_config(config, task)
for entry in task.accepted:
ftp_url = urlparse(entry.get('url'))
current_path = os.path.dirname(ftp_url.path)
try:
ftp = self.ftp_connect(config, ftp_url, current_path)
except:
entry.failed("Unable to connect to server")
break
if not os.path.isdir(config['ftp_tmp_path']):
log.debug('creating base path: %s' % config['ftp_tmp_path'])
os.mkdir(config['ftp_tmp_path'])
file_name = os.path.basename(ftp_url.path)
try:
# Directory
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.cwd(file_name)
self.ftp_walk(ftp, os.path.join(config['ftp_tmp_path'], file_name), config, ftp_url, ftp_url.path)
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.cwd('..')
if config['delete_origin']:
ftp.rmd(file_name)
except ftplib.error_perm:
# File
self.ftp_down(ftp, file_name, config['ftp_tmp_path'], config, ftp_url, current_path)
ftp.close()
def on_task_output(self, task, config):
"""Count this as an output plugin."""
def ftp_walk(self, ftp, tmp_path, config, ftp_url, current_path):
log.debug("DIR->" + ftp.pwd())
log.debug("FTP tmp_path : " + tmp_path)
try:
ftp = self.check_connection(ftp, config, ftp_url, current_path)
dirs = ftp.nlst(ftp.pwd())
except ftplib.error_perm as ex:
log.info("Error %s" % ex)
return ftp
if not dirs:
return ftp
for file_name in (path for path in dirs if path not in ('.', '..')):
file_name = os.path.basename(file_name)
try:
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.cwd(file_name)
if not os.path.isdir(tmp_path):
os.mkdir(tmp_path)
log.debug("Directory %s created" % tmp_path)
ftp = self.ftp_walk(ftp,
os.path.join(tmp_path, os.path.basename(file_name)),
config,
ftp_url,
os.path.join(current_path, os.path.basename(file_name)))
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.cwd('..')
if config['delete_origin']:
ftp.rmd(os.path.basename(file_name))
except ftplib.error_perm:
ftp = self.ftp_down(ftp, os.path.basename(file_name), tmp_path, config, ftp_url, current_path)
ftp = self.check_connection(ftp, config, ftp_url, current_path)
return ftp
def ftp_down(self, ftp, file_name, tmp_path, config, ftp_url, current_path):
log.debug("Downloading %s into %s" % (file_name, tmp_path))
if not os.path.exists(tmp_path):
os.makedirs(tmp_path)
local_file = open(os.path.join(tmp_path, file_name), 'a+b')
ftp = self.check_connection(ftp, config, ftp_url, current_path)
try:
ftp.sendcmd("TYPE I")
file_size = ftp.size(file_name)
except Exception as e:
file_size = 1
max_attempts = 5
log.info("Starting download of %s into %s" % (file_name, tmp_path))
while file_size > local_file.tell():
try:
if local_file.tell() != 0:
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.retrbinary('RETR %s' % file_name, local_file.write, local_file.tell())
else:
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.retrbinary('RETR %s' % file_name, local_file.write)
except Exception as error:
if max_attempts != 0:
log.debug("Retrying download after error %s" % error)
else:
log.error("Too many errors downloading %s. Aborting." % file_name)
break
local_file.close()
if config['delete_origin']:
ftp = self.check_connection(ftp, config, ftp_url, current_path)
ftp.delete(file_name)
return ftp
@event('plugin.register')
def register_plugin():
plugin.register(OutputFtp, 'ftp_download', api_ver=2)
| thalamus/Flexget | flexget/plugins/output/ftp_download.py | Python | mit | 6,524 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/devtools/build/v1/build_events.proto
/*
Package build is a generated protocol buffer package.
It is generated from these files:
google/devtools/build/v1/build_events.proto
google/devtools/build/v1/build_status.proto
google/devtools/build/v1/publish_build_event.proto
It has these top-level messages:
BuildEvent
StreamId
BuildStatus
PublishLifecycleEventRequest
PublishBuildToolEventStreamResponse
OrderedBuildEvent
*/
package build
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"
import google_protobuf1 "github.com/golang/protobuf/ptypes/any"
import google_protobuf2 "github.com/golang/protobuf/ptypes/timestamp"
import google_protobuf3 "github.com/golang/protobuf/ptypes/wrappers"
import _ "google.golang.org/genproto/googleapis/rpc/status"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// The type of console output stream.
type ConsoleOutputStream int32
const (
// Unspecified or unknown.
ConsoleOutputStream_UNKNOWN ConsoleOutputStream = 0
// Normal output stream.
ConsoleOutputStream_STDOUT ConsoleOutputStream = 1
// Error output stream.
ConsoleOutputStream_STDERR ConsoleOutputStream = 2
)
var ConsoleOutputStream_name = map[int32]string{
0: "UNKNOWN",
1: "STDOUT",
2: "STDERR",
}
var ConsoleOutputStream_value = map[string]int32{
"UNKNOWN": 0,
"STDOUT": 1,
"STDERR": 2,
}
func (x ConsoleOutputStream) String() string {
return proto.EnumName(ConsoleOutputStream_name, int32(x))
}
func (ConsoleOutputStream) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
// How did the event stream finish.
type BuildEvent_BuildComponentStreamFinished_FinishType int32
const (
// Unknown or unspecified; callers should never set this value.
BuildEvent_BuildComponentStreamFinished_FINISH_TYPE_UNSPECIFIED BuildEvent_BuildComponentStreamFinished_FinishType = 0
// Set by the event publisher to indicate a build event stream is
// finished.
BuildEvent_BuildComponentStreamFinished_FINISHED BuildEvent_BuildComponentStreamFinished_FinishType = 1
// Set by the WatchBuild RPC server when the publisher of a build event
// stream stops publishing events without publishing a
// BuildComponentStreamFinished event whose type equals FINISHED.
BuildEvent_BuildComponentStreamFinished_EXPIRED BuildEvent_BuildComponentStreamFinished_FinishType = 2
)
var BuildEvent_BuildComponentStreamFinished_FinishType_name = map[int32]string{
0: "FINISH_TYPE_UNSPECIFIED",
1: "FINISHED",
2: "EXPIRED",
}
var BuildEvent_BuildComponentStreamFinished_FinishType_value = map[string]int32{
"FINISH_TYPE_UNSPECIFIED": 0,
"FINISHED": 1,
"EXPIRED": 2,
}
func (x BuildEvent_BuildComponentStreamFinished_FinishType) String() string {
return proto.EnumName(BuildEvent_BuildComponentStreamFinished_FinishType_name, int32(x))
}
func (BuildEvent_BuildComponentStreamFinished_FinishType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor0, []int{0, 5, 0}
}
// Which build component generates this event stream. Each build component
// may generate one event stream.
type StreamId_BuildComponent int32
const (
// Unknown or unspecified; callers should never set this value.
StreamId_UNKNOWN_COMPONENT StreamId_BuildComponent = 0
// A component that coordinates builds.
StreamId_CONTROLLER StreamId_BuildComponent = 1
// A component that runs executables needed to complete a build.
StreamId_WORKER StreamId_BuildComponent = 2
// A component that builds something.
StreamId_TOOL StreamId_BuildComponent = 3
StreamId_DEPRECATED StreamId_BuildComponent = 4
)
var StreamId_BuildComponent_name = map[int32]string{
0: "UNKNOWN_COMPONENT",
1: "CONTROLLER",
2: "WORKER",
3: "TOOL",
4: "DEPRECATED",
}
var StreamId_BuildComponent_value = map[string]int32{
"UNKNOWN_COMPONENT": 0,
"CONTROLLER": 1,
"WORKER": 2,
"TOOL": 3,
"DEPRECATED": 4,
}
func (x StreamId_BuildComponent) String() string {
return proto.EnumName(StreamId_BuildComponent_name, int32(x))
}
func (StreamId_BuildComponent) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1, 0} }
// An event representing some state change that occured in the build. This
// message does not include field for uniquely identifying an event.
type BuildEvent struct {
// The timestamp of this event.
EventTime *google_protobuf2.Timestamp `protobuf:"bytes,1,opt,name=event_time,json=eventTime" json:"event_time,omitempty"`
// //////////////////////////////////////////////////////////////////////////
// Events that indicate a state change of a build request in the build
// queue.
//
// Types that are valid to be assigned to Event:
// *BuildEvent_InvocationAttemptStarted_
// *BuildEvent_InvocationAttemptFinished_
// *BuildEvent_BuildEnqueued_
// *BuildEvent_BuildFinished_
// *BuildEvent_ConsoleOutput_
// *BuildEvent_ComponentStreamFinished
// *BuildEvent_BazelEvent
// *BuildEvent_BuildExecutionEvent
// *BuildEvent_SourceFetchEvent
Event isBuildEvent_Event `protobuf_oneof:"event"`
}
func (m *BuildEvent) Reset() { *m = BuildEvent{} }
func (m *BuildEvent) String() string { return proto.CompactTextString(m) }
func (*BuildEvent) ProtoMessage() {}
func (*BuildEvent) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
type isBuildEvent_Event interface {
isBuildEvent_Event()
}
type BuildEvent_InvocationAttemptStarted_ struct {
InvocationAttemptStarted *BuildEvent_InvocationAttemptStarted `protobuf:"bytes,51,opt,name=invocation_attempt_started,json=invocationAttemptStarted,oneof"`
}
type BuildEvent_InvocationAttemptFinished_ struct {
InvocationAttemptFinished *BuildEvent_InvocationAttemptFinished `protobuf:"bytes,52,opt,name=invocation_attempt_finished,json=invocationAttemptFinished,oneof"`
}
type BuildEvent_BuildEnqueued_ struct {
BuildEnqueued *BuildEvent_BuildEnqueued `protobuf:"bytes,53,opt,name=build_enqueued,json=buildEnqueued,oneof"`
}
type BuildEvent_BuildFinished_ struct {
BuildFinished *BuildEvent_BuildFinished `protobuf:"bytes,55,opt,name=build_finished,json=buildFinished,oneof"`
}
type BuildEvent_ConsoleOutput_ struct {
ConsoleOutput *BuildEvent_ConsoleOutput `protobuf:"bytes,56,opt,name=console_output,json=consoleOutput,oneof"`
}
type BuildEvent_ComponentStreamFinished struct {
ComponentStreamFinished *BuildEvent_BuildComponentStreamFinished `protobuf:"bytes,59,opt,name=component_stream_finished,json=componentStreamFinished,oneof"`
}
type BuildEvent_BazelEvent struct {
BazelEvent *google_protobuf1.Any `protobuf:"bytes,60,opt,name=bazel_event,json=bazelEvent,oneof"`
}
type BuildEvent_BuildExecutionEvent struct {
BuildExecutionEvent *google_protobuf1.Any `protobuf:"bytes,61,opt,name=build_execution_event,json=buildExecutionEvent,oneof"`
}
type BuildEvent_SourceFetchEvent struct {
SourceFetchEvent *google_protobuf1.Any `protobuf:"bytes,62,opt,name=source_fetch_event,json=sourceFetchEvent,oneof"`
}
func (*BuildEvent_InvocationAttemptStarted_) isBuildEvent_Event() {}
func (*BuildEvent_InvocationAttemptFinished_) isBuildEvent_Event() {}
func (*BuildEvent_BuildEnqueued_) isBuildEvent_Event() {}
func (*BuildEvent_BuildFinished_) isBuildEvent_Event() {}
func (*BuildEvent_ConsoleOutput_) isBuildEvent_Event() {}
func (*BuildEvent_ComponentStreamFinished) isBuildEvent_Event() {}
func (*BuildEvent_BazelEvent) isBuildEvent_Event() {}
func (*BuildEvent_BuildExecutionEvent) isBuildEvent_Event() {}
func (*BuildEvent_SourceFetchEvent) isBuildEvent_Event() {}
func (m *BuildEvent) GetEvent() isBuildEvent_Event {
if m != nil {
return m.Event
}
return nil
}
func (m *BuildEvent) GetEventTime() *google_protobuf2.Timestamp {
if m != nil {
return m.EventTime
}
return nil
}
func (m *BuildEvent) GetInvocationAttemptStarted() *BuildEvent_InvocationAttemptStarted {
if x, ok := m.GetEvent().(*BuildEvent_InvocationAttemptStarted_); ok {
return x.InvocationAttemptStarted
}
return nil
}
func (m *BuildEvent) GetInvocationAttemptFinished() *BuildEvent_InvocationAttemptFinished {
if x, ok := m.GetEvent().(*BuildEvent_InvocationAttemptFinished_); ok {
return x.InvocationAttemptFinished
}
return nil
}
func (m *BuildEvent) GetBuildEnqueued() *BuildEvent_BuildEnqueued {
if x, ok := m.GetEvent().(*BuildEvent_BuildEnqueued_); ok {
return x.BuildEnqueued
}
return nil
}
func (m *BuildEvent) GetBuildFinished() *BuildEvent_BuildFinished {
if x, ok := m.GetEvent().(*BuildEvent_BuildFinished_); ok {
return x.BuildFinished
}
return nil
}
func (m *BuildEvent) GetConsoleOutput() *BuildEvent_ConsoleOutput {
if x, ok := m.GetEvent().(*BuildEvent_ConsoleOutput_); ok {
return x.ConsoleOutput
}
return nil
}
func (m *BuildEvent) GetComponentStreamFinished() *BuildEvent_BuildComponentStreamFinished {
if x, ok := m.GetEvent().(*BuildEvent_ComponentStreamFinished); ok {
return x.ComponentStreamFinished
}
return nil
}
func (m *BuildEvent) GetBazelEvent() *google_protobuf1.Any {
if x, ok := m.GetEvent().(*BuildEvent_BazelEvent); ok {
return x.BazelEvent
}
return nil
}
func (m *BuildEvent) GetBuildExecutionEvent() *google_protobuf1.Any {
if x, ok := m.GetEvent().(*BuildEvent_BuildExecutionEvent); ok {
return x.BuildExecutionEvent
}
return nil
}
func (m *BuildEvent) GetSourceFetchEvent() *google_protobuf1.Any {
if x, ok := m.GetEvent().(*BuildEvent_SourceFetchEvent); ok {
return x.SourceFetchEvent
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*BuildEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _BuildEvent_OneofMarshaler, _BuildEvent_OneofUnmarshaler, _BuildEvent_OneofSizer, []interface{}{
(*BuildEvent_InvocationAttemptStarted_)(nil),
(*BuildEvent_InvocationAttemptFinished_)(nil),
(*BuildEvent_BuildEnqueued_)(nil),
(*BuildEvent_BuildFinished_)(nil),
(*BuildEvent_ConsoleOutput_)(nil),
(*BuildEvent_ComponentStreamFinished)(nil),
(*BuildEvent_BazelEvent)(nil),
(*BuildEvent_BuildExecutionEvent)(nil),
(*BuildEvent_SourceFetchEvent)(nil),
}
}
func _BuildEvent_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*BuildEvent)
// event
switch x := m.Event.(type) {
case *BuildEvent_InvocationAttemptStarted_:
b.EncodeVarint(51<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.InvocationAttemptStarted); err != nil {
return err
}
case *BuildEvent_InvocationAttemptFinished_:
b.EncodeVarint(52<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.InvocationAttemptFinished); err != nil {
return err
}
case *BuildEvent_BuildEnqueued_:
b.EncodeVarint(53<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.BuildEnqueued); err != nil {
return err
}
case *BuildEvent_BuildFinished_:
b.EncodeVarint(55<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.BuildFinished); err != nil {
return err
}
case *BuildEvent_ConsoleOutput_:
b.EncodeVarint(56<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.ConsoleOutput); err != nil {
return err
}
case *BuildEvent_ComponentStreamFinished:
b.EncodeVarint(59<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.ComponentStreamFinished); err != nil {
return err
}
case *BuildEvent_BazelEvent:
b.EncodeVarint(60<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.BazelEvent); err != nil {
return err
}
case *BuildEvent_BuildExecutionEvent:
b.EncodeVarint(61<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.BuildExecutionEvent); err != nil {
return err
}
case *BuildEvent_SourceFetchEvent:
b.EncodeVarint(62<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SourceFetchEvent); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("BuildEvent.Event has unexpected type %T", x)
}
return nil
}
func _BuildEvent_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*BuildEvent)
switch tag {
case 51: // event.invocation_attempt_started
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_InvocationAttemptStarted)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_InvocationAttemptStarted_{msg}
return true, err
case 52: // event.invocation_attempt_finished
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_InvocationAttemptFinished)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_InvocationAttemptFinished_{msg}
return true, err
case 53: // event.build_enqueued
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_BuildEnqueued)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_BuildEnqueued_{msg}
return true, err
case 55: // event.build_finished
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_BuildFinished)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_BuildFinished_{msg}
return true, err
case 56: // event.console_output
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_ConsoleOutput)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_ConsoleOutput_{msg}
return true, err
case 59: // event.component_stream_finished
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(BuildEvent_BuildComponentStreamFinished)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_ComponentStreamFinished{msg}
return true, err
case 60: // event.bazel_event
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Any)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_BazelEvent{msg}
return true, err
case 61: // event.build_execution_event
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Any)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_BuildExecutionEvent{msg}
return true, err
case 62: // event.source_fetch_event
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Any)
err := b.DecodeMessage(msg)
m.Event = &BuildEvent_SourceFetchEvent{msg}
return true, err
default:
return false, nil
}
}
func _BuildEvent_OneofSizer(msg proto.Message) (n int) {
m := msg.(*BuildEvent)
// event
switch x := m.Event.(type) {
case *BuildEvent_InvocationAttemptStarted_:
s := proto.Size(x.InvocationAttemptStarted)
n += proto.SizeVarint(51<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_InvocationAttemptFinished_:
s := proto.Size(x.InvocationAttemptFinished)
n += proto.SizeVarint(52<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_BuildEnqueued_:
s := proto.Size(x.BuildEnqueued)
n += proto.SizeVarint(53<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_BuildFinished_:
s := proto.Size(x.BuildFinished)
n += proto.SizeVarint(55<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_ConsoleOutput_:
s := proto.Size(x.ConsoleOutput)
n += proto.SizeVarint(56<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_ComponentStreamFinished:
s := proto.Size(x.ComponentStreamFinished)
n += proto.SizeVarint(59<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_BazelEvent:
s := proto.Size(x.BazelEvent)
n += proto.SizeVarint(60<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_BuildExecutionEvent:
s := proto.Size(x.BuildExecutionEvent)
n += proto.SizeVarint(61<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *BuildEvent_SourceFetchEvent:
s := proto.Size(x.SourceFetchEvent)
n += proto.SizeVarint(62<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// Notification that the build system has attempted to run the build tool.
type BuildEvent_InvocationAttemptStarted struct {
// The number of the invocation attempt, starting at 1 and increasing by 1
// for each new attempt. Can be used to determine if there is a later
// invocation attempt replacing the current one a client is processing.
AttemptNumber int64 `protobuf:"varint,1,opt,name=attempt_number,json=attemptNumber" json:"attempt_number,omitempty"`
}
func (m *BuildEvent_InvocationAttemptStarted) Reset() { *m = BuildEvent_InvocationAttemptStarted{} }
func (m *BuildEvent_InvocationAttemptStarted) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_InvocationAttemptStarted) ProtoMessage() {}
func (*BuildEvent_InvocationAttemptStarted) Descriptor() ([]byte, []int) {
return fileDescriptor0, []int{0, 0}
}
func (m *BuildEvent_InvocationAttemptStarted) GetAttemptNumber() int64 {
if m != nil {
return m.AttemptNumber
}
return 0
}
// Notification that an invocation attempt has finished.
type BuildEvent_InvocationAttemptFinished struct {
// The exit code of the build tool.
ExitCode *google_protobuf3.Int32Value `protobuf:"bytes,2,opt,name=exit_code,json=exitCode" json:"exit_code,omitempty"`
// Final status of the invocation.
InvocationStatus *BuildStatus `protobuf:"bytes,3,opt,name=invocation_status,json=invocationStatus" json:"invocation_status,omitempty"`
}
func (m *BuildEvent_InvocationAttemptFinished) Reset() { *m = BuildEvent_InvocationAttemptFinished{} }
func (m *BuildEvent_InvocationAttemptFinished) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_InvocationAttemptFinished) ProtoMessage() {}
func (*BuildEvent_InvocationAttemptFinished) Descriptor() ([]byte, []int) {
return fileDescriptor0, []int{0, 1}
}
func (m *BuildEvent_InvocationAttemptFinished) GetExitCode() *google_protobuf3.Int32Value {
if m != nil {
return m.ExitCode
}
return nil
}
func (m *BuildEvent_InvocationAttemptFinished) GetInvocationStatus() *BuildStatus {
if m != nil {
return m.InvocationStatus
}
return nil
}
// Notification that the build request is enqueued. It could happen when
// a new build request is inserted into the build queue, or when a
// build request is put back into the build queue due to a previous build
// failure.
type BuildEvent_BuildEnqueued struct {
}
func (m *BuildEvent_BuildEnqueued) Reset() { *m = BuildEvent_BuildEnqueued{} }
func (m *BuildEvent_BuildEnqueued) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_BuildEnqueued) ProtoMessage() {}
func (*BuildEvent_BuildEnqueued) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 2} }
// Notification that the build request has finished, and no further
// invocations will occur. Note that this applies to the entire Build.
// Individual invocations trigger InvocationFinished when they finish.
type BuildEvent_BuildFinished struct {
// Final status of the build.
Status *BuildStatus `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
}
func (m *BuildEvent_BuildFinished) Reset() { *m = BuildEvent_BuildFinished{} }
func (m *BuildEvent_BuildFinished) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_BuildFinished) ProtoMessage() {}
func (*BuildEvent_BuildFinished) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 3} }
func (m *BuildEvent_BuildFinished) GetStatus() *BuildStatus {
if m != nil {
return m.Status
}
return nil
}
// Textual output written to standard output or standard error.
type BuildEvent_ConsoleOutput struct {
// The output stream type.
Type ConsoleOutputStream `protobuf:"varint,1,opt,name=type,enum=google.devtools.build.v1.ConsoleOutputStream" json:"type,omitempty"`
// The output stream content.
//
// Types that are valid to be assigned to Output:
// *BuildEvent_ConsoleOutput_TextOutput
// *BuildEvent_ConsoleOutput_BinaryOutput
Output isBuildEvent_ConsoleOutput_Output `protobuf_oneof:"output"`
}
func (m *BuildEvent_ConsoleOutput) Reset() { *m = BuildEvent_ConsoleOutput{} }
func (m *BuildEvent_ConsoleOutput) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_ConsoleOutput) ProtoMessage() {}
func (*BuildEvent_ConsoleOutput) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 4} }
type isBuildEvent_ConsoleOutput_Output interface {
isBuildEvent_ConsoleOutput_Output()
}
type BuildEvent_ConsoleOutput_TextOutput struct {
TextOutput string `protobuf:"bytes,2,opt,name=text_output,json=textOutput,oneof"`
}
type BuildEvent_ConsoleOutput_BinaryOutput struct {
BinaryOutput []byte `protobuf:"bytes,3,opt,name=binary_output,json=binaryOutput,proto3,oneof"`
}
func (*BuildEvent_ConsoleOutput_TextOutput) isBuildEvent_ConsoleOutput_Output() {}
func (*BuildEvent_ConsoleOutput_BinaryOutput) isBuildEvent_ConsoleOutput_Output() {}
func (m *BuildEvent_ConsoleOutput) GetOutput() isBuildEvent_ConsoleOutput_Output {
if m != nil {
return m.Output
}
return nil
}
func (m *BuildEvent_ConsoleOutput) GetType() ConsoleOutputStream {
if m != nil {
return m.Type
}
return ConsoleOutputStream_UNKNOWN
}
func (m *BuildEvent_ConsoleOutput) GetTextOutput() string {
if x, ok := m.GetOutput().(*BuildEvent_ConsoleOutput_TextOutput); ok {
return x.TextOutput
}
return ""
}
func (m *BuildEvent_ConsoleOutput) GetBinaryOutput() []byte {
if x, ok := m.GetOutput().(*BuildEvent_ConsoleOutput_BinaryOutput); ok {
return x.BinaryOutput
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*BuildEvent_ConsoleOutput) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _BuildEvent_ConsoleOutput_OneofMarshaler, _BuildEvent_ConsoleOutput_OneofUnmarshaler, _BuildEvent_ConsoleOutput_OneofSizer, []interface{}{
(*BuildEvent_ConsoleOutput_TextOutput)(nil),
(*BuildEvent_ConsoleOutput_BinaryOutput)(nil),
}
}
func _BuildEvent_ConsoleOutput_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*BuildEvent_ConsoleOutput)
// output
switch x := m.Output.(type) {
case *BuildEvent_ConsoleOutput_TextOutput:
b.EncodeVarint(2<<3 | proto.WireBytes)
b.EncodeStringBytes(x.TextOutput)
case *BuildEvent_ConsoleOutput_BinaryOutput:
b.EncodeVarint(3<<3 | proto.WireBytes)
b.EncodeRawBytes(x.BinaryOutput)
case nil:
default:
return fmt.Errorf("BuildEvent_ConsoleOutput.Output has unexpected type %T", x)
}
return nil
}
func _BuildEvent_ConsoleOutput_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*BuildEvent_ConsoleOutput)
switch tag {
case 2: // output.text_output
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Output = &BuildEvent_ConsoleOutput_TextOutput{x}
return true, err
case 3: // output.binary_output
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.Output = &BuildEvent_ConsoleOutput_BinaryOutput{x}
return true, err
default:
return false, nil
}
}
func _BuildEvent_ConsoleOutput_OneofSizer(msg proto.Message) (n int) {
m := msg.(*BuildEvent_ConsoleOutput)
// output
switch x := m.Output.(type) {
case *BuildEvent_ConsoleOutput_TextOutput:
n += proto.SizeVarint(2<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.TextOutput)))
n += len(x.TextOutput)
case *BuildEvent_ConsoleOutput_BinaryOutput:
n += proto.SizeVarint(3<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.BinaryOutput)))
n += len(x.BinaryOutput)
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
// Notification of the end of a build event stream published by a build
// component other than CONTROLLER (See StreamId.BuildComponents).
type BuildEvent_BuildComponentStreamFinished struct {
// How the event stream finished.
Type BuildEvent_BuildComponentStreamFinished_FinishType `protobuf:"varint,1,opt,name=type,enum=google.devtools.build.v1.BuildEvent_BuildComponentStreamFinished_FinishType" json:"type,omitempty"`
}
func (m *BuildEvent_BuildComponentStreamFinished) Reset() {
*m = BuildEvent_BuildComponentStreamFinished{}
}
func (m *BuildEvent_BuildComponentStreamFinished) String() string { return proto.CompactTextString(m) }
func (*BuildEvent_BuildComponentStreamFinished) ProtoMessage() {}
func (*BuildEvent_BuildComponentStreamFinished) Descriptor() ([]byte, []int) {
return fileDescriptor0, []int{0, 5}
}
func (m *BuildEvent_BuildComponentStreamFinished) GetType() BuildEvent_BuildComponentStreamFinished_FinishType {
if m != nil {
return m.Type
}
return BuildEvent_BuildComponentStreamFinished_FINISH_TYPE_UNSPECIFIED
}
// Unique identifier for a build event stream.
type StreamId struct {
// The id of a Build message.
BuildId string `protobuf:"bytes,1,opt,name=build_id,json=buildId" json:"build_id,omitempty"`
// The unique invocation ID within this build.
// It should be the same as {invocation} (below) during the migration.
InvocationId string `protobuf:"bytes,6,opt,name=invocation_id,json=invocationId" json:"invocation_id,omitempty"`
// The component that emitted this event.
Component StreamId_BuildComponent `protobuf:"varint,3,opt,name=component,enum=google.devtools.build.v1.StreamId_BuildComponent" json:"component,omitempty"`
// The unique invocation ID within this build.
// It should be the same as {invocation_id} below during the migration.
Invocation string `protobuf:"bytes,4,opt,name=invocation" json:"invocation,omitempty"`
}
func (m *StreamId) Reset() { *m = StreamId{} }
func (m *StreamId) String() string { return proto.CompactTextString(m) }
func (*StreamId) ProtoMessage() {}
func (*StreamId) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *StreamId) GetBuildId() string {
if m != nil {
return m.BuildId
}
return ""
}
func (m *StreamId) GetInvocationId() string {
if m != nil {
return m.InvocationId
}
return ""
}
func (m *StreamId) GetComponent() StreamId_BuildComponent {
if m != nil {
return m.Component
}
return StreamId_UNKNOWN_COMPONENT
}
func (m *StreamId) GetInvocation() string {
if m != nil {
return m.Invocation
}
return ""
}
func init() {
proto.RegisterType((*BuildEvent)(nil), "google.devtools.build.v1.BuildEvent")
proto.RegisterType((*BuildEvent_InvocationAttemptStarted)(nil), "google.devtools.build.v1.BuildEvent.InvocationAttemptStarted")
proto.RegisterType((*BuildEvent_InvocationAttemptFinished)(nil), "google.devtools.build.v1.BuildEvent.InvocationAttemptFinished")
proto.RegisterType((*BuildEvent_BuildEnqueued)(nil), "google.devtools.build.v1.BuildEvent.BuildEnqueued")
proto.RegisterType((*BuildEvent_BuildFinished)(nil), "google.devtools.build.v1.BuildEvent.BuildFinished")
proto.RegisterType((*BuildEvent_ConsoleOutput)(nil), "google.devtools.build.v1.BuildEvent.ConsoleOutput")
proto.RegisterType((*BuildEvent_BuildComponentStreamFinished)(nil), "google.devtools.build.v1.BuildEvent.BuildComponentStreamFinished")
proto.RegisterType((*StreamId)(nil), "google.devtools.build.v1.StreamId")
proto.RegisterEnum("google.devtools.build.v1.ConsoleOutputStream", ConsoleOutputStream_name, ConsoleOutputStream_value)
proto.RegisterEnum("google.devtools.build.v1.BuildEvent_BuildComponentStreamFinished_FinishType", BuildEvent_BuildComponentStreamFinished_FinishType_name, BuildEvent_BuildComponentStreamFinished_FinishType_value)
proto.RegisterEnum("google.devtools.build.v1.StreamId_BuildComponent", StreamId_BuildComponent_name, StreamId_BuildComponent_value)
}
func init() { proto.RegisterFile("google/devtools/build/v1/build_events.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 948 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0xed, 0x6e, 0xe3, 0x54,
0x10, 0x8d, 0xdb, 0xd2, 0x26, 0xd3, 0x24, 0xeb, 0xbd, 0xcb, 0xaa, 0x8e, 0x5b, 0x2d, 0x50, 0x54,
0x09, 0x81, 0x70, 0xd4, 0x14, 0xb4, 0x0b, 0x4b, 0x57, 0xca, 0x87, 0xab, 0x98, 0x2d, 0x76, 0x74,
0xe3, 0xb2, 0x7c, 0x08, 0x05, 0xc7, 0xbe, 0xcd, 0x5a, 0x4a, 0x7c, 0x8d, 0x7d, 0x1d, 0x1a, 0x24,
0x04, 0xcf, 0xc1, 0x03, 0x20, 0xf1, 0x22, 0xbc, 0x12, 0xfc, 0x44, 0xbe, 0xd7, 0x6e, 0x92, 0xb6,
0xe9, 0x6e, 0xd9, 0x7f, 0xf6, 0xcc, 0x99, 0x73, 0x66, 0xc6, 0x67, 0xa2, 0xc0, 0x47, 0x23, 0x4a,
0x47, 0x63, 0x52, 0xf7, 0xc8, 0x94, 0x51, 0x3a, 0x8e, 0xeb, 0xc3, 0xc4, 0x1f, 0x7b, 0xf5, 0xe9,
0xa1, 0x78, 0x18, 0x90, 0x29, 0x09, 0x58, 0xac, 0x85, 0x11, 0x65, 0x14, 0x29, 0x02, 0xac, 0xe5,
0x60, 0x8d, 0x63, 0xb4, 0xe9, 0xa1, 0xba, 0x97, 0xd1, 0x38, 0xa1, 0x5f, 0x77, 0x82, 0x80, 0x32,
0x87, 0xf9, 0x34, 0xc8, 0xea, 0xd4, 0x57, 0x89, 0xc4, 0xcc, 0x61, 0x49, 0x0e, 0xae, 0x65, 0x60,
0xfe, 0x36, 0x4c, 0xce, 0xeb, 0x4e, 0x30, 0xcb, 0x52, 0xef, 0x5c, 0x4d, 0x31, 0x7f, 0x42, 0x62,
0xe6, 0x4c, 0xc2, 0x0c, 0xf0, 0xe8, 0x2a, 0xe0, 0xe7, 0xc8, 0x09, 0x43, 0x12, 0xe5, 0xdc, 0x3b,
0x59, 0x3e, 0x0a, 0xdd, 0xfa, 0xa2, 0xe8, 0xfe, 0x3f, 0x65, 0x80, 0x56, 0xda, 0x8b, 0x9e, 0xce,
0x8b, 0x3e, 0x03, 0xe0, 0x83, 0x0f, 0x52, 0x01, 0x45, 0x7a, 0x57, 0xfa, 0x60, 0xbb, 0xa1, 0x6a,
0xd9, 0xf4, 0x39, 0xb9, 0x66, 0xe7, 0xea, 0xb8, 0xc4, 0xd1, 0xe9, 0x3b, 0xfa, 0x15, 0x54, 0x3f,
0x98, 0x52, 0x97, 0x2f, 0x60, 0xe0, 0x30, 0x46, 0x26, 0x21, 0x4b, 0x27, 0x8c, 0x18, 0xf1, 0x94,
0x23, 0x4e, 0x75, 0xac, 0xad, 0x5a, 0xa4, 0x36, 0x6f, 0x42, 0x33, 0x2e, 0x69, 0x9a, 0x82, 0xa5,
0x2f, 0x48, 0xba, 0x05, 0xac, 0xf8, 0x2b, 0x72, 0xe8, 0x77, 0x09, 0x76, 0x6f, 0xd0, 0x3f, 0xf7,
0x03, 0x3f, 0x7e, 0x49, 0x3c, 0xe5, 0x13, 0xde, 0xc0, 0xb3, 0xff, 0xd7, 0xc0, 0x49, 0xc6, 0xd2,
0x2d, 0xe0, 0x9a, 0xbf, 0x2a, 0x89, 0xbe, 0x87, 0x6a, 0xe6, 0x9d, 0xe0, 0xa7, 0x84, 0x24, 0xc4,
0x53, 0x3e, 0xe5, 0xa2, 0x8d, 0xd7, 0x12, 0x15, 0x8f, 0x59, 0x65, 0xb7, 0x80, 0x2b, 0xc3, 0xc5,
0xc0, 0x9c, 0xfc, 0x72, 0xa2, 0xc7, 0x77, 0x25, 0x5f, 0x98, 0x42, 0x90, 0x2f, 0x76, 0xee, 0xd2,
0x20, 0xa6, 0x63, 0x32, 0xa0, 0x09, 0x0b, 0x13, 0xa6, 0x3c, 0xb9, 0x03, 0x79, 0x5b, 0x94, 0x5a,
0xbc, 0x32, 0x25, 0x77, 0x17, 0x03, 0xe8, 0x37, 0xa8, 0xb9, 0x74, 0x12, 0xd2, 0x20, 0xf5, 0x55,
0xcc, 0x22, 0xe2, 0x4c, 0xe6, 0x43, 0x3c, 0xe5, 0x3a, 0xcd, 0xd7, 0x1f, 0xa2, 0x9d, 0x53, 0xf5,
0x39, 0xd3, 0xc2, 0x4c, 0x3b, 0xee, 0xcd, 0x29, 0xf4, 0x18, 0xb6, 0x87, 0xce, 0x2f, 0x64, 0x2c,
0x6e, 0x5a, 0xf9, 0x82, 0x4b, 0xbe, 0x7d, 0xcd, 0xd5, 0xcd, 0x60, 0xd6, 0x2d, 0x60, 0xe0, 0x50,
0x71, 0x0d, 0x5f, 0xc2, 0xc3, 0xec, 0x83, 0x5e, 0x10, 0x37, 0xe1, 0xbe, 0x12, 0x14, 0xc7, 0xb7,
0x52, 0x3c, 0x10, 0x5f, 0x2e, 0xaf, 0x11, 0x5c, 0x1d, 0x40, 0x31, 0x4d, 0x22, 0x97, 0x0c, 0xce,
0x09, 0x73, 0x5f, 0x66, 0x44, 0xcf, 0x6e, 0x25, 0x92, 0x45, 0xc5, 0x49, 0x5a, 0xc0, 0x59, 0xd4,
0x26, 0x28, 0xab, 0xae, 0x03, 0x1d, 0x40, 0x35, 0x77, 0x7d, 0x90, 0x4c, 0x86, 0x24, 0xe2, 0xf7,
0xbb, 0x8e, 0x2b, 0x59, 0xd4, 0xe4, 0x41, 0xf5, 0x2f, 0x09, 0x6a, 0x2b, 0x0d, 0x8e, 0x9e, 0x40,
0x89, 0x5c, 0xf8, 0x6c, 0xe0, 0x52, 0x8f, 0x28, 0x6b, 0xbc, 0xbb, 0xdd, 0x6b, 0xdd, 0x19, 0x01,
0x3b, 0x6a, 0x7c, 0xed, 0x8c, 0x13, 0x82, 0x8b, 0x29, 0xba, 0x4d, 0x3d, 0x82, 0x30, 0xdc, 0x5f,
0xb8, 0x3f, 0xf1, 0x23, 0xa3, 0xac, 0x73, 0x86, 0x83, 0x57, 0x7c, 0xde, 0x3e, 0x07, 0x63, 0x79,
0x5e, 0x2f, 0x22, 0xea, 0x3d, 0xa8, 0x2c, 0x9d, 0x85, 0x6a, 0x66, 0x81, 0xcb, 0x7e, 0x8f, 0x61,
0x33, 0x93, 0x92, 0xee, 0x22, 0x95, 0x15, 0xa9, 0x7f, 0x4a, 0x50, 0x59, 0xb2, 0x2f, 0x6a, 0xc2,
0x06, 0x9b, 0x85, 0xe2, 0xb7, 0xaf, 0xda, 0xf8, 0x78, 0x35, 0xdd, 0x52, 0x99, 0x70, 0x1c, 0xe6,
0xa5, 0xe8, 0x3d, 0xd8, 0x66, 0xe4, 0x82, 0xe5, 0xa7, 0x94, 0x6e, 0xb1, 0x94, 0x3a, 0x2b, 0x0d,
0x66, 0x2a, 0x07, 0x50, 0x19, 0xfa, 0x81, 0x13, 0xcd, 0x72, 0x50, 0xba, 0xa8, 0x72, 0xb7, 0x80,
0xcb, 0x22, 0x2c, 0x60, 0xad, 0x22, 0x6c, 0x8a, 0xbc, 0xfa, 0xb7, 0x04, 0x7b, 0xb7, 0xf9, 0x1f,
0xfd, 0xb8, 0xd4, 0xf7, 0xe9, 0x1b, 0x1f, 0x94, 0x26, 0x1e, 0xec, 0x59, 0x48, 0xc4, 0x58, 0xfb,
0x1d, 0x80, 0x79, 0x0c, 0xed, 0xc2, 0xce, 0x89, 0x61, 0x1a, 0xfd, 0xee, 0xc0, 0xfe, 0xb6, 0xa7,
0x0f, 0xce, 0xcc, 0x7e, 0x4f, 0x6f, 0x1b, 0x27, 0x86, 0xde, 0x91, 0x0b, 0xa8, 0x0c, 0x45, 0x91,
0xd4, 0x3b, 0xb2, 0x84, 0xb6, 0x61, 0x4b, 0xff, 0xa6, 0x67, 0x60, 0xbd, 0x23, 0xaf, 0xb5, 0xb6,
0xe0, 0x2d, 0x6e, 0xfd, 0xfd, 0x3f, 0xd6, 0xa0, 0x28, 0x24, 0x0d, 0x0f, 0xd5, 0xa0, 0x28, 0x2e,
0xcd, 0xf7, 0xf8, 0x04, 0x25, 0xbc, 0xc5, 0xdf, 0x0d, 0x0f, 0xbd, 0x0f, 0x95, 0x05, 0x5f, 0xf9,
0x9e, 0xb2, 0xc9, 0xf3, 0xe5, 0x79, 0xd0, 0xf0, 0x90, 0x05, 0xa5, 0xcb, 0xeb, 0xe7, 0xbb, 0xac,
0x36, 0x0e, 0x57, 0xaf, 0x20, 0x97, 0xbd, 0xb2, 0x00, 0x3c, 0xe7, 0x40, 0x8f, 0x00, 0xe6, 0x02,
0xca, 0x06, 0x97, 0x5c, 0x88, 0xec, 0xff, 0x00, 0xd5, 0xe5, 0x62, 0xf4, 0x10, 0xee, 0x9f, 0x99,
0xcf, 0x4d, 0xeb, 0x85, 0x39, 0x68, 0x5b, 0x5f, 0xf5, 0x2c, 0x53, 0x37, 0x6d, 0xb9, 0x80, 0xaa,
0x00, 0x6d, 0xcb, 0xb4, 0xb1, 0x75, 0x7a, 0xaa, 0x63, 0x59, 0x42, 0x00, 0x9b, 0x2f, 0x2c, 0xfc,
0x5c, 0xc7, 0xf2, 0x1a, 0x2a, 0xc2, 0x86, 0x6d, 0x59, 0xa7, 0xf2, 0x7a, 0x8a, 0xea, 0xe8, 0x3d,
0xac, 0xb7, 0x9b, 0xb6, 0xde, 0x91, 0x37, 0x3e, 0xfc, 0x1c, 0x1e, 0xdc, 0xe0, 0xaf, 0x74, 0x93,
0x99, 0x86, 0x5c, 0x48, 0x99, 0xfa, 0x76, 0xc7, 0x3a, 0xb3, 0x05, 0x6b, 0xdf, 0xee, 0xe8, 0x18,
0xcb, 0x6b, 0xad, 0x18, 0xf6, 0x5c, 0x3a, 0x59, 0x39, 0x7d, 0xeb, 0xde, 0xdc, 0x01, 0xbd, 0xf4,
0xa2, 0x7b, 0xd2, 0x77, 0xc7, 0x19, 0x78, 0x44, 0xc7, 0x4e, 0x30, 0xd2, 0x68, 0x34, 0xaa, 0x8f,
0x48, 0xc0, 0xef, 0xbd, 0x2e, 0x52, 0x4e, 0xe8, 0xc7, 0xd7, 0xff, 0xc6, 0x3c, 0xe5, 0x0f, 0xff,
0x4a, 0xd2, 0x70, 0x93, 0x83, 0x8f, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x95, 0xa8, 0xb7, 0x58,
0x57, 0x09, 0x00, 0x00,
}
| disintegration/bebop | vendor/google.golang.org/genproto/googleapis/devtools/build/v1/build_events.pb.go | GO | mit | 34,543 |
class AgentReemitJob < ActiveJob::Base
# Given an Agent, re-emit all of agent's events up to (and including) `most_recent_event_id`
def perform(agent, most_recent_event_id, delete_old_events = false)
# `find_each` orders by PK, so events get re-created in the same order
agent.events.where("id <= ?", most_recent_event_id).find_each do |event|
event.reemit!
event.destroy if delete_old_events
end
end
end
| strugee/huginn | app/jobs/agent_reemit_job.rb | Ruby | mit | 435 |
<?php
namespace Josegonzalez\Upload\Validation\Traits;
trait ImageValidationTrait
{
/**
* Check that the file is above the minimum width requirement
*
* @param mixed $check Value to check
* @param int $width Width of Image
* @return bool Success
*/
public static function isAboveMinWidth($check, $width)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list($imgWidth) = getimagesize($check['tmp_name']);
return $width > 0 && $imgWidth >= $width;
}
/**
* Check that the file is below the maximum width requirement
*
* @param mixed $check Value to check
* @param int $width Width of Image
* @return bool Success
*/
public static function isBelowMaxWidth($check, $width)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list($imgWidth) = getimagesize($check['tmp_name']);
return $width > 0 && $imgWidth <= $width;
}
/**
* Check that the file is above the minimum height requirement
*
* @param mixed $check Value to check
* @param int $height Height of Image
* @return bool Success
*/
public static function isAboveMinHeight($check, $height)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list(, $imgHeight) = getimagesize($check['tmp_name']);
return $height > 0 && $imgHeight >= $height;
}
/**
* Check that the file is below the maximum height requirement
*
* @param mixed $check Value to check
* @param int $height Height of Image
* @return bool Success
*/
public static function isBelowMaxHeight($check, $height)
{
// Non-file uploads also mean the height is too big
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
return false;
}
list(, $imgHeight) = getimagesize($check['tmp_name']);
return $height > 0 && $imgHeight <= $height;
}
}
| Phillaf/cakephp-upload | src/Validation/Traits/ImageValidationTrait.php | PHP | mit | 2,309 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* 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
*/
package org.openhab.binding.nest.handler;
import static org.eclipse.smarthome.core.library.types.OnOffType.OFF;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.openhab.binding.nest.NestBindingConstants.*;
import static org.openhab.binding.nest.internal.data.NestDataUtil.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.binding.builder.ThingBuilder;
import org.junit.Test;
import org.openhab.binding.nest.internal.config.NestStructureConfiguration;
/**
* Tests for {@link NestStructureHandler}.
*
* @author Wouter Born - Increase test coverage
*/
public class NestStructureHandlerTest extends NestThingHandlerOSGiTest {
private static final ThingUID STRUCTURE_UID = new ThingUID(THING_TYPE_STRUCTURE, "structure1");
private static final int CHANNEL_COUNT = 11;
public NestStructureHandlerTest() {
super(NestStructureHandler.class);
}
@Override
protected Thing buildThing(Bridge bridge) {
Map<String, Object> properties = new HashMap<>();
properties.put(NestStructureConfiguration.STRUCTURE_ID, STRUCTURE1_STRUCTURE_ID);
return ThingBuilder.create(THING_TYPE_STRUCTURE, STRUCTURE_UID).withLabel("Test Structure")
.withBridge(bridge.getUID()).withChannels(buildChannels(THING_TYPE_STRUCTURE, STRUCTURE_UID))
.withConfiguration(new Configuration(properties)).build();
}
@Test
public void completeStructureUpdate() throws IOException {
assertThat(thing.getChannels().size(), is(CHANNEL_COUNT));
assertThat(thing.getStatus(), is(ThingStatus.OFFLINE));
waitForAssert(() -> assertThat(bridge.getStatus(), is(ThingStatus.ONLINE)));
putStreamingEventData(fromFile(COMPLETE_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.ONLINE)));
assertThatItemHasState(CHANNEL_AWAY, new StringType("HOME"));
assertThatItemHasState(CHANNEL_CO_ALARM_STATE, new StringType("OK"));
assertThatItemHasState(CHANNEL_COUNTRY_CODE, new StringType("US"));
assertThatItemHasState(CHANNEL_ETA_BEGIN, parseDateTimeType("2017-02-02T03:10:08.000Z"));
assertThatItemHasState(CHANNEL_PEAK_PERIOD_END_TIME, parseDateTimeType("2017-07-01T01:03:08.400Z"));
assertThatItemHasState(CHANNEL_PEAK_PERIOD_START_TIME, parseDateTimeType("2017-06-01T13:31:10.870Z"));
assertThatItemHasState(CHANNEL_POSTAL_CODE, new StringType("98056"));
assertThatItemHasState(CHANNEL_RUSH_HOUR_REWARDS_ENROLLMENT, OFF);
assertThatItemHasState(CHANNEL_SECURITY_STATE, new StringType("OK"));
assertThatItemHasState(CHANNEL_SMOKE_ALARM_STATE, new StringType("OK"));
assertThatItemHasState(CHANNEL_TIME_ZONE, new StringType("America/Los_Angeles"));
assertThatAllItemStatesAreNotNull();
}
@Test
public void incompleteStructureUpdate() throws IOException {
assertThat(thing.getChannels().size(), is(CHANNEL_COUNT));
assertThat(thing.getStatus(), is(ThingStatus.OFFLINE));
waitForAssert(() -> assertThat(bridge.getStatus(), is(ThingStatus.ONLINE)));
putStreamingEventData(fromFile(COMPLETE_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.ONLINE)));
assertThatAllItemStatesAreNotNull();
putStreamingEventData(fromFile(INCOMPLETE_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.ONLINE)));
assertThatAllItemStatesAreNull();
}
@Test
public void structureGone() throws IOException {
waitForAssert(() -> assertThat(bridge.getStatus(), is(ThingStatus.ONLINE)));
putStreamingEventData(fromFile(COMPLETE_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.ONLINE)));
putStreamingEventData(fromFile(EMPTY_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.OFFLINE)));
assertThat(thing.getStatusInfo().getStatusDetail(), is(ThingStatusDetail.GONE));
}
@Test
public void channelRefresh() throws IOException {
waitForAssert(() -> assertThat(bridge.getStatus(), is(ThingStatus.ONLINE)));
putStreamingEventData(fromFile(COMPLETE_DATA_FILE_NAME));
waitForAssert(() -> assertThat(thing.getStatus(), is(ThingStatus.ONLINE)));
assertThatAllItemStatesAreNotNull();
updateAllItemStatesToNull();
assertThatAllItemStatesAreNull();
refreshAllChannels();
assertThatAllItemStatesAreNotNull();
}
@Test
public void handleAwayCommands() throws IOException {
handleCommand(CHANNEL_AWAY, new StringType("AWAY"));
assertNestApiPropertyState(STRUCTURE1_STRUCTURE_ID, "away", "away");
handleCommand(CHANNEL_AWAY, new StringType("HOME"));
assertNestApiPropertyState(STRUCTURE1_STRUCTURE_ID, "away", "home");
handleCommand(CHANNEL_AWAY, new StringType("AWAY"));
assertNestApiPropertyState(STRUCTURE1_STRUCTURE_ID, "away", "away");
}
}
| Mr-Eskildsen/openhab2-addons | addons/binding/org.openhab.binding.nest.test/src/test/java/org/openhab/binding/nest/handler/NestStructureHandlerTest.java | Java | epl-1.0 | 5,857 |
/*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2014, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the Eclipse Public License 1.0 as
* published by the Free Software Foundation.
*
* 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 Eclipse
* Public License for more details.
*
* You should have received a copy of the Eclipse 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.ironjacamar.common.api.metadata.spec;
import org.ironjacamar.common.api.metadata.CopyableMetaData;
import java.util.List;
/**
*
* An Activationspec
*
* @author <a href="stefano.maestri@ironjacamar.org">Stefano Maestri</a>
*
*/
public interface Activationspec extends IdDecoratedMetadata, CopyableMetaData<Activationspec>
{
/**
* @return activationspecClass
*/
public XsdString getActivationspecClass();
/**
* @return requiredConfigProperty
*/
public List<RequiredConfigProperty> getRequiredConfigProperties();
/**
* @return configProperty
*/
public List<ConfigProperty> getConfigProperties();
}
| darranl/ironjacamar | common/src/main/java/org/ironjacamar/common/api/metadata/spec/Activationspec.java | Java | epl-1.0 | 1,596 |
/*
* Error.java
*
* Copyright (c) 2012 Mike Strobel
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0.
* A copy of the license can be found in the License.html file at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*/
package com.strobel.reflection;
import static java.lang.String.format;
/**
* @author Mike Strobel
*/
final class Error {
private Error() {
}
public static RuntimeException notGenericParameter(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a generic parameter.",
type.getFullName()
)
);
}
public static RuntimeException notWildcard(final Type type) {
throw new UnsupportedOperationException(
format(
"Type '%s' is not a wildcard or captured type.",
type.getFullName()
)
);
}
public static RuntimeException notBoundedType(final Type type) {
throw new UnsupportedOperationException(
format(
"Type '%s' is not a bounded type.",
type.getFullName()
)
);
}
public static RuntimeException notGenericType(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a generic type.",
type.getFullName()
)
);
}
public static RuntimeException notGenericMethod(final MethodInfo method) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a generic method.",
method.getName()
)
);
}
public static RuntimeException notGenericMethodDefinition(final MethodInfo method) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a generic method definition.",
method.getName()
)
);
}
public static RuntimeException noElementType(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' does not have an element type.",
type.getFullName()
)
);
}
public static RuntimeException notEnumType(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not an enum type.",
type.getFullName()
)
);
}
public static RuntimeException notArrayType(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not an array type.",
type.getFullName()
)
);
}
public static RuntimeException ambiguousMatch() {
return new RuntimeException("Ambiguous match found.");
}
public static RuntimeException incorrectNumberOfTypeArguments() {
return new UnsupportedOperationException(
"Incorrect number of type arguments provided."
);
}
public static RuntimeException incorrectNumberOfTypeArguments(final Type type) {
return new UnsupportedOperationException(
format(
"Incorrect number of type arguments provided for generic type '%s'.",
type.getFullName()
)
);
}
public static RuntimeException notGenericTypeDefinition(final Type type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a generic type definition.",
type.getFullName()
)
);
}
public static RuntimeException notPrimitiveType(final Class<?> type) {
return new UnsupportedOperationException(
format(
"Type '%s' is not a primitive type.",
type.getName()
)
);
}
public static RuntimeException typeParameterNotDefined(final Type typeParameter) {
return new UnsupportedOperationException(
format(
"Generic parameter '%s' is not defined on this type.",
typeParameter.getFullName()
)
);
}
public static RuntimeException couldNotResolveMethod(final Object signature) {
return new RuntimeException(
format(
"Could not resolve method '%s'.",
signature
)
);
}
public static RuntimeException couldNotResolveMember(final MemberInfo member) {
return new MemberResolutionException(member);
}
public static RuntimeException couldNotResolveType(final Object signature) {
return new RuntimeException(
format(
"Could not resolve type '%s'.",
signature
)
);
}
public static RuntimeException couldNotResolveParameterType(final Object signature) {
return new RuntimeException(
format(
"Could not resolve type for parameter '%s'.",
signature
)
);
}
public static RuntimeException typeArgumentsMustContainBoundType() {
return new RuntimeException(
"Type arguments must bind at least one generic parameter."
);
}
public static RuntimeException compoundTypeMayOnlyHaveOneClassBound() {
return new RuntimeException(
"Compound types may only be bounded by one class, and it must be the first type in " +
"the bound list. All other bounds must be interface types."
);
}
public static RuntimeException compoundTypeMayNotHaveGenericParameterBound() {
return new RuntimeException(
"Compound types may not be bounded by a generic parameter."
);
}
public static RuntimeException typeCannotBeInstantiated(final Type<?> t) {
return new IllegalStateException(
format("Type '%s' cannot be instantiated.", t)
);
}
public static RuntimeException typeInstantiationFailed(final Type<?> t, final Throwable cause) {
return new IllegalStateException(
format("Failed to instantiate type '%s'.", t),
cause
);
}
public static RuntimeException rawFieldBindingFailure(final FieldInfo field) {
return new IllegalStateException(
format(
"Could not bind to runtime field '%s' on type '%s'.",
field.getDescription(),
field.getDeclaringType().toString()
)
);
}
public static RuntimeException rawMethodBindingFailure(final MethodBase method) {
return new IllegalStateException(
format(
"Could not bind to runtime method '%s' on type '%s'.",
method.getDescription(),
method.getDeclaringType().toString()
)
);
}
public static RuntimeException targetInvocationException(final Throwable cause) {
return new TargetInvocationException(cause);
}
public static MemberResolutionException couldNotResolveMatchingConstructor() {
return new MemberResolutionException(
"Could not find a constructor matching the provided arguments."
);
}
public static RuntimeException invalidAncestorType(final Type<?> ancestorType, final Type<?> declaringType) {
return new RuntimeException(
format(
"Type '%s' is not an ancestor of type '%s'.",
ancestorType.getFullName(),
declaringType.getFullName()
)
);
}
public static RuntimeException invalidSignatureTypeExpected(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: type expected at position %d (%s).",
position,
signature
)
);
}
public static RuntimeException invalidSignatureTopLevelGenericParameterUnexpected(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: unexpected generic parameter at position %d. (%s)",
position,
signature
)
);
}
public static RuntimeException invalidSignatureNonGenericTypeTypeArguments(final Type<?> type) {
return new IllegalArgumentException(
format(
"Invalid signature: unexpected type arguments specified for non-generic type '%s'.",
type.getBriefDescription()
)
);
}
public static RuntimeException invalidSignatureUnexpectedToken(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: unexpected token at position %d. (%s)",
position,
signature
)
);
}
public static RuntimeException invalidSignatureUnexpectedEnd(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: unexpected end of signature at position %d. (%s)",
position,
signature
)
);
}
public static RuntimeException invalidSignatureExpectedEndOfTypeArguments(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: expected end of type argument list at position %d. (%s)",
position,
signature
)
);
}
public static RuntimeException invalidSignatureExpectedTypeArgument(final String signature, final int position) {
return new IllegalArgumentException(
format(
"Invalid signature: expected type argument at position %d. (%s)",
position,
signature
)
);
}
}
| sgilda/windup | forks/procyon/Procyon.Reflection/src/main/java/com/strobel/reflection/Error.java | Java | epl-1.0 | 10,687 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.organization.api.resource;
import static java.util.Arrays.asList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.commons.lang.Size;
import org.eclipse.che.multiuser.organization.api.OrganizationManager;
import org.eclipse.che.multiuser.organization.shared.model.Organization;
import org.eclipse.che.multiuser.organization.spi.impl.OrganizationImpl;
import org.eclipse.che.multiuser.resource.api.free.DefaultResourcesProvider;
import org.eclipse.che.multiuser.resource.api.type.RamResourceType;
import org.eclipse.che.multiuser.resource.api.type.RuntimeResourceType;
import org.eclipse.che.multiuser.resource.api.type.TimeoutResourceType;
import org.eclipse.che.multiuser.resource.api.type.WorkspaceResourceType;
import org.eclipse.che.multiuser.resource.spi.impl.ResourceImpl;
/**
* Provided free resources that are available for usage by organizational accounts by default.
*
* @author Sergii Leschenko
*/
@Singleton
public class DefaultOrganizationResourcesProvider implements DefaultResourcesProvider {
private final OrganizationManager organizationManager;
private final long ramPerOrganization;
private final int workspacesPerOrganization;
private final int runtimesPerOrganization;
private final long timeout;
@Inject
public DefaultOrganizationResourcesProvider(
OrganizationManager organizationManager,
@Named("che.limits.organization.workspaces.ram") String ramPerOrganization,
@Named("che.limits.organization.workspaces.count") int workspacesPerOrganization,
@Named("che.limits.organization.workspaces.run.count") int runtimesPerOrganization,
@Named("che.limits.workspace.idle.timeout") long timeout) {
this.timeout = TimeUnit.MILLISECONDS.toMinutes(timeout);
this.organizationManager = organizationManager;
this.ramPerOrganization =
"-1".equals(ramPerOrganization) ? -1 : Size.parseSizeToMegabytes(ramPerOrganization);
this.workspacesPerOrganization = workspacesPerOrganization;
this.runtimesPerOrganization = runtimesPerOrganization;
}
@Override
public String getAccountType() {
return OrganizationImpl.ORGANIZATIONAL_ACCOUNT;
}
@Override
public List<ResourceImpl> getResources(String accountId)
throws ServerException, NotFoundException {
final Organization organization = organizationManager.getById(accountId);
// only root organizations should have own resources
if (organization.getParent() == null) {
return asList(
new ResourceImpl(TimeoutResourceType.ID, timeout, TimeoutResourceType.UNIT),
new ResourceImpl(RamResourceType.ID, ramPerOrganization, RamResourceType.UNIT),
new ResourceImpl(
WorkspaceResourceType.ID, workspacesPerOrganization, WorkspaceResourceType.UNIT),
new ResourceImpl(
RuntimeResourceType.ID, runtimesPerOrganization, RuntimeResourceType.UNIT));
}
return Collections.emptyList();
}
}
| akervern/che | multiuser/api/che-multiuser-api-organization/src/main/java/org/eclipse/che/multiuser/organization/api/resource/DefaultOrganizationResourcesProvider.java | Java | epl-1.0 | 3,553 |
class DropRepositoryReferencePublisherHref < ActiveRecord::Migration[5.2]
def change
remove_column :katello_repository_references, :publisher_href
end
end
| Katello/katello | db/migrate/20190513162209_drop_repository_reference_publisher_href.rb | Ruby | gpl-2.0 | 163 |
<?php
/*
Template Name: Content / Sidebar
*/
?><?php get_header(); ?>
<div id="container">
<section id="content">
<?php if( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<div class="entry">
<?php if( esplanade_get_option( 'breadcrumbs' ) ) : ?>
<div id="location">
<?php esplanade_breadcrumbs(); ?>
</div><!-- #location -->
<?php endif; ?>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<div class="clear"></div>
</div><!-- .entry-content -->
<?php wp_link_pages( array( 'before' => '<footer class="entry-utility"><p class="post-pagination">' . __( 'Pages:', 'esplanade' ), 'after' => '</p></footer><!-- .entry-utility -->' ) ); ?>
</div><!-- .entry -->
<?php comments_template(); ?>
</article><!-- .post -->
<?php else : ?>
<?php esplanade_404(); ?>
<?php endif; ?>
</section><!-- #content -->
<?php get_sidebar(); ?>
</div><!-- #container -->
<?php get_footer(); ?> | sudocoda/boynamedsu-wp | wp-content/themes/esplanade/template-content-sidebar.php | PHP | gpl-2.0 | 1,162 |
// objective: allow linking to private virtual functions
// check: class_interface.xml
// config: EXTRACT_PRIV_VIRTUAL = YES
/** @brief An interface */
class Interface {
public:
/**
* @brief Load things.
*
* Calls @ref doLoad().
*/
void load();
private:
/**
* @brief Pure virtual implementation for @ref load()
*
* Details.
*/
virtual void doLoad() = 0;
/**
* @brief Non-pure virtual function
*
* Details.
*/
virtual void doOtherStuff();
/* Undocumented, should not appear in the docs */
virtual void doSomethingUndocumented();
/** @brief A non-virtual private function, not extracted */
void someUtility();
};
| ellert/doxygen | testing/080_extract_private_virtual.cpp | C++ | gpl-2.0 | 720 |
/*
* Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "Creature.h"
#include "GameObject.h"
#include "InstanceScript.h"
#include "zulgurub.h"
DoorData const doorData[] =
{
{ GO_VENOXIS_COIL, DATA_VENOXIS, DOOR_TYPE_ROOM },
{ GO_ARENA_DOOR_1, DATA_MANDOKIR, DOOR_TYPE_ROOM },
{ GO_FORCEFIELD, DATA_KILNARA, DOOR_TYPE_ROOM },
{ GO_ZANZIL_DOOR, DATA_ZANZIL, DOOR_TYPE_ROOM },
//{ GO_THE_CACHE_OF_MADNESS_DOOR, DATA_xxxxxxx, DOOR_TYPE_ROOM },
{ 0, 0, DOOR_TYPE_ROOM }
};
class instance_zulgurub : public InstanceMapScript
{
public:
instance_zulgurub() : InstanceMapScript(ZGScriptName, 859) { }
struct instance_zulgurub_InstanceMapScript : public InstanceScript
{
instance_zulgurub_InstanceMapScript(InstanceMap* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadDoorData(doorData);
}
void OnCreatureCreate(Creature* creature) override
{
switch (creature->GetEntry())
{
case NPC_VENOXIS:
venoxisGUID = creature->GetGUID();
break;
case NPC_MANDOKIR:
mandokirGUID = creature->GetGUID();
break;
case NPC_KILNARA:
kilnaraGUID = creature->GetGUID();
break;
case NPC_ZANZIL:
zanzilGUID = creature->GetGUID();
break;
case NPC_JINDO:
jindoGUID = creature->GetGUID();
break;
case NPC_HAZZARAH:
hazzarahGUID = creature->GetGUID();
break;
case NPC_RENATAKI:
renatakiGUID = creature->GetGUID();
break;
case NPC_WUSHOOLAY:
wushoolayGUID = creature->GetGUID();
break;
case NPC_GRILEK:
grilekGUID = creature->GetGUID();
break;
case NPC_JINDO_TRIGGER:
jindoTiggerGUID = creature->GetGUID();
break;
default:
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_VENOXIS_COIL:
case GO_ARENA_DOOR_1:
case GO_FORCEFIELD:
case GO_ZANZIL_DOOR:
case GO_THE_CACHE_OF_MADNESS_DOOR:
AddDoor(go, true);
break;
default:
break;
}
}
void OnGameObjectRemove(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_VENOXIS_COIL:
case GO_ARENA_DOOR_1:
case GO_FORCEFIELD:
case GO_ZANZIL_DOOR:
case GO_THE_CACHE_OF_MADNESS_DOOR:
AddDoor(go, false);
break;
default:
break;
}
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_VENOXIS:
case DATA_MANDOKIR:
case DATA_KILNARA:
case DATA_ZANZIL:
case DATA_JINDO:
case DATA_HAZZARAH:
case DATA_RENATAKI:
case DATA_WUSHOOLAY:
case DATA_GRILEK:
break;
default:
break;
}
return true;
}
/*
void SetData(uint32 type, uint32 data) override
{
switch (type)
{
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
}
return 0;
}
*/
ObjectGuid GetGuidData(uint32 type) const override
{
switch (type)
{
case DATA_VENOXIS:
return venoxisGUID;
case DATA_MANDOKIR:
return mandokirGUID;
case DATA_KILNARA:
return kilnaraGUID;
case DATA_ZANZIL:
return zanzilGUID;
case DATA_JINDO:
return jindoGUID;
case DATA_HAZZARAH:
return hazzarahGUID;
case DATA_RENATAKI:
return renatakiGUID;
case DATA_WUSHOOLAY:
return wushoolayGUID;
case DATA_GRILEK:
return grilekGUID;
case DATA_JINDOR_TRIGGER:
return jindoTiggerGUID;
default:
break;
}
return ObjectGuid::Empty;
}
protected:
ObjectGuid venoxisGUID;
ObjectGuid mandokirGUID;
ObjectGuid kilnaraGUID;
ObjectGuid zanzilGUID;
ObjectGuid jindoGUID;
ObjectGuid hazzarahGUID;
ObjectGuid renatakiGUID;
ObjectGuid wushoolayGUID;
ObjectGuid grilekGUID;
ObjectGuid jindoTiggerGUID;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_zulgurub_InstanceMapScript(map);
}
};
void AddSC_instance_zulgurub()
{
new instance_zulgurub();
}
| Golrag/TrinityCore | src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp | C++ | gpl-2.0 | 7,268 |
/* This test script is part of GDB, the GNU debugger.
Copyright 2006-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* Author: Paul N. Hilfinger, AdaCore Inc. */
struct Parent {
Parent (int id0) : id(id0) { }
int id;
};
struct Child : public Parent {
Child (int id0) : Parent(id0) { }
};
int f1(Parent& R)
{
return R.id; /* Set breakpoint marker3 here. */
}
int f2(Child& C)
{
return f1(C); /* Set breakpoint marker2 here. */
}
struct OtherParent {
OtherParent (int other_id0) : other_id(other_id0) { }
int other_id;
};
struct MultiChild : public Parent, OtherParent {
MultiChild (int id0) : Parent(id0), OtherParent(id0 * 2) { }
};
int mf1(OtherParent& R)
{
return R.other_id;
}
int mf2(MultiChild& C)
{
return mf1(C);
}
int main(void)
{
Child Q(42);
Child& QR = Q;
/* Set breakpoint marker1 here. */
f2(Q);
f2(QR);
MultiChild MQ(53);
MultiChild& MQR = MQ;
mf2(MQ); /* Set breakpoint MQ here. */
}
| totalspectrum/binutils-propeller | gdb/testsuite/gdb.cp/ref-params.cc | C++ | gpl-2.0 | 1,600 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.3 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2013 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2013
* $Id$
*
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
class CRM_Project_DAO_Task extends CRM_Core_DAO
{
/**
* static instance to hold the table name
*
* @var string
* @static
*/
static $_tableName = 'civicrm_task';
/**
* static instance to hold the field values
*
* @var array
* @static
*/
static $_fields = null;
/**
* static instance to hold the FK relationships
*
* @var string
* @static
*/
static $_links = null;
/**
* static instance to hold the values that can
* be imported
*
* @var array
* @static
*/
static $_import = null;
/**
* static instance to hold the values that can
* be exported
*
* @var array
* @static
*/
static $_export = null;
/**
* static value to see if we should log any modifications to
* this table in the civicrm_log table
*
* @var boolean
* @static
*/
static $_log = true;
/**
* Task ID
*
* @var int unsigned
*/
public $id;
/**
* Task name.
*
* @var string
*/
public $title;
/**
* Optional verbose description of the Task. May be used for display - HTML allowed.
*
* @var string
*/
public $description;
/**
* Configurable task type values (e.g. App Submit, App Review...). FK to civicrm_option_value.
*
* @var int unsigned
*/
public $task_type_id;
/**
* Name of table where Task owner being referenced is stored (e.g. civicrm_contact or civicrm_group).
*
* @var string
*/
public $owner_entity_table;
/**
* Foreign key to Task owner (contact, group, etc.).
*
* @var int unsigned
*/
public $owner_entity_id;
/**
* Name of table where optional Task parent is stored (e.g. civicrm_project, or civicrm_task for sub-tasks).
*
* @var string
*/
public $parent_entity_table;
/**
* Optional foreign key to Task Parent (project, another task, etc.).
*
* @var int unsigned
*/
public $parent_entity_id;
/**
* Task due date.
*
* @var datetime
*/
public $due_date;
/**
* Configurable priority value (e.g. Critical, High, Medium...). FK to civicrm_option_value.
*
* @var int unsigned
*/
public $priority_id;
/**
* Optional key to a process class related to this task (e.g. CRM_Quest_PreApp).
*
* @var string
*/
public $task_class;
/**
* Is this record active? For tasks: can it be assigned, does it appear on open task listings, etc.
*
* @var boolean
*/
public $is_active;
/**
* class constructor
*
* @access public
* @return civicrm_task
*/
function __construct()
{
$this->__table = 'civicrm_task';
parent::__construct();
}
/**
* returns all the column names of this table
*
* @access public
* @return array
*/
static function &fields()
{
if (!(self::$_fields)) {
self::$_fields = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'required' => true,
) ,
'title' => array(
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Title') ,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
) ,
'description' => array(
'name' => 'description',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Description') ,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
) ,
'task_type_id' => array(
'name' => 'task_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Task Type') ,
) ,
'owner_entity_table' => array(
'name' => 'owner_entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Owner Entity Table') ,
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
) ,
'owner_entity_id' => array(
'name' => 'owner_entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Task Owner ID') ,
'required' => true,
) ,
'parent_entity_table' => array(
'name' => 'parent_entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Parent Entity Table') ,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
) ,
'parent_entity_id' => array(
'name' => 'parent_entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Task Parent') ,
) ,
'due_date' => array(
'name' => 'due_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Due Date') ,
) ,
'priority_id' => array(
'name' => 'priority_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Priority') ,
) ,
'task_class' => array(
'name' => 'task_class',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Task Class') ,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Active?') ,
) ,
);
}
return self::$_fields;
}
/**
* returns the names of this table
*
* @access public
* @static
* @return string
*/
static function getTableName()
{
return self::$_tableName;
}
/**
* returns if this table needs to be logged
*
* @access public
* @return boolean
*/
function getLog()
{
return self::$_log;
}
/**
* returns the list of fields that can be imported
*
* @access public
* return array
* @static
*/
static function &import($prefix = false)
{
if (!(self::$_import)) {
self::$_import = array();
$fields = self::fields();
foreach($fields as $name => $field) {
if (CRM_Utils_Array::value('import', $field)) {
if ($prefix) {
self::$_import['task'] = & $fields[$name];
} else {
self::$_import[$name] = & $fields[$name];
}
}
}
}
return self::$_import;
}
/**
* returns the list of fields that can be exported
*
* @access public
* return array
* @static
*/
static function &export($prefix = false)
{
if (!(self::$_export)) {
self::$_export = array();
$fields = self::fields();
foreach($fields as $name => $field) {
if (CRM_Utils_Array::value('export', $field)) {
if ($prefix) {
self::$_export['task'] = & $fields[$name];
} else {
self::$_export[$name] = & $fields[$name];
}
}
}
}
return self::$_export;
}
}
| tomlagier/NoblePower | wp-content/plugins/civicrm/civicrm/CRM/Project/DAO/Task.php | PHP | gpl-2.0 | 8,570 |
<?php
/**
*
* Orders table
*
* @package VirtueMart
* @subpackage Orders
* @author RolandD
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: orders.php 6210 2012-07-04 00:15:41Z Milbo $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
if(!class_exists('VmTableData'))require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmtabledata.php');
/**
* Orders table class
* The class is is used to manage the orders in the shop.
*
* @package VirtueMart
* @author RolandD
* @author Max Milbers
*/
class TableOrders extends VmTableData {
/** @var int Primary key */
var $virtuemart_order_id = 0;
/** @var int User ID */
var $virtuemart_user_id = 0;
/** @var int Vendor ID */
var $virtuemart_vendor_id = 0;
/** @var int Order number */
var $order_number = NULL;
var $order_pass = NULL;
var $customer_number = NULL;
/** @var decimal Order total */
var $order_total = 0.00000;
/** @var decimal Products sales prices */
var $order_salesPrice = 0.00000;
/** @var decimal Order Bill Tax amount */
var $order_billTaxAmount = 0.00000;
/** @var string Order Bill Tax */
var $order_billTax = 0;
/** @var decimal Order Bill Tax amount */
var $order_billDiscountAmount = 0.00000;
/** @var decimal Order Products Discount amount */
var $order_discountAmount = 0.00000;
/** @var decimal Order subtotal */
var $order_subtotal = 0.00000;
/** @var decimal Order tax */
var $order_tax = 0.00000;
/** @var decimal Shipment costs */
var $order_shipment = 0.00000;
/** @var decimal Shipment cost tax */
var $order_shipment_tax = 0.00000;
/** @var decimal Shipment costs */
var $order_payment = 0.00000;
/** @var decimal Shipment cost tax */
var $order_payment_tax = 0.00000;
/** @var decimal Coupon value */
var $coupon_discount = 0.00000;
/** @var string Coupon code */
var $coupon_code = NULL;
/** @var decimal Order discount */
var $order_discount = 0.00000;
/** @var string Order currency */
var $order_currency = NULL;
/** @var char Order status */
var $order_status = NULL;
/** @var char User currency id */
var $user_currency_id = NULL;
/** @var char User currency rate */
var $user_currency_rate = NULL;
/** @var int Payment method ID */
var $virtuemart_paymentmethod_id = NULL;
/** @var int Shipment method ID */
var $virtuemart_shipmentmethod_id = NULL;
/** @var text Customer note */
var $customer_note = 0;
/** @var string Users IP Address */
var $ip_address = 0;
/** @var char Order language */
var $order_language = NULL;
var $delivery_date = NULL;
/**
*
* @author Max Milbers
* @param $db Class constructor; connect to the database
*
*/
function __construct($db) {
parent::__construct('#__virtuemart_orders', 'virtuemart_order_id', $db);
$this->setUniqueName('order_number');
$this->setLoggable();
$this->setTableShortCut('o');
}
function check(){
if(empty($this->order_number)){
if(!class_exists('VirtueMartModelOrders')) require(JPATH_VM_ADMINISTRATOR.DS.'models'.DS.'orders.php');
$this->order_number = VirtueMartModelOrders::generateOrderNumber((string)time());
}
if(empty($this->order_pass)){
$this->order_pass = 'p_'.substr( md5((string)time().$this->order_number ), 0, 5);
}
$adminID = JFactory::getSession()->get('vmAdminID');
if(isset($adminID)) {
$this->created_by = $adminID;
}
return parent::check();
}
/**
* Overloaded delete() to delete records from order_userinfo and order payment as well,
* and write a record to the order history (TODO Or should the hist table be cleaned as well?)
*
* @var integer Order id
* @return boolean True on success
* @author Oscar van Eijk
* @author Kohl Patrick
*/
function delete( $id=null , $where = 0 ){
$this->_db->setQuery('DELETE from `#__virtuemart_order_userinfos` WHERE `virtuemart_order_id` = ' . $id);
if ($this->_db->query() === false) {
vmError($this->_db->getError());
return false;
}
/*vm_order_payment NOT EXIST have to find the table name*/
$this->_db->setQuery( 'SELECT `payment_element` FROM `#__virtuemart_paymentmethods` , `#__virtuemart_orders`
WHERE `#__virtuemart_paymentmethods`.`virtuemart_paymentmethod_id` = `#__virtuemart_orders`.`virtuemart_paymentmethod_id` AND `virtuemart_order_id` = ' . $id );
$paymentTable = '#__virtuemart_payment_plg_'. $this->_db->loadResult();
$this->_db->setQuery('DELETE from `'.$paymentTable.'` WHERE `virtuemart_order_id` = ' . $id);
if ($this->_db->query() === false) {
vmError($this->_db->getError());
return false;
} /*vm_order_shipment NOT EXIST have to find the table name*/
$this->_db->setQuery( 'SELECT `shipment_element` FROM `#__virtuemart_shipmentmethods` , `#__virtuemart_orders`
WHERE `#__virtuemart_shipmentmethods`.`virtuemart_shipmentmethod_id` = `#__virtuemart_orders`.`virtuemart_shipmentmethod_id` AND `virtuemart_order_id` = ' . $id );
$shipmentName = $this->_db->loadResult();
if(empty($shipmentName)){
vmError('Seems the used shipmentmethod got deleted');
//Can we securely prevent this just using
// 'SELECT `shipment_element` FROM `#__virtuemart_shipmentmethods` , `#__virtuemart_orders`
// WHERE `#__virtuemart_shipmentmethods`.`virtuemart_shipmentmethod_id` = `#__virtuemart_orders`.`virtuemart_shipmentmethod_id` AND `virtuemart_order_id` = ' . $id );
} else {
$shipmentTable = '#__virtuemart_shipment_plg_'. $shipmentName;
$this->_db->setQuery('DELETE from `'.$shipmentTable.'` WHERE `virtuemart_order_id` = ' . $id);
if ($this->_db->query() === false) {
vmError('TableOrders delete Order shipmentTable = '.$shipmentTable.' `virtuemart_order_id` = '.$id.' dbErrorMsg '.$this->_db->getError());
return false;
}
}
$_q = 'INSERT INTO `#__virtuemart_order_histories` ('
. ' virtuemart_order_history_id'
. ',virtuemart_order_id'
. ',order_status_code'
. ',created_on'
. ',customer_notified'
. ',comments'
.') VALUES ('
. ' NULL'
. ','.$id
. ",'-'"
. ',NOW()'
. ',0'
. ",'Order deleted'"
.')';
$this->_db->setQuery($_q);
$this->_db->query(); // Ignore error here
return parent::delete($id);
}
}
| snake77se/proyectoszeppelin | tmp/install_546526882469b/administrator/components/com_virtuemart/tables/orders.php | PHP | gpl-2.0 | 6,575 |
<?php
global $siw_social_accounts;
extract($args);
$siw_title = empty($instance['title']) ? 'Follow Us' : apply_filters('widget_title', $instance['title']);
$siw_icons = $instance['icons'];
$siw_labels = $instance['labels'];
$siw_show_title = $instance['show_title'];
echo $before_widget;
if($siw_show_title == '') {
echo $before_title;
echo $siw_title;
echo $after_title;
}
if($siw_labels == 'show') { $ul_class = 'show-labels '; }
else { $ul_class = ''; }
$ul_class .= 'icons-'.$siw_icons;
?>
<?php echo apply_filters('social_icon_opening_tag', '<ul class="'.$ul_class.'">'); ?>
<?php foreach($siw_social_accounts as $siw_title => $id) : ?>
<?php if($instance[$id] != '' && $instance[$id] != 'http://') :
global $siw_data;
global $siw_icon_output;
$siw_data['id'] = $id;
$siw_data['url'] = $instance[$id];
$siw_custom_sizes = array('custom_small','custom_medium','custom_large');
if (in_array($siw_icons, $siw_custom_sizes)) {
$size = str_replace("custom_","",$siw_icons);
$siw_icon_path = STYLESHEETPATH .'/social_icons/'.$size.'/'.$id.'.{gif,jpg,jpeg,png}';
}
else {
$siw_abs_path = str_replace('lib/', '', plugin_dir_path( __FILE__ ));
/* Fix for Windows/XAMPP where the slash goes the wrong way.
Thanks to VictoriousK */
$siw_abs_path = str_replace('\\', '/', $siw_abs_path);
$siw_icon_path = $siw_abs_path . 'icons/'.$siw_icons.'/'.$id.'.{gif,jpg,jpeg,png}';
if($siw_icons == 'large') { $imgsize = 'height="64" width="64"'; }
elseif($siw_icons == 'medium') { $imgsize = 'height="32" width="32"'; }
elseif($siw_icons == 'small') { $imgsize = 'height="16" width="16"'; }
}
$result = glob( $siw_icon_path, GLOB_BRACE );
if($result) {
if (in_array($siw_icons, $siw_custom_sizes)) {
$siw_path = explode('themes', $result[0]);
$siw_icon = get_bloginfo('url').'/wp-content/themes'.$siw_path[1];
}
else {
$siw_path = explode('plugins', $result[0]);
$siw_icon = plugins_url().''.$siw_path[1];
}
}
elseif( $siw_labels != 'show' && $siw_icons != 'small' ) {
$siw_icon = plugins_url().'/social-media-icons-widget/icons/'.$siw_icons.'/_unknown.jpg';
}
else {
$siw_icon = '';
}
if ( $siw_icon ) { $siw_data['image'] = '<img class="site-icon" src="'.$siw_icon.'" alt="'.$siw_title.'" title="'.$siw_title.'" '.$imgsize.' />'; }
else { $siw_data['image'] = ''; }
if($siw_labels != 'show') { $siw_data['title'] = ''; }
else { $siw_data['title'] = '<span class="site-label">'.$siw_title.'</span>'; }
$format = '<li class="%1$s"><a href="%2$s" target="_blank">%3$s%4$s</a></li>';
$siw_icon_output = apply_filters('social_icon_output', $format);
echo vsprintf($siw_icon_output, $siw_data);
?>
<?php endif; ?>
<?php endforeach; ?>
<?php echo apply_filters('social_icon_closing_tag', '</ul>'); ?>
<?php
echo $after_widget;
?> | talhaobject90/quotekart | wp-content/plugins/social-media-icons-widget/lib/widget.php | PHP | gpl-2.0 | 2,863 |
<?php
/****************************************************
* @class : RSSFeedItem
* @parent : RSSFeedBase
* @abstract : no
* @aim : create a new item instance for the feed
* @author : Hugo 'Emacs' HAMON
* @email : webmaster[at]apprendre-php[dot]com
* @version : 1.0
* @changelog :
***************************************************/
class RSSFeedItem extends RSSFeedBase
{
// Attributes
private $_itemAuthor = array();
private $_itemEnclosure = array();
private $_itemGuid = array();
private $_itemSource = array();
private $_comments = '';
// Constructor
/****************************************************
* @function : __construct
* @aim : create the instance of the class
* @access : public
* @static : no
* @param : string $encoding
* @return : void
***************************************************/
public function __construct() {}
// Destructor
/****************************************************
* @function : __destruct
* @aim : delete the instance from the memory
* @access : public
* @static : no
* @param : void
* @return : void
***************************************************/
public function __destruct() {}
// SET methods
/****************************************************
* @function : setAuthor
* @aim : set the item author element
* @access : public
* @static : no
* @param : string $email
* @param : string $name
* @return : void
***************************************************/
public function setAuthor($email, $name='')
{
$this->_itemAuthor['email'] = RSSFeedTools::checkEmail($email);
$this->_itemAuthor['name'] = $name;
}
/****************************************************
* @function : setComments
* @aim : set the item comments element
* @access : public
* @static : no
* @param : string $url
* @return : void
***************************************************/
public function setComments($url)
{
$this->_comments = RSSFeedTools::checkUrl($url);
}
/****************************************************
* @function : setEnclosure
* @aim : set the item enclosure element
* @access : public
* @static : no
* @param : string $url
* @param : int $length
* @param : string $mimeType
* @return : void
***************************************************/
public function setEnclosure($url, $length, $mimeType)
{
if(!empty($url)
&& !empty($length)
&& is_numeric($length)
&& ($length>0)
&& !empty($mimeType))
{
$this->_itemEnclosure['url'] = RSSFeedTools::checkUrl($url);
$this->_itemEnclosure['length'] = intval($length);
$this->_itemEnclosure['type'] = $mimeType;
}
}
/****************************************************
* @function : setGuid
* @aim : set the item guid element
* @access : public
* @static : no
* @param : string $guid
* @param : bool $isPermaLink
* @return : void
***************************************************/
public function setGuid($guid, $isPermaLink=false)
{
if(true === $isPermaLink)
{
$this->_itemGuid['isPermaLink'] = 'true';
}
else
{
$this->_itemGuid['isPermaLink'] = 'false';
}
$this->_itemGuid['content'] = $guid;
}
/****************************************************
* @function : setSource
* @aim : set the item source element
* @access : public
* @static : no
* @param : string $url
* @param : string $content
* @return : void
***************************************************/
public function setSource($url, $content)
{
if(!empty($url) && !empty($content))
{
$this->_itemSource['url'] = RSSFeedTools::checkUrl($url);
$this->_itemSource['content'] = $content;
}
}
// GET methods
/****************************************************
* @function : getAuthor
* @aim : get the item author element
* @access : public
* @static : no
* @param : void
* @return : array $this->_itemAuthor
***************************************************/
public function getAuthor()
{
return $this->_itemAuthor;
}
/****************************************************
* @function : getComments
* @aim : get the item comments element
* @access : public
* @static : no
* @param : void
* @return : string $this->_comments
***************************************************/
public function getComments()
{
return $this->_comments;
}
/****************************************************
* @function : getEnclosure
* @aim : get the item enclosure element
* @access : public
* @static : no
* @param : void
* @return : array $this->_itemEnclosure
***************************************************/
public function getEnclosure()
{
return $this->_itemEnclosure;
}
/****************************************************
* @function : getGuid
* @aim : get the item guid element
* @access : public
* @static : no
* @param : void
* @return : array $this->_itemGuid
***************************************************/
public function getGuid()
{
return $this->_itemGuid;
}
/****************************************************
* @function : getSource
* @aim : get the item source element
* @access : public
* @static : no
* @param : void
* @return : array $this->_itemSource
***************************************************/
public function getSource()
{
return $this->_itemSource;
}
// Other methods
// END CLASS
}
?> | Regis85/gepi | class_php/RSSFeed/RSSFeedItem.class.php | PHP | gpl-2.0 | 5,379 |
/* $Id: RTPathCopyComponents.cpp $ */
/** @file
* IPRT - RTPathCountComponents
*/
/*
* Copyright (C) 2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include "internal/iprt.h"
#include <iprt/path.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/string.h>
#include "internal/path.h"
RTDECL(int) RTPathCopyComponents(char *pszDst, size_t cbDst, const char *pszSrc, size_t cComponents)
{
/*
* Quick input validation.
*/
AssertPtr(pszDst);
AssertPtr(pszSrc);
if (cbDst == 0)
return VERR_BUFFER_OVERFLOW;
/*
* Fend of the simple case where nothing is wanted.
*/
if (cComponents == 0)
{
*pszDst = '\0';
return VINF_SUCCESS;
}
/*
* Parse into the path until we've counted the desired number of objects
* or hit the end.
*/
size_t off = rtPathRootSpecLen(pszSrc);
size_t c = off != 0;
while (c < cComponents && pszSrc[off])
{
c++;
while (!RTPATH_IS_SLASH(pszSrc[off]) && pszSrc[off])
off++;
while (RTPATH_IS_SLASH(pszSrc[off]))
off++;
}
/*
* Copy up to but not including 'off'.
*/
if (off >= cbDst)
return VERR_BUFFER_OVERFLOW;
memcpy(pszDst, pszSrc, off);
pszDst[off] = '\0';
return VINF_SUCCESS;
}
| VirtualMonitor/VirtualMonitor | src/VBox/Runtime/common/path/RTPathCopyComponents.cpp | C++ | gpl-2.0 | 2,491 |
# -*- coding: utf-8 -*-
"""
***************************************************************************
extractprojection.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'September 2013'
__copyright__ = '(C) 2013, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.QtGui import QIcon
from osgeo import gdal, osr
from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
from processing.core.parameters import ParameterRaster
from processing.core.parameters import ParameterBoolean
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
class ExtractProjection(GdalAlgorithm):
INPUT = 'INPUT'
PRJ_FILE = 'PRJ_FILE'
def __init__(self):
super().__init__()
def initAlgorithm(self, config=None):
self.addParameter(ParameterRaster(self.INPUT, self.tr('Input file')))
self.addParameter(ParameterBoolean(self.PRJ_FILE,
self.tr('Create also .prj file'), False))
def name(self):
return 'extractprojection'
def displayName(self):
return self.tr('Extract projection')
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'projection-export.png'))
def group(self):
return self.tr('Raster projections')
def groupId(self):
return 'rasterprojections'
def getConsoleCommands(self, parameters, context, feedback, executing=True):
return ["extractprojection"]
def processAlgorithm(self, parameters, context, feedback):
rasterPath = self.getParameterValue(self.INPUT)
createPrj = self.getParameterValue(self.PRJ_FILE)
raster = gdal.Open(str(rasterPath))
crs = raster.GetProjection()
geotransform = raster.GetGeoTransform()
raster = None
outFileName = os.path.splitext(str(rasterPath))[0]
if crs != '' and createPrj:
tmp = osr.SpatialReference()
tmp.ImportFromWkt(crs)
tmp.MorphToESRI()
crs = tmp.ExportToWkt()
tmp = None
with open(outFileName + '.prj', 'wt') as prj:
prj.write(crs)
with open(outFileName + '.wld', 'wt') as wld:
wld.write('%0.8f\n' % geotransform[1])
wld.write('%0.8f\n' % geotransform[4])
wld.write('%0.8f\n' % geotransform[2])
wld.write('%0.8f\n' % geotransform[5])
wld.write('%0.8f\n' % (geotransform[0] +
0.5 * geotransform[1] +
0.5 * geotransform[2]))
wld.write('%0.8f\n' % (geotransform[3] +
0.5 * geotransform[4] +
0.5 * geotransform[5]))
| CS-SI/QGIS | python/plugins/processing/algs/gdal/extractprojection.py | Python | gpl-2.0 | 3,629 |
// license:BSD-3-Clause
// copyright-holders:Tomasz Slanina, Pierpaolo Prazzoli
/*
Dynamic Dice (??)
Driver by
Tomasz Slanina
Pierpaolo Prazzoli
--
Old, rusty, not working pcb :
Main PCB :
m5l8080ap (8080)
dy_1.bin (1H)
dy_2.bin (1L)
dy_3.bin (1P)
dip 6x (all off)
xtal 18.432 mhz
--
Sub PCB DYNA-529-81ST :
AY-3-8910
Z80
dy_4.bin
dy_5.bin
dy_6.bin (near Z80)
*/
#include "emu.h"
#include "cpu/i8085/i8085.h"
#include "cpu/z80/z80.h"
#include "machine/gen_latch.h"
#include "machine/nvram.h"
#include "sound/ay8910.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
#include "tilemap.h"
class dynadice_state : public driver_device
{
public:
dynadice_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_videoram(*this, "videoram"),
m_maincpu(*this, "maincpu"),
m_gfxdecode(*this, "gfxdecode"),
m_ay8910(*this, "ay8910")
{ }
void dynadice(machine_config &config);
void init_dynadice();
protected:
virtual void machine_start() override;
virtual void machine_reset() override;
virtual void video_start() override;
private:
/* memory pointers */
required_shared_ptr<uint8_t> m_videoram;
// uint8_t * m_nvram; // currently this uses generic nvram handling
required_device<cpu_device> m_maincpu;
required_device<gfxdecode_device> m_gfxdecode;
required_device<ay8910_device> m_ay8910;
/* video-related */
tilemap_t *m_bg_tilemap;
tilemap_t *m_top_tilemap;
/* misc */
int m_ay_data;
void videoram_w(offs_t offset, uint8_t data);
void sound_data_w(uint8_t data);
void sound_control_w(uint8_t data);
TILE_GET_INFO_MEMBER(get_tile_info);
uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void dynadice_io_map(address_map &map);
void dynadice_map(address_map &map);
void dynadice_sound_io_map(address_map &map);
void dynadice_sound_map(address_map &map);
};
void dynadice_state::videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
m_top_tilemap->mark_all_dirty();
}
void dynadice_state::sound_data_w(uint8_t data)
{
m_ay_data = data;
}
void dynadice_state::sound_control_w(uint8_t data)
{
/*
AY 3-8910 :
D0 - BC1
D1 - BC2
D2 - BDIR
D3 - /Reset
*/
if ((data & 7) == 7)
m_ay8910->address_w(m_ay_data);
if ((data & 7) == 6)
m_ay8910->data_w(m_ay_data);
}
void dynadice_state::dynadice_map(address_map &map)
{
map(0x0000, 0x1fff).rom();
map(0x2000, 0x23ff).ram().w(FUNC(dynadice_state::videoram_w)).share("videoram");
map(0x4000, 0x40ff).ram().share("nvram");
}
void dynadice_state::dynadice_io_map(address_map &map)
{
map(0x50, 0x50).portr("IN0");
map(0x51, 0x51).portr("IN1");
map(0x52, 0x52).portr("DSW");
map(0x62, 0x62).nopw();
map(0x63, 0x63).w("soundlatch", FUNC(generic_latch_8_device::write));
map(0x70, 0x77).nopw();
}
void dynadice_state::dynadice_sound_map(address_map &map)
{
map(0x0000, 0x07ff).rom();
map(0x2000, 0x23ff).ram();
}
void dynadice_state::dynadice_sound_io_map(address_map &map)
{
map.global_mask(0xff);
map(0x00, 0x00).r("soundlatch", FUNC(generic_latch_8_device::read));
map(0x01, 0x01).w("soundlatch", FUNC(generic_latch_8_device::write));
map(0x02, 0x02).w(FUNC(dynadice_state::sound_data_w));
map(0x03, 0x03).w(FUNC(dynadice_state::sound_control_w));
}
static INPUT_PORTS_START( dynadice )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_DIPNAME( 0x02, 0x02, "Initialize NVRAM" )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("IN1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) /* increase number of coins */
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) /* decrease number of coins */
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 ) /* start /stop */
PORT_START("DSW")
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ))
PORT_DIPSETTING( 0x04, DEF_STR( 4C_1C ))
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ))
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_1C ))
PORT_DIPSETTING( 0x1c, DEF_STR( 1C_1C ))
PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ))
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ))
PORT_DIPSETTING( 0x10, DEF_STR( 1C_4C ))
PORT_DIPNAME( 0x01, 0x01, "DSW 1-0" )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, "DSW 1-1" )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, "DSW 1-5" )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x40, "DSW 1-6" )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, "DSW 1-7" )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
static const gfx_layout charlayout =
{
8,8,
RGN_FRAC(1,1),
1,
{ 0 },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
8*8
};
static const gfx_layout charlayout2 =
{
8,8,
RGN_FRAC(1,1),
3,
{ 5,6,7 },
{ 0, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 },
{ 0*8*8, 1*8*8, 2*8*8, 3*8*8, 4*8*8, 5*8*8, 6*8*8, 7*8*8 },
8*8*8
};
static GFXDECODE_START( gfx_dynadice )
GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0, 1 ) /* 1bpp */
GFXDECODE_ENTRY( "gfx2", 0, charlayout2, 0, 1 ) /* 3bpp */
GFXDECODE_END
TILE_GET_INFO_MEMBER(dynadice_state::get_tile_info)
{
int code = m_videoram[tile_index];
tileinfo.set(1, code, 0, 0);
}
void dynadice_state::video_start()
{
/* pacman - style videoram layout */
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(dynadice_state::get_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 32);
m_top_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(dynadice_state::get_tile_info)), TILEMAP_SCAN_COLS, 8, 8, 2, 32);
m_bg_tilemap->set_scrollx(0, -16);
}
uint32_t dynadice_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
rectangle myclip = cliprect;
myclip.max_x = 15;
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
m_top_tilemap->draw(screen, bitmap, myclip, 0, 0);
return 0;
}
void dynadice_state::machine_start()
{
save_item(NAME(m_ay_data));
}
void dynadice_state::machine_reset()
{
m_ay_data = 0;
}
void dynadice_state::dynadice(machine_config &config)
{
/* basic machine hardware */
I8080(config, m_maincpu, 18.432_MHz_XTAL / 8);
m_maincpu->set_addrmap(AS_PROGRAM, &dynadice_state::dynadice_map);
m_maincpu->set_addrmap(AS_IO, &dynadice_state::dynadice_io_map);
z80_device &audiocpu(Z80(config, "audiocpu", 18.432_MHz_XTAL / 6));
audiocpu.set_addrmap(AS_PROGRAM, &dynadice_state::dynadice_sound_map);
audiocpu.set_addrmap(AS_IO, &dynadice_state::dynadice_sound_io_map);
NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_0);
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_refresh_hz(60);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(0));
screen.set_size(256+16, 256);
screen.set_visarea(0*8, 34*8-1, 3*8, 28*8-1);
screen.set_screen_update(FUNC(dynadice_state::screen_update));
screen.set_palette("palette");
GFXDECODE(config, m_gfxdecode, "palette", gfx_dynadice);
PALETTE(config, "palette", palette_device::BRG_3BIT);
SPEAKER(config, "mono").front_center();
GENERIC_LATCH_8(config, "soundlatch");
AY8910(config, m_ay8910, 2000000).add_route(ALL_OUTPUTS, "mono", 1.0);
}
ROM_START( dynadice )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "dy_1.bin", 0x0000, 0x1000, CRC(4ad18724) SHA1(78151b02a727f4272eff72765883df9ca09606c3) )
ROM_LOAD( "dy_2.bin", 0x1000, 0x0800, CRC(82cb1873) SHA1(661f33af4a536b7929d432d755ab44f9280f82db) )
ROM_LOAD( "dy_3.bin", 0x1800, 0x0800, CRC(a8edad20) SHA1(b812141f216355c986047969326bd1e036be71e6) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "dy_6.bin", 0x0000, 0x0800, CRC(d4e6e6a3) SHA1(84c0fcfd8326a4301accbd192df6e372b98ae537) )
ROM_REGION( 0x0800, "gfx1", 0 )
ROM_LOAD( "dy_4.bin", 0x0000, 0x0800, CRC(306b851b) SHA1(bf69ed126d32b31e1711ff23c5a75b8a8bd28207) )
ROM_REGION( 0x0800*8, "gfx2", ROMREGION_ERASE00 )
/* gfx data will be rearranged here for 8x8 3bpp tiles */
ROM_REGION( 0x0800, "user1",0 )
ROM_LOAD( "dy_5.bin", 0x0000, 0x0800, CRC(e4799462) SHA1(5cd0f003572540522d72706bc5a8fa6588553031) )
ROM_END
void dynadice_state::init_dynadice()
{
uint8_t *usr1 = memregion("user1")->base();
uint8_t *cpu2 = memregion("audiocpu")->base();
uint8_t *gfx1 = memregion("gfx1")->base();
uint8_t *gfx2 = memregion("gfx2")->base();
cpu2[0x0b] = 0x23; /* bug in game code Dec HL -> Inc HL*/
/* 1bpp tiles -> 3bpp tiles (dy_5.bin contains bg/fg color data for each tile line) */
for (int i = 0; i < 0x800; i++)
for (int j = 0; j < 8; j++)
gfx2[(i << 3) + j] = (gfx1[i] & (0x80 >> j)) ? (usr1[i] & 7) : (usr1[i] >> 4);
}
GAME( 19??, dynadice, 0, dynadice, dynadice, dynadice_state, init_dynadice, ROT90, "<unknown>", "Dynamic Dice", MACHINE_SUPPORTS_SAVE )
| johnparker007/mame | src/mame/drivers/dynadice.cpp | C++ | gpl-2.0 | 9,210 |
/*
* pojos.ChannelAcquisitionData
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2008 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package pojos;
//Java imports
//Third-party libraries
//Application-internal dependencies
import omero.RDouble;
import omero.RInt;
import omero.model.AcquisitionMode;
import omero.model.Binning;
import omero.model.ContrastMethod;
import omero.model.DetectorSettings;
import omero.model.DetectorSettingsI;
import omero.model.FilterSet;
import omero.model.Illumination;
import omero.model.LightPath;
import omero.model.LightSettings;
import omero.model.LightSettingsI;
import omero.model.LightSource;
import omero.model.LogicalChannel;
/**
* Object hosting the acquisition related to a logical channel.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* <small>
* (<b>Internal version:</b> $Revision: $Date: $)
* </small>
* @since 3.0-Beta4
*/
public class ChannelAcquisitionData
extends DataObject
{
/** The settings of the detector. */
private DetectorSettings detectorSettings;
/** The settings of the light source. */
private LightSettings lightSettings;
/** The filterSet used. */
private FilterSetData filterSet;
/** The light path described. */
private LightPathData lightPath;
/** The light source. */
private LightSourceData ligthSource;
/** Flag indicating if the detector settings is dirty. */
private boolean detectorSettingsDirty;
/** Flag indicating if the detector settings is dirty. */
private boolean ligthSourceSettingsDirty;
/** The detector used. */
private DetectorData detector;
/** The otf used. */
private OTFData otf;
/** The binning factor. */
private Binning binning;
/**
* Creates a new instance.
*
* @param channel The image the acquisition data is related to.
* Mustn't be <code>null</code>.
*/
public ChannelAcquisitionData(LogicalChannel channel)
{
if (channel == null)
throw new IllegalArgumentException("Object cannot null.");
setValue(channel);
detectorSettings = channel.getDetectorSettings();
lightSettings = channel.getLightSourceSettings();
FilterSet set = channel.getFilterSet();
if (set != null) filterSet = new FilterSetData(set);
LightPath path = channel.getLightPath();
if (path != null) lightPath = new LightPathData(path);
if (channel.getOtf() != null)
otf = new OTFData(channel.getOtf());
}
/**
* Returns the detector used for that channel.
*
* @return See above.
*/
public DetectorData getDetector()
{
if (detectorSettings == null) return null;
if (detector == null)
detector = new DetectorData(detectorSettings.getDetector());
return detector;
}
/**
* Returns the OTF used for that channel.
*
* @return See above.
*/
public OTFData getOTF() { return otf; }
/**
* Returns the offset set on the detector.
*
* @return See above.
*/
public Double getDetectorSettingsOffset()
{
if (detectorSettings == null) return null;
RDouble value = detectorSettings.getOffsetValue();
if (value == null) return null;
return value.getValue();
}
/**
* Returns the gain set on the detector.
*
* @return See above.
*/
public Double getDetectorSettingsGain()
{
if (detectorSettings == null) return null;
RDouble value = detectorSettings.getGain();
if (value == null) return null;
return value.getValue();
}
/**
* Returns the voltage set on the detector.
*
* @return See above.
*/
public Double getDetectorSettingsVoltage()
{
if (detectorSettings == null) return null;
RDouble value = detectorSettings.getVoltage();
if (value == null) return null;
return value.getValue();
}
/**
* Returns the Read out rate set on the detector.
*
* @return See above.
*/
public Double getDetectorSettingsReadOutRate()
{
if (detectorSettings == null) return null;
RDouble value = detectorSettings.getReadOutRate();
if (value == null) return null;
return value.getValue();
}
/**
* Returns the Binning factor.
*
* @return See above.
*/
public String getDetectorSettingsBinning()
{
if (detectorSettings == null) return "";
Binning value = detectorSettings.getBinning();
if (value == null) return "";
return value.getValue().getValue();
}
/**
* Returns the attenuation of the light source, percent value
* between 0 and 1.
*
* @return See above.
*/
public Double getLigthSettingsAttenuation()
{
if (lightSettings == null) return null;
RDouble value = lightSettings.getAttenuation();
if (value == null) return null;
return value.getValue();
}
/**
* Returns the wavelength of the light source.
*
* @return See above.
*/
public Integer getLigthSettingsWavelength()
{
if (lightSettings == null) return null;
RInt value = lightSettings.getWavelength();
if (value == null) return null;
return value.getValue();
}
/**
* Returns <code>true</code> if there is a filter set linked to the channel
* <code>false</code> otherwise.
*
* @return See above.
*/
public boolean hasFilter() { return filterSet != null; }
/**
* Returns <code>true</code> if there is a light path described
* for that channel, <code>false</code> otherwise.
*
* @return See above.
*/
public boolean hasLightPath() { return lightPath != null; }
/**
* Returns <code>true</code> if there is a detector for that channel,
* <code>false</code> otherwise.
*
* @return See above.
*/
public boolean hasDectector() { return getDetector() != null; }
/**
* Sets the attenuation of the light settings.
*
* @param value The value to set.
*/
public void setLigthSettingsAttenuation(double value)
{
ligthSourceSettingsDirty = true;
if (lightSettings == null) lightSettings = new LightSettingsI();
lightSettings.setAttenuation(omero.rtypes.rdouble(value));
}
/**
* Returns the wavelength of the light source.
*
* @param value The value to set.
*/
public void setLigthSettingsWavelength(int value)
{
ligthSourceSettingsDirty = true;
if (lightSettings == null) lightSettings = new LightSettingsI();
lightSettings.setWavelength(omero.rtypes.rint(value));
}
/**
* Sets the detector's setting offset.
*
* @param value The value to set.
*/
public void setDetectorSettingOffset(double value)
{
detectorSettingsDirty = true;
if (detectorSettings == null)
detectorSettings = new DetectorSettingsI();
detectorSettings.setOffsetValue(omero.rtypes.rdouble(value));
}
/**
* Sets the detector setting's gain.
*
* @param value The value to set.
*/
public void setDetectorSettingsGain(double value)
{
detectorSettingsDirty = true;
if (detectorSettings == null)
detectorSettings = new DetectorSettingsI();
detectorSettings.setGain(omero.rtypes.rdouble(value));
}
/**
* Sets the detector setting's read out rate.
*
* @param value The value to set.
*/
public void setDetectorSettingsReadOutRate(double value)
{
detectorSettingsDirty = true;
if (detectorSettings == null)
detectorSettings = new DetectorSettingsI();
detectorSettings.setReadOutRate(omero.rtypes.rdouble(value));
}
/**
* Sets the detector setting's voltage.
*
* @param value The value to set.
*/
public void setDetectorSettingsVoltage(double value)
{
detectorSettingsDirty = true;
if (detectorSettings == null)
detectorSettings = new DetectorSettingsI();
detectorSettings.setVoltage(omero.rtypes.rdouble(value));
}
/**
* Sets the detector's binning.
*
* @param binning The value to set.
*/
public void setDetectorSettingBinning(Binning binning)
{
this.binning = binning;
}
/**
* Returns the binning enumeration value.
*
* @return See above.
*/
public Binning getDetectorBinningAsEnum() { return binning; }
/**
* Returns <code>true</code> if the detector settings has been updated,
* <code>false</code> otherwise.
*
* @return See above.
*/
public boolean isDetectorSettingsDirty() { return detectorSettingsDirty; }
/**
* Returns <code>true</code> if the light source settings has been updated,
* <code>false</code> otherwise.
*
* @return See above.
*/
public boolean isLightSourceSettingsDirty()
{
return ligthSourceSettingsDirty;
}
/**
* Returns the source of light.
*
* @return See above.
*/
public LightSourceData getLightSource()
{
if (lightSettings == null) return null;
if (ligthSource != null) return ligthSource;
LightSource src = lightSettings.getLightSource();
if (src != null) ligthSource = new LightSourceData(src);
return ligthSource;
}
/**
* Sets the light source associated to the settings.
*
* @param ligthSource The value to set.
*/
public void setLightSource(LightSourceData ligthSource)
{
this.ligthSource = ligthSource;
}
/**
* Returns the light path or <code>null</code>.
*
* @return See above.
*/
public LightPathData getLightPath() { return lightPath; }
/**
* Returns the filter set or <code>null</code>.
*
* @return See above.
*/
public FilterSetData getFilterSet() { return filterSet; }
/**
* Returns the illumination.
*
* @return See above.
*/
public String getIllumination()
{
LogicalChannel lc = (LogicalChannel) asIObject();
if (lc == null) return null;
Illumination value = lc.getIllumination();
if (value != null) return value.getValue().getValue();
return null;
}
/**
* Returns the contrast method.
*
* @return See above.
*/
public String getContrastMethod()
{
LogicalChannel lc = (LogicalChannel) asIObject();
if (lc == null) return null;
ContrastMethod value = lc.getContrastMethod();
if (value != null) return value.getValue().getValue();
return null;
}
/**
* Returns the mode.
*
* @return See above.
*/
public String getMode()
{
LogicalChannel lc = (LogicalChannel) asIObject();
if (lc == null) return null;
AcquisitionMode value = lc.getMode();
if (value != null) return value.getValue().getValue();
return null;
}
}
| joshmoore/openmicroscopy | components/tools/OmeroJava/src/pojos/ChannelAcquisitionData.java | Java | gpl-2.0 | 11,290 |
<?php
/**
* @group edd_tax
*/
class Tests_Taxes extends EDD_UnitTestCase {
protected $_payment_id = null;
protected $_post = null;
public function setUp() {
parent::setUp();
$post_id = $this->factory->post->create( array( 'post_title' => 'Test Download', 'post_type' => 'download', 'post_status' => 'publish' ) );
$meta = array(
'edd_price' => '10.00',
);
foreach( $meta as $key => $value ) {
update_post_meta( $post_id, $key, $value );
}
$this->_post = get_post( $post_id );
/** Generate some sales */
$user = get_userdata(1);
$user_info = array(
'id' => $user->ID,
'email' => $user->user_email,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'discount' => 'none'
);
$download_details = array(
array(
'id' => $this->_post->ID,
'options' => array(
'price_id' => 1
)
)
);
$cart_details = array();
$cart_details[] = array(
'name' => 'Test Download',
'id' => $this->_post->ID,
'item_number' => array(
'id' => $this->_post->ID,
'options' => array(
'price_id' => 1
)
),
'subtotal' => '10',
'discount' => '0',
'tax' => '0.36',
'item_price'=> '10',
'price' => '10.36',
'quantity' => 1,
);
$purchase_data = array(
'price' => '10.36',
'date' => date( 'Y-m-d H:i:s', current_time( 'timestamp' ) ),
'purchase_key' => strtolower( md5( uniqid() ) ),
'user_email' => $user_info['email'],
'user_info' => $user_info,
'currency' => 'USD',
'downloads' => $download_details,
'cart_details' => $cart_details,
'status' => 'publish'
);
$_SERVER['REMOTE_ADDR'] = '10.0.0.0';
$_SERVER['SERVER_NAME'] = 'edd-virtual.local';
$payment_id = edd_insert_payment( $purchase_data );
edd_update_payment_status( $payment_id, 'publish' );
$this->_payment_id = $payment_id;
// Setup global tax rate
edd_update_option( 'enable_taxes', true );
edd_update_option( 'tax_rate', '3.6' );
// Setup country / state tax rates
$tax_rates = array();
$tax_rates[] = array( 'country' => 'US', 'state' => 'AL', 'rate' => 15 );
$tax_rates[] = array( 'country' => 'US', 'state' => 'AZ', 'rate' => .15 );
$tax_rates[] = array( 'country' => 'US', 'state' => 'TX', 'rate' => .13 );
$tax_rates[] = array( 'country' => 'US', 'state' => 'AR', 'rate' => .09 );
$tax_rates[] = array( 'country' => 'US', 'state' => 'HI', 'rate' => .63 );
$tax_rates[] = array( 'country' => 'US', 'state' => 'LA', 'rate' => .96 );
update_option( 'edd_tax_rates', $tax_rates );
}
public function tearDown() {
parent::tearDown();
EDD_Helper_Payment::delete_payment( $this->_payment_id );
}
public function test_use_taxes() {
$this->assertTrue( edd_use_taxes() );
}
public function test_get_tax_rates() {
$this->assertInternalType( 'array', edd_get_tax_rates() );
}
public function test_get_tax_rate() {
$this->assertInternalType( 'float', edd_get_tax_rate( 'US', 'AL' ) );
// Test the one state that has its own rate
$this->assertEquals( '0.15', edd_get_tax_rate( 'US', 'AL' ) );
// Test some other arbitrary states to ensure they fall back to default
$this->assertEquals( '0.036', edd_get_tax_rate( 'US', 'KS' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'US', 'AK' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'US', 'CA' ) );
// Test some other countries to ensure they fall back to default
$this->assertEquals( '0.036', edd_get_tax_rate( 'JP' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'BR' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'CN' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'HK' ) );
}
public function test_get_tax_rate_less_than_one() {
$this->assertEquals( '0.0015', edd_get_tax_rate( 'US', 'AZ' ) );
$this->assertEquals( '0.0013', edd_get_tax_rate( 'US', 'TX' ) );
$this->assertEquals( '0.0009', edd_get_tax_rate( 'US', 'AR' ) );
$this->assertEquals( '0.0063', edd_get_tax_rate( 'US', 'HI' ) );
$this->assertEquals( '0.0096', edd_get_tax_rate( 'US', 'LA' ) );
}
public function test_get_global_tax_rate() {
$this->assertInternalType( 'float', edd_get_tax_rate( 'CA', 'AB' ) );
$this->assertEquals( '0.036', edd_get_tax_rate( 'CA', 'AB' ) );
$this->assertInternalType( 'float', edd_get_tax_rate() );
$this->assertEquals( '0.036', edd_get_tax_rate() );
}
public function test_get_tax_rate_post() {
$_POST['billing_country'] = 'US';
$_POST['state'] = 'AL';
$this->assertEquals( '0.15', edd_get_tax_rate() );
// Reset to origin
unset( $_POST['billing_country'] );
unset( $_POST['state'] );
}
public function test_get_tax_rate_user_address() {
// Prep test (fake is_user_logged_in())
global $current_user;
$current_user = new WP_User(1);
$user_id = get_current_user_id();
$existing_addresss = get_user_meta( $user_id, '_edd_user_address', true );
update_user_meta( $user_id, '_edd_user_address', array(
'line1' => 'First address',
'line2' => 'Line two',
'city' => 'MyCity',
'zip' => '12345',
'country' => 'US',
'state' => 'AL',
) );
// Assert
$this->assertEquals( '0.15', edd_get_tax_rate() );
// Reset to origin
update_post_meta( $user_id, '_edd_user_address', $existing_addresss );
}
public function test_get_tax_rate_global() {
// Prepare test
$existing_tax_rates = get_option( 'edd_tax_rates' );
$tax_rates[] = array( 'country' => 'NL', 'global' => '1', 'rate' => 21 );
update_option( 'edd_tax_rates', $tax_rates );
// Assert
$this->assertEquals( '0.21', edd_get_tax_rate( 'NL' ) );
// Reset to origin
update_option( 'edd_tax_rates', $existing_tax_rates );
}
public function test_get_formatted_tax_rate() {
$this->assertEquals( '3.6%', edd_get_formatted_tax_rate() );
}
public function test_calculate_tax() {
$this->assertEquals( '1.944', edd_calculate_tax( 54 ) );
$this->assertEquals( '1.9692', edd_calculate_tax( 54.7 ) );
$this->assertEquals( '5.5386', edd_calculate_tax( 153.85 ) );
$this->assertEquals( '9.29916', edd_calculate_tax( 258.31 ) );
$this->assertEquals( '37.41552', edd_calculate_tax( 1039.32 ) );
$this->assertEquals( '361.58724', edd_calculate_tax( 10044.09 ) );
$this->assertEquals( '0', edd_calculate_tax( -1.50 ) );
}
public function test_calculate_tax_less_than_one() {
$this->assertEquals( '0.08', edd_format_amount( edd_calculate_tax( 54, 'US', 'AZ' ) ) );
$this->assertEquals( '0.07', edd_format_amount( edd_calculate_tax( 54.7, 'US', 'TX' ) ) );
$this->assertEquals( '0.14', edd_format_amount( edd_calculate_tax( 153.85, 'US', 'AR' ) ) );
$this->assertEquals( '1.63', edd_format_amount( edd_calculate_tax( 258.31, 'US', 'HI' ) ) );
$this->assertEquals( '9.98', edd_format_amount( edd_calculate_tax( 1039.32, 'US', 'LA' ) ) );
}
public function test_calculate_tax_price_includes_tax() {
// Prepare test
$origin_price_include_tax = edd_get_option( 'prices_include_tax' );
edd_update_option( 'prices_include_tax', 'yes' );
// Asserts
$this->assertEquals( '1.87644787645', edd_calculate_tax( 54 ) );
$this->assertEquals( '1.90077220077', edd_calculate_tax( 54.7 ) );
$this->assertEquals( '5.34613899614', edd_calculate_tax( 153.85 ) );
$this->assertEquals( '8.97602316602', edd_calculate_tax( 258.31 ) );
$this->assertEquals( '36.1153667954', edd_calculate_tax( 1039.32 ) );
$this->assertEquals( '349.02243243243356118910014629364013671875', edd_calculate_tax( 10044.09 ) );
// Reset to origin
edd_update_option( 'prices_include_tax', $origin_price_include_tax );
}
public function test_get_sales_tax_for_year() {
$this->assertEquals( '0.36', edd_get_sales_tax_for_year( date( 'Y' ) ) );
$this->assertEquals( '0', edd_get_sales_tax_for_year( date( 'Y' ) - 1 ) );
}
public function test_sales_tax_for_year() {
ob_start();
edd_sales_tax_for_year( date( 'Y' ) );
$this_year = ob_get_clean();
ob_start();
edd_sales_tax_for_year( date( 'Y' ) - 1 );
$last_year = ob_get_clean();
$this->assertEquals( '$0.36', $this_year );
$this->assertEquals( '$0.00', $last_year );
}
public function test_prices_show_tax_on_checkout() {
$this->assertFalse( edd_prices_show_tax_on_checkout() );
}
public function test_prices_include_tax() {
$this->assertFalse( edd_prices_include_tax() );
}
public function test_is_cart_taxed() {
$this->assertTrue( edd_is_cart_taxed() );
}
public function test_display_tax_rates() {
$this->assertFalse( edd_display_tax_rate() );
}
public function test_cart_needs_tax_address_fields() {
$this->assertInternalType( 'bool', edd_cart_needs_tax_address_fields() );
$this->assertTrue( edd_cart_needs_tax_address_fields() );
}
public function test_cart_needs_tax_address_fields_false() {
// Prepare test
$existing_enable_taxes = edd_get_option( 'enable_taxes' );
edd_update_option( 'enable_taxes', false );
// Assert
$this->assertFalse( edd_cart_needs_tax_address_fields() );
// Reset to origin
edd_update_option( 'enable_taxes', $existing_enable_taxes );
}
public function test_download_is_exclusive_of_tax() {
$this->assertFalse( edd_download_is_tax_exclusive( $this->_post->ID ) );
}
public function test_get_payment_tax() {
$this->assertEquals( '0.36', edd_get_payment_tax( $this->_payment_id ) );
}
public function test_payment_tax_updates() {
// Test backwards compat bug in issue/3324
$this->assertEquals( '0.36', edd_get_payment_tax( $this->_payment_id ) );
$current_meta = edd_get_payment_meta( $this->_payment_id );
edd_update_payment_meta( $this->_payment_id, '_edd_payment_meta', $current_meta );
$this->assertEquals( '0.36', edd_get_payment_tax( $this->_payment_id ) );
// Test that when we update _edd_payment_tax, we update the _edd_payment_meta
edd_update_payment_meta( $this->_payment_id, '_edd_payment_tax', 10 );
$meta_array = edd_get_payment_meta( $this->_payment_id, '_edd_payment_meta', true );
$this->assertEquals( 10, $meta_array['tax'] );
$this->assertEquals( 10, edd_get_payment_tax( $this->_payment_id ) );
// Test that when we update the _edd_payment_meta, we update the _edd_payment_tax
$current_meta = edd_get_payment_meta( $this->_payment_id, '_edd_payment_meta', true );
$current_meta['tax'] = 20;
edd_update_payment_meta( $this->_payment_id, '_edd_payment_meta', $current_meta );
$this->assertEquals( 20, edd_get_payment_tax( $this->_payment_id ) );
}
}
| zackkatz/Easy-Digital-Downloads | tests/tests-tax.php | PHP | gpl-2.0 | 10,433 |
<?php
/**
* Class CRM_Core_CodeGen_Util_File
*/
class CRM_Core_CodeGen_Util_File {
/**
* @param $dir
* @param int $perm
*/
public static function createDir($dir, $perm = 0755) {
if (!is_dir($dir)) {
mkdir($dir, $perm, TRUE);
}
}
/**
* @param $dir
*/
public static function cleanTempDir($dir) {
foreach (glob("$dir/*") as $tempFile) {
unlink($tempFile);
}
rmdir($dir);
if (preg_match(':^(.*)\.d$:', $dir, $matches)) {
if (file_exists($matches[1])) {
unlink($matches[1]);
}
}
}
/**
* @param $prefix
*
* @return string
*/
public static function createTempDir($prefix) {
$newTempDir = tempnam(sys_get_temp_dir(), $prefix) . '.d';
if (file_exists($newTempDir)) {
self::removeDir($newTempDir);
}
self::createDir($newTempDir);
return $newTempDir;
}
/**
* Calculate a cumulative digest based on a collection of files.
*
* @param array $files
* List of file names (strings).
* @param callable|string $digest a one-way hash function (string => string)
*
* @return string
*/
public static function digestAll($files, $digest = 'md5') {
$buffer = '';
foreach ($files as $file) {
$buffer .= $digest(file_get_contents($file));
}
return $digest($buffer);
}
/**
* Find the path to the main Civi source tree.
*
* @return string
* @throws RuntimeException
*/
public static function findCoreSourceDir() {
$path = str_replace(DIRECTORY_SEPARATOR, '/', __DIR__);
if (!preg_match(':(.*)/CRM/Core/CodeGen/Util:', $path, $matches)) {
throw new RuntimeException("Failed to determine path of code-gen");
}
return $matches[1];
}
/**
* Find files in several directories using several filename patterns.
*
* @param array $pairs
* Each item is an array(0 => $searchBaseDir, 1 => $filePattern).
* @return array
* Array of file paths
*/
public static function findManyFiles($pairs) {
$files = array();
foreach ($pairs as $pair) {
list ($dir, $pattern) = $pair;
$files = array_merge($files, CRM_Utils_File::findFiles($dir, $pattern));
}
sort($files);
return $files;
}
}
| sharique/d7-civicrm | sites/all/modules/contrib/civicrm/CRM/Core/CodeGen/Util/File.php | PHP | gpl-2.0 | 2,238 |
// uniCenta oPOS - Touch Friendly Point Of Sale
// Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works
// http://www.unicenta.com
//
// This file is part of uniCenta oPOS
//
// uniCenta oPOS 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.
//
// uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.forms;
/**
*
* @author adrianromero
*/
public interface MenuElement {
/**
*
* @param menu
*/
public void addComponent(JPanelMenu menu);
}
| sbandur84/micro-Blagajna | src-pos/com/openbravo/pos/forms/MenuElement.java | Java | gpl-3.0 | 1,074 |
/*
* Copyright 2012 Hannes Janetzek
*
* This file is part of the OpenScienceMap project (http://www.opensciencemap.org).
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.tiling.source;
import static org.oscim.tiling.ITileDataSink.QueryResult.FAILED;
import static org.oscim.tiling.ITileDataSink.QueryResult.SUCCESS;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.oscim.layers.tile.MapTile;
import org.oscim.tiling.ITileCache;
import org.oscim.tiling.ITileCache.TileReader;
import org.oscim.tiling.ITileCache.TileWriter;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource;
import org.oscim.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UrlTileDataSource implements ITileDataSource {
static final Logger log = LoggerFactory.getLogger(UrlTileDataSource.class);
protected final HttpEngine mConn;
protected final ITileDecoder mTileDecoder;
protected final UrlTileSource mTileSource;
protected final boolean mUseCache;
public UrlTileDataSource(UrlTileSource tileSource, ITileDecoder tileDecoder, HttpEngine conn) {
mTileDecoder = tileDecoder;
mTileSource = tileSource;
mUseCache = (tileSource.tileCache != null);
mConn = conn;
}
@Override
public void query(MapTile tile, ITileDataSink sink) {
ITileCache cache = mTileSource.tileCache;
if (mUseCache) {
TileReader c = cache.getTile(tile);
if (c != null) {
InputStream is = c.getInputStream();
try {
if (mTileDecoder.decode(tile, sink, is)) {
sink.completed(SUCCESS);
return;
}
} catch (IOException e) {
log.debug("{} Cache read: {}", tile, e);
} finally {
IOUtils.closeQuietly(is);
}
}
}
boolean ok = false;
TileWriter cacheWriter = null;
try {
mConn.sendRequest(tile);
InputStream is = mConn.read();
if (mUseCache) {
cacheWriter = cache.writeTile(tile);
mConn.setCache(cacheWriter.getOutputStream());
}
ok = mTileDecoder.decode(tile, sink, is);
} catch (SocketException e) {
log.debug("{} Socket Error: {}", tile, e.getMessage());
} catch (SocketTimeoutException e) {
log.debug("{} Socket Timeout", tile);
} catch (UnknownHostException e) {
log.debug("{} Unknown host: {}", tile, e.getMessage());
} catch (IOException e) {
log.debug("{} Network Error: {}", tile, e.getMessage());
} finally {
ok = mConn.requestCompleted(ok);
if (cacheWriter != null)
cacheWriter.complete(ok);
sink.completed(ok ? SUCCESS : FAILED);
}
}
@Override
public void dispose() {
mConn.close();
}
@Override
public void cancel() {
mConn.close();
}
}
| hyl1987419/vtm | vtm/src/org/oscim/tiling/source/UrlTileDataSource.java | Java | gpl-3.0 | 3,375 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.WebView;
import java.util.Map;
/**
* Singleton class for handling preload requests.
*/
public class Preloader {
private final static String LOGTAG = "browser.preloader";
private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
private static final int PRERENDER_TIMEOUT_MILLIS = 30 * 1000; // 30s
private static Preloader sInstance;
private final Context mContext;
private final Handler mHandler;
private final BrowserWebViewFactory mFactory;
private volatile PreloaderSession mSession;
public static void initialize(Context context) {
sInstance = new Preloader(context);
}
public static Preloader getInstance() {
return sInstance;
}
private Preloader(Context context) {
mContext = context.getApplicationContext();
mHandler = new Handler(Looper.getMainLooper());
mSession = null;
mFactory = new BrowserWebViewFactory(context);
}
private PreloaderSession getSession(String id) {
if (mSession == null) {
if (LOGD_ENABLED) Log.d(LOGTAG, "Create new preload session " + id);
mSession = new PreloaderSession(id);
WebViewTimersControl.getInstance().onPrerenderStart(
mSession.getWebView());
return mSession;
} else if (mSession.mId.equals(id)) {
if (LOGD_ENABLED) Log.d(LOGTAG, "Returning existing preload session " + id);
return mSession;
}
if (LOGD_ENABLED) Log.d(LOGTAG, "Existing session in progress : " + mSession.mId +
" returning null.");
return null;
}
private PreloaderSession takeSession(String id) {
PreloaderSession s = null;
if (mSession != null && mSession.mId.equals(id)) {
s = mSession;
mSession = null;
}
if (s != null) {
s.cancelTimeout();
}
return s;
}
public void handlePreloadRequest(String id, String url, Map<String, String> headers,
String searchBoxQuery) {
PreloaderSession s = getSession(id);
if (s == null) {
if (LOGD_ENABLED) Log.d(LOGTAG, "Discarding preload request, existing"
+ " session in progress");
return;
}
s.touch(); // reset timer
PreloadedTabControl tab = s.getTabControl();
if (searchBoxQuery != null) {
tab.loadUrlIfChanged(url, headers);
tab.setQuery(searchBoxQuery);
} else {
tab.loadUrl(url, headers);
}
}
public void cancelSearchBoxPreload(String id) {
PreloaderSession s = getSession(id);
if (s != null) {
s.touch(); // reset timer
PreloadedTabControl tab = s.getTabControl();
tab.searchBoxCancel();
}
}
public void discardPreload(String id) {
PreloaderSession s = takeSession(id);
if (s != null) {
if (LOGD_ENABLED) Log.d(LOGTAG, "Discard preload session " + id);
WebViewTimersControl.getInstance().onPrerenderDone(s == null ? null : s.getWebView());
PreloadedTabControl t = s.getTabControl();
t.destroy();
} else {
if (LOGD_ENABLED) Log.d(LOGTAG, "Ignored discard request " + id);
}
}
/**
* Return a preloaded tab, and remove it from the preloader. This is used when the
* view is about to be displayed.
*/
public PreloadedTabControl getPreloadedTab(String id) {
PreloaderSession s = takeSession(id);
if (LOGD_ENABLED) Log.d(LOGTAG, "Showing preload session " + id + "=" + s);
return s == null ? null : s.getTabControl();
}
private class PreloaderSession {
private final String mId;
private final PreloadedTabControl mTabControl;
private final Runnable mTimeoutTask = new Runnable(){
@Override
public void run() {
if (LOGD_ENABLED) Log.d(LOGTAG, "Preload session timeout " + mId);
discardPreload(mId);
}};
public PreloaderSession(String id) {
mId = id;
mTabControl = new PreloadedTabControl(
new Tab(new PreloadController(mContext), mFactory.createWebView(false)));
touch();
}
public void cancelTimeout() {
mHandler.removeCallbacks(mTimeoutTask);
}
public void touch() {
cancelTimeout();
mHandler.postDelayed(mTimeoutTask, PRERENDER_TIMEOUT_MILLIS);
}
public PreloadedTabControl getTabControl() {
return mTabControl;
}
public WebView getWebView() {
Tab t = mTabControl.getTab();
return t == null? null : t.getWebView();
}
}
}
| MIRAGE-Dev/packages_apps_Browser | src/com/android/browser/Preloader.java | Java | gpl-3.0 | 5,654 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "TensorNFieldFields.H"
#define TEMPLATE template<template<class> class Field>
#include "FieldFieldFunctionsM.C"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#define TensorN_FieldFunctions(tensorType, diagTensorType, sphericalTensorType, \
vectorType, CmptType, args...) \
\
UNARY_FUNCTION(tensorType, tensorType, inv) \
UNARY_FUNCTION(diagTensorType, tensorType, diag) \
UNARY_FUNCTION(tensorType, tensorType, negSumDiag) \
UNARY_FUNCTION(vectorType, tensorType, contractLinear) \
UNARY_FUNCTION(CmptType, tensorType, contractScalar) \
\
BINARY_OPERATOR(tensorType, CmptType, tensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, CmptType, tensorType, /, divide) \
\
BINARY_OPERATOR(vectorType, vectorType, tensorType, /, divide) \
BINARY_TYPE_OPERATOR(vectorType, vectorType, tensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, tensorType, tensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, tensorType, tensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, tensorType, diagTensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, tensorType, diagTensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, diagTensorType, tensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, diagTensorType, tensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, sphericalTensorType, tensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, sphericalTensorType, tensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, tensorType, sphericalTensorType, /, divide) \
BINARY_TYPE_OPERATOR(tensorType, tensorType, sphericalTensorType, /, divide) \
\
BINARY_OPERATOR(tensorType, tensorType, tensorType, +, add) \
BINARY_OPERATOR(tensorType, tensorType, tensorType, -, subtract) \
\
BINARY_TYPE_OPERATOR(tensorType, tensorType, tensorType, +, add) \
BINARY_TYPE_OPERATOR(tensorType, tensorType, tensorType, -, subtract) \
\
BINARY_OPERATOR(tensorType, diagTensorType, tensorType, +, add) \
BINARY_OPERATOR(tensorType, diagTensorType, tensorType, -, subtract) \
\
BINARY_TYPE_OPERATOR(tensorType, diagTensorType, tensorType, +, add) \
BINARY_TYPE_OPERATOR(tensorType, diagTensorType, tensorType, -, subtract) \
\
BINARY_OPERATOR(tensorType, sphericalTensorType, tensorType, +, add) \
BINARY_OPERATOR(tensorType, sphericalTensorType, tensorType, -, subtract) \
\
BINARY_TYPE_OPERATOR(tensorType, sphericalTensorType, tensorType, +, add) \
BINARY_TYPE_OPERATOR(tensorType, sphericalTensorType, tensorType, -, subtract)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
forAllVectorTensorNTypes(TensorN_FieldFunctions)
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#undef TensorN_FieldFunctions
#include "undefFieldFunctionsM.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
| WensiWu/openfoam-extend-foam-extend-3.1 | src/foam/fields/FieldFields/vectorNFieldFields/TensorNFieldFields.C | C++ | gpl-3.0 | 6,042 |
import Ember from 'ember';
export default Ember.Controller.extend({
applicationController: Ember.inject.controller('application'),
stats: Ember.computed.reads('applicationController'),
config: Ember.computed.reads('applicationController.config'),
cachedLogin: Ember.computed('login', {
get() {
return this.get('login') || Ember.$.cookie('login');
},
set(key, value) {
Ember.$.cookie('login', value);
this.set('model.login', value);
return value;
}
})
});
| boehla/open-ethereum-pool | www/app/controllers/index.js | JavaScript | gpl-3.0 | 506 |
package de.rwth;
import gl.GL1Renderer;
import gl.Renderable;
import gl.scenegraph.MeshComponent;
import system.Setup;
import worldData.World;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Log;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
//import com.badlogic.gdx.graphics.g3d.loaders.collada.ColladaLoader;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dLoader;
import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dtLoader;
import com.badlogic.gdx.graphics.g3d.loaders.md2.MD2Loader;
//import com.badlogic.gdx.graphics.g3d.loaders.ogre.OgreXmlLoader;
import com.badlogic.gdx.graphics.g3d.loaders.wavefront.ObjLoader;
import com.badlogic.gdx.graphics.g3d.materials.Material;
import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.keyframe.KeyframedModel;
import com.badlogic.gdx.graphics.g3d.model.skeleton.SkeletonModel;
import com.badlogic.gdx.graphics.g3d.model.still.StillModel;
/**
* The ModelCreator has to load the model from the rendering thread. Therefor it
* implements {@link Renderable} and has to be passed to the {@link Renderer} in
* the
* {@link Setup#_b_addWorldsToRenderer(gl.GLRenderer, gl.GLFactory, geo.GeoObj)}
* methods. The ModelCreator will call the
* {@link ModelLoader#modelLoaded(StillModel, Texture)} method when the model
* was loaded. Then you can create a {@link GDXMesh} with the returned data and
* add it to the {@link World}
*
* @author Spobo
*
*/
public abstract class ModelLoader implements gl.Renderable {
private static final String LOGTAG = "ModelCreator";
private String fileName;
private String textureFileName;
private Texture texture;
private StillModel model;
private KeyframedModel keyFramedModel;
private SkeletonModel skeletonModel;
private GL1Renderer renderer;
public ModelLoader(GL1Renderer renderer, String fileName,
String textureFileName) {
this.renderer = renderer;
this.fileName = fileName;
this.textureFileName = textureFileName;
renderer.addRenderElement(this);
}
private void loadModelFromFile() {
try {
if (textureFileName != null)
texture = new Texture(Gdx.files.internal(textureFileName), true);
} catch (Exception e) {
Log.e(LOGTAG, "Could not load the specified texture: "
+ textureFileName);
e.printStackTrace();
}
/*if (fileName.endsWith(".dae"))
model = ColladaLoader.loadStillModel(Gdx.files.internal(fileName));*/
/*else*/ if (fileName.endsWith(".obj"))
model = new ObjLoader().loadObj(Gdx.files.internal(fileName), true);
else if (fileName.endsWith(".g3d"))
model = G3dLoader.loadStillModel(Gdx.files.internal(fileName));
else if (fileName.endsWith(".md2")) {
keyFramedModel = new MD2Loader().load(Gdx.files.internal(fileName),
1 / 7f);
if (texture != null) {
Material material = new Material("materialTODO", // TODO
new TextureAttribute(texture, 0, "a_tex0"));
if (keyFramedModel != null)
keyFramedModel.setMaterial(material);
}
}
// else if (fileName.endsWith(".xml")) {
// FileHandle skeletonFile = Gdx.files.internal(fileName.replace(
// "mesh.xml", "skeleton.xml"));
// skeletonModel = new OgreXmlLoader().load(
// Gdx.files.internal(fileName), skeletonFile);
// if (texture != null) {
// Material mat = new Material("mat", new TextureAttribute(
// texture, 0, "s_tex"));
// model.setMaterial(mat);
// }
// }
else if (fileName.endsWith(".g3dt")) {
keyFramedModel = G3dtLoader.loadKeyframedModel(
Gdx.files.internal(fileName), false);
Material material = new Material("material", new TextureAttribute(
texture, 0, "s_tex"));
keyFramedModel.setMaterial(material);
}
}
public MeshComponent getGDXShape() {
GDXMesh x = new GDXMesh(model, texture);
return x;
}
@Override
public void render(javax.microedition.khronos.opengles.GL10 gl,
gl.Renderable parent) {
Log.d(LOGTAG, "Trying to load " + fileName);
try {
loadModelFromFile();
} catch (Exception e) {
Log.e(LOGTAG, "Could not load model");
e.printStackTrace();
}
if (model != null)
modelLoaded(new GDXMesh(model, texture));
else if (keyFramedModel != null)
modelLoaded(new GDXMesh(keyFramedModel, texture));
else if (skeletonModel != null)
modelLoaded(new GDXMesh(skeletonModel, texture));
Log.d(LOGTAG, "Result of trying is:");
Log.d(LOGTAG, "fileName=" + fileName);
Log.d(LOGTAG, "textureFileName=" + textureFileName);
Log.d(LOGTAG, "model=" + model);
Log.d(LOGTAG, "keyFramedModel=" + keyFramedModel);
Log.d(LOGTAG, "skeletonModel=" + skeletonModel);
Log.d(LOGTAG, "texture=" + texture);
renderer.removeRenderElement(this);
}
public abstract void modelLoaded(MeshComponent gdxMesh);
}
| sanyaade-g2g-repos/droidar | ModelLoaderAdapters/src/de/rwth/ModelLoader.java | Java | gpl-3.0 | 4,812 |
# -*- coding: utf-8 -*-
from ..internal.OCR import OCR
class GigasizeCom(OCR):
__name__ = "GigasizeCom"
__type__ = "ocr"
__version__ = "0.17"
__status__ = "testing"
__description__ = """Gigasize.com ocr plugin"""
__license__ = "GPLv3"
__authors__ = [("pyLoad Team", "admin@pyload.org")]
def recognize(self, image):
self.load_image(image)
self.threshold(2.8)
self.run_tesser(True, False, False, True)
return self.result_captcha
| Arno-Nymous/pyload | module/plugins/captcha/GigasizeCom.py | Python | gpl-3.0 | 496 |
[{
Name: 'Weather Underground Widget',
Author: 'Generoso Martello',
Version: '2013-03-31',
GroupName: '',
IconImage: 'pages/control/widgets/homegenie/generic/images/wu_logo.png',
StatusText: '',
Description: '',
RenderView: function (cuid, module) {
var container = $(cuid);
var widget = container.find('[data-ui-field=widget]');
//
if (!this.Initialized) {
this.Initialized = true;
// settings button
widget.find('[data-ui-field=settings]').on('click', function () {
HG.WebApp.ProgramEdit._CurrentProgram.Domain = module.Domain;
HG.WebApp.ProgramEdit._CurrentProgram.Address = module.Address;
HG.WebApp.ProgramsList.UpdateOptionsPopup();
});
}
//
var display_location = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.DisplayLocation').Value;
var serviceapi = HG.WebApp.Utility.GetModulePropertyByName(module, 'ConfigureOptions.ApiKey').Value;
if (serviceapi == '' || serviceapi == '?') {
widget.find('[data-ui-field=name]').html('Not configured.');
widget.find('[data-ui-field=sunrise_value]').html(sunrise);
//
widget.find('[data-ui-field=settings]').qtip({
content: {
title: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_title'),
text: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_text'),
button: HG.WebApp.Locales.GetLocaleString('control_widget_notconfigured_button')
},
show: { event: false, ready: true, delay: 1000 },
events: {
hide: function () {
$(this).qtip('destroy');
}
},
hide: { event: false, inactive: 3000 },
style: { classes: 'qtip-red qtip-shadow qtip-rounded qtip-bootstrap' },
position: { my: 'top center', at: 'bottom center' }
});
}
else if (display_location == '') {
widget.find('[data-ui-field=name]').html('Waiting for data...');
widget.find('[data-ui-field=last_updated_value]').html('Not updated!');
}
else {
widget.find('[data-ui-field=name]').html(display_location);
//
var sunrise = HG.WebApp.Utility.GetModulePropertyByName(module, 'Astronomy.Sunrise').Value;
widget.find('[data-ui-field=sunrise_value]').html(sunrise);
//
var sunset = HG.WebApp.Utility.GetModulePropertyByName(module, 'Astronomy.Sunset').Value;
widget.find('[data-ui-field=sunset_value]').html(sunset);
//
var iconurl = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.IconUrl').Value;
widget.find('[data-ui-field=icon]').attr('src', iconurl);
//
var icontext = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Description').Value;
widget.find('[data-ui-field=description]').html(icontext);
//
var last_updated = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.LastUpdated').Value;
widget.find('[data-ui-field=last_updated_value]').html(last_updated);
//
var display_celsius = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.DisplayCelsius').Value;
if (display_celsius == 'TRUE') {
var temperaturec = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.TemperatureC').Value;
widget.find('[data-ui-field=temperature_value]').html(temperaturec + '℃');
} else {
var temperaturef = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.TemperatureF').Value;
widget.find('[data-ui-field=temperature_value]').html(temperaturef + '℉');
}
//
// Forecast data
for (var f = 1; f <= 3; f++)
{
var fIconUrl = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.IconUrl').Value;
widget.find('[data-ui-field=forecast_' + f + '_icon]').attr('src', fIconUrl);
var fDescription = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Description').Value;
widget.find('[data-ui-field=forecast_' + f + '_desc]').html(fDescription);
if (display_celsius == 'TRUE') {
var temperatureMinC = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureC.Low').Value;
var temperatureMaxC = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureC.High').Value;
widget.find('[data-ui-field=forecast_' + f + '_tmin]').html(temperatureMinC + '℃');
widget.find('[data-ui-field=forecast_' + f + '_tmax]').html(temperatureMaxC + '℃');
} else {
var temperatureMinF = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureF.Low').Value;
var temperatureMaxF = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.TemperatureF.High').Value;
widget.find('[data-ui-field=forecast_' + f + '_tmin]').html(temperatureMinF + '℉');
widget.find('[data-ui-field=forecast_' + f + '_tmax]').html(temperatureMaxF + '℉');
}
var displayDate = HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Weekday').Value.substr(0, 3) + ', ';
displayDate += HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Day').Value + ' ';
displayDate += HG.WebApp.Utility.GetModulePropertyByName(module, 'Conditions.Forecast.' + f + '.Month').Value;
widget.find('[data-ui-field=forecast_' + f + '_date]').html(displayDate);
}
}
}
}] | AdnanSattar/HomeGenie | BaseFiles/Common/html/pages/control/widgets/weather/wunderground/conditions.js | JavaScript | gpl-3.0 | 6,270 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "volFields.H"
#include "zeroGradientFvPatchFields.H"
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::PtrList<Foam::scalarField>&
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRs()
{
return RRs_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::PtrList<Foam::scalarField>&
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRg()
{
return RRg_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline const Foam::PtrList<Foam::solidReaction>&
Foam::ODESolidChemistryModel<CompType, SolidThermo,GasThermo>::reactions() const
{
return reactions_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline const Foam::PtrList<GasThermo>&
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::
gasThermo() const
{
return gasThermo_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline const Foam::speciesTable&
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::gasTable() const
{
return pyrolisisGases_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::label
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::nSpecie() const
{
return nSpecie_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::label
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::
nReaction() const
{
return nReaction_;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::tmp<Foam::volScalarField>
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRs
(
const label i
) const
{
tmp<volScalarField> tRRs
(
new volScalarField
(
IOobject
(
"RRs(" + Ys_[i].name() + ')',
this->time().timeName(),
this->mesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
this->mesh(),
dimensionedScalar("zero", dimMass/dimVolume/dimTime, 0.0),
zeroGradientFvPatchScalarField::typeName
)
);
if (this->chemistry_)
{
tRRs().internalField() = RRs_[i];
tRRs().correctBoundaryConditions();
}
return tRRs;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::tmp<Foam::volScalarField>
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRg
(
const label i
) const
{
tmp<volScalarField> tRRg
(
new volScalarField
(
IOobject
(
"RRg(" + this->pyrolisisGases_[i] + ')',
this->time().timeName(),
this->mesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
this->mesh(),
dimensionedScalar("zero", dimMass/dimVolume/dimTime, 0.0),
zeroGradientFvPatchScalarField::typeName
)
);
if (this->chemistry_)
{
tRRg().internalField() = RRg_[i];
tRRg().correctBoundaryConditions();
}
return tRRg;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::tmp<Foam::volScalarField>
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRg() const
{
tmp<volScalarField> tRRg
(
new volScalarField
(
IOobject
(
"RRg",
this->time().timeName(),
this->mesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
this->mesh(),
dimensionedScalar("zero", dimMass/dimVolume/dimTime, 0.0),
zeroGradientFvPatchScalarField::typeName
)
);
if (this->chemistry_)
{
for (label i=0; i < nGases_; i++)
{
tRRg().internalField() += RRg_[i];
}
tRRg().correctBoundaryConditions();
}
return tRRg;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::tmp<Foam::volScalarField>
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RRs() const
{
tmp<volScalarField> tRRs
(
new volScalarField
(
IOobject
(
"RRs",
this->time().timeName(),
this->mesh(),
IOobject::NO_READ,
IOobject::NO_WRITE
),
this->mesh(),
dimensionedScalar("zero", dimMass/dimVolume/dimTime, 0.0),
zeroGradientFvPatchScalarField::typeName
)
);
if (this->chemistry_)
{
for (label i=0; i < nSolids_; i++)
{
tRRs().internalField() += RRs_[i];
}
tRRs().correctBoundaryConditions();
}
return tRRs;
}
template<class CompType, class SolidThermo, class GasThermo>
inline Foam::tmp<Foam::volScalarField>
Foam::ODESolidChemistryModel<CompType, SolidThermo, GasThermo>::RR
(
const label i
) const
{
notImplemented("ODESolidChemistryModel::RR(const label)");
return (Foam::volScalarField::null());
}
// ************************************************************************* //
| morgoth541/of_realFluid | src/thermophysicalModels/solidChemistryModel/ODESolidChemistryModel/ODESolidChemistryModelI.H | C++ | gpl-3.0 | 6,434 |
<?php
namespace Neos\Fusion\Tests\Functional\FusionObjects;
/*
* This file is part of the Neos.Fusion package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
/**
* Testcase for the Fusion View
*
*/
class ProcessorTest extends AbstractFusionObjectTest
{
/**
* @test
*/
public function basicProcessorsWork()
{
$this->assertMultipleFusionPaths('Hello World foo', 'processors/newSyntax/basicProcessor/valueWithNested');
}
/**
* @test
*/
public function basicProcessorsBeforeValueWork()
{
$this->assertMultipleFusionPaths('Hello World foo', 'processors/newSyntax/processorBeforeValue/valueWithNested');
}
/**
* @test
*/
public function extendedSyntaxProcessorsWork()
{
$this->assertMultipleFusionPaths('Hello World foo', 'processors/newSyntax/extendedSyntaxProcessor/valueWithNested');
}
/**
* Data Provider for processorsCanBeUnset
*
* @return array
*/
public function dataProviderForUnsettingProcessors()
{
return array(
array('processors/newSyntax/unset/simple'),
array('processors/newSyntax/unset/prototypes1'),
array('processors/newSyntax/unset/prototypes2'),
array('processors/newSyntax/unset/nestedScope/prototypes3')
);
}
/**
* @test
* @dataProvider dataProviderForUnsettingProcessors
*/
public function processorsCanBeUnset($path)
{
$view = $this->buildView();
$view->setFusionPath($path);
$this->assertEquals('Foobaz', $view->render());
}
/**
* @test
*/
public function usingThisInProcessorWorks()
{
$this->assertFusionPath('my value append', 'processors/newSyntax/usingThisInProcessor');
}
}
| klfman/neos-development-collection | Neos.Fusion/Tests/Functional/FusionObjects/ProcessorTest.php | PHP | gpl-3.0 | 1,986 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "granularPressureModel.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(granularPressureModel, 0);
defineRunTimeSelectionTable(granularPressureModel, dictionary);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::granularPressureModel::granularPressureModel
(
const dictionary& dict
)
:
dict_(dict)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::granularPressureModel::~granularPressureModel()
{}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.1 | applications/solvers/multiphase/twoPhaseEulerFoam/kineticTheoryModels/granularPressureModel/granularPressureModel/granularPressureModel.C | C++ | gpl-3.0 | 1,824 |
package us.mn.state.health.lims.observationhistorytype.daoImpl;
import java.util.List;
import org.hibernate.Query;
import us.mn.state.health.lims.common.daoimpl.GenericDAOImpl;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.log.LogEvent;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.observationhistorytype.dao.ObservationHistoryTypeDAO;
import us.mn.state.health.lims.observationhistorytype.valueholder.ObservationHistoryType;
public class ObservationHistoryTypeDAOImpl extends GenericDAOImpl<String, ObservationHistoryType> implements ObservationHistoryTypeDAO {
public ObservationHistoryTypeDAOImpl() {
super(ObservationHistoryType.class, "OBSERVATION_HISTORY_TYPE");
}
public void delete(List<ObservationHistoryType> entities) throws LIMSRuntimeException {
super.delete(entities, new ObservationHistoryType());
}
@SuppressWarnings("unchecked")
public ObservationHistoryType getByName(String name) throws LIMSRuntimeException {
List<ObservationHistoryType> historyTypeList;
try {
String sql = "from ObservationHistoryType oht where oht.typeName = :name";
Query query = HibernateUtil.getSession().createQuery(sql);
query.setString("name", name);
historyTypeList = query.list();
HibernateUtil.getSession().flush();
HibernateUtil.getSession().clear();
return historyTypeList.size() > 0 ? historyTypeList.get(0) : null;
} catch (Exception e) {
LogEvent.logError("ObservationHistoryTypeDAOImpl ", "getByName()", e.toString());
throw new LIMSRuntimeException("Error in ObservationHistoryTypeDAOImpl getByName()", e);
}
}
}
| mark47/OESandbox | app/src/us/mn/state/health/lims/observationhistorytype/daoImpl/ObservationHistoryTypeDAOImpl.java | Java | mpl-2.0 | 1,679 |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library 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.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionalTests.activeobject.async;
import java.io.Serializable;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.mop.StubObject;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.utils.TimeoutAccounter;
import functionalTests.FunctionalTest;
public class TestAsync extends FunctionalTest {
final static int TIMEOUT = 500;
final static int ESPYLON = (int) (TIMEOUT / 10);
static AO ao;
public TestAsync() {
}
@BeforeClass
static public void createAO() throws ActiveObjectCreationException, NodeException {
ao = PAActiveObject.newActive(AO.class, new Object[] { TIMEOUT });
}
@Before
public void waitServiceQueueIsEmpty() {
// For async test we have to wait the end of the previous service
try {
ao.waitEndOfService();
} catch (Exception e) {
logger.warn(e.getCause(), e);
}
logger.info("Service queue is empty");
}
// async
@Test
public void testVoid() throws ActiveObjectCreationException, NodeException {
long before = System.currentTimeMillis();
ao.m_void();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be synchronous but should be async",
after - before < TIMEOUT + ESPYLON);
}
// sync
@Test
public void testVoidWithException() throws Exception {
long before = System.currentTimeMillis();
ao.m_void_exception();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testChar() {
long before = System.currentTimeMillis();
ao.m_char();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testShort() {
long before = System.currentTimeMillis();
ao.m_short();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testInt() {
long before = System.currentTimeMillis();
ao.m_int();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testLong() {
long before = System.currentTimeMillis();
ao.m_long();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testFinal() {
long before = System.currentTimeMillis();
ao.m_final();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// async
@Test
public void testNonFinal() {
long before = System.currentTimeMillis();
ao.m_non_final();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be synchronous but should be async",
after - before < TIMEOUT + ESPYLON);
}
// sync
@Test
public void testNonFinalWithException() throws Exception {
long before = System.currentTimeMillis();
ao.m_non_final_exception();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testStaticFinal() {
long before = System.currentTimeMillis();
ao.m_static_final();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// async
@Test
public void testStaticNonFinal() {
long before = System.currentTimeMillis();
ao.m_static_non_final();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be synchronous but should be async",
after - before < TIMEOUT + ESPYLON);
}
// sync
@Test
public void testStaticNonFinalWithException() throws Exception {
long before = System.currentTimeMillis();
ao.m_static_non_final_exception();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testObjectArray() throws Exception {
long before = System.currentTimeMillis();
ao.m_object_array();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
// sync
@Test
public void testIntArray() throws Exception {
long before = System.currentTimeMillis();
ao.m_int_array();
long after = System.currentTimeMillis();
logger.info("Waited " + (after - before) + "ms");
Assert.assertTrue(ao instanceof StubObject);
Assert.assertTrue("Method call seems to be async but should be sync", after - before > TIMEOUT -
ESPYLON);
}
public static class AO {
int timeout = -1;
public AO() {
}
public AO(int timeout) {
this.timeout = timeout;
}
// Async
public void m_void() {
sleep();
}
// Sync
public void m_void_exception() throws Exception {
sleep();
}
public char m_char() {
sleep();
return 'c';
}
public short m_short() {
sleep();
return 1;
}
public int m_int() {
sleep();
return 1;
}
public long m_long() {
sleep();
return 1;
}
public FinalClass m_final() {
sleep();
return new FinalClass();
}
public NonFinalClass m_non_final() {
sleep();
return new NonFinalClass();
}
public NonFinalClass m_non_final_exception() throws Exception {
sleep();
return new NonFinalClass();
}
public StaticFinalClass m_static_final() {
sleep();
return new StaticFinalClass();
}
public StaticNonFinalClass m_static_non_final() {
sleep();
return new StaticNonFinalClass();
}
public StaticNonFinalClass m_static_non_final_exception() throws Exception {
sleep();
return new StaticNonFinalClass();
}
public Object[] m_object_array() {
sleep();
return new Object[] { new String("1"), new String("2") };
}
public int[] m_int_array() {
sleep();
return new int[] { 1, 2 };
}
private void sleep() {
TimeoutAccounter time = TimeoutAccounter.getAccounter(timeout);
do {
try {
Thread.sleep(time.getRemainingTimeout());
} catch (InterruptedException e) {
// miam miam miam
}
} while (!time.isTimeoutElapsed());
}
public int waitEndOfService() throws Exception {
// Assume that is call is synchronous
return 0;
}
}
final static public class StaticFinalClass extends Object implements Serializable {
}
static public class StaticNonFinalClass extends Object implements Serializable {
}
}
| moliva/proactive | src/Tests/functionalTests/activeobject/async/TestAsync.java | Java | agpl-3.0 | 10,828 |
<?php
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program 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 with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
/*
* Created on May 29, 2007
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
$module_name = 'sm_Responsable';
$searchdefs[$module_name] = array(
'templateMeta' => array(
'maxColumns' => '3',
'maxColumnsBasic' => '4',
'widths' => array('label' => '10', 'field' => '30'),
),
'layout' => array(
'basic_search' => array(
'name',
array('name'=>'current_user_only', 'label'=>'LBL_CURRENT_USER_FILTER', 'type'=>'bool'),
),
'advanced_search' => array(
'name',
array('name' => 'assigned_user_id', 'label' => 'LBL_ASSIGNED_TO', 'type' => 'enum', 'function' => array('name' => 'get_user_array', 'params' => array(false))),
),
),
);
?>
| auf/crm_auf_org | modules/sm_Responsable/metadata/searchdefs.php | PHP | agpl-3.0 | 3,113 |
/*!
* jQuery Password Strength plugin for Twitter Bootstrap
* Version: 3.0.4
*
* Copyright (c) 2008-2013 Tane Piper
* Copyright (c) 2013 Alejandro Blanco
* Dual licensed under the MIT and GPL licenses.
*/
(function (jQuery) {
// Source: src/i18n.js
var i18n = {};
(function (i18n, i18next) {
'use strict';
i18n.fallback = {
"wordMinLength": "Your password is too short",
"wordMaxLength": "Your password is too long",
"wordInvalidChar": "Your password contains an invalid character",
"wordNotEmail": "Do not use your email as your password",
"wordSimilarToUsername": "Your password cannot contain your username",
"wordTwoCharacterClasses": "Use different character classes",
"wordRepetitions": "Too many repetitions",
"wordSequences": "Your password contains sequences",
"errorList": "Errors:",
"veryWeak": "Very Weak",
"weak": "Weak",
"normal": "Normal",
"medium": "Medium",
"strong": "Strong",
"veryStrong": "Very Strong"
};
i18n.t = function (key) {
var result = '';
// Try to use i18next.com
if (i18next) {
result = i18next.t(key);
} else {
// Fallback to english
result = i18n.fallback[key];
}
return result === key ? '' : result;
};
}(i18n, window.i18next));
// Source: src/rules.js
var rulesEngine = {};
try {
if (!jQuery && module && module.exports) {
var jQuery = require("jquery"),
jsdom = require("jsdom").jsdom;
jQuery = jQuery(jsdom().defaultView);
}
} catch (ignore) {}
(function ($, rulesEngine) {
"use strict";
var validation = {};
rulesEngine.forbiddenSequences = [
"0123456789", "abcdefghijklmnopqrstuvwxyz", "qwertyuiop", "asdfghjkl",
"zxcvbnm", "!@#$%^&*()_+"
];
validation.wordNotEmail = function (options, word, score) {
if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) {
return score;
}
return 0;
};
validation.wordMinLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen < options.common.minChar) {
lenScore = (lenScore + score);
}
return lenScore;
};
validation.wordMaxLength = function (options, word, score) {
var wordlen = word.length,
lenScore = Math.pow(wordlen, options.rules.raisePower);
if (wordlen > options.common.maxChar) {
return score;
}
return lenScore;
};
validation.wordInvalidChar = function (options, word, score) {
if (options.common.invalidCharsRegExp.test(word)) {
return score;
}
return 0;
};
validation.wordMinLengthStaticScore = function (options, word, score) {
return word.length < options.common.minChar ? 0 : score;
};
validation.wordMaxLengthStaticScore = function (options, word, score) {
return word.length > options.common.maxChar ? 0 : score;
};
validation.wordSimilarToUsername = function (options, word, score) {
var username = $(options.common.usernameField).val();
if (username && word.toLowerCase().match(username.replace(/[\-\[\]\/\{\}\(\)\*\+\=\?\:\.\\\^\$\|\!\,]/g, "\\$&").toLowerCase())) {
return score;
}
return 0;
};
validation.wordTwoCharacterClasses = function (options, word, score) {
if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ||
(word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) ||
(word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) {
return score;
}
return 0;
};
validation.wordRepetitions = function (options, word, score) {
if (word.match(/(.)\1\1/)) { return score; }
return 0;
};
validation.wordSequences = function (options, word, score) {
var found = false,
j;
if (word.length > 2) {
$.each(rulesEngine.forbiddenSequences, function (idx, seq) {
if (found) { return; }
var sequences = [seq, seq.split('').reverse().join('')];
$.each(sequences, function (idx, sequence) {
for (j = 0; j < (word.length - 2); j += 1) { // iterate the word trough a sliding window of size 3:
if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
found = true;
}
}
});
});
if (found) { return score; }
}
return 0;
};
validation.wordLowercase = function (options, word, score) {
return word.match(/[a-z]/) && score;
};
validation.wordUppercase = function (options, word, score) {
return word.match(/[A-Z]/) && score;
};
validation.wordOneNumber = function (options, word, score) {
return word.match(/\d+/) && score;
};
validation.wordThreeNumbers = function (options, word, score) {
return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score;
};
validation.wordOneSpecialChar = function (options, word, score) {
return word.match(/[!,@,#,$,%,\^,&,*,?,_,~]/) && score;
};
validation.wordTwoSpecialChar = function (options, word, score) {
return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score;
};
validation.wordUpperLowerCombo = function (options, word, score) {
return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score;
};
validation.wordLetterNumberCombo = function (options, word, score) {
return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score;
};
validation.wordLetterNumberCharCombo = function (options, word, score) {
return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score;
};
validation.wordIsACommonPassword = function (options, word, score) {
if ($.inArray(word, options.rules.commonPasswords) >= 0) {
return score;
}
return 0;
};
rulesEngine.validation = validation;
rulesEngine.executeRules = function (options, word) {
var totalScore = 0;
$.each(options.rules.activated, function (rule, active) {
if (active) {
var score = options.rules.scores[rule],
funct = rulesEngine.validation[rule],
result,
errorMessage;
if (!$.isFunction(funct)) {
funct = options.rules.extra[rule];
}
if ($.isFunction(funct)) {
result = funct(options, word, score);
if (result) {
totalScore += result;
}
if (result < 0 || (!$.isNumeric(result) && !result)) {
errorMessage = options.ui.spanError(options, rule);
if (errorMessage.length > 0) {
options.instances.errors.push(errorMessage);
}
}
}
}
});
return totalScore;
};
}(jQuery, rulesEngine));
try {
if (module && module.exports) {
module.exports = rulesEngine;
}
} catch (ignore) {}
// Source: src/options.js
var defaultOptions = {};
defaultOptions.common = {};
defaultOptions.common.minChar = 6;
defaultOptions.common.maxChar = 20;
defaultOptions.common.usernameField = "#username";
defaultOptions.common.invalidCharsRegExp = new RegExp(/[\s,'"]/);
defaultOptions.common.userInputs = [
// Selectors for input fields with user input
];
defaultOptions.common.onLoad = undefined;
defaultOptions.common.onKeyUp = undefined;
defaultOptions.common.onScore = undefined;
defaultOptions.common.zxcvbn = false;
defaultOptions.common.zxcvbnTerms = [
// List of disrecommended words
];
defaultOptions.common.events = ["keyup", "change", "paste"];
defaultOptions.common.debug = false;
defaultOptions.rules = {};
defaultOptions.rules.extra = {};
defaultOptions.rules.scores = {
wordNotEmail: -100,
wordMinLength: -50,
wordMaxLength: -50,
wordInvalidChar: -100,
wordSimilarToUsername: -100,
wordSequences: -20,
wordTwoCharacterClasses: 2,
wordRepetitions: -25,
wordLowercase: 1,
wordUppercase: 3,
wordOneNumber: 3,
wordThreeNumbers: 5,
wordOneSpecialChar: 3,
wordTwoSpecialChar: 5,
wordUpperLowerCombo: 2,
wordLetterNumberCombo: 2,
wordLetterNumberCharCombo: 2,
wordIsACommonPassword: -100
};
defaultOptions.rules.activated = {
wordNotEmail: true,
wordMinLength: true,
wordMaxLength: false,
wordInvalidChar: false,
wordSimilarToUsername: true,
wordSequences: true,
wordTwoCharacterClasses: true,
wordRepetitions: true,
wordLowercase: true,
wordUppercase: true,
wordOneNumber: true,
wordThreeNumbers: true,
wordOneSpecialChar: true,
wordTwoSpecialChar: true,
wordUpperLowerCombo: true,
wordLetterNumberCombo: true,
wordLetterNumberCharCombo: true,
wordIsACommonPassword: true
};
defaultOptions.rules.raisePower = 1.4;
// List taken from https://github.com/danielmiessler/SecLists (MIT License)
defaultOptions.rules.commonPasswords = [
'123456',
'password',
'12345678',
'qwerty',
'123456789',
'12345',
'1234',
'111111',
'1234567',
'dragon',
'123123',
'baseball',
'abc123',
'football',
'monkey',
'letmein',
'696969',
'shadow',
'master',
'666666',
'qwertyuiop',
'123321',
'mustang',
'1234567890',
'michael',
'654321',
'pussy',
'superman',
'1qaz2wsx',
'7777777',
'fuckyou',
'121212',
'000000',
'qazwsx',
'123qwe',
'killer',
'trustno1',
'jordan',
'jennifer',
'zxcvbnm',
'asdfgh',
'hunter',
'buster',
'soccer',
'harley',
'batman',
'andrew',
'tigger',
'sunshine',
'iloveyou',
'fuckme',
'2000',
'charlie',
'robert',
'thomas',
'hockey',
'ranger',
'daniel',
'starwars',
'klaster',
'112233',
'george',
'asshole',
'computer',
'michelle',
'jessica',
'pepper',
'1111',
'zxcvbn',
'555555',
'11111111',
'131313',
'freedom',
'777777',
'pass',
'fuck',
'maggie',
'159753',
'aaaaaa',
'ginger',
'princess',
'joshua',
'cheese',
'amanda',
'summer',
'love',
'ashley',
'6969',
'nicole',
'chelsea',
'biteme',
'matthew',
'access',
'yankees',
'987654321',
'dallas',
'austin',
'thunder',
'taylor',
'matrix'
];
defaultOptions.ui = {};
defaultOptions.ui.bootstrap2 = false;
defaultOptions.ui.bootstrap3 = false;
defaultOptions.ui.colorClasses = [
"danger", "danger", "danger", "warning", "warning", "success"
];
defaultOptions.ui.showProgressBar = true;
defaultOptions.ui.progressBarEmptyPercentage = 1;
defaultOptions.ui.progressBarMinWidth = 1;
defaultOptions.ui.progressBarMinPercentage = 1;
defaultOptions.ui.progressExtraCssClasses = '';
defaultOptions.ui.progressBarExtraCssClasses = '';
defaultOptions.ui.showPopover = false;
defaultOptions.ui.popoverPlacement = "bottom";
defaultOptions.ui.showStatus = false;
defaultOptions.ui.spanError = function (options, key) {
"use strict";
var text = options.i18n.t(key);
if (!text) { return ''; }
return '<span style="color: #d52929">' + text + '</span>';
};
defaultOptions.ui.popoverError = function (options) {
"use strict";
var errors = options.instances.errors,
errorsTitle = options.i18n.t("errorList"),
message = "<div>" + errorsTitle + "<ul class='error-list' style='margin-bottom: 0;'>";
jQuery.each(errors, function (idx, err) {
message += "<li>" + err + "</li>";
});
message += "</ul></div>";
return message;
};
defaultOptions.ui.showVerdicts = true;
defaultOptions.ui.showVerdictsInsideProgressBar = false;
defaultOptions.ui.useVerdictCssClass = false;
defaultOptions.ui.showErrors = false;
defaultOptions.ui.showScore = false;
defaultOptions.ui.container = undefined;
defaultOptions.ui.viewports = {
progress: undefined,
verdict: undefined,
errors: undefined,
score: undefined
};
defaultOptions.ui.scores = [0, 14, 26, 38, 50];
defaultOptions.i18n = {};
defaultOptions.i18n.t = i18n.t;
// Source: src/ui.js
var ui = {};
(function ($, ui) {
"use strict";
var statusClasses = ["error", "warning", "success"],
verdictKeys = [
"veryWeak", "weak", "normal", "medium", "strong", "veryStrong"
];
ui.getContainer = function (options, $el) {
var $container;
$container = $(options.ui.container);
if (!($container && $container.length === 1)) {
$container = $el.parent();
}
return $container;
};
ui.findElement = function ($container, viewport, cssSelector) {
if (viewport) {
return $container.find(viewport).find(cssSelector);
}
return $container.find(cssSelector);
};
ui.getUIElements = function (options, $el) {
var $container, result;
if (options.instances.viewports) {
return options.instances.viewports;
}
$container = ui.getContainer(options, $el);
result = {};
result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress");
if (options.ui.showVerdictsInsideProgressBar) {
result.$verdict = result.$progressbar.find("span.password-verdict");
}
if (!options.ui.showPopover) {
if (!options.ui.showVerdictsInsideProgressBar) {
result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict");
}
result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list");
}
result.$score = ui.findElement($container, options.ui.viewports.score,
"span.password-score");
options.instances.viewports = result;
return result;
};
ui.initProgressBar = function (options, $el) {
var $container = ui.getContainer(options, $el),
progressbar = "<div class='progress ";
if (options.ui.bootstrap2) {
// Boostrap 2
progressbar += options.ui.progressBarExtraCssClasses +
"'><div class='";
} else {
// Bootstrap 3 & 4
progressbar += options.ui.progressExtraCssClasses + "'><div class='" +
options.ui.progressBarExtraCssClasses + " progress-";
}
progressbar += "bar'>";
if (options.ui.showVerdictsInsideProgressBar) {
progressbar += "<span class='password-verdict'></span>";
}
progressbar += "</div></div>";
if (options.ui.viewports.progress) {
$container.find(options.ui.viewports.progress).append(progressbar);
} else {
$(progressbar).insertAfter($el);
}
};
ui.initHelper = function (options, $el, html, viewport) {
var $container = ui.getContainer(options, $el);
if (viewport) {
$container.find(viewport).append(html);
} else {
$(html).insertAfter($el);
}
};
ui.initVerdict = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-verdict'></span>",
options.ui.viewports.verdict);
};
ui.initErrorList = function (options, $el) {
ui.initHelper(options, $el, "<ul class='error-list'></ul>",
options.ui.viewports.errors);
};
ui.initScore = function (options, $el) {
ui.initHelper(options, $el, "<span class='password-score'></span>",
options.ui.viewports.score);
};
ui.initPopover = function (options, $el) {
try {
$el.popover("destroy");
} catch (error) {
// Bootstrap 4.2.X onwards
$el.popover("dispose");
}
$el.popover({
html: true,
placement: options.ui.popoverPlacement,
trigger: "manual",
content: " "
});
};
ui.initUI = function (options, $el) {
if (options.ui.showPopover) {
ui.initPopover(options, $el);
} else {
if (options.ui.showErrors) { ui.initErrorList(options, $el); }
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.initVerdict(options, $el);
}
}
if (options.ui.showProgressBar) {
ui.initProgressBar(options, $el);
}
if (options.ui.showScore) {
ui.initScore(options, $el);
}
};
ui.updateProgressBar = function (options, $el, cssClass, percentage) {
var $progressbar = ui.getUIElements(options, $el).$progressbar,
$bar = $progressbar.find(".progress-bar"),
cssPrefix = "progress-";
if (options.ui.bootstrap2) {
$bar = $progressbar.find(".bar");
cssPrefix = "";
}
$.each(options.ui.colorClasses, function (idx, value) {
if (options.ui.bootstrap2 || options.ui.bootstrap3) {
$bar.removeClass(cssPrefix + "bar-" + value);
} else {
$bar.removeClass("bg-" + value);
}
});
if (options.ui.bootstrap2 || options.ui.bootstrap3) {
$bar.addClass(cssPrefix + "bar-" + options.ui.colorClasses[cssClass]);
} else {
$bar.addClass("bg-" + options.ui.colorClasses[cssClass]);
}
if (percentage > 0) {
$bar.css("min-width", options.ui.progressBarMinWidth + 'px');
} else {
$bar.css("min-width", '');
}
$bar.css("width", percentage + '%');
};
ui.updateVerdict = function (options, $el, cssClass, text) {
var $verdict = ui.getUIElements(options, $el).$verdict;
$verdict.removeClass(options.ui.colorClasses.join(' '));
if (cssClass > -1) {
$verdict.addClass(options.ui.colorClasses[cssClass]);
}
if (options.ui.showVerdictsInsideProgressBar) {
$verdict.css('white-space', 'nowrap');
}
$verdict.html(text);
};
ui.updateErrors = function (options, $el, remove) {
var $errors = ui.getUIElements(options, $el).$errors,
html = "";
if (!remove) {
$.each(options.instances.errors, function (idx, err) {
html += "<li>" + err + "</li>";
});
}
$errors.html(html);
};
ui.updateScore = function (options, $el, score, remove) {
var $score = ui.getUIElements(options, $el).$score,
html = "";
if (!remove) { html = score.toFixed(2); }
$score.html(html);
};
ui.updatePopover = function (options, $el, verdictText, remove) {
var popover = $el.data("bs.popover"),
html = "",
hide = true;
if (options.ui.showVerdicts &&
!options.ui.showVerdictsInsideProgressBar &&
verdictText.length > 0) {
html = "<h5><span class='password-verdict'>" + verdictText +
"</span></h5>";
hide = false;
}
if (options.ui.showErrors) {
if (options.instances.errors.length > 0) {
hide = false;
}
html += options.ui.popoverError(options);
}
if (hide || remove) {
$el.popover("hide");
return;
}
if (options.ui.bootstrap2) { popover = $el.data("popover"); }
if (popover.$arrow && popover.$arrow.parents("body").length > 0) {
$el.find("+ .popover .popover-content").html(html);
} else {
// It's hidden
if (options.ui.bootstrap2 || options.ui.bootstrap3) {
popover.options.content = html;
} else {
popover.config.content = html;
}
$el.popover("show");
}
};
ui.updateFieldStatus = function (options, $el, cssClass, remove) {
var $target = $el;
if (options.ui.bootstrap2) {
$target = $el.parents(".control-group").first();
} else if (options.ui.bootstrap3) {
$target = $el.parents(".form-group").first();
}
$.each(statusClasses, function (idx, css) {
if (options.ui.bootstrap3) {
css = "has-" + css;
} else if (!options.ui.bootstrap2) { // BS4
if (css === "error") { css = "danger"; }
css = "border-" + css;
}
$target.removeClass(css);
});
if (remove) { return; }
cssClass = statusClasses[Math.floor(cssClass / 2)];
if (options.ui.bootstrap3) {
cssClass = "has-" + cssClass;
} else if (!options.ui.bootstrap2) { // BS4
if (cssClass === "error") { cssClass = "danger"; }
cssClass = "border-" + cssClass;
}
$target.addClass(cssClass);
};
ui.percentage = function (options, score, maximun) {
var result = Math.floor(100 * score / maximun),
min = options.ui.progressBarMinPercentage;
result = result <= min ? min : result;
result = result > 100 ? 100 : result;
return result;
};
ui.getVerdictAndCssClass = function (options, score) {
var level, verdict;
if (score === undefined) { return ['', 0]; }
if (score <= options.ui.scores[0]) {
level = 0;
} else if (score < options.ui.scores[1]) {
level = 1;
} else if (score < options.ui.scores[2]) {
level = 2;
} else if (score < options.ui.scores[3]) {
level = 3;
} else if (score < options.ui.scores[4]) {
level = 4;
} else {
level = 5;
}
verdict = verdictKeys[level];
return [options.i18n.t(verdict), level];
};
ui.updateUI = function (options, $el, score) {
var cssClass, barPercentage, verdictText, verdictCssClass;
cssClass = ui.getVerdictAndCssClass(options, score);
verdictText = score === 0 ? '' : cssClass[0];
cssClass = cssClass[1];
verdictCssClass = options.ui.useVerdictCssClass ? cssClass : -1;
if (options.ui.showProgressBar) {
if (score === undefined) {
barPercentage = options.ui.progressBarEmptyPercentage;
} else {
barPercentage = ui.percentage(options, score, options.ui.scores[4]);
}
ui.updateProgressBar(options, $el, cssClass, barPercentage);
if (options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
}
if (options.ui.showStatus) {
ui.updateFieldStatus(options, $el, cssClass, score === undefined);
}
if (options.ui.showPopover) {
ui.updatePopover(options, $el, verdictText, score === undefined);
} else {
if (options.ui.showVerdicts && !options.ui.showVerdictsInsideProgressBar) {
ui.updateVerdict(options, $el, verdictCssClass, verdictText);
}
if (options.ui.showErrors) {
ui.updateErrors(options, $el, score === undefined);
}
}
if (options.ui.showScore) {
ui.updateScore(options, $el, score, score === undefined);
}
};
}(jQuery, ui));
// Source: src/methods.js
var methods = {};
(function ($, methods) {
"use strict";
var onKeyUp, onPaste, applyToAll;
onKeyUp = function (event) {
var $el = $(event.target),
options = $el.data("pwstrength-bootstrap"),
word = $el.val(),
userInputs,
verdictText,
verdictLevel,
score;
if (options === undefined) { return; }
options.instances.errors = [];
if (word.length === 0) {
score = undefined;
} else {
if (options.common.zxcvbn) {
userInputs = [];
$.each(options.common.userInputs.concat([options.common.usernameField]), function (idx, selector) {
var value = $(selector).val();
if (value) { userInputs.push(value); }
});
userInputs = userInputs.concat(options.common.zxcvbnTerms);
score = zxcvbn(word, userInputs).guesses;
score = Math.log(score) * Math.LOG2E;
} else {
score = rulesEngine.executeRules(options, word);
}
if ($.isFunction(options.common.onScore)) {
score = options.common.onScore(options, word, score);
}
}
ui.updateUI(options, $el, score);
verdictText = ui.getVerdictAndCssClass(options, score);
verdictLevel = verdictText[1];
verdictText = verdictText[0];
if (options.common.debug) {
console.log(score + ' - ' + verdictText);
}
if ($.isFunction(options.common.onKeyUp)) {
options.common.onKeyUp(event, {
score: score,
verdictText: verdictText,
verdictLevel: verdictLevel
});
}
};
onPaste = function (event) {
// This handler is necessary because the paste event fires before the
// content is actually in the input, so we cannot read its value right
// away. Therefore, the timeouts.
var $el = $(event.target),
word = $el.val(),
tries = 0,
callback;
callback = function () {
var newWord = $el.val();
if (newWord !== word) {
onKeyUp(event);
} else if (tries < 3) {
tries += 1;
setTimeout(callback, 100);
}
};
setTimeout(callback, 100);
};
methods.init = function (settings) {
this.each(function (idx, el) {
// Make it deep extend (first param) so it extends also the
// rules and other inside objects
var clonedDefaults = $.extend(true, {}, defaultOptions),
localOptions = $.extend(true, clonedDefaults, settings),
$el = $(el);
localOptions.instances = {};
$el.data("pwstrength-bootstrap", localOptions);
$.each(localOptions.common.events, function (idx, eventName) {
var handler = eventName === "paste" ? onPaste : onKeyUp;
$el.on(eventName, handler);
});
ui.initUI(localOptions, $el);
$el.trigger("keyup");
if ($.isFunction(localOptions.common.onLoad)) {
localOptions.common.onLoad();
}
});
return this;
};
methods.destroy = function () {
this.each(function (idx, el) {
var $el = $(el),
options = $el.data("pwstrength-bootstrap"),
elements = ui.getUIElements(options, $el);
elements.$progressbar.remove();
elements.$verdict.remove();
elements.$errors.remove();
$el.removeData("pwstrength-bootstrap");
});
};
methods.forceUpdate = function () {
this.each(function (idx, el) {
var event = { target: el };
onKeyUp(event);
});
};
methods.addRule = function (name, method, score, active) {
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap");
options.rules.activated[name] = active;
options.rules.scores[name] = score;
options.rules.extra[name] = method;
});
};
applyToAll = function (rule, prop, value) {
this.each(function (idx, el) {
$(el).data("pwstrength-bootstrap").rules[prop][rule] = value;
});
};
methods.changeScore = function (rule, score) {
applyToAll.call(this, rule, "scores", score);
};
methods.ruleActive = function (rule, active) {
applyToAll.call(this, rule, "activated", active);
};
methods.ruleIsMet = function (rule) {
var rulesMetCnt = 0;
if (rule === "wordMinLength") {
rule = "wordMinLengthStaticScore";
} else if (rule === "wordMaxLength") {
rule = "wordMaxLengthStaticScore";
}
this.each(function (idx, el) {
var options = $(el).data("pwstrength-bootstrap"),
ruleFunction = rulesEngine.validation[rule],
result;
if (!$.isFunction(ruleFunction)) {
ruleFunction = options.rules.extra[rule];
}
if ($.isFunction(ruleFunction)) {
result = ruleFunction(options, $(el).val(), 1);
if ($.isNumeric(result)) {
rulesMetCnt += result;
}
}
});
return (rulesMetCnt === this.length);
};
$.fn.pwstrength = function (method) {
var result;
if (methods[method]) {
result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
result = methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.pwstrength-bootstrap");
}
return result;
};
}(jQuery, methods));
}(jQuery)); | tejoesperanto/pasportaservo | pasportaservo/static/pwstrength/js/pwstrength-bootstrap.js | JavaScript | agpl-3.0 | 30,423 |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library 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.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.extensions.pamr.remoteobject;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.remoteobject.AbstractRemoteObjectFactory;
import org.objectweb.proactive.core.remoteobject.InternalRemoteRemoteObject;
import org.objectweb.proactive.core.remoteobject.InternalRemoteRemoteObjectImpl;
import org.objectweb.proactive.core.remoteobject.NotBoundException;
import org.objectweb.proactive.core.remoteobject.RemoteObject;
import org.objectweb.proactive.core.remoteobject.RemoteObjectAdapter;
import org.objectweb.proactive.core.remoteobject.RemoteObjectFactory;
import org.objectweb.proactive.core.remoteobject.RemoteRemoteObject;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.util.converter.remote.ProActiveMarshalInputStream;
import org.objectweb.proactive.core.util.converter.remote.ProActiveMarshalOutputStream;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.extensions.pamr.PAMRConfig;
import org.objectweb.proactive.extensions.pamr.PAMRLog4jCompat;
import org.objectweb.proactive.extensions.pamr.client.Agent;
import org.objectweb.proactive.extensions.pamr.client.AgentImpl;
import org.objectweb.proactive.extensions.pamr.client.ProActiveMessageHandler;
import org.objectweb.proactive.extensions.pamr.exceptions.PAMRException;
import org.objectweb.proactive.extensions.pamr.protocol.AgentID;
import org.objectweb.proactive.extensions.pamr.protocol.MagicCookie;
import org.objectweb.proactive.extensions.pamr.remoteobject.message.PAMRRegistryListRemoteObjectsMessage;
import org.objectweb.proactive.extensions.pamr.remoteobject.message.PAMRRemoteObjectLookupMessage;
import org.objectweb.proactive.extensions.pamr.remoteobject.util.PAMRRegistry;
import org.objectweb.proactive.extensions.pamr.remoteobject.util.socketfactory.PAMRSocketFactorySPI;
import org.objectweb.proactive.extensions.pamr.remoteobject.util.socketfactory.PAMRSocketFactorySelector;
import org.objectweb.proactive.extensions.pamr.remoteobject.util.socketfactory.PAMRSshSocketFactory;
import org.objectweb.proactive.extensions.pamr.router.RouterImpl;
/**
*
* @since ProActive 4.1.0
*/
public class PAMRRemoteObjectFactory extends AbstractRemoteObjectFactory implements RemoteObjectFactory {
static final Logger logger = ProActiveLogger.getLogger(PAMRConfig.Loggers.PAMR_REMOTE_OBJECT);
/** The protocol id of the facotry */
static final public String PROTOCOL_ID = "pamr";
final private Agent agent;
final private PAMRRegistry registry;
final private PAMRException badConfigException;
public PAMRRemoteObjectFactory() {
new PAMRLog4jCompat().ensureCompat();
String errMsg = "";
// Start the agent and contact the router
// Since there is no initialization phase in ProActive, if the router cannot be contacted
// we log the error and throw a runtime exception. We cannot do better here
String routerAddressStr = PAMRConfig.PA_NET_ROUTER_ADDRESS.getValue();
if (routerAddressStr == null) {
errMsg += PAMRConfig.PA_NET_ROUTER_ADDRESS.getName() + " is not set. ";
}
int routerPort;
if (PAMRConfig.PA_NET_ROUTER_PORT.isSet()) {
routerPort = PAMRConfig.PA_NET_ROUTER_PORT.getValue();
if (routerPort <= 0 || routerPort > 65535) {
errMsg += "Invalid router port value: " + routerPort + ". ";
}
} else {
routerPort = RouterImpl.DEFAULT_PORT;
logger.debug(PAMRConfig.PA_NET_ROUTER_PORT.getName() + " not set. Using the default port: " +
routerPort);
}
InetAddress routerAddress = null;
try {
routerAddress = InetAddress.getByName(routerAddressStr);
} catch (UnknownHostException e) {
errMsg += "Router address " + routerAddressStr + " cannot be resolved" + e.getMessage();
}
AgentID agentId = null;
if (PAMRConfig.PA_PAMR_AGENT_ID.isSet()) {
int id = PAMRConfig.PA_PAMR_AGENT_ID.getValue();
agentId = new AgentID(id);
}
MagicCookie magicCookie = null;
if (PAMRConfig.PA_PAMR_AGENT_MAGIC_COOKIE.isSet()) {
String str = PAMRConfig.PA_PAMR_AGENT_MAGIC_COOKIE.getValue();
try {
magicCookie = new MagicCookie(str);
} catch (IllegalArgumentException e) {
errMsg += "Invalid magic cookie: " + e.getMessage();
}
} else {
magicCookie = new MagicCookie();
}
PAMRSocketFactorySPI psf = PAMRSocketFactorySelector.get();
if (psf.getAlias().equals("ssh")) {
PAMRSshSocketFactory ssf = (PAMRSshSocketFactory) psf;
try {
String[] keys = ssf.getSshConfig().getPrivateKeyPath("");
if (keys == null || keys.length == 0) {
throw new IOException("No private key found in " + ssf.getSshConfig().getKeyDir());
}
} catch (IOException e) {
errMsg += "Misconfigured SSH SocketFactory: " + e.getMessage();
}
}
// Properly configured. The agent can be started
AgentImpl agent = null;
if ("".equals(errMsg)) {
try {
agent = new AgentImpl(routerAddress, routerPort, agentId, magicCookie,
ProActiveMessageHandler.class, PAMRSocketFactorySelector.get());
} catch (ProActiveException e) {
errMsg += "Failed to create PAMR agent: " + e.getMessage();
}
}
if ("".equals(errMsg)) {
this.agent = agent;
this.registry = PAMRRegistry.singleton;
this.badConfigException = null;
} else {
this.agent = null;
this.registry = null;
this.badConfigException = new PAMRException("Bad PAMR configuration: " + errMsg);
}
}
private void checkConfig() throws PAMRException {
if (this.badConfigException != null) {
throw this.badConfigException;
}
}
/*
* (non-Javadoc)
*
* @see
* org.objectweb.proactive.core.remoteobject.RemoteObjectFactory#newRemoteObject
* (org.objectweb .proactive.core.remoteobject.RemoteObject)
*/
public RemoteRemoteObject newRemoteObject(InternalRemoteRemoteObject target) throws PAMRException {
checkConfig();
return new PAMRRemoteObject(target, null, agent);
}
/**
* Registers an remote object into the registry
*
* @param urn
* The urn of the body (in fact his url + his name)
* @exception java.io.IOException
* if the remote body cannot be registered
*/
/*
* (non-Javadoc)
*
* @see
* org.objectweb.proactive.core.remoteobject.RemoteObjectFactory#register
* (org.objectweb.proactive .core.remoteobject.RemoteObject, java.net.URI,
* boolean)
*/
public RemoteRemoteObject register(InternalRemoteRemoteObject ro, URI uri, boolean replacePrevious)
throws ProActiveException {
checkConfig();
this.registry.bind(uri, ro, replacePrevious); // throw a ProActiveException if needed
PAMRRemoteObject rro = new PAMRRemoteObject(ro, uri, agent);
if (logger.isDebugEnabled()) {
logger.debug("Registered remote object at endpoint " + uri);
}
return rro;
}
/**
* Unregisters an remote object previously registered into the bodies table
*
* @param urn
* the urn under which the active object has been registered
*/
public void unregister(URI uri) throws ProActiveException {
checkConfig();
registry.unbind(uri);
}
/**
* Looks-up a remote object previously registered in the bodies table .
*
* @param urn
* the urn (in fact its url + name) the remote Body is registered
* to
* @return a UniversalBody
*/
@SuppressWarnings("unchecked")
public <T> RemoteObject<T> lookup(URI uri) throws ProActiveException {
checkConfig();
PAMRRemoteObjectLookupMessage message = new PAMRRemoteObjectLookupMessage(uri, agent);
try {
message.send();
RemoteRemoteObject result = message.getReturnedObject();
if (result == null) {
throw new NotBoundException("The uri " + uri + " is not bound to any known object");
} else {
return new RemoteObjectAdapter(result);
}
} catch (IOException e) {
throw new ProActiveException("Lookup of " + uri + "failed due to network error", e);
}
}
/**
* List all active object previously registered in the registry
*
* @param url
* the url of the host to scan, typically //machine_name
* @return a list of Strings, representing the registered names, and {} if
* no registry
* @exception java.io.IOException
* if scanning reported some problem (registry not found, or
* malformed Url)
*/
/*
* (non-Javadoc)
*
* @see
* org.objectweb.proactive.core.body.BodyAdapterImpl#list(java.lang.String)
*/
public URI[] list(URI uri) throws ProActiveException {
checkConfig();
PAMRRegistryListRemoteObjectsMessage message = new PAMRRegistryListRemoteObjectsMessage(uri, agent);
try {
message.send();
return message.getReturnedObject();
} catch (IOException e) {
throw new ProActiveException("Listing registered remote objects on " + uri +
" failed due to network error", e);
}
}
public String getProtocolId() {
return "pamr";
}
public void unexport(RemoteRemoteObject rro) throws ProActiveException {
checkConfig();
// see PROACTIVE-419
}
public int getPort() {
// Reverse connections are used with message routing so this method is
// irrelevant
return -1;
}
public InternalRemoteRemoteObject createRemoteObject(RemoteObject<?> remoteObject, String name,
boolean rebind) throws ProActiveException {
checkConfig();
if (this.agent.getAgentID() == null) {
throw new ProActiveException(
"PAMR agent has not yet been able to connect to the router. Remote object cannot be created");
}
try {
// Must be a fixed path
if (!name.startsWith("/")) {
name = "/" + name;
}
URI uri = new URI(this.getProtocolId(), null, this.agent.getAgentID().toString(), this.getPort(),
name, null, null);
// register the object on the register
InternalRemoteRemoteObject irro = new InternalRemoteRemoteObjectImpl(remoteObject, uri);
RemoteRemoteObject rmo = register(irro, uri, rebind);
irro.setRemoteRemoteObject(rmo);
return irro;
} catch (URISyntaxException e) {
throw new ProActiveException("Failed to create remote object " + name, e);
}
}
public Agent getAgent() {
return this.agent;
}
public URI getBaseURI() throws ProActiveException {
this.checkConfig();
AgentID id = this.agent.getAgentID();
if (id == null) {
throw new ProActiveException("PAMR Agent is not connected to router");
}
return URI.create(this.getProtocolId() + "://" + id.toString() + "/");
}
public ObjectInputStream getProtocolObjectInputStream(InputStream in) throws IOException {
return new ProActiveMarshalInputStream(in);
}
public ObjectOutputStream getProtocolObjectOutputStream(OutputStream out) throws IOException {
return new ProActiveMarshalOutputStream(out, ProActiveRuntimeImpl.getProActiveRuntime().getURL());
}
}
| jrochas/scale-proactive | src/Extensions/org/objectweb/proactive/extensions/pamr/remoteobject/PAMRRemoteObjectFactory.java | Java | agpl-3.0 | 13,912 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
class Shopware_Tests_Components_Thumbnail_ManagerTest extends \PHPUnit_Framework_TestCase
{
public function testManagerInstance()
{
$manager = Shopware()->Container()->get('thumbnail_manager');
$this->assertInstanceOf('\Shopware\Components\Thumbnail\Manager', $manager);
}
public function testThumbnailGeneration()
{
$manager = Shopware()->Container()->get('thumbnail_manager');
$mediaService = Shopware()->Container()->get('shopware_media.media_service');
$media = $this->getMediaModel();
$sizes = array(
'100x110',
array(120, 130),
array(140),
array(
'width' => 150,
'height' => 160
)
);
$manager->createMediaThumbnail($media, $sizes);
$thumbnailDir = Shopware()->DocPath('media_' . strtolower($media->getType()) . '_thumbnail');
$path = $thumbnailDir . $media->getName();
$this->assertTrue($mediaService->has($path . '_100x110.jpg'));
$this->assertTrue($mediaService->has($path . '_120x130.jpg'));
$this->assertTrue($mediaService->has($path . '_140x140.jpg'));
$this->assertTrue($mediaService->has($path . '_150x160.jpg'));
$mediaService->delete($media->getPath());
}
private function getMediaModel()
{
$mediaService = Shopware()->Container()->get('shopware_media.media_service');
$media = new \Shopware\Models\Media\Media();
$sourcePath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'sw_icon.png';
$imagePath = 'media/unknown/sw_icon.png';
$mediaService->write($imagePath, file_get_contents($sourcePath));
$file = new \Symfony\Component\HttpFoundation\File\File($sourcePath);
$media->setFile($file);
$media->setAlbumId(-10);
$media->setAlbum(Shopware()->Models()->find('Shopware\Models\Media\Album', -10));
$media->setPath(str_replace(Shopware()->DocPath(), '', $imagePath));
$media->setDescription('');
$media->setUserId(0);
return $media;
}
public function testGenerationWithoutPassedSizes()
{
$manager = Shopware()->Container()->get('thumbnail_manager');
$media = $this->getMediaModel();
$sizes = array(
'200x210',
'220x230',
'240x250'
);
$media->getAlbum()->getSettings()->setThumbnailSize($sizes);
$manager->createMediaThumbnail($media);
$thumbnailDir = Shopware()->DocPath('media_' . strtolower($media->getType()) . '_thumbnail');
$mediaService = Shopware()->Container()->get('shopware_media.media_service');
$path = $thumbnailDir . $media->getName();
foreach ($sizes as $size) {
$this->assertTrue($mediaService->has($path . '_' . $size . '.jpg'));
$this->assertTrue($mediaService->has($path . '_' . $size . '.png'));
}
}
public function testGenerationWithoutPassedSizesButProportion()
{
$manager = Shopware()->Container()->get('thumbnail_manager');
$media = $this->getMediaModel();
$sizes = array(
'300x310',
'320x330',
'340x350'
);
$proportionalSizes = array(
'300x298',
'320x318',
'340x337'
);
$media->getAlbum()->getSettings()->setThumbnailSize($sizes);
$manager->createMediaThumbnail($media, array(), true);
$thumbnailDir = Shopware()->DocPath('media_' . strtolower($media->getType()) . '_thumbnail');
$mediaService = Shopware()->Container()->get('shopware_media.media_service');
$path = $thumbnailDir . $media->getName();
foreach ($sizes as $key => $size) {
$this->assertTrue($mediaService->has($path . '_' . $size . '.jpg'));
$this->assertTrue($mediaService->has($path . '_' . $size . '.png'));
$image = imagecreatefromstring($mediaService->read($path . '_' . $size . '.jpg'));
$width = imagesx($image);
$height = imagesy($image);
$this->assertSame($proportionalSizes[$key], $width . 'x' . $height);
}
}
/**
* @expectedException Exception
* @expectedExceptionMessage No album configured for the passed media object and no size passed!
*/
public function testGenerationWithoutAlbum()
{
$media = new \Shopware\Models\Media\Media();
$sourcePath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'sw_icon.png';
$imagePath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'sw_icon_copy.png';
copy($sourcePath, $imagePath);
$file = new \Symfony\Component\HttpFoundation\File\File($imagePath);
$media->setFile($file);
$media->setPath(str_replace(Shopware()->DocPath(), '', $imagePath));
unlink($file->getRealPath());
$manager = Shopware()->Container()->get('thumbnail_manager');
$manager->createMediaThumbnail($media);
}
/**
* @expectedException Exception
* @expectedExceptionMessage File is not an image
*/
public function testGenerationWithEmptyMedia()
{
$media = new \Shopware\Models\Media\Media();
$manager = Shopware()->Container()->get('thumbnail_manager');
$manager->createMediaThumbnail($media);
}
public function testThumbnailCleanUp()
{
$media = $this->getMediaModel();
$defaultSizes = $media->getDefaultThumbnails();
$defaultSize = $defaultSizes[0];
$defaultSize = $defaultSize[0] . 'x' . $defaultSize[1];
$manager = Shopware()->Container()->get('thumbnail_manager');
$manager->createMediaThumbnail($media, array($defaultSize));
$thumbnailDir = Shopware()->DocPath('media_' . strtolower($media->getType()) . '_thumbnail');
$mediaService = Shopware()->Container()->get('shopware_media.media_service');
$path = $thumbnailDir . $media->getName();
$this->assertTrue($mediaService->has($path . '_' . $defaultSize . '.' . $media->getExtension()));
$manager->removeMediaThumbnails($media);
$this->assertFalse($mediaService->has($path . '_' . $defaultSize . '.' . $media->getExtension()));
$mediaService->delete($media->getPath());
$this->assertFalse($mediaService->has($media->getPath()));
}
}
| SvenHerrmann/shopware | tests/Shopware/Tests/Components/Thumbnail/ManagerTest.php | PHP | agpl-3.0 | 7,418 |
# https://djangosnippets.org/snippets/2533/
import inspect
from django.utils.html import strip_tags
from django.utils.encoding import force_unicode
def process_docstring(app, what, name, obj, options, lines):
# This causes import errors if left outside the function
from django.db import models
# Only look at objects that inherit from Django's base model class
if inspect.isclass(obj) and issubclass(obj, models.Model):
# Grab the field list from the meta class
fields = obj._meta.fields
for field in fields:
# Decode and strip any html out of the field's help text
help_text = strip_tags(force_unicode(field.help_text))
# Decode and capitalize the verbose name, for use if there isn't
# any help text
verbose_name = force_unicode(field.verbose_name).capitalize()
if help_text:
# Add the model field to the end of the docstring as a param
# using the help text as the description
lines.append(u':param %s: %s' % (field.attname, help_text))
else:
# Add the model field to the end of the docstring as a param
# using the verbose name as the description
lines.append(u':param %s: %s' % (field.attname, verbose_name))
# Add the field's type to the docstring
if isinstance(field, models.ForeignKey):
to = field.rel.to
lines.append(u':type %s: %s to :class:`~%s.%s`' % (field.attname, type(field).__name__, to.__module__, to.__name__))
else:
lines.append(u':type %s: %s' % (field.attname, type(field).__name__))
# Return the extended docstring
return lines
| waseem18/oh-mainline | vendor/packages/django-http-proxy/docs/_ext/django_models.py | Python | agpl-3.0 | 1,773 |
<?php
$lang->cmd_generate_code = 'Tạo Code';
$lang->widget_name = 'Tên Widget';
$lang->widget_maker = 'Người tạo';
$lang->widget_license = 'Giấy phép';
$lang->widget_history = 'Lịch sử cập nhật';
$lang->widget_info = 'Thông tin Widget';
$lang->widget_cache = 'Bộ nhớ đệm';
$lang->widget_fix_width = 'Cố định chiều rộng';
$lang->widget_width = 'Chiều rộng';
$lang->widget_position = 'Vị trí';
$lang->widget_position_none = 'Dòng tiếp theo';
$lang->widget_position_left = 'Trái';
$lang->widget_position_right = 'Phải';
$lang->widget_margin = 'Lề';
$lang->widget_margin_top = 'Lề trên';
$lang->widget_margin_right = 'Lề phải';
$lang->widget_margin_bottom = 'Lề dưới';
$lang->widget_margin_left = 'Lề trái';
$lang->about_widget_fix_width = 'Hãy kiểm tra để cố định chiều rộng.';
$lang->about_widget_width = 'Hãy đặt chiều rộng cho Widget.';
$lang->about_widget_position = 'Hãy chọn vị trí nếu bạn muốn nhiều Widget cùng hiển thị.';
$lang->about_widget_margin = 'Bạn có thể đặt lề của Widget: Trái, Phải, Trên, Dưới.';
$lang->about_widget_cache = 'Bộ nhớ đệm của Data có thể được sử dụng nếu bạn đặt thời gian cho nó.';
$lang->generated_code = 'Đã tạo Code';
$lang->widgetstyle = 'Kiểu dáng Widget';
$lang->msg_widget_is_not_exists = '\'%s\' không tồn tại.';
$lang->msg_widget_object_is_null = 'Đối tượng của \'%s\' đã không được tạo.';
$lang->msg_widget_proc_is_null = 'proc() của \'%s\' đã không được thực hiện.';
$lang->msg_widget_skin_is_null = 'Bạn cần phải chọn Skin cho Widget.';
$lang->about_widget_code = 'Hãy nhập các thông tin cần thiết, sau đó bấm nút [<b>Tạo Code</b>] để lấy Code thêm vào giao diện.';
$lang->about_widget_code_in_page = 'Sau khi nhập những thông tin cần thiết, bấm nút [<b>Tạo Code</b>] để chèn Code của Widget vào giao diện.';
$lang->about_widget = 'Widget là một ứng dụng nhỏ có thể đặt ở bất kì vị trí nào do người dùng lựa chọn.<br />Nó có thể kết nối với những Module trong Website hay Open API bên ngoài và hiển thị nội dung của Module đó.<br />Thông qua sự thiết lập cấu hình, nó có thể là một ứng dụng rộng dãi.<br />Bạn có thể thêm một Widget bằng cách bấm nút [<b>Tạo Code</b>] để lấy Code thêm vào một Module hay trang nào đó.';
$lang->cmd_content_insert = 'Chèn nội dung của bạn';
$lang->cmd_box_widget_insert = 'Chèn khung Widget';
$lang->cmd_remove_all_widgets = 'Xóa tất cả Widget';
$lang->cmd_widget_size = 'Kích thước';
$lang->cmd_widget_align = 'Căn chỉnh';
$lang->cmd_widget_align_left = 'Trái';
$lang->cmd_widget_align_right = 'Phải';
$lang->cmd_widget_margin = 'Lề';
$lang->cmd_widget_padding = 'Đệm';
$lang->cmd_widget_border = 'Viền';
$lang->cmd_widget_border_solid = 'Viền liền';
$lang->cmd_widget_border_dotted = 'Viền chấm';
$lang->cmd_widget_background_color = 'Màu nền';
$lang->cmd_widget_background_image_url = 'Hình nền';
$lang->cmd_widget_background_image_repeat = 'Lặp lại';
$lang->cmd_widget_background_image_no_repeat = 'Không lặp';
$lang->cmd_widget_background_image_x_repeat = 'Lặp chiều X';
$lang->cmd_widget_background_image_y_repeat = 'Lặp chiều Y';
$lang->cmd_widget_background_image_x = 'Vị trí X';
$lang->cmd_widget_background_image_y = 'Vị trí Y';
| xetown/xe-core | modules/widget/lang/vi.php | PHP | lgpl-2.1 | 3,546 |
package org.alfresco.repo.action.executer;
import org.alfresco.error.AlfrescoRuntimeException;
import org.springframework.extensions.surf.util.I18NUtil;
public class MailActionExecuterMonitor
{
private MailActionExecuter mailActionExceuter;
public String sendTestMessage()
{
try
{
mailActionExceuter.sendTestMessage();
Object[] params = {mailActionExceuter.getTestMessageTo()};
String message = I18NUtil.getMessage("email.outbound.test.send.success", params);
return message;
}
catch
(AlfrescoRuntimeException are)
{
return (are.getMessage());
}
}
public int getNumberFailedSends()
{
return mailActionExceuter.getNumberFailedSends();
}
public int getNumberSuccessfulSends()
{
return mailActionExceuter.getNumberSuccessfulSends();
}
public void setMailActionExecuter(MailActionExecuter mailActionExceuter)
{
this.mailActionExceuter = mailActionExceuter;
}
}
| fxcebx/community-edition | projects/repository/source/java/org/alfresco/repo/action/executer/MailActionExecuterMonitor.java | Java | lgpl-3.0 | 1,066 |
<?php
$model = new shopProductModel();
$sql = "SELECT id FROM `shop_product_skus` WHERE count IS NULL LIMIT 1";
if ($model->query($sql)->fetchField() > 0) {
$model->correctCount();
}
| RomanNosov/convershop | wa-data/protected/wa-installer/backup/wa-apps/shop/lib/updates/5.2.4/1427271828.php | PHP | lgpl-3.0 | 187 |
/*
* bootstrap-table - v1.2.4 - 2014-10-08
* https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2014 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.extend(a.fn.bootstrapTable.defaults,{formatLoadingMessage:function(){return"Cargando, espere por favor..."},formatRecordsPerPage:function(a){return a+" registros por página"},formatShowingRows:function(a,b,c){return"Mostrando "+a+" a "+b+" de "+c+" filas"},formatSearch:function(){return"Buscar"},formatNoMatches:function(){return"No se encontraron registros"}})}(jQuery); | bakasajoshua/web-lims-old | assets/bower_components/bootstrap-table/dist/locale/bootstrap-table-es_AR.min.js | JavaScript | lgpl-3.0 | 549 |
/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* 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/>.
*/
package org.alfresco.repo.dictionary;
import java.util.List;
/**
* Definition of a named value that can be used for property injection.
*
* @author Derek Hulley
*/
public class M2NamedValue
{
private String name;
private String simpleValue = null;
private List<String> listValue = null;
/*package*/ M2NamedValue()
{
}
@Override
public String toString()
{
return (name + "=" + (simpleValue == null ? listValue : simpleValue));
}
public String getName()
{
return name;
}
/**
* @return Returns the raw, unconverted value
*/
public String getSimpleValue()
{
return simpleValue;
}
/**
* @return Returns the list of raw, unconverted values
*/
public List<String> getListValue()
{
return listValue;
}
public void setName(String name)
{
this.name = name;
}
public void setSimpleValue(String simpleValue)
{
this.simpleValue = simpleValue;
}
public void setListValue(List<String> listValue)
{
this.listValue = listValue;
}
public boolean hasSimpleValue()
{
return (this.simpleValue != null);
}
public boolean hasListValue()
{
return (this.listValue != null);
}
}
| nguyentienlong/community-edition | projects/data-model/source/java/org/alfresco/repo/dictionary/M2NamedValue.java | Java | lgpl-3.0 | 2,109 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gobblin.service.modules.restli;
import java.io.IOException;
import java.util.Properties;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.collect.Maps;
import com.linkedin.data.template.RequiredFieldNotPresentException;
import com.linkedin.data.template.StringMap;
import org.apache.gobblin.service.FlowConfig;
import org.apache.gobblin.service.FlowConfigLoggedException;
import org.apache.gobblin.service.FlowConfigResourceLocalHandler;
import org.apache.gobblin.service.FlowId;
import org.apache.gobblin.service.Schedule;
@Test
public class FlowConfigUtilsTest {
private void testFlowSpec(FlowConfig flowConfig) {
try {
FlowConfigResourceLocalHandler.createFlowSpecForConfig(flowConfig);
} catch (FlowConfigLoggedException e) {
Assert.fail("Should not get to here");
}
}
private void testSerDer(FlowConfig flowConfig) {
try {
String serialized = FlowConfigUtils.serializeFlowConfig(flowConfig);
FlowConfig newFlowConfig = FlowConfigUtils.deserializeFlowConfig(serialized);
Assert.assertTrue(testEqual(flowConfig, newFlowConfig));
} catch (IOException e) {
Assert.fail("Should not get to here");
}
}
/**
* Due to default value setting, flow config after deserialization might contain default value.
* Only check f1.equals(f2) is not enough
*/
private boolean testEqual(FlowConfig f1, FlowConfig f2) {
if (f1.equals(f2)) {
return true;
}
// Check Id
Assert.assertTrue(f1.hasId() == f2.hasId());
Assert.assertTrue(f1.getId().equals(f2.getId()));
// Check Schedule
Assert.assertTrue(f1.hasSchedule() == f2.hasSchedule());
if (f1.hasSchedule()) {
Schedule s1 = f1.getSchedule();
Schedule s2 = f2.getSchedule();
Assert.assertTrue(s1.getCronSchedule().equals(s2.getCronSchedule()));
Assert.assertTrue(s1.isRunImmediately().equals(s2.isRunImmediately()));
}
// Check Template URI
Assert.assertTrue(f1.hasTemplateUris() == f2.hasTemplateUris());
if (f1.hasTemplateUris()) {
Assert.assertTrue(f1.getTemplateUris().equals(f2.getTemplateUris()));
}
// Check Properties
Assert.assertTrue(f1.hasProperties() == f2.hasProperties());
if (f1.hasProperties()) {
Assert.assertTrue(f1.getProperties().equals(f2.getProperties()));
}
return true;
}
public void testFullFlowConfig() {
FlowConfig flowConfig = new FlowConfig().setId(new FlowId()
.setFlowName("SN_CRMSYNC")
.setFlowGroup("DYNAMICS-USER-123456789"));
flowConfig.setSchedule(new Schedule()
.setCronSchedule("0 58 2/12 ? * * *")
.setRunImmediately(Boolean.valueOf("true")));
flowConfig.setTemplateUris("FS:///my.template");
Properties properties = new Properties();
properties.put("gobblin.flow.sourceIdentifier", "dynamicsCrm");
properties.put("gobblin.flow.destinationIdentifier", "espresso");
flowConfig.setProperties(new StringMap(Maps.fromProperties(properties)));
testFlowSpec(flowConfig);
testSerDer(flowConfig);
}
public void testFlowConfigWithoutSchedule() {
FlowConfig flowConfig = new FlowConfig().setId(new FlowId()
.setFlowName("SN_CRMSYNC")
.setFlowGroup("DYNAMICS-USER-123456789"));
flowConfig.setTemplateUris("FS:///my.template");
Properties properties = new Properties();
properties.put("gobblin.flow.sourceIdentifier", "dynamicsCrm");
properties.put("gobblin.flow.destinationIdentifier", "espresso");
flowConfig.setProperties(new StringMap(Maps.fromProperties(properties)));
testFlowSpec(flowConfig);
testSerDer(flowConfig);
}
public void testFlowConfigWithDefaultRunImmediately() {
FlowConfig flowConfig = new FlowConfig().setId(new FlowId()
.setFlowName("SN_CRMSYNC")
.setFlowGroup("DYNAMICS-USER-123456789"));
flowConfig.setSchedule(new Schedule()
.setCronSchedule("0 58 2/12 ? * * *"));
flowConfig.setTemplateUris("FS:///my.template");
Properties properties = new Properties();
properties.put("gobblin.flow.sourceIdentifier", "dynamicsCrm");
properties.put("gobblin.flow.destinationIdentifier", "espresso");
flowConfig.setProperties(new StringMap(Maps.fromProperties(properties)));
testFlowSpec(flowConfig);
testSerDer(flowConfig);
}
public void testFlowConfigWithoutTemplateUri() {
FlowConfig flowConfig = new FlowConfig().setId(new FlowId()
.setFlowName("SN_CRMSYNC")
.setFlowGroup("DYNAMICS-USER-123456789"));
flowConfig.setSchedule(new Schedule()
.setCronSchedule("0 58 2/12 ? * * *"));
Properties properties = new Properties();
properties.put("gobblin.flow.sourceIdentifier", "dynamicsCrm");
properties.put("gobblin.flow.destinationIdentifier", "espresso");
flowConfig.setProperties(new StringMap(Maps.fromProperties(properties)));
try {
FlowConfigResourceLocalHandler.createFlowSpecForConfig(flowConfig);
Assert.fail("Should not get to here");
} catch (RequiredFieldNotPresentException e) {
Assert.assertTrue(true, "templateUri cannot be empty");
}
testSerDer(flowConfig);
}
}
| jack-moseley/gobblin | gobblin-service/src/test/java/org/apache/gobblin/service/modules/restli/FlowConfigUtilsTest.java | Java | apache-2.0 | 6,005 |
/*
* Copyright 2014, Google 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.
*/
package org.jf.dexlib2.rewriter;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jf.dexlib2.base.reference.BaseTypeReference;
import org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.ClassDef;
import org.jf.dexlib2.iface.Field;
import org.jf.dexlib2.iface.Method;
import com.google.common.collect.Iterators;
public class ClassDefRewriter implements Rewriter<ClassDef> {
@Nonnull protected final Rewriters rewriters;
public ClassDefRewriter(@Nonnull Rewriters rewriters) {
this.rewriters = rewriters;
}
@Nonnull @Override public ClassDef rewrite(@Nonnull ClassDef classDef) {
return new RewrittenClassDef(classDef);
}
protected class RewrittenClassDef extends BaseTypeReference implements ClassDef {
@Nonnull protected ClassDef classDef;
public RewrittenClassDef(@Nonnull ClassDef classdef) {
this.classDef = classdef;
}
@Override @Nonnull public String getType() {
return rewriters.getTypeRewriter().rewrite(classDef.getType());
}
@Override public int getAccessFlags() {
return classDef.getAccessFlags();
}
@Override @Nullable public String getSuperclass() {
return RewriterUtils.rewriteNullable(rewriters.getTypeRewriter(), classDef.getSuperclass());
}
@Override @Nonnull public Set<String> getInterfaces() {
return RewriterUtils.rewriteSet(rewriters.getTypeRewriter(), classDef.getInterfaces());
}
@Override @Nullable public String getSourceFile() {
return classDef.getSourceFile();
}
@Override @Nonnull public Set<? extends Annotation> getAnnotations() {
return RewriterUtils.rewriteSet(rewriters.getAnnotationRewriter(), classDef.getAnnotations());
}
@Override @Nonnull public Iterable<? extends Field> getStaticFields() {
return RewriterUtils.rewriteIterable(rewriters.getFieldRewriter(), classDef.getStaticFields());
}
@Override @Nonnull public Iterable<? extends Field> getInstanceFields() {
return RewriterUtils.rewriteIterable(rewriters.getFieldRewriter(), classDef.getInstanceFields());
}
@Nonnull
@Override
public Iterable<? extends Field> getFields() {
return new Iterable<Field>() {
@Nonnull
@Override
public Iterator<Field> iterator() {
return Iterators.concat(getStaticFields().iterator(), getInstanceFields().iterator());
}
};
}
@Override @Nonnull public Iterable<? extends Method> getDirectMethods() {
return RewriterUtils.rewriteIterable(rewriters.getMethodRewriter(), classDef.getDirectMethods());
}
@Override @Nonnull public Iterable<? extends Method> getVirtualMethods() {
return RewriterUtils.rewriteIterable(rewriters.getMethodRewriter(), classDef.getVirtualMethods());
}
@Nonnull
@Override
public Iterable<? extends Method> getMethods() {
return new Iterable<Method>() {
@Nonnull
@Override
public Iterator<Method> iterator() {
return Iterators.concat(getDirectMethods().iterator(), getVirtualMethods().iterator());
}
};
}
}
}
| aliosmanyuksel/show-java | app/src/main/java/org/jf/dexlib2/rewriter/ClassDefRewriter.java | Java | apache-2.0 | 5,065 |
//// [tests/cases/conformance/types/import/importTypeGenericTypes.ts] ////
//// [foo.ts]
interface Point<T> {
x: number;
y: number;
data: T;
}
export = Point;
//// [foo2.ts]
namespace Bar {
export interface I<T> {
a: string;
b: number;
data: T;
}
}
export namespace Baz {
export interface J<T> {
a: number;
b: string;
data: T;
}
}
class Bar<T> {
item: Bar.I<T>;
constructor(input: Baz.J<T>) {}
}
export { Bar }
//// [usage.ts]
export const x: import("./foo")<{x: number}> = { x: 0, y: 0, data: {x: 12} };
export let y: import("./foo2").Bar.I<{x: number}> = { a: "", b: 0, data: {x: 12} };
export class Bar2<T> {
item: {a: string, b: number, c: object, data: T};
constructor(input?: any) {}
}
export let shim: typeof import("./foo2") = {
Bar: Bar2
};
//// [foo.js]
"use strict";
exports.__esModule = true;
//// [foo2.js]
"use strict";
exports.__esModule = true;
exports.Bar = void 0;
var Bar = /** @class */ (function () {
function Bar(input) {
}
return Bar;
}());
exports.Bar = Bar;
//// [usage.js]
"use strict";
exports.__esModule = true;
exports.shim = exports.Bar2 = exports.y = exports.x = void 0;
exports.x = { x: 0, y: 0, data: { x: 12 } };
exports.y = { a: "", b: 0, data: { x: 12 } };
var Bar2 = /** @class */ (function () {
function Bar2(input) {
}
return Bar2;
}());
exports.Bar2 = Bar2;
exports.shim = {
Bar: Bar2
};
//// [foo.d.ts]
interface Point<T> {
x: number;
y: number;
data: T;
}
export = Point;
//// [foo2.d.ts]
declare namespace Bar {
interface I<T> {
a: string;
b: number;
data: T;
}
}
export declare namespace Baz {
interface J<T> {
a: number;
b: string;
data: T;
}
}
declare class Bar<T> {
item: Bar.I<T>;
constructor(input: Baz.J<T>);
}
export { Bar };
//// [usage.d.ts]
export declare const x: import("./foo")<{
x: number;
}>;
export declare let y: import("./foo2").Bar.I<{
x: number;
}>;
export declare class Bar2<T> {
item: {
a: string;
b: number;
c: object;
data: T;
};
constructor(input?: any);
}
export declare let shim: typeof import("./foo2");
| Microsoft/TypeScript | tests/baselines/reference/importTypeGenericTypes.js | JavaScript | apache-2.0 | 2,330 |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import absolute_import
import unittest
import hamcrest as hc
from apache_beam.metrics.cells import DistributionData
from apache_beam.metrics.cells import DistributionResult
from apache_beam.metrics.execution import MetricKey
from apache_beam.metrics.execution import MetricResult
from apache_beam.metrics.execution import MetricUpdates
from apache_beam.metrics.metricbase import MetricName
from apache_beam.runners.direct.direct_metrics import DirectMetrics
class DirectMetricsTest(unittest.TestCase):
name1 = MetricName('namespace1', 'name1')
name2 = MetricName('namespace1', 'name2')
name3 = MetricName('namespace2', 'name1')
bundle1 = object() # For this test, any object can be a bundle
bundle2 = object()
def test_combiner_functions(self):
metrics = DirectMetrics()
counter = metrics._counters['anykey']
counter.commit_logical(self.bundle1, 5)
self.assertEqual(counter.extract_committed(), 5)
with self.assertRaises(TypeError):
counter.commit_logical(self.bundle1, None)
distribution = metrics._distributions['anykey']
distribution.commit_logical(self.bundle1, DistributionData(4, 1, 4, 4))
self.assertEqual(distribution.extract_committed(),
DistributionResult(DistributionData(4, 1, 4, 4)))
with self.assertRaises(AttributeError):
distribution.commit_logical(self.bundle1, None)
def test_commit_logical_no_filter(self):
metrics = DirectMetrics()
metrics.commit_logical(
self.bundle1,
MetricUpdates(
counters={MetricKey('step1', self.name1): 5,
MetricKey('step1', self.name2): 8},
distributions={
MetricKey('step1', self.name1): DistributionData(8, 2, 3, 5)}))
metrics.commit_logical(
self.bundle1,
MetricUpdates(
counters={MetricKey('step2', self.name1): 7,
MetricKey('step1', self.name2): 4},
distributions={
MetricKey('step1', self.name1): DistributionData(4, 1, 4, 4)}))
results = metrics.query()
hc.assert_that(
results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name2), 12, 0),
MetricResult(MetricKey('step2', self.name1), 7, 0),
MetricResult(MetricKey('step1', self.name1), 5, 0)]))
hc.assert_that(
results['distributions'],
hc.contains_inanyorder(
MetricResult(MetricKey('step1', self.name1),
DistributionResult(
DistributionData(12, 3, 3, 5)),
DistributionResult(
DistributionData(0, 0, None, None)))))
def test_apply_physical_no_filter(self):
metrics = DirectMetrics()
metrics.update_physical(object(),
MetricUpdates(
counters={MetricKey('step1', self.name1): 5,
MetricKey('step1', self.name3): 8}))
metrics.update_physical(object(),
MetricUpdates(
counters={MetricKey('step2', self.name1): 7,
MetricKey('step1', self.name3): 4}))
results = metrics.query()
hc.assert_that(results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name1), 0, 5),
MetricResult(MetricKey('step1', self.name3), 0, 12),
MetricResult(MetricKey('step2', self.name1), 0, 7)]))
metrics.commit_physical(object(), MetricUpdates())
results = metrics.query()
hc.assert_that(results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name1), 0, 5),
MetricResult(MetricKey('step1', self.name3), 0, 12),
MetricResult(MetricKey('step2', self.name1), 0, 7)]))
def test_apply_physical_logical(self):
metrics = DirectMetrics()
dist_zero = DistributionData(0, 0, None, None)
metrics.update_physical(
object(),
MetricUpdates(
counters={MetricKey('step1', self.name1): 7,
MetricKey('step1', self.name2): 5,
MetricKey('step2', self.name1): 1},
distributions={MetricKey('step1', self.name1):
DistributionData(3, 1, 3, 3),
MetricKey('step2', self.name3):
DistributionData(8, 2, 4, 4)}))
results = metrics.query()
hc.assert_that(results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name1), 0, 7),
MetricResult(MetricKey('step1', self.name2), 0, 5),
MetricResult(MetricKey('step2', self.name1), 0, 1)]))
hc.assert_that(results['distributions'],
hc.contains_inanyorder(*[
MetricResult(
MetricKey('step1', self.name1),
DistributionResult(dist_zero),
DistributionResult(DistributionData(3, 1, 3, 3))),
MetricResult(
MetricKey('step2', self.name3),
DistributionResult(dist_zero),
DistributionResult(DistributionData(8, 2, 4, 4)))]))
metrics.commit_physical(
object(),
MetricUpdates(
counters={MetricKey('step1', self.name1): -3,
MetricKey('step2', self.name1): -5},
distributions={MetricKey('step1', self.name1):
DistributionData(8, 4, 1, 5),
MetricKey('step2', self.name2):
DistributionData(8, 8, 1, 1)}))
results = metrics.query()
hc.assert_that(results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name1), 0, 4),
MetricResult(MetricKey('step1', self.name2), 0, 5),
MetricResult(MetricKey('step2', self.name1), 0, -4)]))
hc.assert_that(results['distributions'],
hc.contains_inanyorder(*[
MetricResult(
MetricKey('step1', self.name1),
DistributionResult(dist_zero),
DistributionResult(DistributionData(11, 5, 1, 5))),
MetricResult(
MetricKey('step2', self.name3),
DistributionResult(dist_zero),
DistributionResult(DistributionData(8, 2, 4, 4))),
MetricResult(
MetricKey('step2', self.name2),
DistributionResult(dist_zero),
DistributionResult(DistributionData(8, 8, 1, 1)))]))
metrics.commit_logical(
object(),
MetricUpdates(
counters={MetricKey('step1', self.name1): 3,
MetricKey('step1', self.name2): 5,
MetricKey('step2', self.name1): -3},
distributions={MetricKey('step1', self.name1):
DistributionData(11, 5, 1, 5),
MetricKey('step2', self.name2):
DistributionData(8, 8, 1, 1),
MetricKey('step2', self.name3):
DistributionData(4, 1, 4, 4)}))
results = metrics.query()
hc.assert_that(results['counters'],
hc.contains_inanyorder(*[
MetricResult(MetricKey('step1', self.name1), 3, 4),
MetricResult(MetricKey('step1', self.name2), 5, 5),
MetricResult(MetricKey('step2', self.name1), -3, -4)]))
hc.assert_that(results['distributions'],
hc.contains_inanyorder(*[
MetricResult(
MetricKey('step1', self.name1),
DistributionResult(DistributionData(11, 5, 1, 5)),
DistributionResult(DistributionData(11, 5, 1, 5))),
MetricResult(
MetricKey('step2', self.name3),
DistributionResult(DistributionData(4, 1, 4, 4)),
DistributionResult(DistributionData(8, 2, 4, 4))),
MetricResult(
MetricKey('step2', self.name2),
DistributionResult(DistributionData(8, 8, 1, 1)),
DistributionResult(DistributionData(8, 8, 1, 1)))]))
if __name__ == '__main__':
unittest.main()
| mxm/incubator-beam | sdks/python/apache_beam/runners/direct/direct_metrics_test.py | Python | apache-2.0 | 9,689 |
import {expect} from 'chai';
import * as Rx from '../../dist/cjs/Rx';
declare const {hot, cold, expectObservable, expectSubscriptions, type};
declare const Symbol: any;
const Observable = Rx.Observable;
const queueScheduler = Rx.Scheduler.queue;
/** @test {zip} */
describe('Observable.zip', () => {
it('should combine a source with a second', () => {
const a = hot('---1---2---3---');
const asubs = '^';
const b = hot('--4--5--6--7--8--');
const bsubs = '^';
const expected = '---x---y---z';
expectObservable(Observable.zip(a, b))
.toBe(expected, { x: ['1', '4'], y: ['2', '5'], z: ['3', '6'] });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should zip the provided observables', (done: MochaDone) => {
const expected = ['a1', 'b2', 'c3'];
let i = 0;
Observable.zip(
Observable.from(['a', 'b', 'c']),
Observable.from([1, 2, 3]), (a: string, b: number) => a + b)
.subscribe((x: string) => {
expect(x).to.equal(expected[i++]);
}, null, done);
});
it('should end once one observable completes and its buffer is empty', () => {
const e1 = hot('---a--b--c--| ');
const e1subs = '^ ! ';
const e2 = hot('------d----e----f--------| ');
const e2subs = '^ ! ';
const e3 = hot('--------h----i----j---------'); // doesn't complete
const e3subs = '^ ! ';
const expected = '--------x----y----(z|) '; // e1 complete and buffer empty
const values = {
x: ['a', 'd', 'h'],
y: ['b', 'e', 'i'],
z: ['c', 'f', 'j']
};
expectObservable(Observable.zip(e1, e2, e3)).toBe(expected, values);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
expectSubscriptions(e3.subscriptions).toBe(e3subs);
});
it('should end once one observable nexts and zips value from completed other ' +
'observable whose buffer is empty', () => {
const e1 = hot('---a--b--c--| ');
const e1subs = '^ ! ';
const e2 = hot('------d----e----f| ');
const e2subs = '^ ! ';
const e3 = hot('--------h----i----j-------'); // doesn't complete
const e3subs = '^ ! ';
const expected = '--------x----y----(z|) '; // e2 buffer empty and signaled complete
const values = {
x: ['a', 'd', 'h'],
y: ['b', 'e', 'i'],
z: ['c', 'f', 'j']
};
expectObservable(Observable.zip(e1, e2, e3)).toBe(expected, values);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
expectSubscriptions(e2.subscriptions).toBe(e2subs);
expectSubscriptions(e3.subscriptions).toBe(e3subs);
});
describe('with iterables', () => {
it('should zip them with values', () => {
const myIterator = <any>{
count: 0,
next: function () {
return { value: this.count++, done: false };
}
};
myIterator[Symbol.iterator] = function () { return this; };
const e1 = hot('---a---b---c---d---|');
const e1subs = '^ !';
const expected = '---w---x---y---z---|';
const values = {
w: ['a', 0],
x: ['b', 1],
y: ['c', 2],
z: ['d', 3]
};
expectObservable(Observable.zip(e1, myIterator)).toBe(expected, values);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should only call `next` as needed', () => {
let nextCalled = 0;
const myIterator = <any>{
count: 0,
next: () => {
nextCalled++;
return { value: this.count++, done: false };
}
};
myIterator[Symbol.iterator] = function() {
return this;
};
Observable.zip(Observable.of(1, 2, 3), myIterator)
.subscribe();
// since zip will call `next()` in advance, total calls when
// zipped with 3 other values should be 4.
expect(nextCalled).to.equal(4);
});
it('should work with never observable and empty iterable', () => {
const a = cold( '-');
const asubs = '^';
const b = [];
const expected = '-';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with empty observable and empty iterable', () => {
const a = cold('|');
const asubs = '(^!)';
const b = [];
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with empty observable and non-empty iterable', () => {
const a = cold('|');
const asubs = '(^!)';
const b = [1];
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with non-empty observable and empty iterable', () => {
const a = hot('---^----a--|');
const asubs = '^ !';
const b = [];
const expected = '--------|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with never observable and non-empty iterable', () => {
const a = cold('-');
const asubs = '^';
const b = [1];
const expected = '-';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with non-empty observable and non-empty iterable', () => {
const a = hot('---^----1--|');
const asubs = '^ ! ';
const b = [2];
const expected = '-----(x|)';
expectObservable(Observable.zip(a, b)).toBe(expected, { x: ['1', 2] });
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with non-empty observable and empty iterable', () => {
const a = hot('---^----#');
const asubs = '^ !';
const b = [];
const expected = '-----#';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with observable which raises error and non-empty iterable', () => {
const a = hot('---^----#');
const asubs = '^ !';
const b = [1];
const expected = '-----#';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with non-empty many observable and non-empty many iterable', () => {
const a = hot('---^--1--2--3--|');
const asubs = '^ ! ';
const b = [4, 5, 6];
const expected = '---x--y--(z|)';
expectObservable(Observable.zip(a, b)).toBe(expected,
{ x: ['1', 4], y: ['2', 5], z: ['3', 6] });
expectSubscriptions(a.subscriptions).toBe(asubs);
});
it('should work with non-empty observable and non-empty iterable selector that throws', () => {
const a = hot('---^--1--2--3--|');
const asubs = '^ !';
const b = [4, 5, 6];
const expected = '---x--#';
const selector = (x: string, y: number) => {
if (y === 5) {
throw new Error('too bad');
} else {
return x + y;
}};
expectObservable(Observable.zip(a, b, selector)).toBe(expected,
{ x: '14' }, new Error('too bad'));
expectSubscriptions(a.subscriptions).toBe(asubs);
});
});
it('should combine two observables and selector', () => {
const a = hot('---1---2---3---');
const asubs = '^';
const b = hot('--4--5--6--7--8--');
const bsubs = '^';
const expected = '---x---y---z';
expectObservable(Observable.zip(a, b, (e1: string, e2: string) => e1 + e2))
.toBe(expected, { x: '14', y: '25', z: '36' });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with n-ary symmetric', () => {
const a = hot('---1-^-1----4----|');
const asubs = '^ ! ';
const b = hot('---1-^--2--5----| ');
const bsubs = '^ ! ';
const c = hot('---1-^---3---6-| ');
const expected = '----x---y-| ';
expectObservable(Observable.zip(a, b, c)).toBe(expected,
{ x: ['1', '2', '3'], y: ['4', '5', '6'] });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with n-ary symmetric selector', () => {
const a = hot('---1-^-1----4----|');
const asubs = '^ ! ';
const b = hot('---1-^--2--5----| ');
const bsubs = '^ ! ';
const c = hot('---1-^---3---6-| ');
const expected = '----x---y-| ';
const observable = Observable.zip(a, b, c,
(r0: string, r1: string, r2: string) => [r0, r1, r2]);
expectObservable(observable).toBe(expected,
{ x: ['1', '2', '3'], y: ['4', '5', '6'] });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with n-ary symmetric array selector', () => {
const a = hot('---1-^-1----4----|');
const asubs = '^ ! ';
const b = hot('---1-^--2--5----| ');
const bsubs = '^ ! ';
const c = hot('---1-^---3---6-| ');
const expected = '----x---y-| ';
const observable = Observable.zip(a, b, c,
(r0: string, r1: string, r2: string) => [r0, r1, r2]);
expectObservable(observable).toBe(expected,
{ x: ['1', '2', '3'], y: ['4', '5', '6'] });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with some data asymmetric 1', () => {
const a = hot('---1-^-1-3-5-7-9-x-y-z-w-u-|');
const asubs = '^ ! ';
const b = hot('---1-^--2--4--6--8--0--| ');
const bsubs = '^ ! ';
const expected = '---a--b--c--d--e--| ';
expectObservable(Observable.zip(a, b, (r1: string, r2: string) => r1 + r2))
.toBe(expected, { a: '12', b: '34', c: '56', d: '78', e: '90' });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with some data asymmetric 2', () => {
const a = hot('---1-^--2--4--6--8--0--| ');
const asubs = '^ ! ';
const b = hot('---1-^-1-3-5-7-9-x-y-z-w-u-|');
const bsubs = '^ ! ';
const expected = '---a--b--c--d--e--| ';
expectObservable(Observable.zip(a, b, (r1: string, r2: string) => r1 + r2))
.toBe(expected, { a: '21', b: '43', c: '65', d: '87', e: '09' });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with some data symmetric', () => {
const a = hot('---1-^-1-3-5-7-9------| ');
const asubs = '^ ! ';
const b = hot('---1-^--2--4--6--8--0--|');
const bsubs = '^ ! ';
const expected = '---a--b--c--d--e-| ';
expectObservable(Observable.zip(a, b, (r1: string, r2: string) => r1 + r2))
.toBe(expected, { a: '12', b: '34', c: '56', d: '78', e: '90' });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with selector throws', () => {
const a = hot('---1-^-2---4----| ');
const asubs = '^ ! ';
const b = hot('---1-^--3----5----|');
const bsubs = '^ ! ';
const expected = '---x----# ';
const selector = (x: string, y: string) => {
if (y === '5') {
throw new Error('too bad');
} else {
return x + y;
}};
const observable = Observable.zip(a, b, selector);
expectObservable(observable).toBe(expected,
{ x: '23' }, new Error('too bad'));
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with right completes first', () => {
const a = hot('---1-^-2-----|');
const asubs = '^ !';
const b = hot('---1-^--3--|');
const bsubs = '^ !';
const expected = '---x--|';
expectObservable(Observable.zip(a, b)).toBe(expected, { x: ['2', '3'] });
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with two nevers', () => {
const a = cold( '-');
const asubs = '^';
const b = cold( '-');
const bsubs = '^';
const expected = '-';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with never and empty', () => {
const a = cold( '-');
const asubs = '(^!)';
const b = cold( '|');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with empty and never', () => {
const a = cold( '|');
const asubs = '(^!)';
const b = cold( '-');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with empty and empty', () => {
const a = cold( '|');
const asubs = '(^!)';
const b = cold( '|');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with empty and non-empty', () => {
const a = cold( '|');
const asubs = '(^!)';
const b = hot( '---1--|');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with non-empty and empty', () => {
const a = hot( '---1--|');
const asubs = '(^!)';
const b = cold( '|');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with never and non-empty', () => {
const a = cold( '-');
const asubs = '^';
const b = hot( '---1--|');
const bsubs = '^ !';
const expected = '-';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with non-empty and never', () => {
const a = hot( '---1--|');
const asubs = '^ !';
const b = cold( '-');
const bsubs = '^';
const expected = '-';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with empty and error', () => {
const a = cold( '|');
const asubs = '(^!)';
const b = hot( '------#', null, 'too bad');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with error and empty', () => {
const a = hot( '------#', null, 'too bad');
const asubs = '(^!)';
const b = cold( '|');
const bsubs = '(^!)';
const expected = '|';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with error', () => {
const a = hot('----------|');
const asubs = '^ ! ';
const b = hot('------# ');
const bsubs = '^ ! ';
const expected = '------# ';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with never and error', () => {
const a = cold( '-');
const asubs = '^ !';
const b = hot('------#');
const bsubs = '^ !';
const expected = '------#';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with error and never', () => {
const a = hot('------#');
const asubs = '^ !';
const b = cold( '-');
const bsubs = '^ !';
const expected = '------#';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with error and error', () => {
const a = hot('------#', null, 'too bad');
const asubs = '^ !';
const b = hot('----------#', null, 'too bad 2');
const bsubs = '^ !';
const expected = '------#';
expectObservable(Observable.zip(a, b)).toBe(expected, null, 'too bad');
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with two sources that eventually raise errors', () => {
const a = hot('--w-----#----', { w: 1 }, 'too bad');
const asubs = '^ !';
const b = hot('-----z-----#-', { z: 2 }, 'too bad 2');
const bsubs = '^ !';
const expected = '-----x--#';
expectObservable(Observable.zip(a, b)).toBe(expected, { x: [1, 2] }, 'too bad');
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with two sources that eventually raise errors (swapped)', () => {
const a = hot('-----z-----#-', { z: 2 }, 'too bad 2');
const asubs = '^ !';
const b = hot('--w-----#----', { w: 1 }, 'too bad');
const bsubs = '^ !';
const expected = '-----x--#';
expectObservable(Observable.zip(a, b)).toBe(expected, { x: [2, 1] }, 'too bad');
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should work with error and some', () => {
const a = cold( '#');
const asubs = '(^!)';
const b = hot( '--1--2--3--');
const bsubs = '(^!)';
const expected = '#';
expectObservable(Observable.zip(a, b)).toBe(expected);
expectSubscriptions(a.subscriptions).toBe(asubs);
expectSubscriptions(b.subscriptions).toBe(bsubs);
});
it('should combine an immediately-scheduled source with an immediately-scheduled second', (done: MochaDone) => {
const a = Observable.of<number>(1, 2, 3, queueScheduler);
const b = Observable.of<number>(4, 5, 6, 7, 8, queueScheduler);
const r = [[1, 4], [2, 5], [3, 6]];
let i = 0;
Observable.zip(a, b).subscribe((vals: Array<number>) => {
expect(vals).to.deep.equal(r[i++]);
}, null, done);
});
it('should support observables', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Rx.Observable<number>;
let b: Rx.Observable<string>;
let c: Rx.Observable<boolean>;
let o1: Rx.Observable<[number, string, boolean]> = Observable.zip(a, b, c);
/* tslint:enable:no-unused-variable */
});
});
it('should support mixed observables and promises', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Promise<number>;
let b: Rx.Observable<string>;
let c: Promise<boolean>;
let d: Rx.Observable<string[]>;
let o1: Rx.Observable<[number, string, boolean, string[]]> = Observable.zip(a, b, c, d);
/* tslint:enable:no-unused-variable */
});
});
it('should support arrays of promises', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Promise<number>[];
let o1: Rx.Observable<number[]> = Observable.zip(a);
let o2: Rx.Observable<number[]> = Observable.zip(...a);
/* tslint:enable:no-unused-variable */
});
});
it('should support arrays of observables', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Rx.Observable<number>[];
let o1: Rx.Observable<number[]> = Observable.zip(a);
let o2: Rx.Observable<number[]> = Observable.zip(...a);
/* tslint:enable:no-unused-variable */
});
});
it('should return Array<T> when given a single promise', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Promise<number>;
let o1: Rx.Observable<number[]> = Observable.zip(a);
/* tslint:enable:no-unused-variable */
});
});
it('should return Array<T> when given a single observable', () => {
type(() => {
/* tslint:disable:no-unused-variable */
let a: Rx.Observable<number>;
let o1: Rx.Observable<number[]> = Observable.zip(a);
/* tslint:enable:no-unused-variable */
});
});
}); | saneyuki/RxJS | spec/observables/zip-spec.ts | TypeScript | apache-2.0 | 21,889 |
def load_current_resource
definition_directory = ::File.join(node["sensu"]["directory"], "conf.d", "mutators")
@definition_path = ::File.join(definition_directory, "#{new_resource.name}.json")
end
action :create do
mutator = Sensu::Helpers.select_attributes(
new_resource,
%w[command timeout]
)
definition = {
"mutators" => {
new_resource.name => Sensu::Helpers.sanitize(mutator)
}
}
f = sensu_json_file @definition_path do
content definition
end
new_resource.updated_by_last_action(f.updated_by_last_action?)
end
action :delete do
f = sensu_json_file @definition_path do
action :delete
end
new_resource.updated_by_last_action(f.updated_by_last_action?)
end
| sh88/aws_chef_repo | providers/mutator.rb | Ruby | apache-2.0 | 718 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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.
import datetime
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import simple_tenant_usage
from nova.compute import api
from nova import context
from nova import flags
from nova.openstack.common import jsonutils
from nova.openstack.common import policy as common_policy
from nova.openstack.common import timeutils
from nova import policy
from nova import test
from nova.tests.api.openstack import fakes
FLAGS = flags.FLAGS
SERVERS = 5
TENANTS = 2
HOURS = 24
ROOT_GB = 10
EPHEMERAL_GB = 20
MEMORY_MB = 1024
VCPUS = 2
NOW = timeutils.utcnow()
START = NOW - datetime.timedelta(hours=HOURS)
STOP = NOW
def fake_instance_type_get(self, context, instance_type_id):
return {'id': 1,
'vcpus': VCPUS,
'root_gb': ROOT_GB,
'ephemeral_gb': EPHEMERAL_GB,
'memory_mb': MEMORY_MB,
'name':
'fakeflavor'}
def get_fake_db_instance(start, end, instance_id, tenant_id):
return {'id': instance_id,
'uuid': '00000000-0000-0000-0000-00000000000000%02d' % instance_id,
'image_ref': '1',
'project_id': tenant_id,
'user_id': 'fakeuser',
'display_name': 'name',
'state_description': 'state',
'instance_type_id': 1,
'launched_at': start,
'terminated_at': end}
def fake_instance_get_active_by_window(self, context, begin, end, project_id):
return [get_fake_db_instance(START,
STOP,
x,
"faketenant_%s" % (x / SERVERS))
for x in xrange(TENANTS * SERVERS)]
class SimpleTenantUsageTest(test.TestCase):
def setUp(self):
super(SimpleTenantUsageTest, self).setUp()
self.stubs.Set(api.API, "get_instance_type",
fake_instance_type_get)
self.stubs.Set(api.API, "get_active_by_window",
fake_instance_get_active_by_window)
self.admin_context = context.RequestContext('fakeadmin_0',
'faketenant_0',
is_admin=True)
self.user_context = context.RequestContext('fakeadmin_0',
'faketenant_0',
is_admin=False)
self.alt_user_context = context.RequestContext('fakeadmin_0',
'faketenant_1',
is_admin=False)
def _test_verify_index(self, start, stop):
req = webob.Request.blank(
'/v2/faketenant_0/os-simple-tenant-usage?start=%s&end=%s' %
(start.isoformat(), stop.isoformat()))
req.method = "GET"
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app(
fake_auth_context=self.admin_context))
self.assertEqual(res.status_int, 200)
res_dict = jsonutils.loads(res.body)
usages = res_dict['tenant_usages']
for i in xrange(TENANTS):
self.assertEqual(int(usages[i]['total_hours']),
SERVERS * HOURS)
self.assertEqual(int(usages[i]['total_local_gb_usage']),
SERVERS * (ROOT_GB + EPHEMERAL_GB) * HOURS)
self.assertEqual(int(usages[i]['total_memory_mb_usage']),
SERVERS * MEMORY_MB * HOURS)
self.assertEqual(int(usages[i]['total_vcpus_usage']),
SERVERS * VCPUS * HOURS)
self.assertFalse(usages[i].get('server_usages'))
def test_verify_index(self):
self._test_verify_index(START, STOP)
def test_verify_index_future_end_time(self):
future = NOW + datetime.timedelta(hours=HOURS)
self._test_verify_index(START, future)
def test_verify_show(self):
self._test_verify_show(START, STOP)
def test_verify_show_future_end_time(self):
future = NOW + datetime.timedelta(hours=HOURS)
self._test_verify_show(START, future)
def _get_tenant_usages(self, detailed=''):
req = webob.Request.blank(
'/v2/faketenant_0/os-simple-tenant-usage?'
'detailed=%s&start=%s&end=%s' %
(detailed, START.isoformat(), STOP.isoformat()))
req.method = "GET"
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app(
fake_auth_context=self.admin_context))
self.assertEqual(res.status_int, 200)
res_dict = jsonutils.loads(res.body)
return res_dict['tenant_usages']
def test_verify_detailed_index(self):
usages = self._get_tenant_usages('1')
for i in xrange(TENANTS):
servers = usages[i]['server_usages']
for j in xrange(SERVERS):
self.assertEqual(int(servers[j]['hours']), HOURS)
def test_verify_simple_index(self):
usages = self._get_tenant_usages(detailed='0')
for i in xrange(TENANTS):
self.assertEqual(usages[i].get('server_usages'), None)
def test_verify_simple_index_empty_param(self):
# NOTE(lzyeval): 'detailed=&start=..&end=..'
usages = self._get_tenant_usages()
for i in xrange(TENANTS):
self.assertEqual(usages[i].get('server_usages'), None)
def _test_verify_show(self, start, stop):
tenant_id = 0
req = webob.Request.blank(
'/v2/faketenant_0/os-simple-tenant-usage/'
'faketenant_%s?start=%s&end=%s' %
(tenant_id, start.isoformat(), stop.isoformat()))
req.method = "GET"
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app(
fake_auth_context=self.user_context))
self.assertEqual(res.status_int, 200)
res_dict = jsonutils.loads(res.body)
usage = res_dict['tenant_usage']
servers = usage['server_usages']
self.assertEqual(len(usage['server_usages']), SERVERS)
uuids = ['00000000-0000-0000-0000-00000000000000%02d' %
(x + (tenant_id * SERVERS)) for x in xrange(SERVERS)]
for j in xrange(SERVERS):
delta = STOP - START
uptime = delta.days * 24 * 3600 + delta.seconds
self.assertEqual(int(servers[j]['uptime']), uptime)
self.assertEqual(int(servers[j]['hours']), HOURS)
self.assertTrue(servers[j]['instance_id'] in uuids)
def test_verify_show_cant_view_other_tenant(self):
req = webob.Request.blank(
'/v2/faketenant_1/os-simple-tenant-usage/'
'faketenant_0?start=%s&end=%s' %
(START.isoformat(), STOP.isoformat()))
req.method = "GET"
req.headers["content-type"] = "application/json"
rules = {
"compute_extension:simple_tenant_usage:show":
[["role:admin"], ["project_id:%(project_id)s"]]
}
common_policy.set_brain(common_policy.HttpBrain(rules))
try:
res = req.get_response(fakes.wsgi_app(
fake_auth_context=self.alt_user_context))
self.assertEqual(res.status_int, 403)
finally:
policy.reset()
class SimpleTenantUsageSerializerTest(test.TestCase):
def _verify_server_usage(self, raw_usage, tree):
self.assertEqual('server_usage', tree.tag)
# Figure out what fields we expect
not_seen = set(raw_usage.keys())
for child in tree:
self.assertTrue(child.tag in not_seen)
not_seen.remove(child.tag)
self.assertEqual(str(raw_usage[child.tag]), child.text)
self.assertEqual(len(not_seen), 0)
def _verify_tenant_usage(self, raw_usage, tree):
self.assertEqual('tenant_usage', tree.tag)
# Figure out what fields we expect
not_seen = set(raw_usage.keys())
for child in tree:
self.assertTrue(child.tag in not_seen)
not_seen.remove(child.tag)
if child.tag == 'server_usages':
for idx, gr_child in enumerate(child):
self._verify_server_usage(raw_usage['server_usages'][idx],
gr_child)
else:
self.assertEqual(str(raw_usage[child.tag]), child.text)
self.assertEqual(len(not_seen), 0)
def test_serializer_show(self):
serializer = simple_tenant_usage.SimpleTenantUsageTemplate()
today = timeutils.utcnow()
yesterday = today - datetime.timedelta(days=1)
raw_usage = dict(
tenant_id='tenant',
total_local_gb_usage=789,
total_vcpus_usage=456,
total_memory_mb_usage=123,
total_hours=24,
start=yesterday,
stop=today,
server_usages=[dict(
instance_id='00000000-0000-0000-0000-0000000000000000',
name='test',
hours=24,
memory_mb=1024,
local_gb=50,
vcpus=1,
tenant_id='tenant',
flavor='m1.small',
started_at=yesterday,
ended_at=today,
state='terminated',
uptime=86400),
dict(
instance_id='00000000-0000-0000-0000-0000000000000002',
name='test2',
hours=12,
memory_mb=512,
local_gb=25,
vcpus=2,
tenant_id='tenant',
flavor='m1.tiny',
started_at=yesterday,
ended_at=today,
state='terminated',
uptime=43200),
],
)
tenant_usage = dict(tenant_usage=raw_usage)
text = serializer.serialize(tenant_usage)
print text
tree = etree.fromstring(text)
self._verify_tenant_usage(raw_usage, tree)
def test_serializer_index(self):
serializer = simple_tenant_usage.SimpleTenantUsagesTemplate()
today = timeutils.utcnow()
yesterday = today - datetime.timedelta(days=1)
raw_usages = [dict(
tenant_id='tenant1',
total_local_gb_usage=1024,
total_vcpus_usage=23,
total_memory_mb_usage=512,
total_hours=24,
start=yesterday,
stop=today,
server_usages=[dict(
instance_id='00000000-0000-0000-0000-0000000000000001',
name='test1',
hours=24,
memory_mb=1024,
local_gb=50,
vcpus=2,
tenant_id='tenant1',
flavor='m1.small',
started_at=yesterday,
ended_at=today,
state='terminated',
uptime=86400),
dict(
instance_id='00000000-0000-0000-0000-0000000000000002',
name='test2',
hours=42,
memory_mb=4201,
local_gb=25,
vcpus=1,
tenant_id='tenant1',
flavor='m1.tiny',
started_at=today,
ended_at=yesterday,
state='terminated',
uptime=43200),
],
),
dict(
tenant_id='tenant2',
total_local_gb_usage=512,
total_vcpus_usage=32,
total_memory_mb_usage=1024,
total_hours=42,
start=today,
stop=yesterday,
server_usages=[dict(
instance_id='00000000-0000-0000-0000-0000000000000003',
name='test3',
hours=24,
memory_mb=1024,
local_gb=50,
vcpus=2,
tenant_id='tenant2',
flavor='m1.small',
started_at=yesterday,
ended_at=today,
state='terminated',
uptime=86400),
dict(
instance_id='00000000-0000-0000-0000-0000000000000002',
name='test2',
hours=42,
memory_mb=4201,
local_gb=25,
vcpus=1,
tenant_id='tenant4',
flavor='m1.tiny',
started_at=today,
ended_at=yesterday,
state='terminated',
uptime=43200),
],
),
]
tenant_usages = dict(tenant_usages=raw_usages)
text = serializer.serialize(tenant_usages)
print text
tree = etree.fromstring(text)
self.assertEqual('tenant_usages', tree.tag)
self.assertEqual(len(raw_usages), len(tree))
for idx, child in enumerate(tree):
self._verify_tenant_usage(raw_usages[idx], child)
| tylertian/Openstack | openstack F/nova/nova/tests/api/openstack/compute/contrib/test_simple_tenant_usage.py | Python | apache-2.0 | 14,592 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.apex.malhar.python.base.requestresponse;
import java.util.Map;
public class PythonInterpreterResponse<T>
{
Class<T> responseTypeClass;
Map<String,Boolean> commandStatus;
// To be used only by the Kryo serializer framework
public PythonInterpreterResponse()
{
}
public PythonInterpreterResponse(Class<T> responseTypeClassHandle)
{
responseTypeClass = responseTypeClassHandle;
}
T response;
public T getResponse()
{
return response;
}
public void setResponse(T response)
{
this.response = response;
}
public Map<String, Boolean> getCommandStatus()
{
return commandStatus;
}
public void setCommandStatus(Map<String, Boolean> commandStatus)
{
this.commandStatus = commandStatus;
}
}
| tweise/apex-malhar | python/src/main/java/org/apache/apex/malhar/python/base/requestresponse/PythonInterpreterResponse.java | Java | apache-2.0 | 1,582 |
/**
* Yobi, Project Hosting SW
*
* Copyright 2013 NAVER Corp.
* http://yobi.io
*
* @author Yi EungJun
*
* 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 controllers;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlRow;
import controllers.annotation.AnonymousCheck;
import models.Label;
import org.apache.commons.lang3.StringUtils;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.avaje.ebean.Expr.icontains;
import static play.libs.Json.toJson;
@AnonymousCheck
public class LabelApp extends Controller {
private static final int MAX_FETCH_LABELS = 1000;
/**
* @param category a group of label to search
* @see <a href="https://github.com/nforge/yobi/blob/master/docs/technical/label-typeahead
* .md>label-typeahead.md</a>
*/
public static Result labels(String query, String category, Integer limit) {
if (!request().accepts("application/json")) {
return status(Http.Status.NOT_ACCEPTABLE);
}
ExpressionList<Label> el =
Label.find.where().and(icontains("category", category), icontains("name", query));
int total = el.findRowCount();
if (total > limit) {
el.setMaxRows(limit);
response().setHeader("Content-Range", "items " + limit + "/" + total);
}
ArrayList<String> labels = new ArrayList<>();
for (Label label: el.findList()) {
labels.add(label.name);
}
return ok(toJson(labels));
}
public static Result categories(String query, Integer limit) {
if (!request().accepts("application/json")) {
return status(Http.Status.NOT_ACCEPTABLE);
}
SqlQuery sqlQuery;
SqlQuery sqlCountQuery;
if (query != null && query.length() > 0) {
String sqlString =
"SELECT DISTINCT category FROM label WHERE lower(category) LIKE :category";
sqlQuery = Ebean
.createSqlQuery(sqlString)
.setParameter("category", "%" + query.toLowerCase() + "%");
sqlCountQuery = Ebean
.createSqlQuery("SELECT COUNT(*) AS cnt FROM (" + sqlString + ")")
.setParameter("category", "%" + query.toLowerCase() + "%");
} else {
String sqlString =
"SELECT DISTINCT category FROM label";
sqlQuery = Ebean
.createSqlQuery(sqlString);
sqlCountQuery = Ebean
.createSqlQuery("SELECT COUNT(*) AS cnt FROM (" + sqlString + ")");
}
int cnt = sqlCountQuery.findUnique().getInteger("cnt");
if (limit > MAX_FETCH_LABELS) {
limit = MAX_FETCH_LABELS;
}
if (cnt > limit) {
sqlQuery.setMaxRows(limit);
response().setHeader("Content-Range", "items " + limit + "/" + cnt);
}
List<String> categories = new ArrayList<>();
for (SqlRow row: sqlQuery.findList()) {
categories.add(row.getString("category"));
}
return ok(toJson(categories));
}
public static Set<Long> getLabelIds(final Http.Request request) {
Set<Long> set = new HashSet<>();
String[] labelIds = request.queryString().get("labelIds");
if (labelIds != null) {
for (String labelId : labelIds) {
if(!StringUtils.isEmpty(labelId)) {
set.add(Long.valueOf(labelId));
}
}
}
return set;
}
}
| ihoneymon/yobi | app/controllers/LabelApp.java | Java | apache-2.0 | 4,277 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for anf module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.autograph.pyct import compiler
from tensorflow.contrib.autograph.pyct import parser
from tensorflow.contrib.autograph.pyct import transformer
from tensorflow.contrib.autograph.pyct.common_transformers import anf
from tensorflow.python.platform import test
class AnfTransformerTest(test.TestCase):
def _simple_source_info(self):
return transformer.EntityInfo(
source_code=None,
source_file=None,
namespace=None,
arg_values=None,
arg_types=None,
owner_type=None)
def test_basic(self):
def test_function():
a = 0
return a
node, _ = parser.parse_entity(test_function)
node = anf.transform(node, self._simple_source_info())
result, _ = compiler.ast_to_object(node)
self.assertEqual(test_function(), result.test_function())
if __name__ == '__main__':
test.main()
| jart/tensorflow | tensorflow/contrib/autograph/pyct/common_transformers/anf_test.py | Python | apache-2.0 | 1,708 |
package com.mapswithme.maps.search;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.mapswithme.maps.R;
import com.mapswithme.maps.widget.recycler.TagItemDecoration;
import com.mapswithme.maps.widget.recycler.TagLayoutManager;
import com.mapswithme.util.Animations;
import com.mapswithme.util.InputUtils;
import com.mapswithme.util.UiUtils;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class HotelsFilterView extends FrameLayout
implements HotelsTypeAdapter.OnTypeSelectedListener
{
private static final String STATE_OPENED = "state_opened";
interface HotelsFilterListener
{
void onCancel();
void onDone(@Nullable HotelsFilter filter);
}
private View mFrame;
private View mFade;
private RatingFilterView mRating;
private PriceFilterView mPrice;
private View mContent;
private View mElevation;
private int mHeaderHeight;
private int mButtonsHeight;
private Drawable mTagsDecorator;
@NonNull
private final Set<HotelsFilter.HotelType> mHotelTypes = new HashSet<>();
@Nullable
private HotelsTypeAdapter mTypeAdapter;
@Nullable
private HotelsFilterListener mListener;
@Nullable
private HotelsFilter mFilter;
private boolean mOpened = false;
public HotelsFilterView(Context context)
{
this(context, null, 0);
}
public HotelsFilterView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public HotelsFilterView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public HotelsFilterView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context)
{
Resources res = context.getResources();
mHeaderHeight = (int) res.getDimension(
UiUtils.getStyledResourceId(context, android.R.attr.actionBarSize));
mButtonsHeight = (int) res.getDimension(R.dimen.height_block_base);
LayoutInflater.from(context).inflate(R.layout.hotels_filter, this, true);
mTagsDecorator = ContextCompat.getDrawable(context, R.drawable.divider_transparent_half);
}
@CallSuper
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
if (isInEditMode())
return;
mFrame = findViewById(R.id.frame);
mFrame.setTranslationY(mFrame.getResources().getDisplayMetrics().heightPixels);
mFade = findViewById(R.id.fade);
mRating = (RatingFilterView) findViewById(R.id.rating);
mPrice = (PriceFilterView) findViewById(R.id.price);
mContent = mFrame.findViewById(R.id.content);
mElevation = mFrame.findViewById(R.id.elevation);
RecyclerView type = (RecyclerView) mContent.findViewById(R.id.type);
type.setLayoutManager(new TagLayoutManager());
type.setNestedScrollingEnabled(false);
type.addItemDecoration(new TagItemDecoration(mTagsDecorator));
mTypeAdapter = new HotelsTypeAdapter(this);
type.setAdapter(mTypeAdapter);
findViewById(R.id.cancel).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
cancel();
}
});
findViewById(R.id.done).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
populateFilter();
if (mListener != null)
mListener.onDone(mFilter);
close();
}
});
findViewById(R.id.reset).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mFilter = null;
mHotelTypes.clear();
if (mListener != null)
mListener.onDone(null);
updateViews();
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (isInEditMode())
return;
mContent.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
mElevation.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = mContent.getMeasuredHeight() + mHeaderHeight + mButtonsHeight
+ mElevation.getMeasuredHeight();
if (height >= getMeasuredHeight())
height = LayoutParams.WRAP_CONTENT;
ViewGroup.LayoutParams lp = mFrame.getLayoutParams();
lp.height = height;
mFrame.setLayoutParams(lp);
}
private void cancel()
{
updateViews();
if (mListener != null)
mListener.onCancel();
close();
}
private void populateFilter()
{
mPrice.updateFilter();
final HotelsFilter.RatingFilter rating = mRating.getFilter();
final HotelsFilter price = mPrice.getFilter();
final HotelsFilter.OneOf oneOf = makeOneOf(mHotelTypes.iterator());
mFilter = combineFilters(rating, price, oneOf);
}
@Nullable
private HotelsFilter.OneOf makeOneOf(@NonNull Iterator<HotelsFilter.HotelType> iterator)
{
if (!iterator.hasNext())
return null;
HotelsFilter.HotelType type = iterator.next();
return new HotelsFilter.OneOf(type, makeOneOf(iterator));
}
@Nullable
private HotelsFilter combineFilters(@NonNull HotelsFilter... filters)
{
HotelsFilter result = null;
for (HotelsFilter filter : filters)
{
if (result == null)
{
result = filter;
continue;
}
if (filter != null)
result = new HotelsFilter.And(filter, result);
}
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if (mOpened && !UiUtils.isViewTouched(event, mFrame))
{
cancel();
return true;
}
super.onTouchEvent(event);
return mOpened;
}
public boolean close()
{
if (!mOpened)
return false;
mOpened = false;
Animations.fadeOutView(mFade, null);
Animations.disappearSliding(mFrame, Animations.BOTTOM, null);
return true;
}
public void open(@Nullable HotelsFilter filter)
{
if (mOpened)
return;
mOpened = true;
mFilter = filter;
Animations.fadeInView(mFade, null);
Animations.appearSliding(mFrame, Animations.BOTTOM, new Runnable()
{
@Override
public void run()
{
updateViews();
}
});
InputUtils.hideKeyboard(this);
}
private void updateViews()
{
if (mFilter == null)
{
mRating.update(null);
mPrice.update(null);
if (mTypeAdapter != null)
updateTypeAdapter(mTypeAdapter, null);
}
else
{
mRating.update(findRatingFilter(mFilter));
mPrice.update(findPriceFilter(mFilter));
if (mTypeAdapter != null)
updateTypeAdapter(mTypeAdapter, findTypeFilter(mFilter));
}
}
@Nullable
private HotelsFilter.RatingFilter findRatingFilter(@NonNull HotelsFilter filter)
{
if (filter instanceof HotelsFilter.RatingFilter)
return (HotelsFilter.RatingFilter) filter;
HotelsFilter.RatingFilter result;
if (filter instanceof HotelsFilter.And)
{
HotelsFilter.And and = (HotelsFilter.And) filter;
result = findRatingFilter(and.mLhs);
if (result == null)
result = findRatingFilter(and.mRhs);
return result;
}
return null;
}
@Nullable
private HotelsFilter findPriceFilter(@NonNull HotelsFilter filter)
{
if (filter instanceof HotelsFilter.PriceRateFilter)
return filter;
if (filter instanceof HotelsFilter.Or)
{
HotelsFilter.Or or = (HotelsFilter.Or) filter;
if (or.mLhs instanceof HotelsFilter.PriceRateFilter
&& or.mRhs instanceof HotelsFilter.PriceRateFilter )
{
return filter;
}
}
HotelsFilter result;
if (filter instanceof HotelsFilter.And)
{
HotelsFilter.And and = (HotelsFilter.And) filter;
result = findPriceFilter(and.mLhs);
if (result == null)
result = findPriceFilter(and.mRhs);
return result;
}
return null;
}
@Nullable
private HotelsFilter.OneOf findTypeFilter(@NonNull HotelsFilter filter)
{
if (filter instanceof HotelsFilter.OneOf)
return (HotelsFilter.OneOf) filter;
HotelsFilter.OneOf result;
if (filter instanceof HotelsFilter.And)
{
HotelsFilter.And and = (HotelsFilter.And) filter;
result = findTypeFilter(and.mLhs);
if (result == null)
result = findTypeFilter(and.mRhs);
return result;
}
return null;
}
private void updateTypeAdapter(@NonNull HotelsTypeAdapter typeAdapter,
@Nullable HotelsFilter.OneOf types)
{
mHotelTypes.clear();
if (types != null)
populateHotelTypes(mHotelTypes, types);
typeAdapter.updateItems(mHotelTypes);
}
private void populateHotelTypes(@NonNull Set<HotelsFilter.HotelType> hotelTypes,
@NonNull HotelsFilter.OneOf types)
{
hotelTypes.add(types.mType);
if (types.mTile != null)
populateHotelTypes(hotelTypes, types.mTile);
}
public void setListener(@Nullable HotelsFilterListener listener)
{
mListener = listener;
}
public void onSaveState(@NonNull Bundle outState)
{
outState.putBoolean(STATE_OPENED, mOpened);
}
public void onRestoreState(@NonNull Bundle state, @Nullable HotelsFilter filter)
{
if (state.getBoolean(STATE_OPENED, false))
open(filter);
}
@Override
public void onTypeSelected(boolean selected, @NonNull HotelsFilter.HotelType type)
{
if (selected)
mHotelTypes.add(type);
else
mHotelTypes.remove(type);
}
}
| goblinr/omim | android/src/com/mapswithme/maps/search/HotelsFilterView.java | Java | apache-2.0 | 10,253 |
#
# 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.
#
from __future__ import print_function
import datetime
import json
import textwrap
import time
from collections import namedtuple
from apache.aurora.client.api import AuroraClientAPI
from apache.aurora.client.base import combine_messages, get_update_page
from apache.aurora.client.cli import (
EXIT_API_ERROR,
EXIT_COMMAND_FAILURE,
EXIT_INVALID_CONFIGURATION,
EXIT_INVALID_PARAMETER,
EXIT_OK,
EXIT_UNKNOWN_ERROR,
Noun,
Verb
)
from apache.aurora.client.cli.context import AuroraCommandContext
from apache.aurora.client.cli.options import (
ALL_INSTANCES,
BIND_OPTION,
BROWSER_OPTION,
CONFIG_ARGUMENT,
HEALTHCHECK_OPTION,
INSTANCES_SPEC_ARGUMENT,
JOBSPEC_ARGUMENT,
JSON_READ_OPTION,
JSON_WRITE_OPTION,
STRICT_OPTION,
CommandOption
)
from apache.aurora.common.aurora_job_key import AuroraJobKey
from gen.apache.aurora.api.constants import ACTIVE_JOB_UPDATE_STATES
from gen.apache.aurora.api.ttypes import JobUpdateAction, JobUpdateKey, JobUpdateStatus
class UpdateController(object):
def __init__(self, api, context):
self.api = api
self.context = context
def get_update_key(self, job_key):
response = self.api.query_job_updates(update_statuses=ACTIVE_JOB_UPDATE_STATES, job_key=job_key)
self.context.log_response_and_raise(response)
summaries = response.result.getJobUpdateSummariesResult.updateSummaries
if response.result.getJobUpdateSummariesResult.updateSummaries:
if len(summaries) == 1:
return summaries[0].key
else:
raise self.context.CommandError(
EXIT_API_ERROR,
"The scheduler returned multiple active updates for this job.")
else:
return None
def _modify_update(self, job_key, mutate_fn, error_msg, success_msg):
update_key = self.get_update_key(job_key)
if update_key is None:
self.context.print_err("No active update found for this job.")
return EXIT_INVALID_PARAMETER
resp = mutate_fn(update_key)
self.context.log_response_and_raise(resp, err_code=EXIT_API_ERROR, err_msg=error_msg)
self.context.print_out(success_msg)
return EXIT_OK
def pause(self, job_key, message):
return self._modify_update(
job_key,
lambda key: self.api.pause_job_update(key, message),
"Failed to pause update due to error:",
"Update has been paused.")
def resume(self, job_key, message):
return self._modify_update(
job_key,
lambda key: self.api.resume_job_update(key, message),
"Failed to resume update due to error:",
"Update has been resumed.")
def abort(self, job_key, message):
return self._modify_update(
job_key,
lambda key: self.api.abort_job_update(key, message),
"Failed to abort update due to error:",
"Update has been aborted.")
def format_timestamp(stamp_millis):
return datetime.datetime.utcfromtimestamp(stamp_millis / 1000).isoformat()
MESSAGE_OPTION = CommandOption(
'--message',
'-m',
type=str,
default=None,
help='Message to include with the update state transition')
class StartUpdate(Verb):
UPDATE_MSG_TEMPLATE = "Job update has started. View your update progress at %s"
WAIT_OPTION = CommandOption(
'--wait',
default=False,
action='store_true',
help='Wait until the update completes')
def __init__(self, clock=time):
self._clock = clock
@property
def name(self):
return 'start'
def get_options(self):
return [
BIND_OPTION,
BROWSER_OPTION,
HEALTHCHECK_OPTION,
JSON_READ_OPTION,
MESSAGE_OPTION,
STRICT_OPTION,
INSTANCES_SPEC_ARGUMENT,
CONFIG_ARGUMENT,
self.WAIT_OPTION
]
@property
def help(self):
return textwrap.dedent("""\
Start a rolling update of a running job, using the update configuration within the config
file as a control for update velocity and failure tolerance.
The updater only takes action on instances in a job that have changed, meaning
that changing a single instance will only induce a restart on the changed task instance.
You may want to consider using the 'aurora job diff' subcommand before updating,
to preview what changes will take effect.
""")
def execute(self, context):
job = context.options.instance_spec.jobkey
instances = (None if context.options.instance_spec.instance == ALL_INSTANCES else
context.options.instance_spec.instance)
config = context.get_job_config(job, context.options.config_file)
if config.raw().has_cron_schedule():
raise context.CommandError(
EXIT_COMMAND_FAILURE,
"Cron jobs may only be updated with \"aurora cron schedule\" command")
api = context.get_api(config.cluster())
try:
resp = api.start_job_update(config, context.options.message, instances)
except AuroraClientAPI.UpdateConfigError as e:
raise context.CommandError(EXIT_INVALID_CONFIGURATION, e.message)
context.log_response_and_raise(resp, err_code=EXIT_API_ERROR,
err_msg="Failed to start update due to error:")
if resp.result:
update_key = resp.result.startJobUpdateResult.key
url = get_update_page(
api,
AuroraJobKey.from_thrift(config.cluster(), update_key.job),
resp.result.startJobUpdateResult.key.id)
context.print_out(self.UPDATE_MSG_TEMPLATE % url)
if context.options.wait:
return wait_for_update(context, self._clock, api, update_key)
else:
context.print_out(combine_messages(resp))
return EXIT_OK
def wait_for_update(context, clock, api, update_key):
cur_state = None
while True:
resp = api.query_job_updates(update_key=update_key)
context.log_response_and_raise(resp)
summaries = resp.result.getJobUpdateSummariesResult.updateSummaries
if len(summaries) == 1:
new_state = summaries[0].state.status
if new_state != cur_state:
cur_state = new_state
context.print_out('Current state %s' % JobUpdateStatus._VALUES_TO_NAMES[cur_state])
if cur_state not in ACTIVE_JOB_UPDATE_STATES:
if cur_state == JobUpdateStatus.ROLLED_FORWARD:
return EXIT_OK
elif cur_state == JobUpdateStatus.ROLLED_BACK:
return EXIT_COMMAND_FAILURE
else:
return EXIT_UNKNOWN_ERROR
clock.sleep(5)
elif len(summaries) == 0:
raise context.CommandError(EXIT_INVALID_PARAMETER, 'Job update not found.')
else:
raise context.CommandError(
EXIT_API_ERROR,
'Scheduler returned multiple updates: %s' % summaries)
UPDATE_ID_ARGUMENT = CommandOption(
'id',
type=str,
nargs='?',
metavar='ID',
help='Update identifier provided by the scheduler when an update was started.')
class UpdateWait(Verb):
def __init__(self, clock=time):
self._clock = clock
@property
def name(self):
return 'wait'
def get_options(self):
return [JOBSPEC_ARGUMENT, UPDATE_ID_ARGUMENT]
@property
def help(self):
return 'Block until an update has entered a terminal state.'
def execute(self, context):
return wait_for_update(
context,
self._clock,
context.get_api(context.options.jobspec.cluster),
JobUpdateKey(job=context.options.jobspec.to_thrift(), id=context.options.id))
class PauseUpdate(Verb):
@property
def name(self):
return 'pause'
def get_options(self):
return [JOBSPEC_ARGUMENT, MESSAGE_OPTION]
@property
def help(self):
return 'Pause an update.'
def execute(self, context):
job_key = context.options.jobspec
return UpdateController(context.get_api(job_key.cluster), context).pause(
job_key,
context.options.message)
class ResumeUpdate(Verb):
@property
def name(self):
return 'resume'
def get_options(self):
return [JOBSPEC_ARGUMENT, MESSAGE_OPTION]
@property
def help(self):
return 'Resume an update.'
def execute(self, context):
job_key = context.options.jobspec
return UpdateController(context.get_api(job_key.cluster), context).resume(
job_key,
context.options.message)
class AbortUpdate(Verb):
@property
def name(self):
return 'abort'
def get_options(self):
return [JOBSPEC_ARGUMENT, MESSAGE_OPTION]
@property
def help(self):
return 'Abort an in-progress update.'
def execute(self, context):
job_key = context.options.jobspec
return UpdateController(context.get_api(job_key.cluster), context).abort(
job_key,
context.options.message)
UpdateFilter = namedtuple('UpdateFilter', ['cluster', 'role', 'env', 'job'])
class ListUpdates(Verb):
@staticmethod
def update_filter(filter_str):
if filter_str is None or filter_str == '':
raise ValueError('Update filter must be non-empty')
parts = filter_str.split('/')
if len(parts) == 0 or len(parts) > 4:
raise ValueError('Update filter must be a path of the form CLUSTER/ROLE/ENV/JOB.')
# Pad with None.
parts = parts + ([None] * (4 - len(parts)))
return UpdateFilter(
cluster=parts[0],
role=parts[1],
env=parts[2],
job=parts[3])
@property
def name(self):
return 'list'
STATUS_GROUPS = dict({
'active': ACTIVE_JOB_UPDATE_STATES,
'all': set(JobUpdateStatus._VALUES_TO_NAMES.keys()),
'blocked': {
JobUpdateStatus.ROLL_FORWARD_AWAITING_PULSE, JobUpdateStatus.ROLL_BACK_AWAITING_PULSE},
'failed': {JobUpdateStatus.ERROR, JobUpdateStatus.FAILED, JobUpdateStatus.ROLLED_BACK},
'inactive': set(JobUpdateStatus._VALUES_TO_NAMES.keys()) - ACTIVE_JOB_UPDATE_STATES,
'paused': {JobUpdateStatus.ROLL_FORWARD_PAUSED, JobUpdateStatus.ROLL_BACK_PAUSED},
'succeeded': {JobUpdateStatus.ROLLED_FORWARD},
}.items() + [(k, {v}) for k, v in JobUpdateStatus._NAMES_TO_VALUES.items()])
def get_options(self):
return [
CommandOption(
'filter',
type=self.update_filter,
metavar="CLUSTER[/ROLE[/ENV[/JOB]]]",
help=('A path-like specifier for the scope of updates to list.')),
CommandOption(
"--status",
choices=self.STATUS_GROUPS,
default=[],
action="append",
help="""Update state to filter by. This may be specified multiple times, in which case
updates matching any of the specified statuses will be included."""),
CommandOption("--user", default=None, metavar="username",
help="The name of the user who initiated the update"),
JSON_WRITE_OPTION
]
@property
def help(self):
return "List summaries of job updates."
COLUMNS = [
('JOB', 47),
('UPDATE ID', 36),
('STATUS', 15),
('CREATED BY', 11),
('STARTED', 19),
('LAST MODIFIED', 19)
]
FORMAT_STR = ' '.join(["{%d:%d}" % (i, col[1]) for i, col in enumerate(COLUMNS)])
HEADER = FORMAT_STR.format(*[c[0] for c in COLUMNS])
def execute(self, context):
update_filter = context.options.filter
cluster = update_filter.cluster
if (update_filter.role is not None
and update_filter.env is not None
and update_filter.job is not None):
job_key = AuroraJobKey(
cluster=cluster,
role=update_filter.role,
env=update_filter.env,
name=update_filter.job)
else:
job_key = None
api = context.get_api(cluster)
filter_statuses = set()
for status in context.options.status:
filter_statuses = filter_statuses.union(set(self.STATUS_GROUPS[status]))
response = api.query_job_updates(
role=update_filter.role if job_key is None else None,
job_key=job_key,
update_statuses=filter_statuses if filter_statuses else None,
user=context.options.user)
context.log_response_and_raise(response)
# The API does not offer a way to query by environment, so if that filter is requested, we
# perform a more broad role-based query and filter here.
summaries = response.result.getJobUpdateSummariesResult.updateSummaries
if job_key is None and update_filter.env is not None:
summaries = [s for s in summaries if s.key.job.environment == update_filter.env]
if context.options.write_json:
result = []
for summary in summaries:
job_entry = {
"job": AuroraJobKey.from_thrift(cluster, summary.key.job).to_path(),
"id": summary.key.id,
"user": summary.user,
"started": format_timestamp(summary.state.createdTimestampMs),
"last_modified": format_timestamp(summary.state.lastModifiedTimestampMs),
"status": JobUpdateStatus._VALUES_TO_NAMES[summary.state.status]
}
result.append(job_entry)
context.print_out(json.dumps(result, indent=2, separators=[',', ': '], sort_keys=False))
else:
if summaries:
context.print_out(self.HEADER)
for summary in summaries:
context.print_out(self.FORMAT_STR.format(
AuroraJobKey.from_thrift(cluster, summary.key.job).to_path(),
summary.key.id,
JobUpdateStatus._VALUES_TO_NAMES[summary.state.status],
summary.user,
format_timestamp(summary.state.createdTimestampMs),
format_timestamp(summary.state.lastModifiedTimestampMs))
)
return EXIT_OK
class UpdateInfo(Verb):
@property
def name(self):
return 'info'
def get_options(self):
return [JSON_WRITE_OPTION, JOBSPEC_ARGUMENT, UPDATE_ID_ARGUMENT]
@property
def help(self):
return """Display detailed status information about a scheduler-driven in-progress update.
If no update ID is provided, information will be displayed about the active
update for the job."""
def execute(self, context):
if context.options.id:
key = JobUpdateKey(job=context.options.jobspec.to_thrift(), id=context.options.id)
else:
key = UpdateController(
context.get_api(context.options.jobspec.cluster),
context).get_update_key(context.options.jobspec)
if key is None:
context.print_err("There is no active update for this job.")
return EXIT_INVALID_PARAMETER
api = context.get_api(context.options.jobspec.cluster)
response = api.get_job_update_details(key)
context.log_response_and_raise(response)
details = response.result.getJobUpdateDetailsResult.details
if context.options.write_json:
result = {
"updateId": ("%s" % details.update.summary.key.id),
"job": str(context.options.jobspec),
"started": details.update.summary.state.createdTimestampMs,
"last_modified": format_timestamp(details.update.summary.state.lastModifiedTimestampMs),
"status": JobUpdateStatus._VALUES_TO_NAMES[details.update.summary.state.status],
"update_events": [],
"instance_update_events": []
}
update_events = details.updateEvents
if update_events is not None and len(update_events) > 0:
for event in update_events:
event_data = {
"status": JobUpdateStatus._VALUES_TO_NAMES[event.status],
"timestampMs": event.timestampMs
}
if event.message:
event_data["message"] = event.message
result["update_events"].append(event_data)
instance_events = details.instanceEvents
if instance_events is not None and len(instance_events) > 0:
for event in instance_events:
result["instance_update_events"].append({
"instance": event.instanceId,
"timestamp": event.timestampMs,
"action": JobUpdateAction._VALUES_TO_NAMES[event.action]
})
context.print_out(json.dumps(result, indent=2, separators=[',', ': '], sort_keys=False))
else:
context.print_out("Job: %s, UpdateID: %s" % (context.options.jobspec,
details.update.summary.key.id))
context.print_out("Started %s, last activity: %s" %
(format_timestamp(details.update.summary.state.createdTimestampMs),
format_timestamp(details.update.summary.state.lastModifiedTimestampMs)))
context.print_out("Current status: %s" %
JobUpdateStatus._VALUES_TO_NAMES[details.update.summary.state.status])
update_events = details.updateEvents
if update_events is not None and len(update_events) > 0:
context.print_out("Update events:")
for event in update_events:
context.print_out("Status: %s at %s" % (
JobUpdateStatus._VALUES_TO_NAMES[event.status],
format_timestamp(event.timestampMs)
), indent=2)
if event.message:
context.print_out(" message: %s" % event.message, indent=4)
instance_events = details.instanceEvents
if instance_events is not None and len(instance_events) > 0:
context.print_out("Instance events:")
for event in instance_events:
context.print_out("Instance %s at %s: %s" % (
event.instanceId, format_timestamp(event.timestampMs),
JobUpdateAction._VALUES_TO_NAMES[event.action]
), indent=2)
return EXIT_OK
class Update(Noun):
@property
def name(self):
return "update"
@property
def help(self):
return "Interact with the aurora update service."
@classmethod
def create_context(cls):
return AuroraCommandContext()
def __init__(self):
super(Update, self).__init__()
self.register_verb(StartUpdate())
self.register_verb(PauseUpdate())
self.register_verb(ResumeUpdate())
self.register_verb(AbortUpdate())
self.register_verb(ListUpdates())
self.register_verb(UpdateInfo())
self.register_verb(UpdateWait())
| shahankhatch/aurora | src/main/python/apache/aurora/client/cli/update.py | Python | apache-2.0 | 18,361 |
# Copyright 2013-2015 ARM Limited
#
# 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.
#
# pylint: disable=R0201
"""
This module contains a few "standard" result processors that write results to
text files in various formats.
"""
import os
import csv
import json
from wlauto import ResultProcessor, Parameter
from wlauto.exceptions import ConfigError
from wlauto.utils.types import list_of_strings
class StandardProcessor(ResultProcessor):
name = 'standard'
description = """
Creates a ``result.txt`` file for every iteration that contains metrics
for that iteration.
The metrics are written in ::
metric = value [units]
format.
"""
def process_iteration_result(self, result, context):
outfile = os.path.join(context.output_directory, 'result.txt')
with open(outfile, 'w') as wfh:
for metric in result.metrics:
line = '{} = {}'.format(metric.name, metric.value)
if metric.units:
line = ' '.join([line, metric.units])
line += '\n'
wfh.write(line)
context.add_artifact('iteration_result', 'result.txt', 'export')
class CsvReportProcessor(ResultProcessor):
"""
Creates a ``results.csv`` in the output directory containing results for
all iterations in CSV format, each line containing a single metric.
"""
name = 'csv'
parameters = [
Parameter('use_all_classifiers', kind=bool, default=False,
global_alias='use_all_classifiers',
description="""
If set to ``True``, this will add a column for every classifier
that features in at least one collected metric.
.. note:: This cannot be ``True`` if ``extra_columns`` is set.
"""),
Parameter('extra_columns', kind=list_of_strings,
description="""
List of classifiers to use as columns.
.. note:: This cannot be set if ``use_all_classifiers`` is ``True``.
"""),
]
def validate(self):
if self.use_all_classifiers and self.extra_columns:
raise ConfigError('extra_columns cannot be specified when use_all_classifiers is True')
def initialize(self, context):
self.results_so_far = [] # pylint: disable=attribute-defined-outside-init
def process_iteration_result(self, result, context):
self.results_so_far.append(result)
self._write_results(self.results_so_far, context)
def process_run_result(self, result, context):
self._write_results(result.iteration_results, context)
context.add_artifact('run_result_csv', 'results.csv', 'export')
def _write_results(self, results, context):
if self.use_all_classifiers:
classifiers = set([])
for ir in results:
for metric in ir.metrics:
classifiers.update(metric.classifiers.keys())
extra_columns = list(classifiers)
elif self.extra_columns:
extra_columns = self.extra_columns
else:
extra_columns = []
outfile = os.path.join(context.run_output_directory, 'results.csv')
with open(outfile, 'wb') as wfh:
writer = csv.writer(wfh)
writer.writerow(['id', 'workload', 'iteration', 'metric', ] +
extra_columns + ['value', 'units'])
for ir in results:
for metric in ir.metrics:
row = ([ir.id, ir.spec.label, ir.iteration, metric.name] +
[str(metric.classifiers.get(c, '')) for c in extra_columns] +
[str(metric.value), metric.units or ''])
writer.writerow(row)
class JsonReportProcessor(ResultProcessor):
"""
Creates a ``results.json`` in the output directory containing results for
all iterations in JSON format.
"""
name = 'json'
def process_run_result(self, result, context):
outfile = os.path.join(context.run_output_directory, 'results.json')
with open(outfile, 'wb') as wfh:
output = []
for result in result.iteration_results:
output.append({
'id': result.id,
'workload': result.workload.name,
'iteration': result.iteration,
'metrics': [dict([(k, v) for k, v in m.__dict__.iteritems()
if not k.startswith('_')])
for m in result.metrics],
})
json.dump(output, wfh, indent=4)
context.add_artifact('run_result_json', 'results.json', 'export')
class SummaryCsvProcessor(ResultProcessor):
"""
Similar to csv result processor, but only contains workloads' summary metrics.
"""
name = 'summary_csv'
def process_run_result(self, result, context):
outfile = os.path.join(context.run_output_directory, 'summary.csv')
with open(outfile, 'wb') as wfh:
writer = csv.writer(wfh)
writer.writerow(['id', 'workload', 'iteration', 'metric', 'value', 'units'])
for result in result.iteration_results:
for metric in result.metrics:
if metric.name in result.workload.summary_metrics:
row = [result.id, result.workload.name, result.iteration,
metric.name, str(metric.value), metric.units or '']
writer.writerow(row)
context.add_artifact('run_result_summary', 'summary.csv', 'export')
| bjackman/workload-automation | wlauto/result_processors/standard.py | Python | apache-2.0 | 6,207 |
/*
* Copyright 2004 The Closure Compiler 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 com.google.javascript.jscomp;
public final class RemoveUnusedVarsTest extends CompilerTestCase {
private boolean removeGlobal;
private boolean preserveFunctionExpressionNames;
private boolean modifyCallSites;
public RemoveUnusedVarsTest() {
super("function alert() {}");
enableNormalize();
}
@Override
public void setUp() {
removeGlobal = true;
preserveFunctionExpressionNames = false;
modifyCallSites = false;
compareJsDoc = false;
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
return new RemoveUnusedVars(
compiler, removeGlobal, preserveFunctionExpressionNames,
modifyCallSites);
}
public void testRemoveUnusedVars() {
// Test lots of stuff
test("var a;var b=3;var c=function(){};var x=A();var y; var z;" +
"function A(){B()} function B(){C(b)} function C(){} " +
"function X(){Y()} function Y(z){Z(x)} function Z(){y} " +
"P=function(){A()}; " +
"try{0}catch(e){a}",
"var a;var b=3;A();function A(){B()}" +
"function B(){C(b)}" +
"function C(){}" +
"P=function(){A()}" +
";try{0}catch(e){a}");
// Test removal from if {} blocks
test("var i=0;var j=0;if(i>0){var k=1;}",
"var i=0;if(i>0);");
// Test with for loop
test("for (var i in booyah) {" +
" if (i > 0) x += ', ';" +
" var arg = 'foo';" +
" if (arg.length > 40) {" +
" var unused = 'bar';" + // this variable is unused
" arg = arg.substr(0, 40) + '...';" +
" }" +
" x += arg;" +
"}",
"for(var i in booyah){if(i>0)x+=\", \";" +
"var arg=\"foo\";if(arg.length>40)arg=arg.substr(0,40)+\"...\";" +
"x+=arg}");
// Test with function expressions in another function call
test("function A(){}" +
"if(0){function B(){}}win.setTimeout(function(){A()})",
"function A(){}" +
"if(0);win.setTimeout(function(){A()})");
// Test with recursive functions
test("function A(){A()}function B(){B()}B()",
"function B(){B()}B()");
// Test with multiple var declarations.
test("var x,y=2,z=3;A(x);B(z);var a,b,c=4;C()",
"var x,z=3;A(x);B(z);C()");
// Test with for loop declarations
test("for(var i=0,j=0;i<10;){}" +
"for(var x=0,y=0;;y++){}" +
"for(var a,b;;){a}" +
"for(var c,d;;);" +
"for(var item in items){}",
"for(var i=0;i<10;);" +
"for(var y=0;;y++);" +
"for(var a;;)a;" +
"for(;;);" +
"for(var item in items);");
// Test multiple passes required
test("var a,b,c,d;var e=[b,c];var x=e[3];var f=[d];print(f[0])",
"var d;var f=[d];print(f[0])");
// Test proper scoping (static vs dynamic)
test("var x;function A(){var x;B()}function B(){print(x)}A()",
"var x;function A(){B()}function B(){print(x)}A()");
// Test closures in a return statement
test("function A(){var x;return function(){print(x)}}A()",
"function A(){var x;return function(){print(x)}}A()");
// Test other closures, multiple passes
test("function A(){}function B(){" +
"var c,d,e,f,g,h;" +
"function C(){print(c)}" +
"var handler=function(){print(d)};" +
"var handler2=function(){handler()};" +
"e=function(){print(e)};" +
"if(1){function G(){print(g)}}" +
"arr=[function(){print(h)}];" +
"return function(){print(f)}}B()",
"function B(){" +
"var f,h;" +
"if(1);" +
"arr=[function(){print(h)}];" +
"return function(){print(f)}}B()");
// Test exported names
test("var a,b=1; function _A1() {this.foo(a)}",
"var a;function _A1(){this.foo(a)}");
// Test undefined (i.e. externally defined) names
test("undefinedVar = 1", "undefinedVar=1");
// Test unused vars with side effects
test("var a,b=foo(),c=i++,d;var e=boo();var f;print(d);",
"foo(); i++; var d; boo(); print(d)");
test("var a,b=foo()", "foo()");
test("var b=foo(),a", "foo()");
test("var a,b=foo(a)", "var a; foo(a);");
}
public void testFunctionArgRemoval() {
// remove all function arguments
test("var b=function(c,d){return};b(1,2)",
"var b=function(){return};b(1,2)");
// remove no function arguments
testSame("var b=function(c,d){return c+d};b(1,2)");
testSame("var b=function(e,f,c,d){return c+d};b(1,2)");
// remove some function arguments
test("var b=function(c,d,e,f){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b(1,2)");
test("var b=function(e,c,f,d,g){return c+d};b(1,2)",
"var b=function(e,c,f,d){return c+d};b(1,2)");
}
public void testFunctionArgRemovalFromCallSites() {
this.modifyCallSites = true;
// remove all function arguments
test("var b=function(c,d){return};b(1,2)",
"var b=function(){return};b()");
// remove no function arguments
testSame("var b=function(c,d){return c+d};b(1,2)");
test("var b=function(e,f,c,d){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b()");
// remove some function arguments
test("var b=function(c,d,e,f){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b(1,2)");
test("var b=function(e,c,f,d,g){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b(2)");
}
public void testFunctionsDeadButEscaped() {
testSame("function b(a) { a = 1; print(arguments[0]) }; b(6)");
testSame("function b(a) { var c = 2; a = c; print(arguments[0]) }; b(6)");
}
public void testVarInControlStructure() {
test("if (true) var b = 3;", "if(true);");
test("if (true) var b = 3; else var c = 5;", "if(true);else;");
test("while (true) var b = 3;", "while(true);");
test("for (;;) var b = 3;", "for(;;);");
test("do var b = 3; while(true)", "do;while(true)");
test("with (true) var b = 3;", "with(true);");
test("f: var b = 3;","f:{}");
}
public void testRValueHoisting() {
test("var x = foo();", "foo()");
test("var x = {a: foo()};", "({a:foo()})");
test("var x=function y(){}", "");
}
public void testModule() {
test(createModules(
"var unreferenced=1; function x() { foo(); }" +
"function uncalled() { var x; return 2; }",
"var a,b; function foo() { this.foo(a); } x()"),
new String[] {
"function x(){foo()}",
"var a;function foo(){this.foo(a)}x()"
});
}
public void testRecursiveFunction1() {
testSame("(function x(){return x()})()");
}
public void testRecursiveFunction2() {
test("var x = 3; (function x() { return x(); })();",
"(function x$$1(){return x$$1()})()");
}
public void testFunctionWithName1() {
test("var x=function f(){};x()",
"var x=function(){};x()");
preserveFunctionExpressionNames = true;
testSame("var x=function f(){};x()");
}
public void testFunctionWithName2() {
test("foo(function bar(){})",
"foo(function(){})");
preserveFunctionExpressionNames = true;
testSame("foo(function bar(){})");
}
public void testRemoveGlobal1() {
removeGlobal = false;
testSame("var x=1");
test("var y=function(x){var z;}", "var y=function(x){}");
}
public void testRemoveGlobal2() {
removeGlobal = false;
testSame("var x=1");
test("function y(x){var z;}", "function y(x){}");
}
public void testRemoveGlobal3() {
removeGlobal = false;
testSame("var x=1");
test("function x(){function y(x){var z;}y()}",
"function x(){function y(x){}y()}");
}
public void testRemoveGlobal4() {
removeGlobal = false;
testSame("var x=1");
test("function x(){function y(x){var z;}}",
"function x(){}");
}
public void testIssue168a() {
test("function _a(){" +
" (function(x){ _b(); })(1);" +
"}" +
"function _b(){" +
" _a();" +
"}",
"function _a(){(function(){_b()})(1)}" +
"function _b(){_a()}");
}
public void testIssue168b() {
removeGlobal = false;
test("function a(){" +
" (function(x){ b(); })(1);" +
"}" +
"function b(){" +
" a();" +
"}",
"function a(){(function(x){b()})(1)}" +
"function b(){a()}");
}
public void testUnusedAssign1() {
test("var x = 3; x = 5;", "");
}
public void testUnusedAssign2() {
test("function f(a) { a = 3; } this.x = f;",
"function f(){} this.x=f");
}
public void testUnusedAssign3() {
// e can't be removed, so we don't try to remove the dead assign.
// We might be able to improve on this case.
test("try { throw ''; } catch (e) { e = 3; }",
"try{throw\"\";}catch(e){e=3}");
}
public void testUnusedAssign4() {
test("function f(a, b) { this.foo(b); a = 3; } this.x = f;",
"function f(a,b){this.foo(b);}this.x=f");
}
public void testUnusedAssign5() {
test("var z = function f() { f = 3; }; z();",
"var z=function(){};z()");
}
public void testUnusedAssign5b() {
test("var z = function f() { f = alert(); }; z();",
"var z=function(){alert()};z()");
}
public void testUnusedAssign6() {
test("var z; z = 3;", "");
}
public void testUnusedAssign6b() {
test("var z; z = alert();", "alert()");
}
public void testUnusedAssign7() {
// This loop is normalized to "var i;for(i in..."
test("var a = 3; for (var i in {}) { i = a; }",
// TODO(johnlenz): "i = a" should be removed here.
"var a = 3; var i; for (i in {}) {i = a;}");
}
public void testUnusedAssign8() {
// This loop is normalized to "var i;for(i in..."
test("var a = 3; for (var i in {}) { i = a; } alert(a);",
// TODO(johnlenz): "i = a" should be removed here.
"var a = 3; var i; for (i in {}) {i = a} alert(a);");
}
public void testUnusedAssign9() {
test("function b(a) { a = 1; arguments=1; }; b(6)",
"function b() { arguments=1; }; b(6)");
}
public void testUnusedPropAssign1() {
test("var x = {}; x.foo = 3;", "");
}
public void testUnusedPropAssign1b() {
test("var x = {}; x.foo = alert();", "alert()");
}
public void testUnusedPropAssign2() {
test("var x = {}; x['foo'] = 3;", "");
}
public void testUnusedPropAssign2b() {
test("var x = {}; x[alert()] = alert();", "alert(),alert()");
}
public void testUnusedPropAssign3() {
test("var x = {}; x['foo'] = {}; x['bar'] = 3", "");
}
public void testUnusedPropAssign3b() {
test("var x = {}; x[alert()] = alert(); x[alert() + alert()] = alert()",
"alert(),alert();(alert() + alert()),alert()");
}
public void testUnusedPropAssign4() {
test("var x = {foo: 3}; x['foo'] = 5;", "");
}
public void testUnusedPropAssign5() {
test("var x = {foo: bar()}; x['foo'] = 5;",
"var x={foo:bar()};x[\"foo\"]=5");
}
public void testUnusedPropAssign6() {
test("var x = function() {}; x.prototype.bar = function() {};", "");
}
public void testUnusedPropAssign7() {
test("var x = {}; x[x.foo] = x.bar;", "");
}
public void testUnusedPropAssign7b() {
testSame("var x = {}; x[x.foo] = alert(x.bar);");
}
public void testUnusedPropAssign7c() {
test("var x = {}; x[alert(x.foo)] = x.bar;",
"var x={};x[alert(x.foo)]=x.bar");
}
public void testUsedPropAssign1() {
test("function f(x) { x.bar = 3; } f({});",
"function f(x){x.bar=3}f({})");
}
public void testUsedPropAssign2() {
test("try { throw z; } catch (e) { e.bar = 3; }",
"try{throw z;}catch(e){e.bar=3}");
}
public void testUsedPropAssign3() {
// This pass does not do flow analysis.
test("var x = {}; x.foo = 3; x = bar();",
"var x={};x.foo=3;x=bar()");
}
public void testUsedPropAssign4() {
test("var y = foo(); var x = {}; x.foo = 3; y[x.foo] = 5;",
"var y=foo();var x={};x.foo=3;y[x.foo]=5");
}
public void testUsedPropAssign5() {
test("var y = foo(); var x = 3; y[x] = 5;",
"var y=foo();var x=3;y[x]=5");
}
public void testUsedPropAssign6() {
test("var x = newNodeInDom(doc); x.innerHTML = 'new text';",
"var x=newNodeInDom(doc);x.innerHTML=\"new text\"");
}
public void testUsedPropAssign7() {
testSame("var x = {}; for (x in alert()) { x.foo = 3; }");
}
public void testUsedPropAssign8() {
testSame("for (var x in alert()) { x.foo = 3; }");
}
public void testUsedPropAssign9() {
testSame(
"var x = {}; x.foo = newNodeInDom(doc); x.foo.innerHTML = 'new test';");
}
public void testDependencies1() {
test("var a = 3; var b = function() { alert(a); };", "");
}
public void testDependencies1b() {
test("var a = 3; var b = alert(function() { alert(a); });",
"var a=3;alert(function(){alert(a)})");
}
public void testDependencies1c() {
test("var a = 3; var _b = function() { alert(a); };",
"var a=3;var _b=function(){alert(a)}");
}
public void testDependencies2() {
test("var a = 3; var b = 3; b = function() { alert(a); };", "");
}
public void testDependencies2b() {
test("var a = 3; var b = 3; b = alert(function() { alert(a); });",
"var a=3;alert(function(){alert(a)})");
}
public void testDependencies2c() {
testSame("var a=3;var _b=3;_b=function(){alert(a)}");
}
public void testGlobalVarReferencesLocalVar() {
testSame("var a=3;function f(){var b=4;a=b}alert(a + f())");
}
public void testLocalVarReferencesGlobalVar1() {
testSame("var a=3;function f(b, c){b=a; alert(b + c);} f();");
}
public void testLocalVarReferencesGlobalVar2() {
test("var a=3;function f(b, c){b=a; alert(c);} f();",
"function f(b, c) { alert(c); } f();");
this.modifyCallSites = true;
test("var a=3;function f(b, c){b=a; alert(c);} f();",
"function f(c) { alert(c); } f();");
}
public void testNestedAssign1() {
test("var b = null; var a = (b = 3); alert(a);",
"var a = 3; alert(a);");
}
public void testNestedAssign2() {
test("var a = 1; var b = 2; var c = (b = a); alert(c);",
"var a = 1; var c = a; alert(c);");
}
public void testNestedAssign3() {
test("var b = 0; var z; z = z = b = 1; alert(b);",
"var b = 0; b = 1; alert(b);");
}
public void testCallSiteInteraction() {
this.modifyCallSites = true;
testSame("var b=function(){return};b()");
testSame("var b=function(c){return c};b(1)");
test("var b=function(c){};b.call(null, x)",
"var b=function(){};b.call(null)");
test("var b=function(c){};b.apply(null, x)",
"var b=function(){};b.apply(null, x)");
test("var b=function(c){return};b(1)",
"var b=function(){return};b()");
test("var b=function(c){return};b(1,2)",
"var b=function(){return};b()");
test("var b=function(c){return};b(1,2);b(3,4)",
"var b=function(){return};b();b()");
// Here there is a unknown reference to the function so we can't
// change the signature.
test("var b=function(c,d){return d};b(1,2);b(3,4);b.length",
"var b=function(c,d){return d};b(0,2);b(0,4);b.length");
test("var b=function(c){return};b(1,2);b(3,new x())",
"var b=function(){return};b();b(new x())");
test("var b=function(c){return};b(1,2);b(new x(),4)",
"var b=function(){return};b();b(new x())");
test("var b=function(c,d){return d};b(1,2);b(new x(),4)",
"var b=function(c,d){return d};b(0,2);b(new x(),4)");
test("var b=function(c,d,e){return d};b(1,2,3);b(new x(),4,new x())",
"var b=function(c,d){return d};b(0,2);b(new x(),4,new x())");
// Recursive calls are OK.
test("var b=function(c,d){b(1,2);return d};b(3,4);b(5,6)",
"var b=function(d){b(2);return d};b(4);b(6)");
testSame("var b=function(c){return arguments};b(1,2);b(3,4)");
// remove all function arguments
test("var b=function(c,d){return};b(1,2)",
"var b=function(){return};b()");
// remove no function arguments
testSame("var b=function(c,d){return c+d};b(1,2)");
// remove some function arguments
test("var b=function(e,f,c,d){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b()");
test("var b=function(c,d,e,f){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b(1,2)");
test("var b=function(e,c,f,d,g){return c+d};b(1,2)",
"var b=function(c,d){return c+d};b(2)");
// multiple definitions of "b", the parameters can be removed but
// the call sites are left unmodified for now.
test("var b=function(c,d){};var b=function(e,f){};b(1,2)",
"var b=function(){};var b=function(){};b(1,2)");
}
public void testCallSiteInteraction_constructors() {
this.modifyCallSites = true;
// The third level tests that the functions which have already been looked
// at get re-visited if they are changed by a call site removal.
test("var Ctor1=function(a,b){return a};" +
"var Ctor2=function(a,b){Ctor1.call(this,a,b)};" +
"goog$inherits(Ctor2, Ctor1);" +
"new Ctor2(1,2)",
"var Ctor1=function(a){return a};" +
"var Ctor2=function(a){Ctor1.call(this,a)};" +
"goog$inherits(Ctor2, Ctor1);" +
"new Ctor2(1)");
}
public void testFunctionArgRemovalCausingInconsistency() {
this.modifyCallSites = true;
// Test the case where an unused argument is removed and the argument
// contains a call site in its subtree (will cause the call site's parent
// pointer to be null).
test("var a=function(x,y){};" +
"var b=function(z){};" +
"a(new b, b)",
"var a=function(){};" +
"var b=function(){};" +
"a(new b)");
}
public void testRemoveUnusedVarsPossibleNpeCase() {
this.modifyCallSites = true;
test("var a = [];" +
"var register = function(callback) {a[0] = callback};" +
"register(function(transformer) {});" +
"register(function(transformer) {});",
"var register=function(){};register();register()");
}
public void testDoNotOptimizeJSCompiler_renameProperty() {
this.modifyCallSites = true;
// Only the function definition can be modified, none of the call sites.
test("function JSCompiler_renameProperty(a) {};" +
"JSCompiler_renameProperty('a');",
"function JSCompiler_renameProperty() {};" +
"JSCompiler_renameProperty('a');");
}
public void testDoNotOptimizeJSCompiler_ObjectPropertyString() {
this.modifyCallSites = true;
test("function JSCompiler_ObjectPropertyString(a, b) {};" +
"JSCompiler_ObjectPropertyString(window,'b');",
"function JSCompiler_ObjectPropertyString() {};" +
"JSCompiler_ObjectPropertyString(window,'b');");
}
public void testDoNotOptimizeSetters() {
testSame("({set s(a) {}})");
}
public void testRemoveSingletonClass1() {
test("function goog$addSingletonGetter(a){}" +
"/**@constructor*/function a(){}" +
"goog$addSingletonGetter(a);",
"");
}
public void testRemoveInheritedClass1() {
test("function goog$inherits(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$inherits(b,a); new a",
"function a(){} new a");
}
public void testRemoveInheritedClass2() {
test("function goog$inherits(){}" +
"function goog$mixin(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"/**@constructor*/function c(){}" +
"goog$inherits(b,a);" +
"goog$mixin(c.prototype,b.prototype);",
"");
}
public void testRemoveInheritedClass3() {
testSame("/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$inherits(b,a); new b");
}
public void testRemoveInheritedClass4() {
testSame("function goog$inherits(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$inherits(b,a);" +
"/**@constructor*/function c(){}" +
"goog$inherits(c,b); new c");
}
public void testRemoveInheritedClass5() {
test("function goog$inherits(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$inherits(b,a);" +
"/**@constructor*/function c(){}" +
"goog$inherits(c,b); new b",
"function goog$inherits(){}" +
"function a(){}" +
"function b(){}" +
"goog$inherits(b,a); new b");
}
public void testRemoveInheritedClass6() {
test("function goog$mixin(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"/**@constructor*/function c(){}" +
"/**@constructor*/function d(){}" +
"goog$mixin(b.prototype,a.prototype);" +
"goog$mixin(c.prototype,a.prototype); new c;" +
"goog$mixin(d.prototype,a.prototype)",
"function goog$mixin(){}" +
"function a(){}" +
"function c(){}" +
"goog$mixin(c.prototype,a.prototype); new c");
}
public void testRemoveInheritedClass7() {
test("function goog$mixin(){}" +
"/**@constructor*/function a(){alert(goog$mixin(a, a))}" +
"/**@constructor*/function b(){}" +
"goog$mixin(b.prototype,a.prototype); new a",
"function goog$mixin(){}" +
"function a(){alert(goog$mixin(a, a))} new a");
}
public void testRemoveInheritedClass8() {
test("/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"/**@constructor*/function c(){}" +
"b.inherits(a);c.mixin(b.prototype)",
"");
}
public void testRemoveInheritedClass9() {
testSame("/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"/**@constructor*/function c(){}" +
"b.inherits(a);c.mixin(b.prototype);new c");
}
public void testRemoveInheritedClass10() {
test("function goog$inherits(){}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$inherits(b,a); new a;" +
"var c = a; var d = a.g; new b",
"function goog$inherits(){}" +
"function a(){} function b(){} goog$inherits(b,a); new a; new b");
}
public void testRemoveInheritedClass11() {
testSame("function goog$inherits(){}" +
"function goog$mixin(a,b){goog$inherits(a,b)}" +
"/**@constructor*/function a(){}" +
"/**@constructor*/function b(){}" +
"goog$mixin(b.prototype,a.prototype);new b");
}
public void testRemoveInheritedClass12() {
testSame("function goog$inherits(){}" +
"/**@constructor*/function a(){}" +
"var b = {};" +
"goog$inherits(b.foo, a)");
}
public void testReflectedMethods() {
this.modifyCallSites = true;
testSame(
"/** @constructor */" +
"function Foo() {}" +
"Foo.prototype.handle = function(x, y) { alert(y); };" +
"var x = goog.reflect.object(Foo, {handle: 1});" +
"for (var i in x) { x[i].call(x); }" +
"window['Foo'] = Foo;");
}
public void testIssue618_1() {
this.removeGlobal = false;
testSame(
"function f() {\n" +
" var a = [], b;\n" +
" a.push(b = []);\n" +
" b[0] = 1;\n" +
" return a;\n" +
"}");
}
public void testIssue618_2() {
this.removeGlobal = false;
testSame(
"var b;\n" +
"a.push(b = []);\n" +
"b[0] = 1;\n");
}
}
| jimmytuc/closure-compiler | test/com/google/javascript/jscomp/RemoveUnusedVarsTest.java | Java | apache-2.0 | 24,407 |
/*
Copyright 2014 The Kubernetes 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 cmd
import (
"bytes"
"net/http"
"testing"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest/fake"
"k8s.io/kubernetes/pkg/api/legacyscheme"
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
"k8s.io/kubernetes/pkg/kubectl/scheme"
)
func TestCreateNamespace(t *testing.T) {
namespaceObject := &v1.Namespace{}
namespaceObject.Name = "my-namespace"
tf := cmdtesting.NewTestFactory()
codec := legacyscheme.Codecs.LegacyCodec(scheme.Versions...)
ns := legacyscheme.Codecs
tf.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Version: "v1"},
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces" && m == "POST":
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: objBody(codec, namespaceObject)}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateNamespace(tf, buf)
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{namespaceObject.Name})
expectedOutput := "namespace/" + namespaceObject.Name + "\n"
if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
}
}
| timoreimann/kubernetes | pkg/kubectl/cmd/create_namespace_test.go | GO | apache-2.0 | 1,944 |
// { "framework": "Vue" }
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(571)
)
/* script */
__vue_exports__ = __webpack_require__(572)
/* template */
var __vue_template__ = __webpack_require__(573)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/apache-incubator-weex/examples/vue/style/style-item.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__._scopeId = "data-v-768350d6"
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
if (typeof __register_static_styles__ === "function") {
__register_static_styles__(__vue_options__._scopeId, __vue_styles__)
}
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ },
/***/ 571:
/***/ function(module, exports) {
module.exports = {
"item": {
"marginRight": 10,
"width": 160,
"height": 75,
"paddingLeft": 8,
"paddingRight": 8,
"paddingTop": 8,
"paddingBottom": 8
},
"txt": {
"color": "#eeeeee"
}
}
/***/ },
/***/ 572:
/***/ function(module, exports) {
'use strict';
//
//
//
//
//
//
//
module.exports = {
props: {
value: { default: '' },
type: { default: '0' } // 0, 1
},
computed: {
bgColor: function bgColor() {
return this.type == '1' ? '#7BA3A8' : '#BEAD92';
}
}
};
/***/ },
/***/ 573:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('text', {
staticClass: ["item", "txt"],
style: {
backgroundColor: _vm.bgColor
},
attrs: {
"value": _vm.value
}
})
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ }
/******/ }); | MrRaindrop/incubator-weex | ios/playground/bundlejs/vue/style/style-item.js | JavaScript | apache-2.0 | 3,888 |
/*
* Copyright 2000-2013 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.
*/
/*
* @author max
*/
package com.intellij.util.io;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
public class RandomAccessFileInputStream extends InputStream {
private final RandomAccessFile raf;
private long cur;
private long limit;
public RandomAccessFileInputStream(final RandomAccessFile raf, final long pos, final long limit) {
this.raf = raf;
setup(pos, limit);
}
public void setup(final long pos, final long limit) {
this.cur = pos;
this.limit = limit;
}
public RandomAccessFileInputStream(final RandomAccessFile raf, final long pos) throws IOException {
this(raf, pos, raf.length());
}
@Override
public int available()
{
return (int)(limit - cur);
}
@Override
public void close()
{
//do nothing because we want to leave the random access file open.
}
@Override
public int read() throws IOException
{
int retval = -1;
if( cur < limit )
{
raf.seek( cur );
cur++;
retval = raf.read();
}
return retval;
}
@Override
public int read( @NotNull byte[] b, int offset, int length ) throws IOException
{
//only allow a read of the amount available.
if( length > available() )
{
length = available();
}
int amountRead = -1;
//only read if there are bytes actually available, otherwise
//return -1 if the EOF has been reached.
if( available() > 0 )
{
raf.seek( cur );
amountRead = raf.read( b, offset, length );
}
//update the current cursor position.
if( amountRead > 0 )
{
cur += amountRead;
}
return amountRead;
}
@Override
public long skip( long amountToSkip )
{
long amountSkipped = Math.min( amountToSkip, available() );
cur+= amountSkipped;
return amountSkipped;
}
} | goodwinnk/intellij-community | platform/util/src/com/intellij/util/io/RandomAccessFileInputStream.java | Java | apache-2.0 | 2,545 |
// @target: es5
let o = { a: 1, b: 'no' }
let o2 = { b: 'yes', c: true }
let swap = { a: 'yes', b: -1 };
let addAfter: { a: number, b: string, c: boolean } =
{ ...o, c: false }
let addBefore: { a: number, b: string, c: boolean } =
{ c: false, ...o }
// Note: ignore still changes the order that properties are printed
let ignore: { a: number, b: string } =
{ b: 'ignored', ...o }
let override: { a: number, b: string } =
{ ...o, b: 'override' }
let nested: { a: number, b: boolean, c: string } =
{ ...{ a: 3, ...{ b: false, c: 'overriden' } }, c: 'whatever' }
let combined: { a: number, b: string, c: boolean } =
{ ...o, ...o2 }
let combinedBefore: { a: number, b: string, c: boolean } =
{ b: 'ok', ...o, ...o2 }
let combinedMid: { a: number, b: string, c: boolean } =
{ ...o, b: 'ok', ...o2 }
let combinedAfter: { a: number, b: string, c: boolean } =
{ ...o, ...o2, b: 'ok' }
let combinedNested: { a: number, b: boolean, c: string, d: string } =
{ ...{ a: 4, ...{ b: false, c: 'overriden' } }, d: 'actually new', ...{ a: 5, d: 'maybe new' } }
let combinedNestedChangeType: { a: number, b: boolean, c: number } =
{ ...{ a: 1, ...{ b: false, c: 'overriden' } }, c: -1 }
let propertyNested: { a: { a: number, b: string } } =
{ a: { ... o } }
// accessors don't copy the descriptor
// (which means that readonly getters become read/write properties)
let op = { get a () { return 6 } };
let getter: { a: number, c: number } =
{ ...op, c: 7 }
getter.a = 12;
// functions result in { }
let spreadFunc = { ...(function () { }) };
// any results in any
let anything: any;
let spreadAny = { ...anything };
// methods are not enumerable
class C { p = 1; m() { } }
let c: C = new C()
let spreadC: { p: number } = { ...c }
// own methods are enumerable
let cplus: { p: number, plus(): void } = { ...c, plus() { return this.p + 1; } };
cplus.plus();
// new field's type conflicting with existing field is OK
let changeTypeAfter: { a: string, b: string } =
{ ...o, a: 'wrong type?' }
let changeTypeBefore: { a: number, b: string } =
{ a: 'wrong type?', ...o };
let changeTypeBoth: { a: string, b: number } =
{ ...o, ...swap };
// optional
let definiteBoolean: { sn: boolean };
let definiteString: { sn: string };
let optionalString: { sn?: string };
let optionalNumber: { sn?: number };
let optionalUnionStops: { sn: string | number | boolean } = { ...definiteBoolean, ...definiteString, ...optionalNumber };
let optionalUnionDuplicates: { sn: string | number } = { ...definiteBoolean, ...definiteString, ...optionalString, ...optionalNumber };
let allOptional: { sn?: string | number } = { ...optionalString, ...optionalNumber };
// computed property
let computedFirst: { a: number, b: string, "before everything": number } =
{ ['before everything']: 12, ...o, b: 'yes' }
let computedMiddle: { a: number, b: string, c: boolean, "in the middle": number } =
{ ...o, ['in the middle']: 13, b: 'maybe?', ...o2 }
let computedAfter: { a: number, b: string, "at the end": number } =
{ ...o, b: 'yeah', ['at the end']: 14 }
// shortcut syntax
let a = 12;
let shortCutted: { a: number, b: string } = { ...o, a }
// non primitive
let spreadNonPrimitive = { ...<object>{}};
| mkusher/TypeScript | tests/cases/conformance/types/spread/objectSpread.ts | TypeScript | apache-2.0 | 3,234 |
//// [inheritanceMemberAccessorOverridingAccessor.ts]
class a {
get x() {
return "20";
}
set x(aValue: string) {
}
}
class b extends a {
get x() {
return "20";
}
set x(aValue: string) {
}
}
//// [inheritanceMemberAccessorOverridingAccessor.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var a = (function () {
function a() {
}
Object.defineProperty(a.prototype, "x", {
get: function () {
return "20";
},
set: function (aValue) {
},
enumerable: true,
configurable: true
});
return a;
}());
var b = (function (_super) {
__extends(b, _super);
function b() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(b.prototype, "x", {
get: function () {
return "20";
},
set: function (aValue) {
},
enumerable: true,
configurable: true
});
return b;
}(a));
| mihailik/TypeScript | tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js | JavaScript | apache-2.0 | 1,503 |
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.ui;
import com.google.gerrit.client.FormatUtil;
import com.google.gerrit.client.RpcStatus;
import com.google.gerrit.client.admin.Util;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.common.data.AccountInfo;
import com.google.gerrit.common.data.ReviewerInfo;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle;
import java.util.ArrayList;
import java.util.List;
/** Suggestion Oracle for reviewers. */
public class ReviewerSuggestOracle extends HighlightSuggestOracle {
private Change.Id changeId;
@Override
protected void onRequestSuggestions(final Request req, final Callback callback) {
RpcStatus.hide(new Runnable() {
public void run() {
SuggestUtil.SVC.suggestChangeReviewer(changeId, req.getQuery(),
req.getLimit(), new GerritCallback<List<ReviewerInfo>>() {
public void onSuccess(final List<ReviewerInfo> result) {
final List<ReviewerSuggestion> r =
new ArrayList<ReviewerSuggestion>(result
.size());
for (final ReviewerInfo reviewer : result) {
r.add(new ReviewerSuggestion(reviewer));
}
callback.onSuggestionsReady(req, new Response(r));
}
});
}
});
}
public void setChange(Change.Id changeId) {
this.changeId = changeId;
}
private static class ReviewerSuggestion implements SuggestOracle.Suggestion {
private final ReviewerInfo reviewerInfo;
ReviewerSuggestion(final ReviewerInfo reviewerInfo) {
this.reviewerInfo = reviewerInfo;
}
public String getDisplayString() {
final AccountInfo accountInfo = reviewerInfo.getAccountInfo();
if (accountInfo != null) {
return FormatUtil.nameEmail(accountInfo);
}
return reviewerInfo.getGroup().getName() + " ("
+ Util.C.suggestedGroupLabel() + ")";
}
public String getReplacementString() {
final AccountInfo accountInfo = reviewerInfo.getAccountInfo();
if (accountInfo != null) {
return FormatUtil.nameEmail(accountInfo);
}
return reviewerInfo.getGroup().getName();
}
}
}
| m1kah/gerrit-contributions | gerrit-gwtui/src/main/java/com/google/gerrit/client/ui/ReviewerSuggestOracle.java | Java | apache-2.0 | 2,951 |
package org.bouncycastle.crypto.prng;
import java.security.SecureRandom;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Pack;
public class X931SecureRandomBuilder
{
private SecureRandom random; // JDK 1.1 complains on final.
private EntropySourceProvider entropySourceProvider;
private byte[] dateTimeVector;
/**
* Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with
* predictionResistant set to false.
* <p>
* Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
* the default SecureRandom does for its generateSeed() call.
* </p>
*/
public X931SecureRandomBuilder()
{
this(new SecureRandom(), false);
}
/**
* Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value
* for prediction resistance.
* <p>
* Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
* the passed in SecureRandom does for its generateSeed() call.
* </p>
* @param entropySource
* @param predictionResistant
*/
public X931SecureRandomBuilder(SecureRandom entropySource, boolean predictionResistant)
{
this.random = entropySource;
this.entropySourceProvider = new BasicEntropySourceProvider(random, predictionResistant);
}
/**
* Create a builder which makes creates the SecureRandom objects from a specified entropy source provider.
* <p>
* <b>Note:</b> If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored.
* </p>
* @param entropySourceProvider a provider of EntropySource objects.
*/
public X931SecureRandomBuilder(EntropySourceProvider entropySourceProvider)
{
this.random = null;
this.entropySourceProvider = entropySourceProvider;
}
public X931SecureRandomBuilder setDateTimeVector(byte[] dateTimeVector)
{
this.dateTimeVector = dateTimeVector;
return this;
}
/**
* Construct a X9.31 secure random generator using the passed in engine and key. If predictionResistant is true the
* generator will be reseeded on each request.
*
* @param engine a block cipher to use as the operator.
* @param key the block cipher key to initialise engine with.
* @param predictionResistant true if engine to be reseeded on each use, false otherwise.
* @return a SecureRandom.
*/
public X931SecureRandom build(BlockCipher engine, KeyParameter key, boolean predictionResistant)
{
if (dateTimeVector == null)
{
dateTimeVector = new byte[engine.getBlockSize()];
Pack.longToBigEndian(System.currentTimeMillis(), dateTimeVector, 0);
}
engine.init(true, key);
return new X931SecureRandom(random, new X931RNG(engine, dateTimeVector, entropySourceProvider.get(engine.getBlockSize() * 8)), predictionResistant);
}
}
| thedrummeraki/Aki-SSL | src/org/bouncycastle/crypto/prng/X931SecureRandomBuilder.java | Java | apache-2.0 | 3,209 |
package io.pivotal.gemfire.spark.connector.javaapi;
import io.pivotal.gemfire.spark.connector.GemFireConnectionConf;
import io.pivotal.gemfire.spark.connector.streaming.GemFireDStreamFunctions;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.api.java.JavaDStream;
import java.util.Properties;
import static io.pivotal.gemfire.spark.connector.javaapi.JavaAPIHelper.*;
/**
* A Java API wrapper over {@link org.apache.spark.streaming.api.java.JavaDStream}
* to provide GemFire Spark Connector functionality.
*
* <p>To obtain an instance of this wrapper, use one of the factory methods in {@link
* io.pivotal.gemfire.spark.connector.javaapi.GemFireJavaUtil} class.</p>
*/
public class GemFireJavaDStreamFunctions<T> {
public final GemFireDStreamFunctions<T> dsf;
public GemFireJavaDStreamFunctions(JavaDStream<T> ds) {
this.dsf = new GemFireDStreamFunctions<T>(ds.dstream());
}
/**
* Save the JavaDStream to GemFire key-value store.
* @param regionPath the full path of region that the DStream is stored
* @param func the PairFunction that converts elements of JavaDStream to key/value pairs
* @param connConf the GemFireConnectionConf object that provides connection to GemFire cluster
* @param opConf the optional parameters for this operation
*/
public <K, V> void saveToGemfire(
String regionPath, PairFunction<T, K, V> func, GemFireConnectionConf connConf, Properties opConf) {
dsf.saveToGemfire(regionPath, func, connConf, propertiesToScalaMap(opConf));
}
/**
* Save the JavaDStream to GemFire key-value store.
* @param regionPath the full path of region that the DStream is stored
* @param func the PairFunction that converts elements of JavaDStream to key/value pairs
* @param opConf the optional parameters for this operation
*/
public <K, V> void saveToGemfire(
String regionPath, PairFunction<T, K, V> func, Properties opConf) {
dsf.saveToGemfire(regionPath, func, dsf.defaultConnectionConf(), propertiesToScalaMap(opConf));
}
/**
* Save the JavaDStream to GemFire key-value store.
* @param regionPath the full path of region that the DStream is stored
* @param func the PairFunction that converts elements of JavaDStream to key/value pairs
* @param connConf the GemFireConnectionConf object that provides connection to GemFire cluster
*/
public <K, V> void saveToGemfire(
String regionPath, PairFunction<T, K, V> func, GemFireConnectionConf connConf) {
dsf.saveToGemfire(regionPath, func, connConf, emptyStrStrMap());
}
/**
* Save the JavaDStream to GemFire key-value store.
* @param regionPath the full path of region that the DStream is stored
* @param func the PairFunction that converts elements of JavaDStream to key/value pairs
*/
public <K, V> void saveToGemfire(
String regionPath, PairFunction<T, K, V> func) {
dsf.saveToGemfire(regionPath, func, dsf.defaultConnectionConf(), emptyStrStrMap());
}
}
| ysung-pivotal/incubator-geode | gemfire-spark-connector/gemfire-spark-connector/src/main/java/io/pivotal/gemfire/spark/connector/javaapi/GemFireJavaDStreamFunctions.java | Java | apache-2.0 | 3,026 |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.edgent.apps.runtime;
import org.apache.edgent.execution.Job;
import org.apache.edgent.execution.services.JobRegistryService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Helpers for parsing generating and parsing a JSON representation of job
* monitoring events.
*/
class JobMonitorAppEvent {
/**
* Creates a JsonObject wrapping a {@code JobRegistryService} event type
* and Job info.
*
* @param evType the event type
* @param job the job
* @return the wrapped data
*/
static JsonObject toJsonObject(JobRegistryService.EventType evType, Job job) {
JsonObject value = new JsonObject();
value.addProperty("time", (Number)System.currentTimeMillis());
value.addProperty("event", evType.toString());
JsonObject obj = new JsonObject();
obj.addProperty("id", job.getId());
obj.addProperty("name", job.getName());
obj.addProperty("state", job.getCurrentState().toString());
obj.addProperty("nextState", job.getNextState().toString());
obj.addProperty("health", job.getHealth().toString());
obj.addProperty("lastError", job.getLastError());
value.add("job", obj);
return value;
}
/**
* Gets the {@code job} JsonObject from the given JSON value.
*
* @param value a JSON object
* @return the job JsonObject
*/
static JsonObject getJob(JsonObject value) {
JsonObject job = value.getAsJsonObject("job");
if (job == null) {
throw new IllegalArgumentException("Could not find the job object in: " + value);
}
return job;
}
/**
* Gets the {@code name} string property from the given job JSON object.
*
* @param job the job JSON object
* @return the job name
* @throws IllegalArgumentException if it could not find the property
*/
static String getJobName(JsonObject job) {
return getProperty(job, "name");
}
/**
* Gets the {@code health} string property from the given job JSON object.
*
* @param job the job JSON object
* @return the job health
* @throws IllegalArgumentException if it could not find the property
*/
static String getJobHealth(JsonObject job) {
return getProperty(job, "health");
}
/**
* Gets a string property with the specified name from the given JSON
* object.
*
* @param value a JSON object
* @param name the property name
* @return the property value
*
* @throws IllegalArgumentException if could not find a property with the
* given name
*/
static String getProperty(JsonObject value, String name) {
JsonElement e = value.get(name);
if (e != null && e.isJsonPrimitive()) {
try {
return e.getAsString();
} catch (Exception ex) {
}
}
throw new IllegalArgumentException("Could not find the " + name + " property in: " + value);
}
}
| vdogaru/incubator-quarks | apps/runtime/src/main/java/org/apache/edgent/apps/runtime/JobMonitorAppEvent.java | Java | apache-2.0 | 3,846 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joefernandez.irrduino.android.remote;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.joefernandez.irrduino.android.remote.ViewReportActivity.IrrduinoServerRequestTask;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class IrrduinoRemoteActivity extends Activity {
private static final String TAG = "IrrduinoRemoteActivity";
private static final String CMD_ALL_OFF = "/off";
private static final String CMD_ZONE_PREFIX = "/zone";
private static final String CMD_ON = "/ON";
private static final String CMD_STATUS = "/status";
private static final int ZONE_GARDEN = 1;
private static final int ZONE_BACK_LAWN1 = 2;
private static final int ZONE_BACK_LAWN2 = 3;
private static final int ZONE_BACK_LAWN3 = 4;
private static final int ZONE_PATIO = 5;
private static final int ZONE_FLOWER_BED = 6;
private static final int ZONE_FRONT_LAWN1 = 7;
private static final int ZONE_FRONT_LAWN2 = 8;
private SharedPreferences settings;
private boolean settingsChanged = true;
private String controllerAddress;
protected int zoneRunTime = 1;
protected EditText statusText;
protected CountDownTimer timer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinnerRunTime = (Spinner) findViewById(R.id.spinner_runtimes);
spinnerRunTime.setAdapter(getSpinnerAdapter());
spinnerRunTime.setOnItemSelectedListener(new RuntimeItemSelectedListener());
statusText = (EditText) findViewById(R.id.status_text);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("taskResult");
if (value != null && value.length() > 0){
statusText.setText(value);
}
}
Button allOff = (Button) findViewById(R.id.button_all_stop);
allOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
statusText.setText("Sending...");
new IrrduinoCommandTask().execute(getControllerAddress() + CMD_ALL_OFF);
}
});
Button zone1 = (Button) findViewById(R.id.button_garden);
zone1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_GARDEN, zoneRunTime);
}
});
Button zone2 = (Button) findViewById(R.id.button_backyard_lawn_1);
zone2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_BACK_LAWN1, zoneRunTime);
}
});
Button zone3 = (Button) findViewById(R.id.button_backyard_lawn_2);
zone3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_BACK_LAWN2, zoneRunTime);
}
});
Button zone4 = (Button) findViewById(R.id.button_backyard_lawn_3);
zone4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_BACK_LAWN3, zoneRunTime);
}
});
Button zone5 = (Button) findViewById(R.id.button_patio_plants);
zone5.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_PATIO, zoneRunTime);
}
});
// Zone 6 (backyard left side flower beds, is not hooked up)
// Button zone6 = (Button) findViewById(R.id.button_patio_plants);
// zone6.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// sendZoneRunCommand(ZONE_FLOWER_BED, zoneRunTime);
// }
// });
Button zone7 = (Button) findViewById(R.id.button_frontyard_lawn_1);
zone7.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_FRONT_LAWN1, zoneRunTime);
}
});
Button zone8 = (Button) findViewById(R.id.button_frontyard_lawn_2);
zone8.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendZoneRunCommand(ZONE_FRONT_LAWN2, zoneRunTime);
}
});
// Request global status from controller (run *last*)
requestSystemStatus();
}
@Override
protected void onResume() {
super.onResume();
// Request global status from controller
requestSystemStatus();
}
private void requestSystemStatus(){
// get settings
settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getString(Settings.CONTROLLER_HOST_NAME,
Settings.DEFAULT_CONTROLLER_HOST).compareTo(Settings.DEFAULT_CONTROLLER_HOST) == 0){
// default setting, warn user
statusText.setText("Report server is not set,\n specify a server in Settings.");
}
else{
statusText.setText("Requesting status...");
new IrrduinoCommandTask().execute(getControllerAddress() + CMD_STATUS);
}
}
private void sendZoneRunCommand(int zone, int minutes){
statusText.setText("Sending...");
IrrduinoZoneRunTask zrt = new IrrduinoZoneRunTask(zone, minutes);
// command format: http://myirrduinocontroller.com/zone3/ON/1
zrt.execute(getControllerAddress() + CMD_ZONE_PREFIX +
zone + CMD_ON + "/" + minutes);
}
private String getControllerAddress(){
if (controllerAddress == null || settingsChanged){
settings = PreferenceManager.getDefaultSharedPreferences(this);
String host = settings.getString(Settings.CONTROLLER_HOST_NAME,
Settings.DEFAULT_CONTROLLER_HOST);
String port = settings.getString(Settings.CONTROLLER_HOST_PORT,
Settings.DEFAULT_CONTROLLER_PORT);
controllerAddress = "http://"+host;
if (port != null && !port.equalsIgnoreCase("80")){
controllerAddress += ":"+port;
}
settingsChanged = false;
}
return controllerAddress;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final Intent intent;
// Handle item selection
switch (item.getItemId()) {
case R.id.preferences:
intent = new Intent(this, Settings.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
settingsChanged = true;
return true;
case R.id.report:
intent = new Intent(this, ViewReportActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected String parseJsonStatus(String statusJson){
try {
JSONObject response = new JSONObject(statusJson);
if (response.has("zones")) {
return "Zones: " + response.getString("zones");
}
if (response.has("system status")){
return "System: "+response.getString("system status");
}
}
catch (JSONException e) {
Log.d(TAG, "Unable to parse JSON response: "+ statusJson);
return "System: Not available";
}
return "System: No information";
}
/** Async Task code (for Irrduino Controller requests) */
public class IrrduinoCommandTask extends HttpCommandTask {
private static final String TAG = "IrrduinoCommandTask";
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(String result) {
if (result != null) {
if (timer != null) {
timer.cancel();
}
if (result.length() < 256) {
statusText.setText(parseJsonStatus(result));
} else {
// something went wrong with the request. Log it.
Log.d(TAG, "Error processing command. Unexpected return result:\n" + result);
statusText.setText("Error processing command.");
}
} else {
statusText.setText("Error processing command.");
}
}
}
/** Async Task code (for Irrduino Controller requests) */
public class IrrduinoZoneRunTask extends HttpCommandTask {
private static final String TAG = "IrrduinoZoneRunTask";
public int zone = 0;
public int minutes = 1;
public IrrduinoZoneRunTask(int zone, int minutes){
this.zone = zone;
this.minutes = minutes;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(String result) {
if (result != null) {
// statusText.setText(result);
if (timer != null) {
timer.onFinish();
}
timer = new CountDownTimer(60000 * minutes, 1000) {
public void onTick(long millisUntilFinished) {
statusText.setText("Running Zone " + zone + ": "+ millisUntilFinished / 1000);
}
public void onFinish() {
statusText.setText("Zone " + zone + ": OFF");
}
}.start();
} else {
statusText.setText("Error processing command.");
}
}
}
//=== Duration Spinner management functions ===================================================
public class RuntimeItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
zoneRunTime = ((SpinnerItemData) parent.getItemAtPosition(pos)).value;
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public ArrayAdapter<SpinnerItemData> getSpinnerAdapter(){
ArrayAdapter<SpinnerItemData> adapter =
new ArrayAdapter<SpinnerItemData>(
this,
android.R.layout.simple_spinner_item);
adapter.add(new SpinnerItemData("1 Minute", 1));
adapter.add(new SpinnerItemData("2 Minutes", 2));
adapter.add(new SpinnerItemData("3 Minutes", 3));
adapter.add(new SpinnerItemData("4 Minutes", 4));
adapter.add(new SpinnerItemData("5 Minutes", 5));
adapter.add(new SpinnerItemData("6 Minutes", 6));
adapter.add(new SpinnerItemData("7 Minutes", 7));
adapter.add(new SpinnerItemData("8 Minutes", 8));
adapter.add(new SpinnerItemData("9 Minutes", 9));
adapter.add(new SpinnerItemData("10 Minutes", 10));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
public class SpinnerItemData {
public String key;
public int value;
SpinnerItemData(String key, int value){
this.key = key;
this.value = value;
}
@Override
public String toString(){
return key;
}
}
}
| jesuscorral/irrduino | IrrduinoDroid/IrrduinoRemote/src/com/joefernandez/irrduino/android/remote/IrrduinoRemoteActivity.java | Java | apache-2.0 | 12,329 |
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.dao;
/**
* Exception thrown when an attempt to insert or update data
* results in violation of an integrity constraint. Note that this
* is not purely a relational concept; unique primary keys are
* required by most database types.
*
* @author Rod Johnson
*/
@SuppressWarnings("serial")
public class DataIntegrityViolationException extends NonTransientDataAccessException {
/**
* Constructor for DataIntegrityViolationException.
* @param msg the detail message
*/
public DataIntegrityViolationException(String msg) {
super(msg);
}
/**
* Constructor for DataIntegrityViolationException.
* @param msg the detail message
* @param cause the root cause from the data access API in use
*/
public DataIntegrityViolationException(String msg, Throwable cause) {
super(msg, cause);
}
}
| shivpun/spring-framework | spring-tx/src/main/java/org/springframework/dao/DataIntegrityViolationException.java | Java | apache-2.0 | 1,461 |
package org.apache.lucene.spatial.query;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Rectangle;
import org.apache.lucene.util.LuceneTestCase;
import org.junit.Test;
import java.text.ParseException;
//Tests SpatialOperation somewhat too
public class SpatialArgsParserTest extends LuceneTestCase {
private SpatialContext ctx = SpatialContext.GEO;
//The args parser is only dependent on the ctx for IO so I don't care to test
// with other implementations.
@Test
public void testArgsParser() throws Exception {
SpatialArgsParser parser = new SpatialArgsParser();
String arg = SpatialOperation.IsWithin + "(Envelope(-10, 10, 20, -20))";
SpatialArgs out = parser.parse(arg, ctx);
assertEquals(SpatialOperation.IsWithin, out.getOperation());
Rectangle bounds = (Rectangle) out.getShape();
assertEquals(-10.0, bounds.getMinX(), 0D);
assertEquals(10.0, bounds.getMaxX(), 0D);
// Disjoint should not be scored
arg = SpatialOperation.IsDisjointTo + " (Envelope(-10,-20,20,10))";
out = parser.parse(arg, ctx);
assertEquals(SpatialOperation.IsDisjointTo, out.getOperation());
try {
parser.parse(SpatialOperation.IsDisjointTo + "[ ]", ctx);
fail("spatial operations need args");
}
catch (Exception ex) {//expected
}
try {
parser.parse("XXXX(Envelope(-10, 10, 20, -20))", ctx);
fail("unknown operation!");
}
catch (Exception ex) {//expected
}
assertAlias(SpatialOperation.IsWithin, "CoveredBy");
assertAlias(SpatialOperation.IsWithin, "COVEREDBY");
assertAlias(SpatialOperation.IsWithin, "coveredBy");
assertAlias(SpatialOperation.IsWithin, "Within");
assertAlias(SpatialOperation.IsEqualTo, "Equals");
assertAlias(SpatialOperation.IsDisjointTo, "disjoint");
assertAlias(SpatialOperation.Contains, "Covers");
}
private void assertAlias(SpatialOperation op, final String name) throws ParseException {
String arg;
SpatialArgs out;
arg = name + "(Point(0 0))";
out = new SpatialArgsParser().parse(arg, ctx);
assertEquals(op, out.getOperation());
}
}
| smartan/lucene | src/test/java/org/apache/lucene/spatial/query/SpatialArgsParserTest.java | Java | apache-2.0 | 2,951 |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.facet.histogram;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilderException;
import org.elasticsearch.search.facet.AbstractFacetBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* A facet builder of histogram facets.
*
*
*/
public class HistogramFacetBuilder extends AbstractFacetBuilder {
private String keyFieldName;
private String valueFieldName;
private long interval = -1;
private HistogramFacet.ComparatorType comparatorType;
private Object from;
private Object to;
/**
* Constructs a new histogram facet with the provided facet logical name.
*
* @param name The logical name of the facet
*/
public HistogramFacetBuilder(String name) {
super(name);
}
/**
* The field name to perform the histogram facet. Translates to perform the histogram facet
* using the provided field as both the {@link #keyField(String)} and {@link #valueField(String)}.
*/
public HistogramFacetBuilder field(String field) {
this.keyFieldName = field;
return this;
}
/**
* The field name to use in order to control where the hit will "fall into" within the histogram
* entries. Essentially, using the key field numeric value, the hit will be "rounded" into the relevant
* bucket controlled by the interval.
*/
public HistogramFacetBuilder keyField(String keyField) {
this.keyFieldName = keyField;
return this;
}
/**
* The field name to use as the value of the hit to compute data based on values within the interval
* (for example, total).
*/
public HistogramFacetBuilder valueField(String valueField) {
this.valueFieldName = valueField;
return this;
}
/**
* The interval used to control the bucket "size" where each key value of a hit will fall into.
*/
public HistogramFacetBuilder interval(long interval) {
this.interval = interval;
return this;
}
/**
* The interval used to control the bucket "size" where each key value of a hit will fall into.
*/
public HistogramFacetBuilder interval(long interval, TimeUnit unit) {
return interval(unit.toMillis(interval));
}
/**
* Sets the bounds from and to for the facet. Both performs bounds check and includes only
* values within the bounds, and improves performance.
*/
public HistogramFacetBuilder bounds(Object from, Object to) {
this.from = from;
this.to = to;
return this;
}
public HistogramFacetBuilder comparator(HistogramFacet.ComparatorType comparatorType) {
this.comparatorType = comparatorType;
return this;
}
/**
* Should the facet run in global mode (not bounded by the search query) or not (bounded by
* the search query). Defaults to <tt>false</tt>.
*/
public HistogramFacetBuilder global(boolean global) {
super.global(global);
return this;
}
/**
* Marks the facet to run in a specific scope.
*/
@Override
public HistogramFacetBuilder scope(String scope) {
super.scope(scope);
return this;
}
/**
* An additional filter used to further filter down the set of documents the facet will run on.
*/
public HistogramFacetBuilder facetFilter(FilterBuilder filter) {
this.facetFilter = filter;
return this;
}
/**
* Sets the nested path the facet will execute on. A match (root object) will then cause all the
* nested objects matching the path to be computed into the facet.
*/
public HistogramFacetBuilder nested(String nested) {
this.nested = nested;
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (keyFieldName == null) {
throw new SearchSourceBuilderException("field must be set on histogram facet for facet [" + name + "]");
}
if (interval < 0) {
throw new SearchSourceBuilderException("interval must be set on histogram facet for facet [" + name + "]");
}
builder.startObject(name);
builder.startObject(HistogramFacet.TYPE);
if (valueFieldName != null) {
builder.field("key_field", keyFieldName);
builder.field("value_field", valueFieldName);
} else {
builder.field("field", keyFieldName);
}
builder.field("interval", interval);
if (from != null && to != null) {
builder.field("from", from);
builder.field("to", to);
}
if (comparatorType != null) {
builder.field("comparator", comparatorType.description());
}
builder.endObject();
addFilterFacetAndGlobal(builder, params);
builder.endObject();
return builder;
}
}
| Kreolwolf1/Elastic | src/main/java/org/elasticsearch/search/facet/histogram/HistogramFacetBuilder.java | Java | apache-2.0 | 5,903 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.plan;
import com.google.common.collect.ImmutableList;
import java.util.List;
/**
* Children of a {@link org.apache.calcite.plan.RelOptRuleOperand} and the
* policy for matching them.
*
* <p>Often created by calling one of the following methods:
* {@link RelOptRule#some},
* {@link RelOptRule#none},
* {@link RelOptRule#any},
* {@link RelOptRule#unordered}.
*
* @deprecated Use {@link RelRule.OperandBuilder}
*/
@Deprecated // to be removed before 2.0
public class RelOptRuleOperandChildren {
static final RelOptRuleOperandChildren ANY_CHILDREN =
new RelOptRuleOperandChildren(
RelOptRuleOperandChildPolicy.ANY,
ImmutableList.of());
static final RelOptRuleOperandChildren LEAF_CHILDREN =
new RelOptRuleOperandChildren(
RelOptRuleOperandChildPolicy.LEAF,
ImmutableList.of());
final RelOptRuleOperandChildPolicy policy;
final ImmutableList<RelOptRuleOperand> operands;
public RelOptRuleOperandChildren(
RelOptRuleOperandChildPolicy policy,
List<RelOptRuleOperand> operands) {
this.policy = policy;
this.operands = ImmutableList.copyOf(operands);
}
}
| vlsi/incubator-calcite | core/src/main/java/org/apache/calcite/plan/RelOptRuleOperandChildren.java | Java | apache-2.0 | 1,973 |
/*
* Created on May 31, 2004
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012/04/25 Added @Override annotation to the appropriate method.
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2017/11/06 Marked as Deprecated
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
package org.parosproxy.paros.core.proxy;
import java.net.Socket;
// import org.parosproxy.paros.network.HttpUtil;
@Deprecated
public class ProxyThreadSSL extends ProxyThread {
ProxyThreadSSL(ProxyServerSSL server, Socket socket) {
super(server, socket);
// originProcess = ProxyThread.getOriginatingProcess(inSocket.getPort());
// if (originProcess != null) {
// originProcess.setForwardThread(thread);
// }
//
// thread.setPriority(Thread.NORM_PRIORITY-1);
}
@Override
protected void disconnect() {
// long startTime = System.currentTimeMillis();
// while (originProcess!=null && !originProcess.isForwardInputBufferEmpty() &&
// System.currentTimeMillis() - startTime < 3000) {
// HttpUtil.sleep(300);
// }
//
// if (originProcess != null) {
// originProcess.setDisconnect(true);
// try {
// originProcess.getThread().join(2000);
// } catch (InterruptedException e) {
// }
//
// }
super.disconnect();
}
}
| psiinon/zaproxy | zap/src/main/java/org/parosproxy/paros/core/proxy/ProxyThreadSSL.java | Java | apache-2.0 | 2,258 |
import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import Point from '../src/ol/geom/Point.js';
import VectorLayer from '../src/ol/layer/Vector.js';
import VectorSource from '../src/ol/source/Vector.js';
import View from '../src/ol/View.js';
import {Fill, RegularShape, Stroke, Style} from '../src/ol/style.js';
const stroke = new Stroke({color: 'black', width: 2});
const fill = new Fill({color: 'red'});
const styles = {
'square': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
angle: Math.PI / 4,
}),
}),
'rectangle': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
radius: 10 / Math.SQRT2,
radius2: 10,
points: 4,
angle: 0,
scale: [1, 0.5],
}),
}),
'triangle': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 3,
radius: 10,
rotation: Math.PI / 4,
angle: 0,
}),
}),
'star': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 5,
radius: 10,
radius2: 4,
angle: 0,
}),
}),
'cross': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
radius2: 0,
angle: 0,
}),
}),
'x': new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
radius2: 0,
angle: Math.PI / 4,
}),
}),
'stacked': [
new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 5,
angle: Math.PI / 4,
displacement: [0, 10],
}),
}),
new Style({
image: new RegularShape({
fill: fill,
stroke: stroke,
points: 4,
radius: 10,
angle: Math.PI / 4,
}),
}),
],
};
const styleKeys = [
'x',
'cross',
'star',
'triangle',
'square',
'rectangle',
'stacked',
];
const count = 250;
const features = new Array(count);
const e = 4500000;
for (let i = 0; i < count; ++i) {
const coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
features[i] = new Feature(new Point(coordinates));
features[i].setStyle(
styles[styleKeys[Math.floor(Math.random() * styleKeys.length)]]
);
}
const source = new VectorSource({
features: features,
});
const vectorLayer = new VectorLayer({
source: source,
});
const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
| adube/ol3 | examples/regularshape.js | JavaScript | bsd-2-clause | 2,662 |
class Openvpn < Formula
desc "SSL/TLS VPN implementing OSI layer 2 or 3 secure network extension"
homepage "https://openvpn.net/index.php/download/community-downloads.html"
url "https://swupdate.openvpn.org/community/releases/openvpn-2.4.2.tar.xz"
mirror "https://build.openvpn.net/downloads/releases/openvpn-2.4.2.tar.xz"
sha256 "df5c4f384b7df6b08a2f6fa8a84b9fd382baf59c2cef1836f82e2a7f62f1bff9"
revision 1
bottle do
sha256 "25f10d0697d4c4c0f94554a118d232dfc996975ffc488d76f57df05152a7e978" => :sierra
sha256 "d4527016eaf2d60ce7732fd85592e1d3b64d4f33878592b04834b09de5dbe134" => :el_capitan
sha256 "6a52d439580030f7a2b85e7de7f90fd9f1eaeed09e03f1f202d19a5c614a412d" => :yosemite
end
# Requires tuntap for < 10.10
depends_on :macos => :yosemite
depends_on "pkg-config" => :build
depends_on "lzo"
depends_on "openssl"
resource "pkcs11-helper" do
url "https://github.com/OpenSC/pkcs11-helper/releases/download/pkcs11-helper-1.22/pkcs11-helper-1.22.tar.bz2"
sha256 "fbc15f5ffd5af0200ff2f756cb4388494e0fb00b4f2b186712dce6c48484a942"
end
def install
vendor = buildpath/"brew_vendor"
resource("pkcs11-helper").stage do
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{vendor}/pkcs11-helper",
"--disable-threading",
"--disable-slotevent",
"--disable-shared"
system "make", "install"
end
ENV.prepend_path "PKG_CONFIG_PATH", vendor/"pkcs11-helper/lib/pkgconfig"
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--with-crypto-library=openssl",
"--enable-pkcs11",
"--prefix=#{prefix}"
system "make", "install"
# Install OpenVPN's new contrib helper allowing the use of
# macOS keychain certificates with OpenVPN.
cd "contrib/keychain-mcd" do
system "make"
sbin.install "keychain-mcd"
man8.install "keychain-mcd.8"
end
inreplace "sample/sample-config-files/openvpn-startup.sh",
"/etc/openvpn", "#{etc}/openvpn"
(doc/"samples").install Dir["sample/sample-*"]
(etc/"openvpn").install doc/"samples/sample-config-files/client.conf"
(etc/"openvpn").install doc/"samples/sample-config-files/server.conf"
# We don't use PolarSSL, so this file is unnecessary & somewhat confusing.
rm doc/"README.polarssl"
end
def post_install
(var/"run/openvpn").mkpath
end
plist_options :startup => true
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd";>
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_sbin}/openvpn</string>
<string>--config</string>
<string>#{etc}/openvpn/openvpn.conf</string>
</array>
<key>OnDemand</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>TimeOut</key>
<integer>90</integer>
<key>WatchPaths</key>
<array>
<string>#{etc}/openvpn</string>
</array>
<key>WorkingDirectory</key>
<string>#{etc}/openvpn</string>
</dict>
</plist>
EOS
end
test do
system sbin/"openvpn", "--show-ciphers"
end
end
| fvioz/homebrew-core | Formula/openvpn.rb | Ruby | bsd-2-clause | 3,601 |
cask 'sunsama' do
version '1.0.0'
sha256 'b110481cc0aa30db62cdcf1f3eb445a1da5bf2080b51f73190829665ae6511dd'
url "http://download.sunsama.com/desktop/Sunsama-#{version}.dmg"
appcast 'https://s3-us-west-2.amazonaws.com/download.sunsama.com/desktop/latest-mac.yml'
name 'Sunsama'
homepage 'https://app.sunsama.com/desktop'
app 'Sunsama.app'
end
| sscotth/homebrew-cask | Casks/sunsama.rb | Ruby | bsd-2-clause | 358 |
// Copyright 2013 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 "components/nacl/renderer/ppb_nacl_private_impl.h"
#include <numeric>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/containers/scoped_ptr_hash_map.h"
#include "base/cpu.h"
#include "base/files/file.h"
#include "base/json/json_reader.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h"
#include "components/nacl/common/nacl_host_messages.h"
#include "components/nacl/common/nacl_messages.h"
#include "components/nacl/common/nacl_nonsfi_util.h"
#include "components/nacl/common/nacl_switches.h"
#include "components/nacl/common/nacl_types.h"
#include "components/nacl/renderer/file_downloader.h"
#include "components/nacl/renderer/histogram.h"
#include "components/nacl/renderer/json_manifest.h"
#include "components/nacl/renderer/manifest_downloader.h"
#include "components/nacl/renderer/manifest_service_channel.h"
#include "components/nacl/renderer/nexe_load_manager.h"
#include "components/nacl/renderer/platform_info.h"
#include "components/nacl/renderer/pnacl_translation_resource_host.h"
#include "components/nacl/renderer/progress_event.h"
#include "components/nacl/renderer/trusted_plugin_channel.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/sandbox_init.h"
#include "content/public/renderer/pepper_plugin_instance.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "native_client/src/public/imc_types.h"
#include "net/base/data_url.h"
#include "net/base/net_errors.h"
#include "net/http/http_util.h"
#include "ppapi/c/pp_bool.h"
#include "ppapi/c/private/pp_file_handle.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
#include "ppapi/shared_impl/ppapi_preferences.h"
#include "ppapi/shared_impl/var.h"
#include "ppapi/shared_impl/var_tracker.h"
#include "ppapi/thunk/enter.h"
#include "third_party/WebKit/public/platform/WebURLLoader.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
#include "third_party/WebKit/public/web/WebURLLoaderOptions.h"
namespace nacl {
namespace {
// The pseudo-architecture used to indicate portable native client.
const char* const kPortableArch = "portable";
// The base URL for resources used by the PNaCl translator processes.
const char* kPNaClTranslatorBaseUrl = "chrome://pnacl-translator/";
base::LazyInstance<scoped_refptr<PnaclTranslationResourceHost> >
g_pnacl_resource_host = LAZY_INSTANCE_INITIALIZER;
bool InitializePnaclResourceHost() {
// Must run on the main thread.
content::RenderThread* render_thread = content::RenderThread::Get();
if (!render_thread)
return false;
if (!g_pnacl_resource_host.Get().get()) {
g_pnacl_resource_host.Get() = new PnaclTranslationResourceHost(
render_thread->GetIOMessageLoopProxy());
render_thread->AddFilter(g_pnacl_resource_host.Get().get());
}
return true;
}
bool CanOpenViaFastPath(content::PepperPluginInstance* plugin_instance,
const GURL& gurl) {
// Fast path only works for installed file URLs.
if (!gurl.SchemeIs("chrome-extension"))
return PP_kInvalidFileHandle;
// IMPORTANT: Make sure the document can request the given URL. If we don't
// check, a malicious app could probe the extension system. This enforces a
// same-origin policy which prevents the app from requesting resources from
// another app.
blink::WebSecurityOrigin security_origin =
plugin_instance->GetContainer()->element().document().securityOrigin();
return security_origin.canRequest(gurl);
}
// This contains state that is produced by LaunchSelLdr() and consumed
// by StartPpapiProxy().
struct InstanceInfo {
InstanceInfo() : plugin_pid(base::kNullProcessId), plugin_child_id(0) {}
GURL url;
ppapi::PpapiPermissions permissions;
base::ProcessId plugin_pid;
int plugin_child_id;
IPC::ChannelHandle channel_handle;
};
class NaClPluginInstance {
public:
NaClPluginInstance(PP_Instance instance):
nexe_load_manager(instance), pexe_size(0) {}
NexeLoadManager nexe_load_manager;
scoped_ptr<JsonManifest> json_manifest;
scoped_ptr<InstanceInfo> instance_info;
// When translation is complete, this records the size of the pexe in
// bytes so that it can be reported in a later load event.
uint64_t pexe_size;
};
typedef base::ScopedPtrHashMap<PP_Instance, scoped_ptr<NaClPluginInstance>>
InstanceMap;
base::LazyInstance<InstanceMap> g_instance_map = LAZY_INSTANCE_INITIALIZER;
NaClPluginInstance* GetNaClPluginInstance(PP_Instance instance) {
InstanceMap& map = g_instance_map.Get();
InstanceMap::iterator iter = map.find(instance);
if (iter == map.end())
return NULL;
return iter->second;
}
NexeLoadManager* GetNexeLoadManager(PP_Instance instance) {
NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
if (!nacl_plugin_instance)
return NULL;
return &nacl_plugin_instance->nexe_load_manager;
}
JsonManifest* GetJsonManifest(PP_Instance instance) {
NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
if (!nacl_plugin_instance)
return NULL;
return nacl_plugin_instance->json_manifest.get();
}
static const PP_NaClFileInfo kInvalidNaClFileInfo = {
PP_kInvalidFileHandle,
0, // token_lo
0, // token_hi
};
int GetRoutingID(PP_Instance instance) {
// Check that we are on the main renderer thread.
DCHECK(content::RenderThread::Get());
content::RendererPpapiHost* host =
content::RendererPpapiHost::GetForPPInstance(instance);
if (!host)
return 0;
return host->GetRoutingIDForWidget(instance);
}
// Returns whether the channel_handle is valid or not.
bool IsValidChannelHandle(const IPC::ChannelHandle& channel_handle) {
if (channel_handle.name.empty()) {
return false;
}
#if defined(OS_POSIX)
if (channel_handle.socket.fd == -1) {
return false;
}
#endif
return true;
}
void PostPPCompletionCallback(PP_CompletionCallback callback,
int32_t status) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data, status));
}
bool ManifestResolveKey(PP_Instance instance,
bool is_helper_process,
const std::string& key,
std::string* full_url,
PP_PNaClOptions* pnacl_options);
typedef base::Callback<void(int32_t, const PP_NaClFileInfo&)>
DownloadFileCallback;
void DownloadFile(PP_Instance instance,
const std::string& url,
const DownloadFileCallback& callback);
PP_Bool StartPpapiProxy(PP_Instance instance);
// Thin adapter from PPP_ManifestService to ManifestServiceChannel::Delegate.
// Note that user_data is managed by the caller of LaunchSelLdr. Please see
// also PP_ManifestService's comment for more details about resource
// management.
class ManifestServiceProxy : public ManifestServiceChannel::Delegate {
public:
ManifestServiceProxy(PP_Instance pp_instance, NaClAppProcessType process_type)
: pp_instance_(pp_instance), process_type_(process_type) {}
~ManifestServiceProxy() override {}
void StartupInitializationComplete() override {
if (StartPpapiProxy(pp_instance_) == PP_TRUE) {
NaClPluginInstance* nacl_plugin_instance =
GetNaClPluginInstance(pp_instance_);
JsonManifest* manifest = GetJsonManifest(pp_instance_);
if (nacl_plugin_instance && manifest) {
NexeLoadManager* load_manager =
&nacl_plugin_instance->nexe_load_manager;
std::string full_url;
PP_PNaClOptions pnacl_options;
bool uses_nonsfi_mode;
JsonManifest::ErrorInfo error_info;
if (manifest->GetProgramURL(&full_url,
&pnacl_options,
&uses_nonsfi_mode,
&error_info)) {
int64_t exe_size = nacl_plugin_instance->pexe_size;
if (exe_size == 0)
exe_size = load_manager->nexe_size();
load_manager->ReportLoadSuccess(full_url, exe_size, exe_size);
}
}
}
}
void OpenResource(
const std::string& key,
const ManifestServiceChannel::OpenResourceCallback& callback) override {
DCHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
BelongsToCurrentThread());
// For security hardening, disable open_resource() when it is isn't
// needed. PNaCl pexes can't use open_resource(), but general nexes
// and the PNaCl translator nexes may use it.
if (process_type_ != kNativeNaClProcessType &&
process_type_ != kPNaClTranslatorProcessType) {
// Return an error.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(base::File()), 0, 0));
return;
}
std::string url;
// TODO(teravest): Clean up pnacl_options logic in JsonManifest so we don't
// have to initialize it like this here.
PP_PNaClOptions pnacl_options;
pnacl_options.translate = PP_FALSE;
pnacl_options.is_debug = PP_FALSE;
pnacl_options.use_subzero = PP_FALSE;
pnacl_options.opt_level = 2;
bool is_helper_process = process_type_ == kPNaClTranslatorProcessType;
if (!ManifestResolveKey(pp_instance_, is_helper_process, key, &url,
&pnacl_options)) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, base::Passed(base::File()), 0, 0));
return;
}
// We have to call DidDownloadFile, even if this object is destroyed, so
// that the handle inside PP_NaClFileInfo isn't leaked. This means that the
// callback passed to this function shouldn't have a weak pointer to an
// object either.
//
// TODO(teravest): Make a type like PP_NaClFileInfo to use for DownloadFile
// that would close the file handle on destruction.
DownloadFile(pp_instance_, url,
base::Bind(&ManifestServiceProxy::DidDownloadFile, callback));
}
private:
static void DidDownloadFile(
ManifestServiceChannel::OpenResourceCallback callback,
int32_t pp_error,
const PP_NaClFileInfo& file_info) {
if (pp_error != PP_OK) {
callback.Run(base::File(), 0, 0);
return;
}
callback.Run(base::File(file_info.handle),
file_info.token_lo,
file_info.token_hi);
}
PP_Instance pp_instance_;
NaClAppProcessType process_type_;
DISALLOW_COPY_AND_ASSIGN(ManifestServiceProxy);
};
blink::WebURLLoader* CreateWebURLLoader(const blink::WebDocument& document,
const GURL& gurl) {
blink::WebURLLoaderOptions options;
options.untrustedHTTP = true;
// Options settings here follow the original behavior in the trusted
// plugin and PepperURLLoaderHost.
if (document.securityOrigin().canRequest(gurl)) {
options.allowCredentials = true;
} else {
// Allow CORS.
options.crossOriginRequestPolicy =
blink::WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
}
return document.frame()->createAssociatedURLLoader(options);
}
blink::WebURLRequest CreateWebURLRequest(const blink::WebDocument& document,
const GURL& gurl) {
blink::WebURLRequest request;
request.initialize();
request.setURL(gurl);
request.setFirstPartyForCookies(document.firstPartyForCookies());
return request;
}
int32_t FileDownloaderToPepperError(FileDownloader::Status status) {
switch (status) {
case FileDownloader::SUCCESS:
return PP_OK;
case FileDownloader::ACCESS_DENIED:
return PP_ERROR_NOACCESS;
case FileDownloader::FAILED:
return PP_ERROR_FAILED;
// No default case, to catch unhandled Status values.
}
return PP_ERROR_FAILED;
}
NaClAppProcessType PP_ToNaClAppProcessType(
PP_NaClAppProcessType pp_process_type) {
#define STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(pp, nonpp) \
static_assert(static_cast<int>(pp) == static_cast<int>(nonpp), \
"PP_NaClAppProcessType differs from NaClAppProcessType");
STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_UNKNOWN_NACL_PROCESS_TYPE,
kUnknownNaClProcessType);
STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_NATIVE_NACL_PROCESS_TYPE,
kNativeNaClProcessType);
STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_PNACL_PROCESS_TYPE,
kPNaClProcessType);
STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_PNACL_TRANSLATOR_PROCESS_TYPE,
kPNaClTranslatorProcessType);
STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_NUM_NACL_PROCESS_TYPES,
kNumNaClProcessTypes);
#undef STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ
DCHECK(pp_process_type > PP_UNKNOWN_NACL_PROCESS_TYPE &&
pp_process_type < PP_NUM_NACL_PROCESS_TYPES);
return static_cast<NaClAppProcessType>(pp_process_type);
}
// Launch NaCl's sel_ldr process.
void LaunchSelLdr(PP_Instance instance,
PP_Bool main_service_runtime,
const char* alleged_url,
const PP_NaClFileInfo* nexe_file_info,
PP_Bool uses_nonsfi_mode,
PP_NaClAppProcessType pp_process_type,
void* imc_handle,
PP_CompletionCallback callback) {
CHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
BelongsToCurrentThread());
NaClAppProcessType process_type = PP_ToNaClAppProcessType(pp_process_type);
// Create the manifest service proxy here, so on error case, it will be
// destructed (without passing it to ManifestServiceChannel).
scoped_ptr<ManifestServiceChannel::Delegate> manifest_service_proxy(
new ManifestServiceProxy(instance, process_type));
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
int routing_id = GetRoutingID(instance);
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
DCHECK(plugin_instance);
if (!routing_id || !load_manager || !plugin_instance) {
if (nexe_file_info->handle != PP_kInvalidFileHandle) {
base::File closer(nexe_file_info->handle);
}
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE, base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
InstanceInfo instance_info;
instance_info.url = GURL(alleged_url);
uint32_t perm_bits = ppapi::PERMISSION_NONE;
// Conditionally block 'Dev' interfaces. We do this for the NaCl process, so
// it's clearer to developers when they are using 'Dev' inappropriately. We
// must also check on the trusted side of the proxy.
if (load_manager->DevInterfacesEnabled())
perm_bits |= ppapi::PERMISSION_DEV;
instance_info.permissions =
ppapi::PpapiPermissions::GetForCommandLine(perm_bits);
std::vector<NaClResourcePrefetchRequest> resource_prefetch_request_list;
if (process_type == kNativeNaClProcessType) {
JsonManifest* manifest = GetJsonManifest(instance);
if (manifest) {
manifest->GetPrefetchableFiles(&resource_prefetch_request_list);
for (size_t i = 0; i < resource_prefetch_request_list.size(); ++i) {
const GURL gurl(resource_prefetch_request_list[i].resource_url);
// Important security check. Do not remove.
if (!CanOpenViaFastPath(plugin_instance, gurl)) {
resource_prefetch_request_list.clear();
break;
}
}
}
}
IPC::PlatformFileForTransit nexe_for_transit =
IPC::InvalidPlatformFileForTransit();
#if defined(OS_POSIX)
if (nexe_file_info->handle != PP_kInvalidFileHandle)
nexe_for_transit = base::FileDescriptor(nexe_file_info->handle, true);
#elif defined(OS_WIN)
// Duplicate the handle on the browser side instead of the renderer.
// This is because BrokerGetFileForProcess isn't part of content/public, and
// it's simpler to do the duplication in the browser anyway.
nexe_for_transit = nexe_file_info->handle;
#else
# error Unsupported target platform.
#endif
std::string error_message_string;
NaClLaunchResult launch_result;
if (!sender->Send(new NaClHostMsg_LaunchNaCl(
NaClLaunchParams(
instance_info.url.spec(),
nexe_for_transit,
nexe_file_info->token_lo,
nexe_file_info->token_hi,
resource_prefetch_request_list,
routing_id,
perm_bits,
PP_ToBool(uses_nonsfi_mode),
process_type),
&launch_result,
&error_message_string))) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
load_manager->set_nonsfi(PP_ToBool(uses_nonsfi_mode));
if (!error_message_string.empty()) {
// Even on error, some FDs/handles may be passed to here.
// We must release those resources.
// See also nacl_process_host.cc.
IPC::PlatformFileForTransitToFile(launch_result.imc_channel_handle);
base::SharedMemory::CloseHandle(launch_result.crash_info_shmem_handle);
if (PP_ToBool(main_service_runtime)) {
load_manager->ReportLoadError(PP_NACL_ERROR_SEL_LDR_LAUNCH,
"ServiceRuntime: failed to start",
error_message_string);
}
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
instance_info.channel_handle = launch_result.ppapi_ipc_channel_handle;
instance_info.plugin_pid = launch_result.plugin_pid;
instance_info.plugin_child_id = launch_result.plugin_child_id;
// Don't save instance_info if channel handle is invalid.
if (IsValidChannelHandle(instance_info.channel_handle)) {
NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
nacl_plugin_instance->instance_info.reset(new InstanceInfo(instance_info));
}
*(static_cast<NaClHandle*>(imc_handle)) =
IPC::PlatformFileForTransitToPlatformFile(
launch_result.imc_channel_handle);
// Store the crash information shared memory handle.
load_manager->set_crash_info_shmem_handle(
launch_result.crash_info_shmem_handle);
// Create the trusted plugin channel.
if (IsValidChannelHandle(launch_result.trusted_ipc_channel_handle)) {
bool is_helper_nexe = !PP_ToBool(main_service_runtime);
scoped_ptr<TrustedPluginChannel> trusted_plugin_channel(
new TrustedPluginChannel(
load_manager,
launch_result.trusted_ipc_channel_handle,
content::RenderThread::Get()->GetShutdownEvent(),
is_helper_nexe));
load_manager->set_trusted_plugin_channel(trusted_plugin_channel.Pass());
} else {
PostPPCompletionCallback(callback, PP_ERROR_FAILED);
return;
}
// Create the manifest service handle as well.
if (IsValidChannelHandle(launch_result.manifest_service_ipc_channel_handle)) {
scoped_ptr<ManifestServiceChannel> manifest_service_channel(
new ManifestServiceChannel(
launch_result.manifest_service_ipc_channel_handle,
base::Bind(&PostPPCompletionCallback, callback),
manifest_service_proxy.Pass(),
content::RenderThread::Get()->GetShutdownEvent()));
load_manager->set_manifest_service_channel(
manifest_service_channel.Pass());
}
}
PP_Bool StartPpapiProxy(PP_Instance instance) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager)
return PP_FALSE;
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!plugin_instance) {
DLOG(ERROR) << "GetInstance() failed";
return PP_FALSE;
}
NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
if (!nacl_plugin_instance->instance_info) {
DLOG(ERROR) << "Could not find instance ID";
return PP_FALSE;
}
scoped_ptr<InstanceInfo> instance_info =
nacl_plugin_instance->instance_info.Pass();
PP_ExternalPluginResult result = plugin_instance->SwitchToOutOfProcessProxy(
base::FilePath().AppendASCII(instance_info->url.spec()),
instance_info->permissions,
instance_info->channel_handle,
instance_info->plugin_pid,
instance_info->plugin_child_id);
if (result == PP_EXTERNAL_PLUGIN_OK) {
// Log the amound of time that has passed between the trusted plugin being
// initialized and the untrusted plugin being initialized. This is
// (roughly) the cost of using NaCl, in terms of startup time.
load_manager->ReportStartupOverhead();
return PP_TRUE;
} else if (result == PP_EXTERNAL_PLUGIN_ERROR_MODULE) {
load_manager->ReportLoadError(PP_NACL_ERROR_START_PROXY_MODULE,
"could not initialize module.");
} else if (result == PP_EXTERNAL_PLUGIN_ERROR_INSTANCE) {
load_manager->ReportLoadError(PP_NACL_ERROR_START_PROXY_MODULE,
"could not create instance.");
}
return PP_FALSE;
}
int UrandomFD(void) {
#if defined(OS_POSIX)
return base::GetUrandomFD();
#else
return -1;
#endif
}
int32_t BrokerDuplicateHandle(PP_FileHandle source_handle,
uint32_t process_id,
PP_FileHandle* target_handle,
uint32_t desired_access,
uint32_t options) {
#if defined(OS_WIN)
return content::BrokerDuplicateHandle(source_handle, process_id,
target_handle, desired_access,
options);
#else
return 0;
#endif
}
// Convert a URL to a filename for GetReadonlyPnaclFd.
// Must be kept in sync with PnaclCanOpenFile() in
// components/nacl/browser/nacl_file_host.cc.
std::string PnaclComponentURLToFilename(const std::string& url) {
// PNaCl component URLs aren't arbitrary URLs; they are always either
// generated from ManifestResolveKey or PnaclResources::ReadResourceInfo.
// So, it's safe to just use string parsing operations here instead of
// URL-parsing ones.
DCHECK(base::StartsWith(url, kPNaClTranslatorBaseUrl,
base::CompareCase::SENSITIVE));
std::string r = url.substr(std::string(kPNaClTranslatorBaseUrl).length());
// Use white-listed-chars.
size_t replace_pos;
static const char* white_list = "abcdefghijklmnopqrstuvwxyz0123456789_";
replace_pos = r.find_first_not_of(white_list);
while(replace_pos != std::string::npos) {
r = r.replace(replace_pos, 1, "_");
replace_pos = r.find_first_not_of(white_list);
}
return r;
}
PP_FileHandle GetReadonlyPnaclFd(const char* url,
bool is_executable,
uint64_t* nonce_lo,
uint64_t* nonce_hi) {
std::string filename = PnaclComponentURLToFilename(url);
IPC::PlatformFileForTransit out_fd = IPC::InvalidPlatformFileForTransit();
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
if (!sender->Send(new NaClHostMsg_GetReadonlyPnaclFD(
std::string(filename), is_executable,
&out_fd, nonce_lo, nonce_hi))) {
return PP_kInvalidFileHandle;
}
if (out_fd == IPC::InvalidPlatformFileForTransit()) {
return PP_kInvalidFileHandle;
}
return IPC::PlatformFileForTransitToPlatformFile(out_fd);
}
void GetReadExecPnaclFd(const char* url,
PP_NaClFileInfo* out_file_info) {
*out_file_info = kInvalidNaClFileInfo;
out_file_info->handle = GetReadonlyPnaclFd(url, true /* is_executable */,
&out_file_info->token_lo,
&out_file_info->token_hi);
}
PP_FileHandle CreateTemporaryFile(PP_Instance instance) {
IPC::PlatformFileForTransit transit_fd = IPC::InvalidPlatformFileForTransit();
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
if (!sender->Send(new NaClHostMsg_NaClCreateTemporaryFile(
&transit_fd))) {
return PP_kInvalidFileHandle;
}
if (transit_fd == IPC::InvalidPlatformFileForTransit()) {
return PP_kInvalidFileHandle;
}
return IPC::PlatformFileForTransitToPlatformFile(transit_fd);
}
int32_t GetNumberOfProcessors() {
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
int32_t num_processors = 1;
return sender->Send(new NaClHostMsg_NaClGetNumProcessors(&num_processors)) ?
num_processors : 1;
}
void GetNexeFd(PP_Instance instance,
const std::string& pexe_url,
uint32_t opt_level,
const base::Time& last_modified_time,
const std::string& etag,
bool has_no_store_header,
bool use_subzero,
base::Callback<void(int32_t, bool, PP_FileHandle)> callback) {
if (!InitializePnaclResourceHost()) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback,
static_cast<int32_t>(PP_ERROR_FAILED),
false,
PP_kInvalidFileHandle));
return;
}
PnaclCacheInfo cache_info;
cache_info.pexe_url = GURL(pexe_url);
// TODO(dschuff): Get this value from the pnacl json file after it
// rolls in from NaCl.
cache_info.abi_version = 1;
cache_info.opt_level = opt_level;
cache_info.last_modified = last_modified_time;
cache_info.etag = etag;
cache_info.has_no_store_header = has_no_store_header;
cache_info.use_subzero = use_subzero;
cache_info.sandbox_isa = GetSandboxArch();
cache_info.extra_flags = GetCpuFeatures();
g_pnacl_resource_host.Get()->RequestNexeFd(
GetRoutingID(instance),
instance,
cache_info,
callback);
}
void LogTranslationFinishedUMA(const std::string& uma_suffix,
int32_t opt_level,
int32_t unknown_opt_level,
int64_t nexe_size,
int64_t pexe_size,
int64_t compile_time_us,
base::TimeDelta total_time) {
HistogramEnumerate("NaCl.Options.PNaCl.OptLevel" + uma_suffix, opt_level,
unknown_opt_level + 1);
HistogramKBPerSec("NaCl.Perf.PNaClLoadTime.CompileKBPerSec" + uma_suffix,
pexe_size / 1024, compile_time_us);
HistogramSizeKB("NaCl.Perf.Size.PNaClTranslatedNexe" + uma_suffix,
nexe_size / 1024);
HistogramSizeKB("NaCl.Perf.Size.Pexe" + uma_suffix, pexe_size / 1024);
HistogramRatio("NaCl.Perf.Size.PexeNexeSizePct" + uma_suffix, pexe_size,
nexe_size);
HistogramTimeTranslation(
"NaCl.Perf.PNaClLoadTime.TotalUncachedTime" + uma_suffix,
total_time.InMilliseconds());
HistogramKBPerSec(
"NaCl.Perf.PNaClLoadTime.TotalUncachedKBPerSec" + uma_suffix,
pexe_size / 1024, total_time.InMicroseconds());
}
void ReportTranslationFinished(PP_Instance instance,
PP_Bool success,
int32_t opt_level,
PP_Bool use_subzero,
int64_t nexe_size,
int64_t pexe_size,
int64_t compile_time_us) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (success == PP_TRUE && load_manager) {
base::TimeDelta total_time =
base::Time::Now() - load_manager->pnacl_start_time();
static const int32_t kUnknownOptLevel = 4;
if (opt_level < 0 || opt_level > 3)
opt_level = kUnknownOptLevel;
// Log twice: once to cover all PNaCl UMA, and then a second
// time with the more specific UMA (Subzero vs LLC).
std::string uma_suffix(use_subzero ? ".Subzero" : ".LLC");
LogTranslationFinishedUMA("", opt_level, kUnknownOptLevel, nexe_size,
pexe_size, compile_time_us, total_time);
LogTranslationFinishedUMA(uma_suffix, opt_level, kUnknownOptLevel,
nexe_size, pexe_size, compile_time_us,
total_time);
}
// If the resource host isn't initialized, don't try to do that here.
// Just return because something is already very wrong.
if (g_pnacl_resource_host.Get().get() == NULL)
return;
g_pnacl_resource_host.Get()->ReportTranslationFinished(instance, success);
// Record the pexe size for reporting in a later load event.
NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
if (nacl_plugin_instance) {
nacl_plugin_instance->pexe_size = pexe_size;
}
}
PP_FileHandle OpenNaClExecutable(PP_Instance instance,
const char* file_url,
uint64_t* nonce_lo,
uint64_t* nonce_hi) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager)
return PP_kInvalidFileHandle;
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!plugin_instance)
return PP_kInvalidFileHandle;
GURL gurl(file_url);
// Important security check. Do not remove.
if (!CanOpenViaFastPath(plugin_instance, gurl))
return PP_kInvalidFileHandle;
IPC::PlatformFileForTransit out_fd = IPC::InvalidPlatformFileForTransit();
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
*nonce_lo = 0;
*nonce_hi = 0;
base::FilePath file_path;
if (!sender->Send(
new NaClHostMsg_OpenNaClExecutable(GetRoutingID(instance),
GURL(file_url),
!load_manager->nonsfi(),
&out_fd,
nonce_lo,
nonce_hi))) {
return PP_kInvalidFileHandle;
}
if (out_fd == IPC::InvalidPlatformFileForTransit())
return PP_kInvalidFileHandle;
return IPC::PlatformFileForTransitToPlatformFile(out_fd);
}
void DispatchEvent(PP_Instance instance,
PP_NaClEventType event_type,
const char* resource_url,
PP_Bool length_is_computable,
uint64_t loaded_bytes,
uint64_t total_bytes) {
ProgressEvent event(event_type,
resource_url,
PP_ToBool(length_is_computable),
loaded_bytes,
total_bytes);
DispatchProgressEvent(instance, event);
}
void ReportLoadError(PP_Instance instance,
PP_NaClError error,
const char* error_message) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
if (load_manager)
load_manager->ReportLoadError(error, error_message);
}
void InstanceCreated(PP_Instance instance) {
InstanceMap& map = g_instance_map.Get();
CHECK(map.find(instance) == map.end()); // Sanity check.
scoped_ptr<NaClPluginInstance> new_instance(new NaClPluginInstance(instance));
map.add(instance, new_instance.Pass());
}
void InstanceDestroyed(PP_Instance instance) {
InstanceMap& map = g_instance_map.Get();
InstanceMap::iterator iter = map.find(instance);
CHECK(iter != map.end());
// The erase may call NexeLoadManager's destructor prior to removing it from
// the map. In that case, it is possible for the trusted Plugin to re-enter
// the NexeLoadManager (e.g., by calling ReportLoadError). Passing out the
// NexeLoadManager to a local scoped_ptr just ensures that its entry is gone
// from the map prior to the destructor being invoked.
scoped_ptr<NaClPluginInstance> temp(map.take(instance));
map.erase(iter);
}
PP_Bool NaClDebugEnabledForURL(const char* alleged_nmf_url) {
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClDebug))
return PP_FALSE;
IPC::Sender* sender = content::RenderThread::Get();
DCHECK(sender);
bool should_debug = false;
return PP_FromBool(
sender->Send(new NaClHostMsg_NaClDebugEnabledForURL(GURL(alleged_nmf_url),
&should_debug)) &&
should_debug);
}
void Vlog(const char* message) {
VLOG(1) << message;
}
void InitializePlugin(PP_Instance instance,
uint32_t argc,
const char* argn[],
const char* argv[]) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (load_manager)
load_manager->InitializePlugin(argc, argn, argv);
}
void DownloadManifestToBuffer(PP_Instance instance,
struct PP_CompletionCallback callback);
bool CreateJsonManifest(PP_Instance instance,
const std::string& manifest_url,
const std::string& manifest_data);
void RequestNaClManifest(PP_Instance instance,
PP_CompletionCallback callback) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
std::string url = load_manager->GetManifestURLArgument();
if (url.empty() || !load_manager->RequestNaClManifest(url)) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
const GURL& base_url = load_manager->manifest_base_url();
if (base_url.SchemeIs("data")) {
GURL gurl(base_url);
std::string mime_type;
std::string charset;
std::string data;
int32_t error = PP_ERROR_FAILED;
if (net::DataURL::Parse(gurl, &mime_type, &charset, &data)) {
if (data.size() <= ManifestDownloader::kNaClManifestMaxFileBytes) {
if (CreateJsonManifest(instance, base_url.spec(), data))
error = PP_OK;
} else {
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_TOO_LARGE,
"manifest file too large.");
}
} else {
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
"could not load manifest url.");
}
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data, error));
} else {
DownloadManifestToBuffer(instance, callback);
}
}
PP_Var GetManifestBaseURL(PP_Instance instance) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager)
return PP_MakeUndefined();
const GURL& gurl = load_manager->manifest_base_url();
if (!gurl.is_valid())
return PP_MakeUndefined();
return ppapi::StringVar::StringToPPVar(gurl.spec());
}
void ProcessNaClManifest(PP_Instance instance, const char* program_url) {
nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
if (load_manager)
load_manager->ProcessNaClManifest(program_url);
}
void DownloadManifestToBufferCompletion(PP_Instance instance,
struct PP_CompletionCallback callback,
base::Time start_time,
PP_NaClError pp_nacl_error,
const std::string& data);
void DownloadManifestToBuffer(PP_Instance instance,
struct PP_CompletionCallback callback) {
nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!load_manager || !plugin_instance) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
}
const blink::WebDocument& document =
plugin_instance->GetContainer()->element().document();
const GURL& gurl = load_manager->manifest_base_url();
scoped_ptr<blink::WebURLLoader> url_loader(
CreateWebURLLoader(document, gurl));
blink::WebURLRequest request = CreateWebURLRequest(document, gurl);
// ManifestDownloader deletes itself after invoking the callback.
ManifestDownloader* manifest_downloader = new ManifestDownloader(
url_loader.Pass(),
load_manager->is_installed(),
base::Bind(DownloadManifestToBufferCompletion,
instance, callback, base::Time::Now()));
manifest_downloader->Load(request);
}
void DownloadManifestToBufferCompletion(PP_Instance instance,
struct PP_CompletionCallback callback,
base::Time start_time,
PP_NaClError pp_nacl_error,
const std::string& data) {
base::TimeDelta download_time = base::Time::Now() - start_time;
HistogramTimeSmall("NaCl.Perf.StartupTime.ManifestDownload",
download_time.InMilliseconds());
nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
if (!load_manager) {
callback.func(callback.user_data, PP_ERROR_ABORTED);
return;
}
int32_t pp_error;
switch (pp_nacl_error) {
case PP_NACL_ERROR_LOAD_SUCCESS:
pp_error = PP_OK;
break;
case PP_NACL_ERROR_MANIFEST_LOAD_URL:
pp_error = PP_ERROR_FAILED;
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
"could not load manifest url.");
break;
case PP_NACL_ERROR_MANIFEST_TOO_LARGE:
pp_error = PP_ERROR_FILETOOBIG;
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_TOO_LARGE,
"manifest file too large.");
break;
case PP_NACL_ERROR_MANIFEST_NOACCESS_URL:
pp_error = PP_ERROR_NOACCESS;
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_NOACCESS_URL,
"access to manifest url was denied.");
break;
default:
NOTREACHED();
pp_error = PP_ERROR_FAILED;
load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
"could not load manifest url.");
}
if (pp_error == PP_OK) {
std::string base_url = load_manager->manifest_base_url().spec();
if (!CreateJsonManifest(instance, base_url, data))
pp_error = PP_ERROR_FAILED;
}
callback.func(callback.user_data, pp_error);
}
bool CreateJsonManifest(PP_Instance instance,
const std::string& manifest_url,
const std::string& manifest_data) {
HistogramSizeKB("NaCl.Perf.Size.Manifest",
static_cast<int32_t>(manifest_data.length() / 1024));
nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
if (!load_manager)
return false;
const char* isa_type;
if (load_manager->IsPNaCl())
isa_type = kPortableArch;
else
isa_type = GetSandboxArch();
scoped_ptr<nacl::JsonManifest> j(
new nacl::JsonManifest(
manifest_url.c_str(),
isa_type,
IsNonSFIModeEnabled(),
PP_ToBool(NaClDebugEnabledForURL(manifest_url.c_str()))));
JsonManifest::ErrorInfo error_info;
if (j->Init(manifest_data.c_str(), &error_info)) {
GetNaClPluginInstance(instance)->json_manifest.reset(j.release());
return true;
}
load_manager->ReportLoadError(error_info.error, error_info.string);
return false;
}
PP_Bool ManifestGetProgramURL(PP_Instance instance,
PP_Var* pp_full_url,
PP_PNaClOptions* pnacl_options,
PP_Bool* pp_uses_nonsfi_mode) {
nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
JsonManifest* manifest = GetJsonManifest(instance);
if (manifest == NULL)
return PP_FALSE;
bool uses_nonsfi_mode;
std::string full_url;
JsonManifest::ErrorInfo error_info;
if (manifest->GetProgramURL(&full_url, pnacl_options, &uses_nonsfi_mode,
&error_info)) {
*pp_full_url = ppapi::StringVar::StringToPPVar(full_url);
*pp_uses_nonsfi_mode = PP_FromBool(uses_nonsfi_mode);
// Check if we should use Subzero (x86-32 / non-debugging case for now).
if (pnacl_options->opt_level == 0 && !pnacl_options->is_debug &&
strcmp(GetSandboxArch(), "x86-32") == 0 &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnablePNaClSubzero)) {
pnacl_options->use_subzero = PP_TRUE;
// Subzero -O2 is closer to LLC -O0, so indicate -O2.
pnacl_options->opt_level = 2;
}
return PP_TRUE;
}
if (load_manager)
load_manager->ReportLoadError(error_info.error, error_info.string);
return PP_FALSE;
}
bool ManifestResolveKey(PP_Instance instance,
bool is_helper_process,
const std::string& key,
std::string* full_url,
PP_PNaClOptions* pnacl_options) {
// For "helper" processes (llc and ld, for PNaCl translation), we resolve
// keys manually as there is no existing .nmf file to parse.
if (is_helper_process) {
pnacl_options->translate = PP_FALSE;
*full_url = std::string(kPNaClTranslatorBaseUrl) + GetSandboxArch() + "/" +
key;
return true;
}
JsonManifest* manifest = GetJsonManifest(instance);
if (manifest == NULL)
return false;
return manifest->ResolveKey(key, full_url, pnacl_options);
}
PP_Bool GetPNaClResourceInfo(PP_Instance instance,
PP_Var* llc_tool_name,
PP_Var* ld_tool_name,
PP_Var* subzero_tool_name) {
static const char kFilename[] = "chrome://pnacl-translator/pnacl.json";
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager)
return PP_FALSE;
uint64_t nonce_lo = 0;
uint64_t nonce_hi = 0;
base::File file(GetReadonlyPnaclFd(kFilename, false /* is_executable */,
&nonce_lo, &nonce_hi));
if (!file.IsValid()) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
"The Portable Native Client (pnacl) component is not "
"installed. Please consult chrome://components for more "
"information.");
return PP_FALSE;
}
base::File::Info file_info;
if (!file.GetInfo(&file_info)) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
std::string("GetPNaClResourceInfo, GetFileInfo failed for: ") +
kFilename);
return PP_FALSE;
}
if (file_info.size > 1 << 20) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
std::string("GetPNaClResourceInfo, file too large: ") + kFilename);
return PP_FALSE;
}
scoped_ptr<char[]> buffer(new char[file_info.size + 1]);
if (buffer.get() == NULL) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
std::string("GetPNaClResourceInfo, couldn't allocate for: ") +
kFilename);
return PP_FALSE;
}
int rc = file.Read(0, buffer.get(), file_info.size);
if (rc < 0) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
std::string("GetPNaClResourceInfo, reading failed for: ") + kFilename);
return PP_FALSE;
}
// Null-terminate the bytes we we read from the file.
buffer.get()[rc] = 0;
// Expect the JSON file to contain a top-level object (dictionary).
base::JSONReader json_reader;
int json_read_error_code;
std::string json_read_error_msg;
scoped_ptr<base::Value> json_data(json_reader.ReadAndReturnError(
buffer.get(),
base::JSON_PARSE_RFC,
&json_read_error_code,
&json_read_error_msg));
if (!json_data) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
std::string("Parsing resource info failed: JSON parse error: ") +
json_read_error_msg);
return PP_FALSE;
}
base::DictionaryValue* json_dict;
if (!json_data->GetAsDictionary(&json_dict)) {
load_manager->ReportLoadError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
"Parsing resource info failed: Malformed JSON dictionary");
return PP_FALSE;
}
std::string pnacl_llc_name;
if (json_dict->GetString("pnacl-llc-name", &pnacl_llc_name))
*llc_tool_name = ppapi::StringVar::StringToPPVar(pnacl_llc_name);
std::string pnacl_ld_name;
if (json_dict->GetString("pnacl-ld-name", &pnacl_ld_name))
*ld_tool_name = ppapi::StringVar::StringToPPVar(pnacl_ld_name);
std::string pnacl_sz_name;
if (json_dict->GetString("pnacl-sz-name", &pnacl_sz_name))
*subzero_tool_name = ppapi::StringVar::StringToPPVar(pnacl_sz_name);
return PP_TRUE;
}
PP_Var GetCpuFeatureAttrs() {
return ppapi::StringVar::StringToPPVar(GetCpuFeatures());
}
// Encapsulates some of the state for a call to DownloadNexe to prevent
// argument lists from getting too long.
struct DownloadNexeRequest {
PP_Instance instance;
std::string url;
PP_CompletionCallback callback;
base::Time start_time;
};
// A utility class to ensure that we don't send progress events more often than
// every 10ms for a given file.
class ProgressEventRateLimiter {
public:
explicit ProgressEventRateLimiter(PP_Instance instance)
: instance_(instance) { }
void ReportProgress(const std::string& url,
int64_t total_bytes_received,
int64_t total_bytes_to_be_received) {
base::Time now = base::Time::Now();
if (now - last_event_ > base::TimeDelta::FromMilliseconds(10)) {
DispatchProgressEvent(instance_,
ProgressEvent(PP_NACL_EVENT_PROGRESS,
url,
total_bytes_to_be_received >= 0,
total_bytes_received,
total_bytes_to_be_received));
last_event_ = now;
}
}
private:
PP_Instance instance_;
base::Time last_event_;
};
void DownloadNexeCompletion(const DownloadNexeRequest& request,
PP_NaClFileInfo* out_file_info,
FileDownloader::Status status,
base::File target_file,
int http_status);
void DownloadNexe(PP_Instance instance,
const char* url,
PP_NaClFileInfo* out_file_info,
PP_CompletionCallback callback) {
CHECK(url);
CHECK(out_file_info);
DownloadNexeRequest request;
request.instance = instance;
request.url = url;
request.callback = callback;
request.start_time = base::Time::Now();
// Try the fast path for retrieving the file first.
PP_FileHandle handle = OpenNaClExecutable(instance,
url,
&out_file_info->token_lo,
&out_file_info->token_hi);
if (handle != PP_kInvalidFileHandle) {
DownloadNexeCompletion(request,
out_file_info,
FileDownloader::SUCCESS,
base::File(handle),
200);
return;
}
// The fast path didn't work, we'll fetch the file using URLLoader and write
// it to local storage.
base::File target_file(CreateTemporaryFile(instance));
GURL gurl(url);
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!plugin_instance) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(callback.func, callback.user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
}
const blink::WebDocument& document =
plugin_instance->GetContainer()->element().document();
scoped_ptr<blink::WebURLLoader> url_loader(
CreateWebURLLoader(document, gurl));
blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
ProgressEventRateLimiter* tracker = new ProgressEventRateLimiter(instance);
// FileDownloader deletes itself after invoking DownloadNexeCompletion.
FileDownloader* file_downloader = new FileDownloader(
url_loader.Pass(),
target_file.Pass(),
base::Bind(&DownloadNexeCompletion, request, out_file_info),
base::Bind(&ProgressEventRateLimiter::ReportProgress,
base::Owned(tracker), std::string(url)));
file_downloader->Load(url_request);
}
void DownloadNexeCompletion(const DownloadNexeRequest& request,
PP_NaClFileInfo* out_file_info,
FileDownloader::Status status,
base::File target_file,
int http_status) {
int32_t pp_error = FileDownloaderToPepperError(status);
int64_t bytes_read = -1;
if (pp_error == PP_OK && target_file.IsValid()) {
base::File::Info info;
if (target_file.GetInfo(&info))
bytes_read = info.size;
}
if (bytes_read == -1) {
target_file.Close();
pp_error = PP_ERROR_FAILED;
}
base::TimeDelta download_time = base::Time::Now() - request.start_time;
NexeLoadManager* load_manager = GetNexeLoadManager(request.instance);
if (load_manager) {
load_manager->NexeFileDidOpen(pp_error,
target_file,
http_status,
bytes_read,
request.url,
download_time);
}
if (pp_error == PP_OK && target_file.IsValid())
out_file_info->handle = target_file.TakePlatformFile();
else
out_file_info->handle = PP_kInvalidFileHandle;
request.callback.func(request.callback.user_data, pp_error);
}
void DownloadFileCompletion(
const DownloadFileCallback& callback,
FileDownloader::Status status,
base::File file,
int http_status) {
int32_t pp_error = FileDownloaderToPepperError(status);
PP_NaClFileInfo file_info;
if (pp_error == PP_OK) {
file_info.handle = file.TakePlatformFile();
file_info.token_lo = 0;
file_info.token_hi = 0;
} else {
file_info = kInvalidNaClFileInfo;
}
callback.Run(pp_error, file_info);
}
void DownloadFile(PP_Instance instance,
const std::string& url,
const DownloadFileCallback& callback) {
DCHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
BelongsToCurrentThread());
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
DCHECK(load_manager);
if (!load_manager) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
kInvalidNaClFileInfo));
return;
}
// Handle special PNaCl support files which are installed on the user's
// machine.
if (url.find(kPNaClTranslatorBaseUrl, 0) == 0) {
PP_NaClFileInfo file_info = kInvalidNaClFileInfo;
PP_FileHandle handle = GetReadonlyPnaclFd(url.c_str(),
false /* is_executable */,
&file_info.token_lo,
&file_info.token_hi);
if (handle == PP_kInvalidFileHandle) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
kInvalidNaClFileInfo));
return;
}
file_info.handle = handle;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(callback, static_cast<int32_t>(PP_OK), file_info));
return;
}
// We have to ensure that this url resolves relative to the plugin base url
// before downloading it.
const GURL& test_gurl = load_manager->plugin_base_url().Resolve(url);
if (!test_gurl.is_valid()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
kInvalidNaClFileInfo));
return;
}
// Try the fast path for retrieving the file first.
uint64_t file_token_lo = 0;
uint64_t file_token_hi = 0;
PP_FileHandle file_handle = OpenNaClExecutable(instance,
url.c_str(),
&file_token_lo,
&file_token_hi);
if (file_handle != PP_kInvalidFileHandle) {
PP_NaClFileInfo file_info;
file_info.handle = file_handle;
file_info.token_lo = file_token_lo;
file_info.token_hi = file_token_hi;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(callback, static_cast<int32_t>(PP_OK), file_info));
return;
}
// The fast path didn't work, we'll fetch the file using URLLoader and write
// it to local storage.
base::File target_file(CreateTemporaryFile(instance));
GURL gurl(url);
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!plugin_instance) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
kInvalidNaClFileInfo));
}
const blink::WebDocument& document =
plugin_instance->GetContainer()->element().document();
scoped_ptr<blink::WebURLLoader> url_loader(
CreateWebURLLoader(document, gurl));
blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
ProgressEventRateLimiter* tracker = new ProgressEventRateLimiter(instance);
// FileDownloader deletes itself after invoking DownloadNexeCompletion.
FileDownloader* file_downloader = new FileDownloader(
url_loader.Pass(),
target_file.Pass(),
base::Bind(&DownloadFileCompletion, callback),
base::Bind(&ProgressEventRateLimiter::ReportProgress,
base::Owned(tracker), std::string(url)));
file_downloader->Load(url_request);
}
void LogTranslateTime(const char* histogram_name,
int64_t time_in_us) {
ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
FROM_HERE,
base::Bind(&HistogramTimeTranslation,
std::string(histogram_name),
time_in_us / 1000));
}
void LogBytesCompiledVsDowloaded(PP_Bool use_subzero,
int64_t pexe_bytes_compiled,
int64_t pexe_bytes_downloaded) {
HistogramRatio("NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded",
pexe_bytes_compiled, pexe_bytes_downloaded);
HistogramRatio(
use_subzero
? "NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded.Subzero"
: "NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded.LLC",
pexe_bytes_compiled, pexe_bytes_downloaded);
}
void SetPNaClStartTime(PP_Instance instance) {
NexeLoadManager* load_manager = GetNexeLoadManager(instance);
if (load_manager)
load_manager->set_pnacl_start_time(base::Time::Now());
}
// PexeDownloader is responsible for deleting itself when the download
// finishes.
class PexeDownloader : public blink::WebURLLoaderClient {
public:
PexeDownloader(PP_Instance instance,
scoped_ptr<blink::WebURLLoader> url_loader,
const std::string& pexe_url,
int32_t pexe_opt_level,
bool use_subzero,
const PPP_PexeStreamHandler* stream_handler,
void* stream_handler_user_data)
: instance_(instance),
url_loader_(url_loader.Pass()),
pexe_url_(pexe_url),
pexe_opt_level_(pexe_opt_level),
use_subzero_(use_subzero),
stream_handler_(stream_handler),
stream_handler_user_data_(stream_handler_user_data),
success_(false),
expected_content_length_(-1),
weak_factory_(this) {}
void Load(const blink::WebURLRequest& request) {
url_loader_->loadAsynchronously(request, this);
}
private:
void didReceiveResponse(blink::WebURLLoader* loader,
const blink::WebURLResponse& response) override {
success_ = (response.httpStatusCode() == 200);
if (!success_)
return;
expected_content_length_ = response.expectedContentLength();
// Defer loading after receiving headers. This is because we may already
// have a cached translated nexe, so check for that now.
url_loader_->setDefersLoading(true);
std::string etag = response.httpHeaderField("etag").utf8();
std::string last_modified =
response.httpHeaderField("last-modified").utf8();
base::Time last_modified_time;
base::Time::FromString(last_modified.c_str(), &last_modified_time);
bool has_no_store_header = false;
std::string cache_control =
response.httpHeaderField("cache-control").utf8();
for (const std::string& cur : base::SplitString(
cache_control, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
if (base::ToLowerASCII(cur) == "no-store")
has_no_store_header = true;
}
GetNexeFd(
instance_, pexe_url_, pexe_opt_level_, last_modified_time, etag,
has_no_store_header, use_subzero_,
base::Bind(&PexeDownloader::didGetNexeFd, weak_factory_.GetWeakPtr()));
}
void didGetNexeFd(int32_t pp_error,
bool cache_hit,
PP_FileHandle file_handle) {
if (!content::PepperPluginInstance::Get(instance_)) {
delete this;
return;
}
HistogramEnumerate("NaCl.Perf.PNaClCache.IsHit", cache_hit, 2);
HistogramEnumerate(use_subzero_ ? "NaCl.Perf.PNaClCache.IsHit.Subzero"
: "NaCl.Perf.PNaClCache.IsHit.LLC",
cache_hit, 2);
if (cache_hit) {
stream_handler_->DidCacheHit(stream_handler_user_data_, file_handle);
// We delete the PexeDownloader at this point since we successfully got a
// cached, translated nexe.
delete this;
return;
}
stream_handler_->DidCacheMiss(stream_handler_user_data_,
expected_content_length_,
file_handle);
// No translated nexe was found in the cache, so we should download the
// file to start streaming it.
url_loader_->setDefersLoading(false);
}
void didReceiveData(blink::WebURLLoader* loader,
const char* data,
int data_length,
int encoded_data_length) override {
if (content::PepperPluginInstance::Get(instance_)) {
// Stream the data we received to the stream callback.
stream_handler_->DidStreamData(stream_handler_user_data_,
data,
data_length);
}
}
void didFinishLoading(blink::WebURLLoader* loader,
double finish_time,
int64_t total_encoded_data_length) override {
int32_t result = success_ ? PP_OK : PP_ERROR_FAILED;
if (content::PepperPluginInstance::Get(instance_))
stream_handler_->DidFinishStream(stream_handler_user_data_, result);
delete this;
}
void didFail(blink::WebURLLoader* loader,
const blink::WebURLError& error) override {
if (content::PepperPluginInstance::Get(instance_))
stream_handler_->DidFinishStream(stream_handler_user_data_,
PP_ERROR_FAILED);
delete this;
}
PP_Instance instance_;
scoped_ptr<blink::WebURLLoader> url_loader_;
std::string pexe_url_;
int32_t pexe_opt_level_;
bool use_subzero_;
const PPP_PexeStreamHandler* stream_handler_;
void* stream_handler_user_data_;
bool success_;
int64_t expected_content_length_;
base::WeakPtrFactory<PexeDownloader> weak_factory_;
};
void StreamPexe(PP_Instance instance,
const char* pexe_url,
int32_t opt_level,
PP_Bool use_subzero,
const PPP_PexeStreamHandler* handler,
void* handler_user_data) {
content::PepperPluginInstance* plugin_instance =
content::PepperPluginInstance::Get(instance);
if (!plugin_instance) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(handler->DidFinishStream, handler_user_data,
static_cast<int32_t>(PP_ERROR_FAILED)));
return;
}
GURL gurl(pexe_url);
const blink::WebDocument& document =
plugin_instance->GetContainer()->element().document();
scoped_ptr<blink::WebURLLoader> url_loader(
CreateWebURLLoader(document, gurl));
PexeDownloader* downloader =
new PexeDownloader(instance, url_loader.Pass(), pexe_url, opt_level,
PP_ToBool(use_subzero), handler, handler_user_data);
blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
// Mark the request as requesting a PNaCl bitcode file,
// so that component updater can detect this user action.
url_request.addHTTPHeaderField(
blink::WebString::fromUTF8("Accept"),
blink::WebString::fromUTF8("application/x-pnacl, */*"));
url_request.setRequestContext(blink::WebURLRequest::RequestContextObject);
downloader->Load(url_request);
}
const PPB_NaCl_Private nacl_interface = {
&LaunchSelLdr,
&UrandomFD,
&BrokerDuplicateHandle,
&GetReadExecPnaclFd,
&CreateTemporaryFile,
&GetNumberOfProcessors,
&ReportTranslationFinished,
&DispatchEvent,
&ReportLoadError,
&InstanceCreated,
&InstanceDestroyed,
&GetSandboxArch,
&Vlog,
&InitializePlugin,
&RequestNaClManifest,
&GetManifestBaseURL,
&ProcessNaClManifest,
&ManifestGetProgramURL,
&GetPNaClResourceInfo,
&GetCpuFeatureAttrs,
&DownloadNexe,
&LogTranslateTime,
&LogBytesCompiledVsDowloaded,
&SetPNaClStartTime,
&StreamPexe
};
} // namespace
const PPB_NaCl_Private* GetNaClPrivateInterface() {
return &nacl_interface;
}
} // namespace nacl
| Chilledheart/chromium | components/nacl/renderer/ppb_nacl_private_impl.cc | C++ | bsd-3-clause | 64,120 |
/*
* Copyright (c), Microsoft Open Technologies, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "win32_types.h"
#include "Win32_FDAPI.h"
#include <Windows.h>
#include <WinNT.h>
#include <errno.h>
#include <stdio.h>
#include <wchar.h>
#include <Psapi.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <assert.h>
#define QFORK_MAIN_IMPL
#include "Win32_QFork.h"
#include "Win32_QFork_impl.h"
#include "Win32_dlmalloc.h"
#include "Win32_SmartHandle.h"
#include "Win32_Service.h"
#include "Win32_CommandLine.h"
#include "Win32_RedisLog.h"
#include "Win32_StackTrace.h"
#include "Win32_ThreadControl.h"
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <exception>
#include <algorithm>
#include <memory>
using namespace std;
#ifndef PAGE_REVERT_TO_FILE_MAP
#define PAGE_REVERT_TO_FILE_MAP 0x80000000 // From Win8.1 SDK
#endif
const int64_t cSentinelHeapSize = 30 * 1024 * 1024;
extern "C" int checkForSentinelMode(int argc, char **argv);
extern "C" void InitTimeFunctions();
extern "C"
{
void*(*g_malloc)(size_t) = nullptr;
void*(*g_calloc)(size_t, size_t) = nullptr;
void*(*g_realloc)(void*, size_t) = nullptr;
void(*g_free)(void*) = nullptr;
size_t(*g_msize)(void*) = nullptr;
// forward def from util.h.
PORT_LONGLONG memtoll(const char *p, int *err);
}
//#define DEBUG_WITH_PROCMON
#ifdef DEBUG_WITH_PROCMON
#define FILE_DEVICE_PROCMON_LOG 0x00009535
#define IOCTL_EXTERNAL_LOG_DEBUGOUT (ULONG) CTL_CODE( FILE_DEVICE_PROCMON_LOG, 0x81, METHOD_BUFFERED, FILE_WRITE_ACCESS )
HANDLE hProcMonDevice = INVALID_HANDLE_VALUE;
BOOL WriteToProcmon (wstring message)
{
if (hProcMonDevice != INVALID_HANDLE_VALUE) {
DWORD nb = 0;
return DeviceIoControl(
hProcMonDevice,
IOCTL_EXTERNAL_LOG_DEBUGOUT,
(LPVOID)(message.c_str()),
(DWORD)(message.length() * sizeof(wchar_t)),
NULL,
0,
&nb,
NULL);
} else {
return FALSE;
}
}
#endif
/*
Redis is an in memory DB. We need to share the redis database with a quasi-forked process so that we can do the RDB and AOF saves
without halting the main redis process, or crashing due to code that was never designed to be thread safe. Essentially we need to
replicate the COW behavior of fork() on Windows, but we don't actually need a complete fork() implementation. A complete fork()
implementation would require subsystem level support to make happen. The following is required to make this quasi-fork scheme work:
DLMalloc (http://g.oswego.edu/dl/html/malloc.html):
- replaces malloc/realloc/free, either by manual patching of the zmalloc code in Redis or by patching the CRT routines at link time
- partitions space into segments that it allocates from (currently configured as 64MB chunks)
- we map/unmap these chunks as requested into a memory map (unmapping allows the system to decide how to reduce the physical memory
pressure on system)
DLMallocMemoryMap:
- An uncomitted memory map whose size is the total physical memory on the system less some memory for the rest of the system so that
we avoid excessive swapping.
- This is reserved high in VM space so that it can be mapped at a specific address in the child qforked process (ASLR must be
disabled for these processes)
- This must be mapped in exactly the same virtual memory space in both forker and forkee.
QForkConrolMemoryMap:
- contains a map of the allocated segments in the DLMallocMemoryMap
- contains handles for inter-process synchronization
- contains pointers to some of the global data in the parent process if mapped into DLMallocMemoryMap, and a copy of any other
required global data
QFork process:
- a copy of the parent process with a command line specifying QFork behavior
- when a COW operation is requested via an event signal
- opens the DLMAllocMemoryMap with PAGE_WRITECOPY
- reserve space for DLMAllocMemoryMap at the memory location specified in ControlMemoryMap
- locks the DLMalloc segments as specified in QForkConrolMemoryMap
- maps global data from the QForkConrolMEmoryMap into this process
- executes the requested operation
- unmaps all the mm views (discarding any writes)
- signals the parent when the operation is complete
How the parent invokes the QFork process:
- protects mapped memory segments with VirtualProtect using PAGE_WRITECOPY (both the allocated portions of DLMAllocMemoryMap and
the QForkConrolMemoryMap)
- QForked process is signaled to process command
- Parent waits (asynchronously) until QForked process signals that operation is complete, then as an atomic operation:
- signals and waits for the forked process to terminate
- resotres protection status on mapped blocks
- determines which pages have been modified and copies these to a buffer
- unmaps the view of the heap (discarding COW changes form the view)
- remaps the view
- copies the changes back into the view
*/
#ifndef LODWORD
#define LODWORD(_qw) ((DWORD)(_qw))
#endif
#ifndef HIDWORD
#define HIDWORD(_qw) ((DWORD)(((_qw) >> (sizeof(DWORD)*8)) & DWORD(~0)))
#endif
const SIZE_T cAllocationGranularity = 1 << 18; // 256KB per heap block (matches large block allocation threshold of dlmalloc)
const int cMaxBlocks = 1 << 24; // 256KB * 16M heap blocks = 4TB. 4TB is the largest memory config Windows supports at present.
const char* cMapFileBaseName = "RedisQFork";
const int cDeadForkWait = 30000;
size_t pageSize = 0;
#ifndef _WIN64
size_t cDefaultmaxHeap32Bit = pow(2, 29);
#endif
enum class BlockState : std::uint8_t {bsINVALID = 0, bsUNMAPPED = 1, bsMAPPED = 2};
struct QForkControl {
HANDLE heapMemoryMapFile;
HANDLE heapMemoryMap;
int availableBlocksInHeap; // number of blocks in blockMap (dynamically determined at run time)
SIZE_T heapBlockSize;
BlockState heapBlockMap[cMaxBlocks];
LPVOID heapStart;
OperationType typeOfOperation;
HANDLE operationComplete;
HANDLE operationFailed;
// global data pointers to be passed to the forked process
QForkBeginInfo globalData;
BYTE DLMallocGlobalState[1000];
size_t DLMallocGlobalStateSize;
};
QForkControl* g_pQForkControl;
HANDLE g_hQForkControlFileMap;
HANDLE g_hForkedProcess = 0;
DWORD g_systemAllocationGranularity;
int g_ChildExitCode = 0; // For child process
bool ReportSpecialSystemErrors(int error) {
switch (error)
{
case ERROR_COMMITMENT_LIMIT:
{
::redisLog(
REDIS_WARNING,
"\n"
"The Windows version of Redis allocates a memory mapped heap for sharing with\n"
"the forked process used for persistence operations. In order to share this\n"
"memory, Windows allocates from the system paging file a portion equal to the\n"
"size of the Redis heap. At this time there is insufficient contiguous free\n"
"space available in the system paging file for this operation (Windows error \n"
"0x5AF). To work around this you may either increase the size of the system\n"
"paging file, or decrease the size of the Redis heap with the --maxheap flag.\n"
"Sometimes a reboot will defragment the system paging file sufficiently for \n"
"this operation to complete successfully.\n"
"\n"
"Please see the documentation included with the binary distributions for more \n"
"details on the --maxheap flag.\n"
"\n"
"Redis can not continue. Exiting."
);
return true;
}
case ERROR_DISK_FULL:
{
::redisLog(
REDIS_WARNING,
"\n"
"The Windows version of Redis allocates a large memory mapped file for sharing\n"
"the heap with the forked process used in persistence operations. This file\n"
"will be created in the current working directory or the directory specified by\n"
"the 'heapdir' directive in the .conf file. Windows is reporting that there is \n"
"insufficient disk space available for this file (Windows error 0x70).\n"
"\n"
"You may fix this problem by either reducing the size of the Redis heap with\n"
"the --maxheap flag, or by moving the heap file to a local drive with sufficient\n"
"space."
"\n"
"Please see the documentation included with the binary distributions for more \n"
"details on the --maxheap and --heapdir flags.\n"
"\n"
"Redis can not continue. Exiting."
);
return true;
}
default:
return false;
}
}
BOOL QForkChildInit(HANDLE QForkConrolMemoryMapHandle, DWORD ParentProcessID) {
try {
SmartHandle shParent(
OpenProcess(SYNCHRONIZE | PROCESS_DUP_HANDLE, TRUE, ParentProcessID),
string("Could not open parent process"));
SmartHandle shMMFile(shParent, QForkConrolMemoryMapHandle);
SmartFileView<QForkControl> sfvParentQForkControl(
shMMFile,
FILE_MAP_COPY,
string("Could not map view of QForkControl in child. Is system swap file large enough?"));
g_pQForkControl = sfvParentQForkControl;
// duplicate handles and stuff into control structure (parent protected by PAGE_WRITECOPY)
SmartHandle dupHeapFileHandle(shParent, sfvParentQForkControl->heapMemoryMapFile);
g_pQForkControl->heapMemoryMapFile = dupHeapFileHandle;
SmartHandle dupOperationComplete(shParent, sfvParentQForkControl->operationComplete);
g_pQForkControl->operationComplete = dupOperationComplete;
SmartHandle dupOperationFailed(shParent, sfvParentQForkControl->operationFailed);
g_pQForkControl->operationFailed = dupOperationFailed;
// create section handle on MM file
SIZE_T mmSize = g_pQForkControl->availableBlocksInHeap * cAllocationGranularity;
SmartFileMapHandle sfmhMapFile(
g_pQForkControl->heapMemoryMapFile,
PAGE_WRITECOPY,
#ifdef _WIN64
HIDWORD(mmSize),
#else
0,
#endif
LODWORD(mmSize),
string("Could not open file mapping object in child"));
g_pQForkControl->heapMemoryMap = sfmhMapFile;
// The key to mapping a heap larger than physical memory is to not map it all at once.
SmartFileView<byte> sfvHeap(
g_pQForkControl->heapMemoryMap,
FILE_MAP_COPY,
0, 0,
cAllocationGranularity, // Only map a portion of the heap . Deal with the unmapped pages with a VEH.
g_pQForkControl->heapStart,
string("Could not map heap in forked process. Is system swap file large enough?"));
// setup DLMalloc global data
if( SetDLMallocGlobalState(g_pQForkControl->DLMallocGlobalStateSize, g_pQForkControl->DLMallocGlobalState) != 0) {
throw std::runtime_error("DLMalloc global state copy failed.");
}
// copy redis globals into fork process
SetupGlobals(g_pQForkControl->globalData.globalData, g_pQForkControl->globalData.globalDataSize, g_pQForkControl->globalData.dictHashSeed);
// execute requested operation
if (g_pQForkControl->typeOfOperation == OperationType::otRDB) {
g_ChildExitCode = do_rdbSave(g_pQForkControl->globalData.filename);
} else if (g_pQForkControl->typeOfOperation == OperationType::otAOF) {
g_ChildExitCode = do_aofSave(g_pQForkControl->globalData.filename);
} else if (g_pQForkControl->typeOfOperation == OperationType::otSocket) {
LPWSAPROTOCOL_INFO lpProtocolInfo = (LPWSAPROTOCOL_INFO) g_pQForkControl->globalData.protocolInfo;
int pipe_write_fd = fdapi_open_osfhandle((intptr_t)g_pQForkControl->globalData.pipe_write_handle, _O_APPEND);
for (int i = 0; i < g_pQForkControl->globalData.numfds; i++) {
g_pQForkControl->globalData.fds[i] = WSASocket(FROM_PROTOCOL_INFO,
FROM_PROTOCOL_INFO,
FROM_PROTOCOL_INFO,
&lpProtocolInfo[i],
0,
WSA_FLAG_OVERLAPPED);
}
g_ChildExitCode = do_socketSave(g_pQForkControl->globalData.fds,
g_pQForkControl->globalData.numfds,
g_pQForkControl->globalData.clientids,
pipe_write_fd);
} else {
throw runtime_error("unexpected operation type");
}
// let parent know we are done
SetEvent(g_pQForkControl->operationComplete);
g_pQForkControl = NULL;
return TRUE;
}
catch(std::system_error syserr) {
if (ReportSpecialSystemErrors(syserr.code().value()) == false) {
::redisLog(REDIS_WARNING, "QForkChildInit: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what());
}
}
catch(std::runtime_error runerr) {
::redisLog(REDIS_WARNING, "QForkChildInit: runtime error caught. message=%s\n", runerr.what());
}
if (g_pQForkControl != NULL) {
if (g_pQForkControl->operationFailed != NULL) {
SetEvent(g_pQForkControl->operationFailed);
}
g_pQForkControl = NULL;
}
return FALSE;
}
string GetLocalAppDataFolder() {
char localAppDataPath[_MAX_PATH];
HRESULT hr;
if (S_OK != (hr = SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, localAppDataPath))) {
throw std::system_error(hr, system_category(), "SHGetFolderPathA failed");
}
char redisAppDataPath[_MAX_PATH];
if (NULL == PathCombineA(redisAppDataPath, localAppDataPath, "Redis")) {
throw std::system_error(hr, system_category(), "PathCombineA failed");
}
if (PathIsDirectoryA(redisAppDataPath) == FALSE) {
if (CreateDirectoryA(redisAppDataPath, NULL) == FALSE) {
throw std::system_error(hr, system_category(), "CreateDirectoryA failed");
}
}
return redisAppDataPath;
}
string g_MMFDir;
string GetWorkingDirectory() {
if (g_MMFDir.length() == 0) {
string workingDir;
if (g_argMap.find(cHeapDir) != g_argMap.end()) {
workingDir = g_argMap[cHeapDir][0][0];
std::replace(workingDir.begin(), workingDir.end(), '/', '\\');
if (PathIsRelativeA(workingDir.c_str())) {
char cwd[MAX_PATH];
if (0 == ::GetCurrentDirectoryA(MAX_PATH, cwd)) {
throw std::system_error(GetLastError(), system_category(), "GetCurrentDirectoryA failed");
}
char fullPath[_MAX_PATH];
if (NULL == PathCombineA(fullPath, cwd, workingDir.c_str())) {
throw std::system_error(GetLastError(), system_category(), "PathCombineA failed");
}
workingDir = fullPath;
}
} else {
workingDir = GetLocalAppDataFolder();
}
if (workingDir.at(workingDir.length() - 1) != '\\') {
workingDir = workingDir.append("\\");
}
g_MMFDir = workingDir;
}
return g_MMFDir;
}
BOOL QForkParentInit(__int64 maxheapBytes) {
try {
// allocate file map for qfork control so it can be passed to the forked process
g_hQForkControlFileMap = CreateFileMappingW(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0, sizeof(QForkControl),
NULL);
if (g_hQForkControlFileMap == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"CreateFileMapping failed");
}
g_pQForkControl = (QForkControl*)MapViewOfFile(
g_hQForkControlFileMap,
FILE_MAP_ALL_ACCESS,
0, 0,
0);
if (g_pQForkControl == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"MapViewOfFile failed");
}
// This must be called only once per process! Calling it more times than that will not recreate existing
// section, and dlmalloc will ultimately fail with an access violation. Once is good.
if (dlmallopt(M_GRANULARITY, cAllocationGranularity) == 0) {
throw std::system_error(
GetLastError(),
system_category(),
"DLMalloc failed initializing allocation granularity.");
}
g_pQForkControl->heapBlockSize = cAllocationGranularity;
// ensure the number of blocks is a multiple of cAllocationGranularity
SIZE_T allocationBlocks = (SIZE_T)maxheapBytes / cAllocationGranularity;
allocationBlocks += ((maxheapBytes % cAllocationGranularity) != 0);
g_pQForkControl->availableBlocksInHeap = (int)allocationBlocks;
if (g_pQForkControl->availableBlocksInHeap <= 0) {
throw std::runtime_error(
"Invalid number of heap blocks.");
}
// FILE_FLAG_DELETE_ON_CLOSE will not clean up files in the case of a BSOD or power failure.
// Clean up anything we can to prevent excessive disk usage.
char heapMemoryMapWildCard[MAX_PATH];
WIN32_FIND_DATAA fd;
sprintf_s(
heapMemoryMapWildCard,
MAX_PATH,
"%s%s_*.dat",
GetWorkingDirectory().c_str(),
cMapFileBaseName);
HANDLE hFind = FindFirstFileA(heapMemoryMapWildCard, &fd);
while (hFind != INVALID_HANDLE_VALUE) {
// Failure likely means the file is in use by another redis instance.
DeleteFileA(fd.cFileName);
if (FALSE == FindNextFileA(hFind, &fd)) {
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
}
string workingDir = GetWorkingDirectory();
char heapMemoryMapPath[MAX_PATH];
sprintf_s(
heapMemoryMapPath,
MAX_PATH,
"%s%s_%d.dat",
workingDir.c_str(),
cMapFileBaseName,
GetCurrentProcessId());
g_pQForkControl->heapMemoryMapFile =
CreateFileA(
heapMemoryMapPath,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL| FILE_FLAG_DELETE_ON_CLOSE,
NULL );
if (g_pQForkControl->heapMemoryMapFile == INVALID_HANDLE_VALUE) {
throw std::system_error(
GetLastError(),
system_category(),
"CreateFileW failed.");
}
SIZE_T mmSize = g_pQForkControl->availableBlocksInHeap * cAllocationGranularity;
g_pQForkControl->heapMemoryMap =
CreateFileMappingW(
g_pQForkControl->heapMemoryMapFile,
NULL,
PAGE_READWRITE,
#ifdef _WIN64
HIDWORD(mmSize),
#else
0,
#endif
LODWORD(mmSize),
NULL);
if (g_pQForkControl->heapMemoryMap == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"CreateFileMapping failed.");
}
// Find a place in the virtual memory space where we can reserve space for our allocations that is likely
// to be available in the forked process. (If this ever fails in the forked process, we will have to launch
// the forked process and negotiate for a shared memory address here.)
LPVOID pHigh = VirtualAllocEx(
GetCurrentProcess(),
NULL,
mmSize,
MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN,
PAGE_READWRITE);
if (pHigh == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"VirtualAllocEx failed.");
}
if (VirtualFree(pHigh, 0, MEM_RELEASE) == FALSE) {
throw std::system_error(
GetLastError(),
system_category(),
"VirtualFree failed.");
}
g_pQForkControl->heapStart =
MapViewOfFileEx(
g_pQForkControl->heapMemoryMap,
FILE_MAP_ALL_ACCESS,
0,0,
0,
pHigh);
if (g_pQForkControl->heapStart == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"MapViewOfFileEx failed.");
}
for (int n = 0; n < cMaxBlocks; n++) {
g_pQForkControl->heapBlockMap[n] =
((n < g_pQForkControl->availableBlocksInHeap) ?
BlockState::bsUNMAPPED : BlockState::bsINVALID);
}
g_pQForkControl->typeOfOperation = OperationType::otINVALID;
g_pQForkControl->operationComplete = CreateEvent(NULL,TRUE,FALSE,NULL);
if (g_pQForkControl->operationComplete == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"CreateEvent failed.");
}
g_pQForkControl->operationFailed = CreateEvent(NULL,TRUE,FALSE,NULL);
if (g_pQForkControl->operationFailed == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"CreateEvent failed.");
}
return TRUE;
}
catch(std::system_error syserr) {
if (ReportSpecialSystemErrors(syserr.code().value()) == false) {
::redisLog(REDIS_WARNING, "QForkParentInit: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what());
}
}
catch(std::runtime_error runerr) {
::redisLog(REDIS_WARNING, "QForkParentInit: runtime error caught. message=%s\n", runerr.what());
}
catch(...) {
::redisLog(REDIS_WARNING, "QForkParentInit: other exception caught.\n");
}
return FALSE;
}
LONG CALLBACK VectoredHeapMapper(PEXCEPTION_POINTERS info) {
if (info->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
info->ExceptionRecord->NumberParameters == 2) {
intptr_t failingMemoryAddress = info->ExceptionRecord->ExceptionInformation[1];
intptr_t heapStart = (intptr_t)g_pQForkControl->heapStart;
intptr_t heapEnd = heapStart + ((SIZE_T)g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize);
if (failingMemoryAddress >= heapStart && failingMemoryAddress < heapEnd)
{
intptr_t startOfMapping = failingMemoryAddress - failingMemoryAddress % g_systemAllocationGranularity;
intptr_t mmfOffset = startOfMapping - heapStart;
size_t bytesToMap = min((size_t)g_systemAllocationGranularity, (size_t)(heapEnd - startOfMapping));
LPVOID pMapped = MapViewOfFileEx(
g_pQForkControl->heapMemoryMap,
FILE_MAP_COPY,
#ifdef _WIN64
HIDWORD(mmfOffset),
#else
0,
#endif
LODWORD(mmfOffset),
bytesToMap,
(LPVOID)startOfMapping);
if(pMapped != NULL)
{
return EXCEPTION_CONTINUE_EXECUTION;
}
else
{
DWORD err = GetLastError();
::redisLog(REDIS_WARNING, "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===");
::redisLog(REDIS_WARNING, "--- FATAL ERROR MAPPING VIEW OF MAP FILE");
::redisLog(REDIS_WARNING, "\t MapViewOfFileEx failed with error 0x%08X.", err);
::redisLog(REDIS_WARNING, "\t startOfMapping 0x%p", startOfMapping);
::redisLog(REDIS_WARNING, "\t heapStart 0x%p", heapStart);
::redisLog(REDIS_WARNING, "\t heapEnd 0x%p", heapEnd);
::redisLog(REDIS_WARNING, "\t failing access location 0x%p", failingMemoryAddress);
::redisLog(REDIS_WARNING, "\t offset into mmf to start mapping 0x%p", mmfOffset);
::redisLog(REDIS_WARNING, "\t start of new mapping 0x%p", startOfMapping);
::redisLog(REDIS_WARNING, "\t bytes to map 0x%p\n", bytesToMap);
if (err == 0x000005AF) {
::redisLog(REDIS_WARNING, "The system paging file is too small for this operation to complete.");
::redisLog(REDIS_WARNING, "See https://github.com/MSOpenTech/redis/wiki/Memory-Configuration");
::redisLog(REDIS_WARNING, "for more information on configuring the system paging file for Redis.");
}
::redisLog(REDIS_WARNING, "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n");
// Call exit to avoid executing the Unhandled Exceptiont Handler since we don't need a call stack
exit(1);
}
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
// QFork API
StartupStatus QForkStartup(int argc, char** argv) {
bool foundChildFlag = false;
int sentinelMode = checkForSentinelMode(argc, argv);
HANDLE QForkConrolMemoryMapHandle = NULL;
DWORD PPID = 0;
__int64 maxheapBytes = -1;
__int64 maxmemoryBytes = -1;
int memtollerr = 0;
SYSTEM_INFO si;
GetSystemInfo(&si);
g_systemAllocationGranularity = si.dwAllocationGranularity;
if (g_argMap.find(cQFork) != g_argMap.end()) {
// Child command line looks like: --QFork [QForkConrolMemoryMap handle] [parent process id]
foundChildFlag = true;
char* endPtr;
QForkConrolMemoryMapHandle = (HANDLE)strtoul(g_argMap[cQFork].at(0).at(0).c_str(),&endPtr,10);
char* end = NULL;
PPID = strtoul(g_argMap[cQFork].at(0).at(1).c_str(), &end, 10);
} else {
if (g_argMap.find(cMaxHeap) != g_argMap.end()) {
int mtollerr = 0;
maxheapBytes = memtoll(g_argMap[cMaxHeap].at(0).at(0).c_str(), &memtollerr);
}
if (g_argMap.find(cMaxMemory) != g_argMap.end()) {
int mtollerr = 0;
maxmemoryBytes = memtoll(g_argMap[cMaxMemory].at(0).at(0).c_str(), &memtollerr);
}
}
PERFORMANCE_INFORMATION perfinfo;
perfinfo.cb = sizeof(PERFORMANCE_INFORMATION);
if (FALSE == GetPerformanceInfo(&perfinfo, sizeof(PERFORMANCE_INFORMATION))) {
::redisLog(REDIS_WARNING, "GetPerformanceInfo failed.\n");
::redisLog(REDIS_WARNING, "Failing startup.\n");
return StartupStatus::ssFAILED;
}
pageSize = perfinfo.PageSize;
/*
Not specifying the maxmemory or maxheap flags will result in the default behavior of: new key generation not
bounded by heap usage, and the heap size equal to the size of physical memory.
Redis will respect the maxmemory flag by preventing new key creation when the number of bytes allocated in the heap
exceeds the level specified by the maxmemory flag. This does not account for heap fragmentation or memory usage by
the heap allocator. To allow for this extra space maxheapBytes is implicitly set to (1.5 * maxmemory [rounded up
to the nearest cAllocationGranularity boundary]). The maxheap flag may be specified along with the maxmemory flag to
increase the heap further than this.
If the maxmemory flag is not specified, but the maxheap flag is specified, the heap is sized according to this flag
(rounded up to the nearest cAllocationGranularity boundary). The heap may be configured larger than physical memory with
this flag. If maxmemory is sufficiently large enough, the heap will also be made larger than physical memory. This
has implications for the system swap file size requirement and disk usage as discussed below. Specifying a heap larger
than physical memory allows Redis to continue operating into virtual memory up to the limit of the heap size specified.
Since the heap is entirely contained in the memory mapped file we are creating to share with the forked process, the
size of the memory mapped file will be equal to the size of the heap. There must be sufficient disk space for this file.
For instance, launching Redis on a server machine with 512GB of RAM and no flags specified for either maxmemory or
maxheap will result in the allocation of a 512GB memory mapped file. Redis will fail to launch if there is not enough
space available on the disk where redis is being launched from for this file.
During forking the system swap file will be used for managing virtual memory sharing and the copy on write pages for both
forker and forkee. There must be sufficient swap space availability for this. The maximum size of this swap space commit
is roughly equal to (physical memory + (2 * size of the memory allocated in the redis heap)). For instance, if the heap is nearly
maxed out on an 8GB machine and the heap has been configured to be twice the size of physical memory, the swap file comittment
will be (physical + (2 * (2 * physical)) or (5 * physical). By default Windows will dynamically allocate a swap file that will
expand up to about (3.5 * physical). In this case the forked process will fail with ERROR_COMMITMENT_LIMIT (1455/0x5AF) error.
The fix for this is to ensure the system swap space is sufficiently large enough to handle this. The reason that the default
heap size is equal to physical memory is so that Redis will work on a freshly configured OS without requireing reconfiguring
either Redis or the machine (max comittment of (3 * physical)).
*/
int64_t maxMemoryPlusHalf = (3 * maxmemoryBytes) / 2;
if( maxmemoryBytes != -1 ) {
if (maxheapBytes < maxMemoryPlusHalf) {
maxheapBytes = maxMemoryPlusHalf;
}
}
if( maxheapBytes == -1 ) {
if (sentinelMode == 1) {
// Sentinel mode does not need a large heap. This conserves disk space and page file reservation requirements.
maxheapBytes = cSentinelHeapSize;
} else {
#ifdef _WIN64
maxheapBytes = perfinfo.PhysicalTotal * pageSize;
#else
maxheapBytes = cDefaultmaxHeap32Bit;
#endif
}
}
if (foundChildFlag) {
LPVOID exceptionHandler = AddVectoredExceptionHandler( 1, VectoredHeapMapper );
StartupStatus retVal = StartupStatus::ssFAILED;
try {
retVal = QForkChildInit(QForkConrolMemoryMapHandle, PPID) ? StartupStatus::ssCHILD_EXIT : StartupStatus::ssFAILED;
} catch (...) { }
RemoveVectoredExceptionHandler(exceptionHandler);
return retVal;
} else {
return QForkParentInit(maxheapBytes) ? StartupStatus::ssCONTINUE_AS_PARENT : StartupStatus::ssFAILED;
}
}
BOOL QForkShutdown() {
if(g_hForkedProcess != NULL) {
TerminateProcess(g_hForkedProcess, -1);
CloseHandle(g_hForkedProcess);
g_hForkedProcess = NULL;
}
if( g_pQForkControl != NULL )
{
if (g_pQForkControl->operationComplete != NULL) {
CloseHandle(g_pQForkControl->operationComplete);
g_pQForkControl->operationComplete = NULL;
}
if (g_pQForkControl->operationFailed != NULL) {
CloseHandle(g_pQForkControl->operationFailed);
g_pQForkControl->operationFailed = NULL;
}
if (g_pQForkControl->heapMemoryMap != NULL) {
CloseHandle(g_pQForkControl->heapMemoryMap);
g_pQForkControl->heapMemoryMap = NULL;
}
if (g_pQForkControl->heapMemoryMapFile != INVALID_HANDLE_VALUE) {
CloseHandle(g_pQForkControl->heapMemoryMapFile);
g_pQForkControl->heapMemoryMapFile = INVALID_HANDLE_VALUE;
}
if (g_pQForkControl->heapStart != NULL) {
UnmapViewOfFile(g_pQForkControl->heapStart);
g_pQForkControl->heapStart = NULL;
}
if(g_pQForkControl != NULL) {
UnmapViewOfFile(g_pQForkControl);
g_pQForkControl = NULL;
}
if (g_hQForkControlFileMap != NULL) {
CloseHandle(g_hQForkControlFileMap);
g_hQForkControlFileMap = NULL;
};
}
return TRUE;
}
void CopyForkOperationData(OperationType type, LPVOID globalData, int sizeOfGlobalData, uint32_t dictHashSeed) {
// copy operation data
g_pQForkControl->typeOfOperation = type;
if (sizeOfGlobalData > MAX_GLOBAL_DATA) {
throw std::runtime_error("Global state too large.");
}
memcpy(&(g_pQForkControl->globalData.globalData), globalData, sizeOfGlobalData);
g_pQForkControl->globalData.globalDataSize = sizeOfGlobalData;
g_pQForkControl->globalData.dictHashSeed = dictHashSeed;
GetDLMallocGlobalState(&g_pQForkControl->DLMallocGlobalStateSize, NULL);
if (g_pQForkControl->DLMallocGlobalStateSize > sizeof(g_pQForkControl->DLMallocGlobalState)) {
throw std::runtime_error("DLMalloc global state too large.");
}
if(GetDLMallocGlobalState(&g_pQForkControl->DLMallocGlobalStateSize, g_pQForkControl->DLMallocGlobalState) != 0) {
throw std::runtime_error("DLMalloc global state copy failed.");
}
// protect both the heap and the fork control map from propagating local changes
DWORD oldProtect = 0;
if (VirtualProtect(g_pQForkControl, sizeof(QForkControl), PAGE_WRITECOPY, &oldProtect) == FALSE) {
throw std::system_error(
GetLastError(),
system_category(),
"BeginForkOperation: VirtualProtect failed for the fork control map");
}
if (VirtualProtect(
g_pQForkControl->heapStart,
g_pQForkControl->availableBlocksInHeap * g_pQForkControl->heapBlockSize,
PAGE_WRITECOPY,
&oldProtect) == FALSE ) {
throw std::system_error(
GetLastError(),
system_category(),
"BeginForkOperation: VirtualProtect failed for the heap");
}
}
void CreateChildProcess(PROCESS_INFORMATION *pi, char* logfile, DWORD dwCreationFlags = 0) {
// ensure events are in the correst state
if (ResetEvent(g_pQForkControl->operationComplete) == FALSE ) {
throw std::system_error(
GetLastError(),
system_category(),
"BeginForkOperation: ResetEvent() failed.");
}
if (ResetEvent(g_pQForkControl->operationFailed) == FALSE ) {
throw std::system_error(
GetLastError(),
system_category(),
"BeginForkOperation: ResetEvent() failed.");
}
// Launch the "forked" process
char fileName[MAX_PATH];
if (0 == GetModuleFileNameA(NULL, fileName, MAX_PATH)) {
throw system_error(
GetLastError(),
system_category(),
"Failed to get module name.");
}
STARTUPINFOA si;
memset(&si,0, sizeof(STARTUPINFOA));
si.cb = sizeof(STARTUPINFOA);
char arguments[_MAX_PATH];
memset(arguments,0,_MAX_PATH);
sprintf_s(
arguments,
_MAX_PATH,
"\"%s\" --%s %llu %lu --%s \"%s\"",
fileName,
cQFork.c_str(),
(uint64_t)g_hQForkControlFileMap,
GetCurrentProcessId(),
cLogfile.c_str(),
(logfile != NULL && logfile[0] != '\0') ? logfile : "stdout");
if (FALSE == CreateProcessA(fileName, arguments, NULL, NULL, TRUE, dwCreationFlags, NULL, NULL, &si, pi)) {
throw system_error(
GetLastError(),
system_category(),
"Problem creating child process" );
}
g_hForkedProcess = pi->hProcess;
}
typedef void (*CHILD_PID_HOOK)(DWORD pid);
pid_t BeginForkOperation(OperationType type, LPVOID globalData, int sizeOfGlobalData, uint32_t dictHashSeed, char* logfile, CHILD_PID_HOOK pidHook = NULL) {
PROCESS_INFORMATION pi;
try {
pi.hProcess = INVALID_HANDLE_VALUE;
pi.dwProcessId = -1;
if (pidHook != NULL) {
CreateChildProcess(&pi, logfile, CREATE_SUSPENDED);
pidHook(pi.dwProcessId);
CopyForkOperationData(type, globalData, sizeOfGlobalData, dictHashSeed);
ResumeThread(pi.hThread);
} else {
CopyForkOperationData(type, globalData, sizeOfGlobalData, dictHashSeed);
CreateChildProcess(&pi, logfile, 0);
}
CloseHandle(pi.hThread);
return pi.dwProcessId;
}
catch(std::system_error syserr) {
::redisLog(REDIS_WARNING, "BeginForkOperation: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what());
}
catch(std::runtime_error runerr) {
::redisLog(REDIS_WARNING, "BeginForkOperation: runtime error caught. message=%s\n", runerr.what());
}
catch(...) {
::redisLog(REDIS_WARNING, "BeginForkOperation: other exception caught.\n");
}
if (pi.hProcess != INVALID_HANDLE_VALUE) {
TerminateProcess(pi.hProcess, 1);
}
return -1;
}
pid_t BeginForkOperation_Rdb(
char *filename,
LPVOID globalData,
int sizeOfGlobalData,
unsigned __int32 dictHashSeed,
char* logfile)
{
strcpy_s(g_pQForkControl->globalData.filename, filename);
return BeginForkOperation(otRDB, globalData, sizeOfGlobalData, dictHashSeed, logfile);
}
pid_t BeginForkOperation_Aof(
char *filename,
LPVOID globalData,
int sizeOfGlobalData,
unsigned __int32 dictHashSeed,
char* logfile)
{
strcpy_s(g_pQForkControl->globalData.filename, filename);
return BeginForkOperation(otAOF, globalData, sizeOfGlobalData, dictHashSeed, logfile);
}
void BeginForkOperation_Socket_PidHook(DWORD dwProcessId) {
WSAPROTOCOL_INFO* protocolInfo = (WSAPROTOCOL_INFO*)dlmalloc(sizeof(WSAPROTOCOL_INFO) * g_pQForkControl->globalData.numfds);
g_pQForkControl->globalData.protocolInfo = protocolInfo;
for(int i = 0; i < g_pQForkControl->globalData.numfds; i++) {
WSADuplicateSocket(g_pQForkControl->globalData.fds[i], dwProcessId, &protocolInfo[i]);
}
}
pid_t BeginForkOperation_Socket(
int *fds,
int numfds,
uint64_t *clientids,
int pipe_write_fd,
LPVOID globalData,
int sizeOfGlobalData,
unsigned __int32 dictHashSeed,
char* logfile)
{
g_pQForkControl->globalData.fds = fds;
g_pQForkControl->globalData.numfds = numfds;
g_pQForkControl->globalData.clientids = clientids;
HANDLE pipe_write_handle = (HANDLE)_get_osfhandle(pipe_write_fd);
// The handle is already inheritable so there is no need to duplicate it
g_pQForkControl->globalData.pipe_write_handle = (pipe_write_handle);
return BeginForkOperation(otSocket,
globalData,
sizeOfGlobalData,
dictHashSeed,
logfile,
BeginForkOperation_Socket_PidHook);
}
OperationStatus GetForkOperationStatus() {
if (WaitForSingleObject(g_pQForkControl->operationComplete, 0) == WAIT_OBJECT_0) {
return OperationStatus::osCOMPLETE;
}
if (WaitForSingleObject(g_pQForkControl->operationFailed, 0) == WAIT_OBJECT_0) {
return OperationStatus::osFAILED;
}
if (g_hForkedProcess) {
// Verify if the child process is still running
if (WaitForSingleObject(g_hForkedProcess, 0) == WAIT_OBJECT_0) {
// The child process is not running, close the handle and report the status
// setting the operationFailed event
CloseHandle(g_hForkedProcess);
g_hForkedProcess = 0;
if (g_pQForkControl->operationFailed != NULL) {
SetEvent(g_pQForkControl->operationFailed);
}
return OperationStatus::osFAILED;
} else {
return OperationStatus::osINPROGRESS;
}
}
return OperationStatus::osUNSTARTED;
}
BOOL AbortForkOperation()
{
try {
if( g_hForkedProcess != 0 )
{
if (TerminateProcess(g_hForkedProcess, 1) == FALSE) {
throw std::system_error(
GetLastError(),
system_category(),
"EndForkOperation: Killing forked process failed.");
}
CloseHandle(g_hForkedProcess);
g_hForkedProcess = 0;
}
return EndForkOperation(NULL);
}
catch(std::system_error syserr) {
::redisLog(REDIS_WARNING, "AbortForkOperation(): 0x%08x - %s\n", syserr.code().value(), syserr.what());
// If we can not properly restore fork state, then another fork operation is not possible.
exit(1);
}
catch( ... ) {
::redisLog(REDIS_WARNING, "Some other exception caught in EndForkOperation().\n");
exit(1);
}
return FALSE;
}
void RejoinCOWPages(HANDLE mmHandle, byte* mmStart, size_t mmSize) {
SmartFileView<byte> copyView(
mmHandle,
FILE_MAP_WRITE,
0,
0,
mmSize,
string("RejoinCOWPages: Could not map COW back-copy view."));
for (byte* mmAddress = mmStart; mmAddress < mmStart + mmSize; ) {
MEMORY_BASIC_INFORMATION memInfo;
if (!VirtualQuery(
mmAddress,
&memInfo,
sizeof(memInfo))) {
throw system_error(
GetLastError(),
system_category(),
"RejoinCOWPages: VirtualQuery failure");
}
byte* regionEnd = (byte*)memInfo.BaseAddress + memInfo.RegionSize;
if (memInfo.Protect != PAGE_WRITECOPY) {
byte* srcEnd = min(regionEnd, mmStart + mmSize);
memcpy(copyView + (mmAddress - mmStart), mmAddress, srcEnd - mmAddress);
}
mmAddress = regionEnd;
}
// If the COWs are not discarded, then there is no way of propagating changes into subsequent fork operations.
#if FALSE
// This doesn't work. Disabling for now.
if (IsWindowsVersionAtLeast(6, 2, 0)) {
// restores all page protections on the view and culls the COW pages.
DWORD oldProtect;
if (FALSE == VirtualProtect(mmStart, mmSize, PAGE_READWRITE | PAGE_REVERT_TO_FILE_MAP, &oldProtect)) {
throw std::system_error(GetLastError(), std::system_category(), "RejoinCOWPages: COW cull failed");
}
} else
#endif
{
// Prior to Win8 unmapping the view was the only way to discard the COW pages from the view. Unfortunately this forces
// the view to be completely flushed to disk, which is a bit inefficient.
if (UnmapViewOfFile(mmStart) == FALSE) {
throw std::system_error(
GetLastError(),
system_category(),
"RejoinCOWPages: UnmapViewOfFile failed.");
}
// There is a race condition here. Something could map into the virtual address space used by the heap at the moment
// we are discarding local changes. There is nothing to do but report the problem and exit. This problem does not
// exist with the code above in Win8+ as the view is never unmapped.
LPVOID remapped =
MapViewOfFileEx(
mmHandle,
FILE_MAP_ALL_ACCESS,
0, 0,
0,
mmStart);
if (remapped == NULL) {
throw std::system_error(
GetLastError(),
system_category(),
"RejoinCOWPages: MapViewOfFileEx failed.");
}
}
}
BOOL EndForkOperation(int * pExitCode) {
try {
if( g_hForkedProcess != 0 )
{
if (WaitForSingleObject(g_hForkedProcess, cDeadForkWait) == WAIT_TIMEOUT) {
if (TerminateProcess(g_hForkedProcess, 1) == FALSE) {
throw std::system_error(
GetLastError(),
system_category(),
"EndForkOperation: Killing forked process failed.");
}
}
if (pExitCode != NULL) {
GetExitCodeProcess(g_hForkedProcess, (DWORD*)pExitCode);
}
CloseHandle(g_hForkedProcess);
g_hForkedProcess = 0;
}
if (ResetEvent(g_pQForkControl->operationComplete) == FALSE ) {
throw std::system_error(
GetLastError(),
system_category(),
"EndForkOperation: ResetEvent() failed.");
}
if (ResetEvent(g_pQForkControl->operationFailed) == FALSE ) {
throw std::system_error(
GetLastError(),
system_category(),
"EndForkOperation: ResetEvent() failed.");
}
// move local changes back into memory mapped views for next fork operation
RejoinCOWPages(
g_pQForkControl->heapMemoryMap,
(byte*)g_pQForkControl->heapStart,
g_pQForkControl->availableBlocksInHeap * cAllocationGranularity);
RejoinCOWPages(
g_hQForkControlFileMap,
(byte*)g_pQForkControl,
sizeof(QForkControl));
return TRUE;
}
catch(std::system_error syserr) {
::redisLog(REDIS_WARNING, "EndForkOperation: 0x%08x - %s\n", syserr.code().value(), syserr.what());
// If we can not properly restore fork state, then another fork operation is not possible.
exit(1);
}
catch( ... ) {
::redisLog(REDIS_WARNING, "Some other exception caught in EndForkOperation().\n");
exit(1);
}
return FALSE;
}
int blocksMapped = 0;
int totalAllocCalls = 0;
int totalFreeCalls = 0;
LPVOID AllocHeapBlock(size_t size, BOOL allocateHigh) {
totalAllocCalls++;
LPVOID retPtr = (LPVOID)NULL;
if (size % g_pQForkControl->heapBlockSize != 0 ) {
errno = EINVAL;
return retPtr;
}
int contiguousBlocksToAllocate = (int)(size / g_pQForkControl->heapBlockSize);
if (contiguousBlocksToAllocate > g_pQForkControl->availableBlocksInHeap) {
errno = ENOMEM;
return retPtr;
}
size_t mapped = 0;
int startIndex = allocateHigh ? g_pQForkControl->availableBlocksInHeap - 1 : 0;
int endIndex = allocateHigh ?
contiguousBlocksToAllocate - 2 :
g_pQForkControl->availableBlocksInHeap - contiguousBlocksToAllocate + 1;
int direction = allocateHigh ? -1 : 1;
int blockIndex = 0;
int contiguousBlocksFound = 0;
for(blockIndex = startIndex;
blockIndex != endIndex;
blockIndex += direction) {
for (int n = 0; n < contiguousBlocksToAllocate; n++) {
assert((blockIndex + n * direction >= 0) &&
(blockIndex + n * direction < g_pQForkControl->availableBlocksInHeap));
if (g_pQForkControl->heapBlockMap[blockIndex + n * direction] == BlockState::bsUNMAPPED) {
contiguousBlocksFound++;
}
else {
contiguousBlocksFound = 0;
break;
}
}
if (contiguousBlocksFound == contiguousBlocksToAllocate) {
break;
}
}
if (contiguousBlocksFound == contiguousBlocksToAllocate) {
int allocationStart = blockIndex + (allocateHigh ? 1 - contiguousBlocksToAllocate : 0);
LPVOID blockStart =
reinterpret_cast<byte*>(g_pQForkControl->heapStart) +
(g_pQForkControl->heapBlockSize * allocationStart);
for(int n = 0; n < contiguousBlocksToAllocate; n++ ) {
g_pQForkControl->heapBlockMap[allocationStart+n] = BlockState::bsMAPPED;
blocksMapped++;
mapped += g_pQForkControl->heapBlockSize;
}
retPtr = blockStart;
}
else {
errno = ENOMEM;
}
return retPtr;
}
BOOL FreeHeapBlock(LPVOID block, size_t size)
{
totalFreeCalls++;
if (size == 0) {
return FALSE;
}
INT_PTR ptrDiff = reinterpret_cast<byte*>(block) - reinterpret_cast<byte*>(g_pQForkControl->heapStart);
if (ptrDiff < 0 || (ptrDiff % g_pQForkControl->heapBlockSize) != 0) {
return FALSE;
}
int blockIndex = (int)(ptrDiff / g_pQForkControl->heapBlockSize);
if (blockIndex >= g_pQForkControl->availableBlocksInHeap) {
return FALSE;
}
int contiguousBlocksToFree = (int)(size / g_pQForkControl->heapBlockSize);
if (VirtualUnlock(block, size) == FALSE) {
DWORD err = GetLastError();
if (err != ERROR_NOT_LOCKED) {
return FALSE;
}
};
for (int n = 0; n < contiguousBlocksToFree; n++ ) {
blocksMapped--;
g_pQForkControl->heapBlockMap[blockIndex + n] = BlockState::bsUNMAPPED;
}
return TRUE;
}
void SetupLogging() {
bool serviceRun = g_argMap.find(cServiceRun) != g_argMap.end();
string syslogEnabledValue = (g_argMap.find(cSyslogEnabled) != g_argMap.end() ? g_argMap[cSyslogEnabled].at(0).at(0) : cNo);
bool syslogEnabled = (syslogEnabledValue.compare(cYes) == 0) || serviceRun;
string syslogIdent = (g_argMap.find(cSyslogIdent) != g_argMap.end() ? g_argMap[cSyslogIdent].at(0).at(0) : cDefaultSyslogIdent);
string logFileName = (g_argMap.find(cLogfile) != g_argMap.end() ? g_argMap[cLogfile].at(0).at(0) : cDefaultLogfile);
setSyslogEnabled(syslogEnabled);
if (syslogEnabled) {
setSyslogIdent(syslogIdent.c_str());
} else {
setLogFile(logFileName.c_str());
}
}
extern "C"
{
BOOL IsPersistenceAvailable() {
if (g_argMap.find(cPersistenceAvailable) != g_argMap.end()) {
return (g_argMap[cPersistenceAvailable].at(0).at(0) != cNo);
} else {
return true;
}
}
// The external main() is redefined as redis_main() by Win32_QFork.h.
// The CRT will call this replacement main() before the previous main()
// is invoked so that the QFork allocator can be setup prior to anything
// Redis will allocate.
int main(int argc, char* argv[]) {
try {
InitTimeFunctions();
ParseCommandLineArguments(argc, argv);
SetupLogging();
StackTraceInit();
InitThreadControl();
} catch (system_error syserr) {
exit(-1);
} catch (runtime_error runerr) {
cout << runerr.what() << endl;
exit(-1);
} catch (invalid_argument &iaerr) {
cout << iaerr.what() << endl;
exit(-1);
} catch (exception othererr) {
cout << othererr.what() << endl;
exit(-1);
}
try {
#ifdef DEBUG_WITH_PROCMON
hProcMonDevice =
CreateFile(
L"\\\\.\\Global\\ProcmonDebugLogger",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
#endif
// service commands do not launch an instance of redis directly
if (HandleServiceCommands(argc, argv) == TRUE) {
return 0;
}
// Setup memory allocation scheme for persistence mode
if (IsPersistenceAvailable() == TRUE) {
g_malloc = dlmalloc;
g_calloc = dlcalloc;
g_realloc = dlrealloc;
g_free = dlfree;
g_msize = reinterpret_cast<size_t(*)(void*)>(dlmalloc_usable_size);
} else {
g_malloc = malloc;
g_calloc = calloc;
g_realloc = realloc;
g_free = free;
g_msize = _msize;
}
if (IsPersistenceAvailable() == TRUE) {
StartupStatus status = QForkStartup(argc, argv);
if (status == ssCONTINUE_AS_PARENT) {
int retval = redis_main(argc, argv);
QForkShutdown();
return retval;
} else if (status == ssCHILD_EXIT) {
// child is done - clean up and exit
QForkShutdown();
return g_ChildExitCode;
} else if (status == ssFAILED) {
// parent or child failed initialization
return 1;
} else {
// unexpected status return
return 2;
}
} else {
return redis_main(argc, argv);
}
} catch (std::system_error syserr) {
::redisLog(REDIS_WARNING, "main: system error caught. error code=0x%08x, message=%s\n", syserr.code().value(), syserr.what());
} catch (std::runtime_error runerr) {
::redisLog(REDIS_WARNING, "main: runtime error caught. message=%s\n", runerr.what());
} catch (...) {
::redisLog(REDIS_WARNING, "main: other exception caught.\n");
}
}
}
| hanmichael/redis | src/Win32_Interop/Win32_QFork.cpp | C++ | bsd-3-clause | 55,270 |
"""
Filtering and resampling data
=============================
Some artifacts are restricted to certain frequencies and can therefore
be fixed by filtering. An artifact that typically affects only some
frequencies is due to the power line.
Power-line noise is a noise created by the electrical network.
It is composed of sharp peaks at 50Hz (or 60Hz depending on your
geographical location). Some peaks may also be present at the harmonic
frequencies, i.e. the integer multiples of
the power-line frequency, e.g. 100Hz, 150Hz, ... (or 120Hz, 180Hz, ...).
This tutorial covers some basics of how to filter data in MNE-Python.
For more in-depth information about filter design in general and in
MNE-Python in particular, check out
:ref:`sphx_glr_auto_tutorials_plot_background_filtering.py`.
"""
import numpy as np
import mne
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_eog_proj.fif'
tmin, tmax = 0, 20 # use the first 20s of data
# Setup for reading the raw data (save memory by cropping the raw data
# before loading it)
raw = mne.io.read_raw_fif(raw_fname)
raw.crop(tmin, tmax).load_data()
raw.info['bads'] = ['MEG 2443', 'EEG 053'] # bads + 2 more
fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz
n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2
# Pick a subset of channels (here for speed reason)
selection = mne.read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
stim=False, exclude='bads', selection=selection)
# Let's first check out all channel types
raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False)
###############################################################################
# Removing power-line noise with notch filtering
# ----------------------------------------------
#
# Removing power-line noise can be done with a Notch filter, directly on the
# Raw object, specifying an array of frequency to be cut off:
raw.notch_filter(np.arange(60, 241, 60), picks=picks, filter_length='auto',
phase='zero')
raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False)
###############################################################################
# Removing power-line noise with low-pass filtering
# -------------------------------------------------
#
# If you're only interested in low frequencies, below the peaks of power-line
# noise you can simply low pass filter the data.
# low pass filtering below 50 Hz
raw.filter(None, 50., fir_design='firwin')
raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False)
###############################################################################
# High-pass filtering to remove slow drifts
# -----------------------------------------
#
# To remove slow drifts, you can high pass.
#
# .. warning:: In several applications such as event-related potential (ERP)
# and event-related field (ERF) analysis, high-pass filters with
# cutoff frequencies greater than 0.1 Hz are usually considered
# problematic since they significantly change the shape of the
# resulting averaged waveform (see examples in
# :ref:`tut_filtering_hp_problems`). In such applications, apply
# high-pass filters with caution.
raw.filter(1., None, fir_design='firwin')
raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False)
###############################################################################
# To do the low-pass and high-pass filtering in one step you can do
# a so-called *band-pass* filter by running the following:
# band-pass filtering in the range 1 Hz - 50 Hz
raw.filter(1, 50., fir_design='firwin')
###############################################################################
# Downsampling and decimation
# ---------------------------
#
# When performing experiments where timing is critical, a signal with a high
# sampling rate is desired. However, having a signal with a much higher
# sampling rate than necessary needlessly consumes memory and slows down
# computations operating on the data. To avoid that, you can downsample
# your time series. Since downsampling raw data reduces the timing precision
# of events, it is recommended only for use in procedures that do not require
# optimal precision, e.g. computing EOG or ECG projectors on long recordings.
#
# .. note:: A *downsampling* operation performs a low-pass (to prevent
# aliasing) followed by *decimation*, which selects every
# :math:`N^{th}` sample from the signal. See
# :func:`scipy.signal.resample` and
# :func:`scipy.signal.resample_poly` for examples.
#
# Data resampling can be done with *resample* methods.
raw.resample(100, npad="auto") # set sampling frequency to 100Hz
raw.plot_psd(area_mode='range', tmax=10.0, picks=picks)
###############################################################################
# To avoid this reduction in precision, the suggested pipeline for
# processing final data to be analyzed is:
#
# 1. low-pass the data with :meth:`mne.io.Raw.filter`.
# 2. Extract epochs with :class:`mne.Epochs`.
# 3. Decimate the Epochs object using :meth:`mne.Epochs.decimate` or the
# ``decim`` argument to the :class:`mne.Epochs` object.
#
# We also provide the convenience methods :meth:`mne.Epochs.resample` and
# :meth:`mne.Evoked.resample` to downsample or upsample data, but these are
# less optimal because they will introduce edge artifacts into every epoch,
# whereas filtering the raw data will only introduce edge artifacts only at
# the start and end of the recording.
| teonlamont/mne-python | tutorials/plot_artifacts_correction_filtering.py | Python | bsd-3-clause | 5,783 |
package com.example.test;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.rule.ActivityTestRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.Assert;
@RunWith(AndroidJUnit4.class)
public class MainActivities {
@Rule
public ActivityTestRule<MainActivity> activityRule =
new ActivityTestRule(MainActivity.class);
@Test
public void getActivity() {
Assert.assertNotNull(activityRule.getActivity());
Assert.assertTrue(activityRule.getActivity() instanceof MainActivity);
}
}
| adsinc/android-sdk-plugin | sbt-test/android-sdk-plugin/android-test-kit/src/androidTest/java/com/example/test/MainActivities.java | Java | bsd-3-clause | 602 |
using System;
namespace HttpServer
{
/// <summary>
/// An unhandled exception have been caught by the system.
/// </summary>
public class ExceptionEventArgs : EventArgs
{
private readonly Exception _exception;
/// <summary>
/// Initializes a new instance of the <see cref="ExceptionEventArgs"/> class.
/// </summary>
/// <param name="exception">Caught exception.</param>
public ExceptionEventArgs(Exception exception)
{
_exception = exception;
}
/// <summary>
/// caught exception
/// </summary>
public Exception Exception
{
get { return _exception; }
}
}
}
| kf6kjg/halcyon | ThirdParty/HttpServer/HttpServer/ExceptionEventArgs.cs | C# | bsd-3-clause | 721 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <filesystem>
// class path
// path(path const&)
#include "filesystem_include.h"
#include <type_traits>
#include <cassert>
#include "test_macros.h"
int main(int, char**) {
using namespace fs;
static_assert(std::is_copy_constructible<path>::value, "");
static_assert(!std::is_nothrow_copy_constructible<path>::value, "should not be noexcept");
const std::string s("foo");
const path p(s);
path p2(p);
assert(p.native() == s);
assert(p2.native() == s);
return 0;
}
| endlessm/chromium-browser | third_party/llvm/libcxx/test/std/input.output/filesystems/class.path/path.member/path.construct/copy.pass.cpp | C++ | bsd-3-clause | 890 |
module.exports.middleware = function(req, res, next) {
req.rootUrl = function() {
var port = req.app.settings.port;
res.locals.requested_url = req.protocol + '://' + req.hostname + (port == 80 || port == 443 ? '' : ':' + port);
return req.protocol + "://" + req.get('host');
};
req.fullPath = function() {
return req.rootUrl() + req.path;
};
return next();
};
| andrewvy/slack-pongbot | lib/url.js | JavaScript | isc | 387 |
// add_test.js
/* globals add */
describe('Addition', function () {
it('should add numbers', function () {
expect(add(2, 4)).toBe(6)
expect(add(2, 4)).not.toBe(2)
})
})
| dmitriz/baseline-utils | demo/min-karma-function_test.js | JavaScript | mit | 182 |
<?php
$container->loadFromExtension('security', array(
'firewalls' => array(
'main' => array(
'form_login' => array(
'login_path' => '/login',
),
'logout_on_user_change' => true,
),
),
'role_hierarchy' => array(
'FOO' => 'BAR',
'ADMIN' => 'USER',
),
));
| smoers/bird | vendor/symfony/symfony/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/merge_import.php | PHP | mit | 351 |
const common = require('../../../../lib/common');
const commands = require('../../../schema').commands;
const table = 'actions';
const message1 = `Adding table: ${table}`;
const message2 = `Dropping table: ${table}`;
module.exports.up = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (exists) {
common.logging.warn(message1);
return;
}
common.logging.info(message1);
return commands.createTable(table, connection);
});
};
module.exports.down = (options) => {
const connection = options.connection;
return connection.schema.hasTable(table)
.then(function (exists) {
if (!exists) {
common.logging.warn(message2);
return;
}
common.logging.info(message2);
return commands.deleteTable(table, connection);
});
};
| dingotiles/ghost-for-cloudfoundry | versions/3.3.0/core/server/data/migrations/versions/2.14/1-add-actions-table.js | JavaScript | mit | 998 |
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def table_specific(context, table_id):
"""Safely include a fragment specific to the given table, but handle no special info gracefully."""
try:
fragment_path = "table/specific/%s.html" % table_id
t = template.loader.get_template(fragment_path)
return t.render(context)
except template.TemplateDoesNotExist:
return ""
| uscensusbureau/censusreporter | censusreporter/apps/census/templatetags/tabletags.py | Python | mit | 462 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Regression using the DNNRegressor Estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import imports85 # pylint: disable=g-bad-import-order
STEPS = 5000
def main(argv):
"""Builds, trains, and evaluates the model."""
assert len(argv) == 1
(x_train, y_train), (x_test, y_test) = imports85.load_data()
# Build the training input_fn.
input_train = tf.estimator.inputs.pandas_input_fn(
x=x_train, y=y_train, num_epochs=None, shuffle=True)
# Build the validation input_fn.
input_test = tf.estimator.inputs.pandas_input_fn(
x=x_test, y=y_test, shuffle=True)
# The first way assigns a unique weight to each category. To do this you must
# specify the category's vocabulary (values outside this specification will
# receive a weight of zero). Here we specify the vocabulary using a list of
# options. The vocabulary can also be specified with a vocabulary file (using
# `categorical_column_with_vocabulary_file`). For features covering a
# range of positive integers use `categorical_column_with_identity`.
body_style_vocab = ["hardtop", "wagon", "sedan", "hatchback", "convertible"]
body_style = tf.feature_column.categorical_column_with_vocabulary_list(
key="body-style", vocabulary_list=body_style_vocab)
make = tf.feature_column.categorical_column_with_hash_bucket(
key="make", hash_bucket_size=50)
feature_columns = [
tf.feature_column.numeric_column(key="curb-weight"),
tf.feature_column.numeric_column(key="highway-mpg"),
# Since this is a DNN model, convert categorical columns from sparse
# to dense.
# Wrap them in an `indicator_column` to create a
# one-hot vector from the input.
tf.feature_column.indicator_column(body_style),
# Or use an `embedding_column` to create a trainable vector for each
# index.
tf.feature_column.embedding_column(make, dimension=3),
]
# Build a DNNRegressor, with 2x20-unit hidden layers, with the feature columns
# defined above as input.
model = tf.estimator.DNNRegressor(
hidden_units=[20, 20], feature_columns=feature_columns)
# Train the model.
model.train(input_fn=input_train, steps=STEPS)
# Evaluate how the model performs on data it has not yet seen.
eval_result = model.evaluate(input_fn=input_test)
# The evaluation returns a Python dictionary. The "average_loss" key holds the
# Mean Squared Error (MSE).
average_loss = eval_result["average_loss"]
# Convert MSE to Root Mean Square Error (RMSE).
print("\n" + 80 * "*")
print("\nRMS error for the test set: ${:.0f}".format(average_loss**0.5))
print()
if __name__ == "__main__":
# The Estimator periodically generates "INFO" logs; make these logs visible.
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(main=main)
| xuleiboy1234/autoTitle | tensorflow/tensorflow/examples/get_started/regression/dnn_regression.py | Python | mit | 3,579 |
package org.spongycastle.bcpg;
import java.io.IOException;
import org.spongycastle.util.Arrays;
import org.spongycastle.util.Strings;
/**
* Basic type for a user ID packet.
*/
public class UserIDPacket
extends ContainedPacket
{
private byte[] idData;
public UserIDPacket(
BCPGInputStream in)
throws IOException
{
this.idData = in.readAll();
}
public UserIDPacket(
String id)
{
this.idData = Strings.toUTF8ByteArray(id);
}
public UserIDPacket(byte[] rawID)
{
this.idData = Arrays.clone(rawID);
}
public String getID()
{
return Strings.fromUTF8ByteArray(idData);
}
public byte[] getRawID()
{
return Arrays.clone(idData);
}
public boolean equals(Object o)
{
if (o instanceof UserIDPacket)
{
return Arrays.areEqual(this.idData, ((UserIDPacket)o).idData);
}
return false;
}
public int hashCode()
{
return Arrays.hashCode(this.idData);
}
public void encode(
BCPGOutputStream out)
throws IOException
{
out.writePacket(USER_ID, idData, true);
}
}
| open-keychain/spongycastle | pg/src/main/java/org/spongycastle/bcpg/UserIDPacket.java | Java | mit | 1,216 |
class CreateStorytimeMedia < ActiveRecord::Migration
def change
create_table :storytime_media do |t|
t.string :file
t.references :user, index: true
t.timestamps
end
end
end
| Oliviergg/storytime | db/migrate/20140511200849_create_storytime_media.rb | Ruby | mit | 204 |
#include "allocator.hpp"
#include <string.h>
#include <assert.h>
#include <stdlib.h>
// Address sanitizer
#if defined(__has_feature)
# define ADDRESS_SANITIZER __has_feature(address_sanitizer)
#else
# if defined(__SANITIZE_ADDRESS__)
# define ADDRESS_SANITIZER 1
# else
# define ADDRESS_SANITIZER 0
# endif
#endif
// Low-level allocation functions
#if defined(_WIN32) || defined(_WIN64)
# ifdef __MWERKS__
# pragma ANSI_strict off // disable ANSI strictness to include windows.h
# pragma cpp_extensions on // enable some extensions to include windows.h
# endif
# if defined(_MSC_VER)
# pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union
# endif
# ifdef _XBOX_VER
# define NOD3D
# include <xtl.h>
# else
# include <windows.h>
# endif
namespace
{
const size_t page_size = 4096;
size_t align_to_page(size_t value)
{
return (value + page_size - 1) & ~(page_size - 1);
}
void* allocate_page_aligned(size_t size)
{
// We can't use VirtualAlloc because it has 64Kb granularity so we run out of address space quickly
// We can't use malloc because of occasional problems with CW on CRT termination
static HANDLE heap = HeapCreate(0, 0, 0);
void* result = HeapAlloc(heap, 0, size + page_size);
return reinterpret_cast<void*>(align_to_page(reinterpret_cast<size_t>(result)));
}
void* allocate(size_t size)
{
size_t aligned_size = align_to_page(size);
void* ptr = allocate_page_aligned(aligned_size + page_size);
if (!ptr) return 0;
char* end = static_cast<char*>(ptr) + aligned_size;
DWORD old_flags;
VirtualProtect(end, page_size, PAGE_NOACCESS, &old_flags);
return end - size;
}
void deallocate(void* ptr, size_t size)
{
size_t aligned_size = align_to_page(size);
void* rptr = static_cast<char*>(ptr) + size - aligned_size;
DWORD old_flags;
VirtualProtect(rptr, aligned_size + page_size, PAGE_NOACCESS, &old_flags);
}
}
#elif (defined(__APPLE__) || defined(__linux__)) && (defined(__i386) || defined(__x86_64)) && !ADDRESS_SANITIZER
# include <sys/mman.h>
namespace
{
const size_t page_size = 4096;
size_t align_to_page(size_t value)
{
return (value + page_size - 1) & ~(page_size - 1);
}
void* allocate_page_aligned(size_t size)
{
void* result = malloc(size + page_size);
return reinterpret_cast<void*>(align_to_page(reinterpret_cast<size_t>(result)));
}
void* allocate(size_t size)
{
size_t aligned_size = align_to_page(size);
void* ptr = allocate_page_aligned(aligned_size + page_size);
if (!ptr) return 0;
char* end = static_cast<char*>(ptr) + aligned_size;
int res = mprotect(end, page_size, PROT_NONE);
assert(res == 0);
(void)!res;
return end - size;
}
void deallocate(void* ptr, size_t size)
{
size_t aligned_size = align_to_page(size);
void* rptr = static_cast<char*>(ptr) + size - aligned_size;
int res = mprotect(rptr, aligned_size + page_size, PROT_NONE);
assert(res == 0);
(void)!res;
}
}
#else
namespace
{
void* allocate(size_t size)
{
return malloc(size);
}
void deallocate(void* ptr, size_t size)
{
(void)size;
free(ptr);
}
}
#endif
// High-level allocation functions
const size_t memory_alignment = sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*);
void* memory_allocate(size_t size)
{
void* result = allocate(size + memory_alignment);
if (!result) return 0;
memcpy(result, &size, sizeof(size_t));
return static_cast<char*>(result) + memory_alignment;
}
size_t memory_size(void* ptr)
{
assert(ptr);
size_t result;
memcpy(&result, static_cast<char*>(ptr) - memory_alignment, sizeof(size_t));
return result;
}
void memory_deallocate(void* ptr)
{
if (!ptr) return;
size_t size = memory_size(ptr);
deallocate(static_cast<char*>(ptr) - memory_alignment, size + memory_alignment);
}
| zeux/pugixml | tests/allocator.cpp | C++ | mit | 3,808 |
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// 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.
#ifndef LUABIND_POLICY_HPP_INCLUDED
#define LUABIND_POLICY_HPP_INCLUDED
#include <luabind/config.hpp>
#include <typeinfo>
#include <string>
#include <memory>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_array.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/bind/arg.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/limits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/version.hpp>
#include <luabind/detail/class_registry.hpp>
#include <luabind/detail/primitives.hpp>
#include <luabind/detail/object_rep.hpp>
#include <luabind/detail/typetraits.hpp>
#include <luabind/detail/debug.hpp>
#include <luabind/detail/class_rep.hpp>
#include <luabind/detail/has_get_pointer.hpp>
#include <luabind/detail/make_instance.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <luabind/detail/decorate_type.hpp>
#include <luabind/weak_ref.hpp>
#include <luabind/back_reference_fwd.hpp>
#include <luabind/value_wrapper.hpp>
#include <luabind/from_stack.hpp>
#include <luabind/typeid.hpp>
namespace luabind
{
namespace detail
{
struct conversion_policy_base {};
}
template<int N, bool HasArg = true>
struct conversion_policy : detail::conversion_policy_base
{
BOOST_STATIC_CONSTANT(int, index = N);
BOOST_STATIC_CONSTANT(bool, has_arg = HasArg);
};
class index_map
{
public:
index_map(const int* m): m_map(m) {}
int operator[](int index) const
{
return m_map[index];
}
private:
const int* m_map;
};
// template<class T> class functor;
class weak_ref;
}
namespace luabind { namespace detail
{
template<class H, class T>
struct policy_cons
{
typedef H head;
typedef T tail;
template<class U>
policy_cons<U, policy_cons<H,T> > operator,(policy_cons<U,detail::null_type>)
{
return policy_cons<U, policy_cons<H,T> >();
}
template<class U>
policy_cons<U, policy_cons<H,T> > operator+(policy_cons<U,detail::null_type>)
{
return policy_cons<U, policy_cons<H,T> >();
}
template<class U>
policy_cons<U, policy_cons<H,T> > operator|(policy_cons<U,detail::null_type>)
{
return policy_cons<U, policy_cons<H,T> >();
}
};
struct indirection_layer
{
template<class T>
indirection_layer(const T&);
};
yes_t is_policy_cons_test(const null_type&);
template<class H, class T>
yes_t is_policy_cons_test(const policy_cons<H,T>&);
no_t is_policy_cons_test(...);
template<class T>
struct is_policy_cons
{
static const T& t;
BOOST_STATIC_CONSTANT(bool, value =
sizeof(is_policy_cons_test(t)) == sizeof(yes_t));
typedef boost::mpl::bool_<value> type;
};
template<bool>
struct is_string_literal
{
static no_t helper(indirection_layer);
static yes_t helper(const char*);
};
template<>
struct is_string_literal<false>
{
static no_t helper(indirection_layer);
};
namespace mpl = boost::mpl;
template <class T, class Clone>
void make_pointee_instance(lua_State* L, T& x, mpl::true_, Clone)
{
if (get_pointer(x))
{
make_instance(L, x);
}
else
{
lua_pushnil(L);
}
}
template <class T>
void make_pointee_instance(lua_State* L, T& x, mpl::false_, mpl::true_)
{
std::auto_ptr<T> ptr(new T(x));
make_instance(L, ptr);
}
template <class T>
void make_pointee_instance(lua_State* L, T& x, mpl::false_, mpl::false_)
{
make_instance(L, &x);
}
template <class T, class Clone>
void make_pointee_instance(lua_State* L, T& x, Clone)
{
make_pointee_instance(L, x, has_get_pointer<T>(), Clone());
}
// ********** pointer converter ***********
struct pointer_converter
{
typedef pointer_converter type;
typedef mpl::false_ is_native;
pointer_converter()
: result(0)
{}
void* result;
int const consumed_args(...)
{
return 1;
}
template<class T>
void apply(lua_State* L, T* ptr)
{
if (ptr == 0)
{
lua_pushnil(L);
return;
}
if (luabind::get_back_reference(L, ptr))
return;
make_instance(L, ptr);
}
template<class T>
T* apply(lua_State*, by_pointer<T>, int)
{
return static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_pointer<T>, int index)
{
if (lua_isnil(L, index)) return 0;
object_rep* obj = get_instance(L, index);
if (obj == 0) return -1;
if (obj->is_const())
return -1;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, by_pointer<T>, int)
{}
};
// ******* value converter *******
struct value_converter
{
typedef value_converter type;
typedef mpl::false_ is_native;
int const consumed_args(...)
{
return 1;
}
value_converter()
: result(0)
{}
void* result;
template<class T>
void apply(lua_State* L, T x)
{
if (luabind::get_back_reference(L, x))
return;
make_pointee_instance(L, x, mpl::true_());
}
template<class T>
T apply(lua_State*, by_value<T>, int)
{
return *static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_value<T>, int index)
{
// special case if we get nil in, try to match the holder type
if (lua_isnil(L, index))
return -1;
object_rep* obj = get_instance(L, index);
if (obj == 0) return -1;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
// ******* const pointer converter *******
struct const_pointer_converter
{
typedef const_pointer_converter type;
typedef mpl::false_ is_native;
int const consumed_args(...)
{
return 1;
}
const_pointer_converter()
: result(0)
{}
void* result;
template<class T>
void apply(lua_State* L, const T* ptr)
{
if (ptr == 0)
{
lua_pushnil(L);
return;
}
if (luabind::get_back_reference(L, ptr))
return;
make_instance(L, ptr);
}
template<class T>
T const* apply(lua_State*, by_const_pointer<T>, int)
{
return static_cast<T const*>(result);
}
template<class T>
int match(lua_State* L, by_const_pointer<T>, int index)
{
if (lua_isnil(L, index)) return 0;
object_rep* obj = get_instance(L, index);
if (obj == 0) return -1; // if the type is not one of our own registered types, classify it as a non-match
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
if (s.second >= 0 && !obj->is_const())
s.second += 10;
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
// ******* reference converter *******
struct ref_converter : pointer_converter
{
typedef ref_converter type;
typedef mpl::false_ is_native;
int const consumed_args(...)
{
return 1;
}
template<class T>
void apply(lua_State* L, T& ref)
{
if (luabind::get_back_reference(L, ref))
return;
make_pointee_instance(L, ref, mpl::false_());
}
template<class T>
T& apply(lua_State* L, by_reference<T>, int index)
{
assert(!lua_isnil(L, index));
return *pointer_converter::apply(L, by_pointer<T>(), index);
}
template<class T>
int match(lua_State* L, by_reference<T>, int index)
{
object_rep* obj = get_instance(L, index);
if (obj == 0) return -1;
if (obj->is_const())
return -1;
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
// ******** const reference converter *********
struct const_ref_converter
{
typedef const_ref_converter type;
typedef mpl::false_ is_native;
int const consumed_args(...)
{
return 1;
}
const_ref_converter()
: result(0)
{}
void* result;
template<class T>
void apply(lua_State* L, T const& ref)
{
if (luabind::get_back_reference(L, ref))
return;
make_pointee_instance(L, ref, mpl::false_());
}
template<class T>
T const& apply(lua_State*, by_const_reference<T>, int)
{
return *static_cast<T*>(result);
}
template<class T>
int match(lua_State* L, by_const_reference<T>, int index)
{
object_rep* obj = get_instance(L, index);
if (obj == 0) return -1; // if the type is not one of our own registered types, classify it as a non-match
std::pair<void*, int> s = obj->get_instance(registered_class<T>::id);
if (s.second >= 0 && !obj->is_const())
s.second += 10;
result = s.first;
return s.second;
}
template<class T>
void converter_postcall(lua_State*, by_const_reference<T>, int)
{
}
};
// ****** enum converter ********
struct enum_converter
{
typedef enum_converter type;
typedef mpl::true_ is_native;
int const consumed_args(...)
{
return 1;
}
void apply(lua_State* L, int val)
{
lua_pushnumber(L, val);
}
template<class T>
T apply(lua_State* L, by_value<T>, int index)
{
return static_cast<T>(static_cast<int>(lua_tonumber(L, index)));
}
template<class T>
static int match(lua_State* L, by_value<T>, int index)
{
if (lua_isnumber(L, index)) return 0; else return -1;
}
template<class T>
T apply(lua_State* L, by_const_reference<T>, int index)
{
return static_cast<T>(static_cast<int>(lua_tonumber(L, index)));
}
template<class T>
static int match(lua_State* L, by_const_reference<T>, int index)
{
if (lua_isnumber(L, index)) return 0; else return -1;
}
template<class T>
void converter_postcall(lua_State*, T, int) {}
};
template <class U>
struct value_wrapper_converter
{
typedef value_wrapper_converter<U> type;
typedef mpl::true_ is_native;
int const consumed_args(...)
{
return 1;
}
template<class T>
T apply(lua_State* L, by_const_reference<T>, int index)
{
return T(from_stack(L, index));
}
template<class T>
T apply(lua_State* L, by_value<T>, int index)
{
return apply(L, by_const_reference<T>(), index);
}
template<class T>
static int match(lua_State* L, by_const_reference<T>, int index)
{
return value_wrapper_traits<T>::check(L, index)
? (std::numeric_limits<int>::max)() / LUABIND_MAX_ARITY
: -1;
}
template<class T>
static int match(lua_State* L, by_value<T>, int index)
{
return match(L, by_const_reference<T>(), index);
}
void converter_postcall(...) {}
template<class T>
void apply(lua_State* interpreter, T const& value_wrapper)
{
value_wrapper_traits<T>::unwrap(interpreter, value_wrapper);
}
};
template <class T>
struct default_converter_generator
: mpl::eval_if<
is_value_wrapper_arg<T>
, value_wrapper_converter<T>
, mpl::eval_if<
boost::is_enum<typename boost::remove_reference<T>::type>
, enum_converter
, mpl::eval_if<
is_nonconst_pointer<T>
, pointer_converter
, mpl::eval_if<
is_const_pointer<T>
, const_pointer_converter
, mpl::eval_if<
is_nonconst_reference<T>
, ref_converter
, mpl::eval_if<
is_const_reference<T>
, const_ref_converter
, value_converter
>
>
>
>
>
>
{};
} // namespace detail
// *********** default_policy *****************
template <class T>
struct default_converter
: detail::default_converter_generator<T>::type
{};
template <class T, class Derived = default_converter<T> >
struct native_converter_base
{
typedef boost::mpl::true_ is_native;
int const consumed_args(...)
{
return 1;
}
template <class U>
void converter_postcall(lua_State*, U const&, int)
{}
int match(lua_State* L, detail::by_value<T>, int index)
{
return derived().compute_score(L, index);
}
int match(lua_State* L, detail::by_value<T const>, int index)
{
return derived().compute_score(L, index);
}
int match(lua_State* L, detail::by_const_reference<T>, int index)
{
return derived().compute_score(L, index);
}
T apply(lua_State* L, detail::by_value<T>, int index)
{
return derived().from(L, index);
}
T apply(lua_State* L, detail::by_value<T const>, int index)
{
return derived().from(L, index);
}
T apply(lua_State* L, detail::by_const_reference<T>, int index)
{
return derived().from(L, index);
}
void apply(lua_State* L, T const& value)
{
derived().to(L, value);
}
Derived& derived()
{
return static_cast<Derived&>(*this);
}
};
template <class T>
lua_Integer as_lua_integer(T v)
{
return static_cast<lua_Integer>(v);
}
template <class T>
lua_Number as_lua_number(T v)
{
return static_cast<lua_Number>(v);
}
# define LUABIND_NUMBER_CONVERTER(type, kind) \
template <> \
struct default_converter<type> \
: native_converter_base<type> \
{ \
int compute_score(lua_State* L, int index) \
{ \
return lua_type(L, index) == LUA_TNUMBER ? 0 : -1; \
}; \
\
type from(lua_State* L, int index) \
{ \
return static_cast<type>(BOOST_PP_CAT(lua_to, kind)(L, index)); \
} \
\
void to(lua_State* L, type const& value) \
{ \
BOOST_PP_CAT(lua_push, kind)(L, BOOST_PP_CAT(as_lua_, kind)(value)); \
} \
}; \
\
template <> \
struct default_converter<type const> \
: default_converter<type> \
{}; \
\
template <> \
struct default_converter<type const&> \
: default_converter<type> \
{};
LUABIND_NUMBER_CONVERTER(char, integer)
LUABIND_NUMBER_CONVERTER(signed char, integer)
LUABIND_NUMBER_CONVERTER(unsigned char, integer)
LUABIND_NUMBER_CONVERTER(signed short, integer)
LUABIND_NUMBER_CONVERTER(unsigned short, integer)
LUABIND_NUMBER_CONVERTER(signed int, integer)
LUABIND_NUMBER_CONVERTER(unsigned int, number)
LUABIND_NUMBER_CONVERTER(unsigned long, number)
LUABIND_NUMBER_CONVERTER(signed long, integer)
LUABIND_NUMBER_CONVERTER(float, number)
LUABIND_NUMBER_CONVERTER(double, number)
LUABIND_NUMBER_CONVERTER(long double, number)
# undef LUABIND_NUMBER_CONVERTER
template <>
struct default_converter<bool>
: native_converter_base<bool>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TBOOLEAN ? 0 : -1;
}
bool from(lua_State* L, int index)
{
return lua_toboolean(L, index) == 1;
}
void to(lua_State* L, bool value)
{
lua_pushboolean(L, value);
}
};
template <>
struct default_converter<bool const>
: default_converter<bool>
{};
template <>
struct default_converter<bool const&>
: default_converter<bool>
{};
template <>
struct default_converter<std::string>
: native_converter_base<std::string>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TSTRING ? 0 : -1;
}
std::string from(lua_State* L, int index)
{
return std::string(lua_tostring(L, index), lua_strlen(L, index));
}
void to(lua_State* L, std::string const& value)
{
lua_pushlstring(L, value.data(), value.size());
}
};
template <>
struct default_converter<std::string const>
: default_converter<std::string>
{};
template <>
struct default_converter<std::string const&>
: default_converter<std::string>
{};
template <>
struct default_converter<char const*>
{
typedef boost::mpl::true_ is_native;
int const consumed_args(...)
{
return 1;
}
template <class U>
static int match(lua_State* L, U, int index)
{
int type = lua_type(L, index);
return (type == LUA_TSTRING || type == LUA_TNIL) ? 0 : -1;
}
template <class U>
char const* apply(lua_State* L, U, int index)
{
return lua_tostring(L, index);
}
void apply(lua_State* L, char const* str)
{
lua_pushstring(L, str);
}
template <class U>
void converter_postcall(lua_State*, U, int)
{}
};
template <>
struct default_converter<const char* const>
: default_converter<char const*>
{};
template <>
struct default_converter<char*>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter<char const[N]>
: default_converter<char const*>
{};
template <std::size_t N>
struct default_converter<char[N]>
: default_converter<char const*>
{};
template <>
struct default_converter<lua_State*>
{
int const consumed_args(...)
{
return 0;
}
template <class U>
lua_State* apply(lua_State* L, U, int)
{
return L;
}
template <class U>
static int match(lua_State*, U, int)
{
return 0;
}
template <class U>
void converter_postcall(lua_State*, U, int) {}
};
namespace detail
{
struct default_policy : converter_policy_tag
{
BOOST_STATIC_CONSTANT(bool, has_arg = true);
template<class T>
static void precall(lua_State*, T, int) {}
template<class T, class Direction>
struct apply
{
typedef default_converter<T> type;
};
};
template<class T>
struct is_primitive
: default_converter<T>::is_native
{};
// ============== new policy system =================
template<int, class> struct find_conversion_policy;
template<bool IsConverter = false>
struct find_conversion_impl
{
template<int N, class Policies>
struct apply
{
typedef typename find_conversion_policy<N, typename Policies::tail>::type type;
};
};
template<>
struct find_conversion_impl<true>
{
template<int N, class Policies>
struct apply
{
typedef typename Policies::head head;
typedef typename Policies::tail tail;
BOOST_STATIC_CONSTANT(bool, found = (N == head::index));
typedef typename
boost::mpl::if_c<found
, head
, typename find_conversion_policy<N, tail>::type
>::type type;
};
};
template<class Policies>
struct find_conversion_impl2
{
template<int N>
struct apply
: find_conversion_impl<
boost::is_base_and_derived<conversion_policy_base, typename Policies::head>::value
>::template apply<N, Policies>
{
};
};
template<>
struct find_conversion_impl2<detail::null_type>
{
template<int N>
struct apply
{
typedef default_policy type;
};
};
template<int N, class Policies>
struct find_conversion_policy : find_conversion_impl2<Policies>::template apply<N>
{
};
template<class List>
struct policy_list_postcall
{
typedef typename List::head head;
typedef typename List::tail tail;
static void apply(lua_State* L, const index_map& i)
{
head::postcall(L, i);
policy_list_postcall<tail>::apply(L, i);
}
};
template<>
struct policy_list_postcall<detail::null_type>
{
static void apply(lua_State*, const index_map&) {}
};
// ==================================================
// ************** precall and postcall on policy_cons *********************
template<class List>
struct policy_precall
{
typedef typename List::head head;
typedef typename List::tail tail;
static void apply(lua_State* L, int index)
{
head::precall(L, index);
policy_precall<tail>::apply(L, index);
}
};
template<>
struct policy_precall<detail::null_type>
{
static void apply(lua_State*, int) {}
};
template<class List>
struct policy_postcall
{
typedef typename List::head head;
typedef typename List::tail tail;
static void apply(lua_State* L, int index)
{
head::postcall(L, index);
policy_postcall<tail>::apply(L, index);
}
};
template<>
struct policy_postcall<detail::null_type>
{
static void apply(lua_State*, int) {}
};
template <class Policies, class Sought>
struct has_policy
: mpl::if_<
boost::is_same<typename Policies::head, Sought>
, mpl::true_
, has_policy<typename Policies::tail, Sought>
>::type
{};
template <class Sought>
struct has_policy<null_type, Sought>
: mpl::false_
{};
}} // namespace luabind::detail
namespace luabind { namespace
{
#if defined(__GNUC__) && ( \
(BOOST_VERSION < 103500) \
|| (BOOST_VERSION < 103900 && (__GNUC__ * 100 + __GNUC_MINOR__ <= 400)) \
|| (__GNUC__ * 100 + __GNUC_MINOR__ < 400))
static inline boost::arg<0> return_value()
{
return boost::arg<0>();
}
static inline boost::arg<0> result()
{
return boost::arg<0>();
}
# define LUABIND_PLACEHOLDER_ARG(N) boost::arg<N>(*)()
#elif defined(BOOST_MSVC) || defined(__MWERKS__) \
|| (BOOST_VERSION >= 103900 && defined(__GNUC__) \
&& (__GNUC__ * 100 + __GNUC_MINOR__ == 400))
static boost::arg<0> return_value;
static boost::arg<0> result;
# define LUABIND_PLACEHOLDER_ARG(N) boost::arg<N>
#else
boost::arg<0> return_value;
boost::arg<0> result;
# define LUABIND_PLACEHOLDER_ARG(N) boost::arg<N>
#endif
}}
#endif // LUABIND_POLICY_HPP_INCLUDED
| luabind/luabind | luabind/detail/policy.hpp | C++ | mit | 23,365 |
<?php
namespace Bigcommerce\Unit\Api;
use Bigcommerce\Api\Filter;
class FilterTest extends \PHPUnit_Framework_TestCase
{
public function testToQueryBuildsAnAppropriateQueryString()
{
$filter = new Filter(array('a' => 1, 'b' => 'orange'));
$this->assertSame('?a=1&b=orange', $filter->toQuery());
}
public function testUpdateParameter()
{
$filter = new Filter(array('a' => 'b'));
$this->assertSame('?a=b', $filter->toQuery());
$filter->a = 'c';
$this->assertSame('?a=c', $filter->toQuery());
}
public function testStaticCreateMethodAssumesIntegerParameterIsPageNumber()
{
$filter = Filter::create(1);
$this->assertSame('?page=1', $filter->toQuery());
}
public function testStaticCreateMethodReturnsFilterObjectIfCalledWithFilterObject()
{
$original = new Filter(array('a' => 'b'));
$filter = Filter::create($original);
$this->assertSame($original, $filter);
}
public function testStaticCreateMethodReturnsCorrectlyConfiguredFilter()
{
$filter = Filter::create(array('a' => 'b'));
$this->assertSame('?a=b', $filter->toQuery());
}
}
| lord2800/bigcommerce-api-php | test/Unit/Api/FilterTest.php | PHP | mit | 1,199 |
<?php
/*
* This file is part of jwt-auth
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tymon\JWTAuth\Providers\Auth;
use Tymon\JWTAuth\Contracts\Providers\Auth;
use Cartalyst\Sentinel\Sentinel as SentinelAuth;
class Sentinel implements Auth
{
/**
* @var \Cartalyst\Sentinel\Sentinel
*/
protected $sentinel;
/**
* @param \Cartalyst\Sentinel\Sentinel $sentinel
*/
public function __construct(SentinelAuth $sentinel)
{
$this->sentinel = $sentinel;
}
/**
* Check a user's credentials
*
* @param array $credentials
*
* @return mixed
*/
public function byCredentials(array $credentials)
{
return $this->sentinel->stateless($credentials);
}
/**
* Authenticate a user via the id
*
* @param mixed $id
*
* @return boolean
*/
public function byId($id)
{
if ($user = $this->sentinel->getUserRepository()->findById($id)) {
$this->sentinel->setUser($user);
return true;
}
return false;
}
/**
* Get the currently authenticated user
*
* @return \Cartalyst\Sentinel\Users\UserInterface
*/
public function user()
{
return $this->sentinel->getUser();
}
}
| levieraf/jwt-auth | src/Providers/Auth/Sentinel.php | PHP | mit | 1,436 |
package org.spongycastle.asn1.cmp;
import java.util.Enumeration;
import org.spongycastle.asn1.ASN1EncodableVector;
import org.spongycastle.asn1.ASN1Object;
import org.spongycastle.asn1.ASN1Primitive;
import org.spongycastle.asn1.ASN1Sequence;
import org.spongycastle.asn1.ASN1TaggedObject;
import org.spongycastle.asn1.DERSequence;
import org.spongycastle.asn1.DERUTF8String;
public class PKIFreeText
extends ASN1Object
{
ASN1Sequence strings;
public static PKIFreeText getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
public static PKIFreeText getInstance(
Object obj)
{
if (obj instanceof PKIFreeText)
{
return (PKIFreeText)obj;
}
else if (obj != null)
{
return new PKIFreeText(ASN1Sequence.getInstance(obj));
}
return null;
}
private PKIFreeText(
ASN1Sequence seq)
{
Enumeration e = seq.getObjects();
while (e.hasMoreElements())
{
if (!(e.nextElement() instanceof DERUTF8String))
{
throw new IllegalArgumentException("attempt to insert non UTF8 STRING into PKIFreeText");
}
}
strings = seq;
}
public PKIFreeText(
DERUTF8String p)
{
strings = new DERSequence(p);
}
public PKIFreeText(
String p)
{
this(new DERUTF8String(p));
}
public PKIFreeText(
DERUTF8String[] strs)
{
strings = new DERSequence(strs);
}
public PKIFreeText(
String[] strs)
{
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i < strs.length; i++)
{
v.add(new DERUTF8String(strs[i]));
}
strings = new DERSequence(v);
}
/**
* Return the number of string elements present.
*
* @return number of elements present.
*/
public int size()
{
return strings.size();
}
/**
* Return the UTF8STRING at index i.
*
* @param i index of the string of interest
* @return the string at index i.
*/
public DERUTF8String getStringAt(
int i)
{
return (DERUTF8String)strings.getObjectAt(i);
}
/**
* <pre>
* PKIFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
* </pre>
*/
public ASN1Primitive toASN1Primitive()
{
return strings;
}
}
| Skywalker-11/spongycastle | core/src/main/java/org/spongycastle/asn1/cmp/PKIFreeText.java | Java | mit | 2,571 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
#include "platform/platformTimer.h"
#include "core/util/journal/process.h"
#include "console/engineAPI.h"
void TimeManager::_updateTime()
{
// Calculate & filter time delta since last event.
// How long since last update?
S32 delta = mTimer->getElapsedMs();
// Now - we want to try to sleep until the time threshold will hit.
S32 msTillThresh = (mBackground ? mBackgroundThreshold : mForegroundThreshold) - delta;
if(msTillThresh > 0)
{
// There's some time to go, so let's sleep.
Platform::sleep( msTillThresh );
}
// Ok - let's grab the new elapsed and send that out.
S32 finalDelta = mTimer->getElapsedMs();
mTimer->reset();
timeEvent.trigger(finalDelta);
}
TimeManager::TimeManager()
{
mBackground = false;
mTimer = PlatformTimer::create();
Process::notify(this, &TimeManager::_updateTime, PROCESS_TIME_ORDER);
mForegroundThreshold = 5;
mBackgroundThreshold = 10;
}
TimeManager::~TimeManager()
{
Process::remove(this, &TimeManager::_updateTime);
delete mTimer;
}
void TimeManager::setForegroundThreshold(const S32 msInterval)
{
AssertFatal(msInterval > 0, "TimeManager::setForegroundThreshold - should have at least 1 ms between time events to avoid math problems!");
mForegroundThreshold = msInterval;
}
const S32 TimeManager::getForegroundThreshold() const
{
return mForegroundThreshold;
}
void TimeManager::setBackgroundThreshold(const S32 msInterval)
{
AssertFatal(msInterval > 0, "TimeManager::setBackgroundThreshold - should have at least 1 ms between time events to avoid math problems!");
mBackgroundThreshold = msInterval;
}
const S32 TimeManager::getBackgroundThreshold() const
{
return mBackgroundThreshold;
}
//----------------------------------------------------------------------------------
PlatformTimer::PlatformTimer()
{
}
PlatformTimer::~PlatformTimer()
{
}
// Exposes PlatformTimer to script for when high precision is needed.
#include "core/util/tDictionary.h"
#include "console/console.h"
class ScriptTimerMan
{
public:
ScriptTimerMan();
~ScriptTimerMan();
S32 startTimer();
S32 stopTimer( S32 id );
protected:
static S32 smNextId;
typedef Map<S32,PlatformTimer*> TimerMap;
TimerMap mTimers;
};
S32 ScriptTimerMan::smNextId = 1;
ScriptTimerMan::ScriptTimerMan()
{
}
ScriptTimerMan::~ScriptTimerMan()
{
TimerMap::Iterator itr = mTimers.begin();
for ( ; itr != mTimers.end(); itr++ )
delete itr->value;
mTimers.clear();
}
S32 ScriptTimerMan::startTimer()
{
PlatformTimer *timer = PlatformTimer::create();
mTimers.insert( smNextId, timer );
smNextId++;
return ( smNextId - 1 );
}
S32 ScriptTimerMan::stopTimer( S32 id )
{
TimerMap::Iterator itr = mTimers.find( id );
if ( itr == mTimers.end() )
return -1;
PlatformTimer *timer = itr->value;
S32 elapsed = timer->getElapsedMs();
mTimers.erase( itr );
delete timer;
return elapsed;
}
ScriptTimerMan gScriptTimerMan;
DefineEngineFunction( startPrecisionTimer, S32, (), , "startPrecisionTimer() - Create and start a high resolution platform timer. Returns the timer id." )
{
return gScriptTimerMan.startTimer();
}
DefineEngineFunction( stopPrecisionTimer, S32, ( S32 id), , "stopPrecisionTimer( S32 id ) - Stop and destroy timer with the passed id. Returns the elapsed milliseconds." )
{
return gScriptTimerMan.stopTimer( id );
} | Bloodknight/Torque3D | Engine/source/platform/platformTimer.cpp | C++ | mit | 4,689 |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2014, 2018 Oracle and/or its affiliates.
// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_TEST_DISTANCE_BRUTE_FORCE_HPP
#define BOOST_GEOMETRY_TEST_DISTANCE_BRUTE_FORCE_HPP
#include <iterator>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/or.hpp>
#include <boost/range.hpp>
#include <boost/geometry/core/reverse_dispatch.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tag_cast.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/iterators/segment_iterator.hpp>
#include <boost/geometry/algorithms/distance.hpp>
#include <boost/geometry/algorithms/intersects.hpp>
#include <boost/geometry/algorithms/not_implemented.hpp>
namespace boost { namespace geometry
{
namespace unit_test
{
namespace detail { namespace distance_brute_force
{
struct distance_from_bg
{
template <typename G>
struct use_distance_from_bg
{
typedef typename boost::mpl::or_
<
boost::is_same<typename tag<G>::type, point_tag>,
typename boost::mpl::or_
<
boost::is_same<typename tag<G>::type, segment_tag>,
boost::is_same<typename tag<G>::type, box_tag>
>::type
>::type type;
};
template <typename Geometry1, typename Geometry2, typename Strategy>
static inline
typename distance_result<Geometry1, Geometry2, Strategy>::type
apply(Geometry1 const& geometry1,
Geometry2 const& geometry2,
Strategy const& strategy)
{
BOOST_MPL_ASSERT((typename use_distance_from_bg<Geometry1>::type));
BOOST_MPL_ASSERT((typename use_distance_from_bg<Geometry2>::type));
return geometry::distance(geometry1, geometry2, strategy);
}
};
template <typename Geometry1, typename Geometry2, typename Strategy>
inline
typename distance_result<Geometry1, Geometry2, Strategy>::type
bg_distance(Geometry1 const& geometry1,
Geometry2 const& geometry2,
Strategy const& strategy)
{
return distance_from_bg::apply(geometry1, geometry2, strategy);
}
template <typename Policy>
struct one_to_many
{
template <typename Geometry, typename Iterator, typename Strategy>
static inline typename distance_result
<
Geometry,
typename std::iterator_traits<Iterator>::value_type,
Strategy
>::type
apply(Geometry const& geometry, Iterator begin, Iterator end,
Strategy const& strategy)
{
typedef typename distance_result
<
Geometry,
typename std::iterator_traits<Iterator>::value_type,
Strategy
>::type distance_type;
bool first = true;
distance_type d_min(0);
for (Iterator it = begin; it != end; ++it, first = false)
{
distance_type d = Policy::apply(geometry, *it, strategy);
if ( first || d < d_min )
{
d_min = d;
}
}
return d_min;
}
};
}} // namespace detail::distance_brute_force
namespace dispatch
{
template
<
typename Geometry1,
typename Geometry2,
typename Strategy,
typename Tag1 = typename tag_cast
<
typename tag<Geometry1>::type,
segment_tag,
linear_tag
>::type,
typename Tag2 = typename tag_cast
<
typename tag<Geometry2>::type,
segment_tag,
linear_tag
>::type,
bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value
>
struct distance_brute_force
: not_implemented<Geometry1, Geometry2>
{};
template
<
typename Geometry1,
typename Geometry2,
typename Strategy,
typename Tag1,
typename Tag2
>
struct distance_brute_force<Geometry1, Geometry2, Strategy, Tag1, Tag2, true>
{
static inline typename distance_result<Geometry1, Geometry2, Strategy>::type
apply(Geometry1 const& geometry1,
Geometry2 const& geometry2,
Strategy const& strategy)
{
return distance_brute_force
<
Geometry2, Geometry1, Strategy
>::apply(geometry2, geometry1, strategy);
}
};
//===================================================================
template
<
typename Point1,
typename Point2,
typename Strategy
>
struct distance_brute_force
<
Point1, Point2, Strategy,
point_tag, point_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
template
<
typename Point,
typename Segment,
typename Strategy
>
struct distance_brute_force
<
Point, Segment, Strategy,
point_tag, segment_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
template
<
typename Point,
typename Linear,
typename Strategy
>
struct distance_brute_force
<
Point, Linear, Strategy,
point_tag, linear_tag, false
>
{
typedef typename distance_result
<
Point, Linear, Strategy
>::type distance_type;
static inline distance_type apply(Point const& point,
Linear const& linear,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
detail::distance_brute_force::distance_from_bg
>::apply(point,
geometry::segments_begin(linear),
geometry::segments_end(linear),
strategy);
}
};
template
<
typename Point,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
Point, Ring, Strategy,
point_tag, ring_tag, false
>
{
typedef typename distance_result
<
Point, Ring, Strategy
>::type distance_type;
static inline distance_type apply(Point const& point,
Ring const& ring,
Strategy const& strategy)
{
if (geometry::covered_by(point, ring))
{
return 0;
}
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Point,
typename std::iterator_traits
<
segment_iterator<Ring const>
>::value_type,
Strategy
>
>::apply(point,
geometry::segments_begin(ring),
geometry::segments_end(ring),
strategy);
}
};
//TODO do it more brute force (also in all polygon-geometry cases)
template
<
typename Point,
typename Polygon,
typename Strategy
>
struct distance_brute_force
<
Point, Polygon, Strategy,
point_tag, polygon_tag, false
>
{
typedef typename distance_result
<
Point, Polygon, Strategy
>::type distance_type;
static inline distance_type apply(Point const& point,
Polygon const& polygon,
Strategy const& strategy)
{
return geometry::distance(point, polygon, strategy);
}
};
template
<
typename Point,
typename Box,
typename Strategy
>
struct distance_brute_force
<
Point, Box, Strategy,
point_tag, box_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
template
<
typename Point,
typename MultiPoint,
typename Strategy
>
struct distance_brute_force
<
Point, MultiPoint, Strategy,
point_tag, multi_point_tag, false
>
{
typedef typename distance_result
<
Point, MultiPoint, Strategy
>::type distance_type;
static inline distance_type apply(Point const& p,
MultiPoint const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
detail::distance_brute_force::distance_from_bg
>::apply(p, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename Point,
typename MultiPolygon,
typename Strategy
>
struct distance_brute_force
<
Point, MultiPolygon, Strategy,
point_tag, multi_polygon_tag, false
>
{
typedef typename distance_result
<
Point, MultiPolygon, Strategy
>::type distance_type;
static inline distance_type apply(Point const& p,
MultiPolygon const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Point,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(p, boost::begin(mp), boost::end(mp), strategy);
}
};
//=======================================================================
template
<
typename Linear,
typename Segment,
typename Strategy
>
struct distance_brute_force
<
Linear, Segment, Strategy,
linear_tag, segment_tag, false
>
{
typedef typename distance_result
<
Linear, Segment, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
Segment const& segment,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
detail::distance_brute_force::distance_from_bg
>::apply(segment,
geometry::segments_begin(linear),
geometry::segments_end(linear),
strategy);
}
};
template
<
typename Linear1,
typename Linear2,
typename Strategy
>
struct distance_brute_force
<
Linear1, Linear2, Strategy,
linear_tag, linear_tag, false
>
{
typedef typename distance_result
<
Linear1, Linear2, Strategy
>::type distance_type;
static inline distance_type apply(Linear1 const& linear1,
Linear2 const& linear2,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Linear1,
typename std::iterator_traits
<
segment_iterator<Linear2 const>
>::value_type,
Strategy
>
>::apply(linear1,
geometry::segments_begin(linear2),
geometry::segments_end(linear2),
strategy);
}
};
template
<
typename Linear,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
Linear, Ring, Strategy,
linear_tag, ring_tag, false
>
{
typedef typename distance_result
<
Linear, Ring, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
Ring const& ring,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Linear,
typename std::iterator_traits
<
segment_iterator<Ring const>
>::value_type,
Strategy
>
>::apply(linear,
geometry::segments_begin(ring),
geometry::segments_end(ring),
strategy);
}
};
template
<
typename Linear,
typename Polygon,
typename Strategy
>
struct distance_brute_force
<
Linear, Polygon, Strategy,
linear_tag, polygon_tag, false
>
{
typedef typename distance_result
<
Linear, Polygon, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
Polygon const& polygon,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Polygon,
typename std::iterator_traits
<
segment_iterator<Linear const>
>::value_type,
Strategy
>
>::apply(polygon,
geometry::segments_begin(linear),
geometry::segments_end(linear),
strategy);
}
};
template
<
typename Linear,
typename Box,
typename Strategy
>
struct distance_brute_force
<
Linear, Box, Strategy,
linear_tag, box_tag, false
>
{
typedef typename distance_result
<
Linear, Box, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
Box const& box,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
detail::distance_brute_force::distance_from_bg
>::apply(box,
geometry::segments_begin(linear),
geometry::segments_end(linear),
strategy);
}
};
template
<
typename Linear,
typename MultiPoint,
typename Strategy
>
struct distance_brute_force
<
Linear, MultiPoint, Strategy,
linear_tag, multi_point_tag, false
>
{
typedef typename distance_result
<
Linear, MultiPoint, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
MultiPoint const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Linear,
typename boost::range_value<MultiPoint>::type,
Strategy
>
>::apply(linear, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename Linear,
typename MultiPolygon,
typename Strategy
>
struct distance_brute_force
<
Linear, MultiPolygon, Strategy,
linear_tag, multi_polygon_tag, false
>
{
typedef typename distance_result
<
Linear, MultiPolygon, Strategy
>::type distance_type;
static inline distance_type apply(Linear const& linear,
MultiPolygon const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Linear,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(linear, boost::begin(mp), boost::end(mp), strategy);
}
};
//=================================================================
template
<
typename Polygon,
typename Segment,
typename Strategy
>
struct distance_brute_force
<
Polygon, Segment, Strategy,
polygon_tag, segment_tag, false
>
{
typedef typename distance_result
<
Polygon, Segment, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& polygon,
Segment const& segment,
Strategy const& strategy)
{
return geometry::distance(segment, polygon, strategy);
}
};
template
<
typename Polygon,
typename Linear,
typename Strategy
>
struct distance_brute_force
<
Polygon, Linear, Strategy,
polygon_tag, linear_tag, false
>
{
typedef typename distance_result
<
Polygon, Linear, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& polygon,
Linear const& linear,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Polygon,
typename std::iterator_traits
<
segment_iterator<Linear const>
>::value_type,
Strategy
>
>::apply(polygon,
geometry::segments_begin(linear),
geometry::segments_end(linear),
strategy);
}
};
template
<
typename Polygon1,
typename Polygon2,
typename Strategy
>
struct distance_brute_force
<
Polygon1, Polygon2, Strategy,
polygon_tag, polygon_tag, false
>
{
typedef typename distance_result
<
Polygon1, Polygon2, Strategy
>::type distance_type;
static inline distance_type apply(Polygon1 const& polygon1,
Polygon2 const& polygon2,
Strategy const& strategy)
{
return geometry::distance(polygon1, polygon2, strategy);
}
};
template
<
typename Polygon,
typename MultiPoint,
typename Strategy
>
struct distance_brute_force
<
Polygon, MultiPoint, Strategy,
polygon_tag, multi_point_tag, false
>
{
typedef typename distance_result
<
Polygon, MultiPoint, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& polygon,
MultiPoint const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Polygon,
typename boost::range_value<MultiPoint>::type,
Strategy
>
>::apply(polygon, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename Polygon,
typename MultiPolygon,
typename Strategy
>
struct distance_brute_force
<
Polygon, MultiPolygon, Strategy,
polygon_tag, multi_polygon_tag, false
>
{
typedef typename distance_result
<
Polygon, MultiPolygon, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& poly,
MultiPolygon const& mp,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Polygon,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(poly, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename Polygon,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
Polygon, Ring, Strategy,
polygon_tag, ring_tag, false
>
{
typedef typename distance_result
<
Polygon, Ring, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& polygon,
Ring const& ring,
Strategy const& strategy)
{
return geometry::distance(ring, polygon, strategy);
}
};
template
<
typename Polygon,
typename Box,
typename Strategy
>
struct distance_brute_force
<
Polygon, Box, Strategy,
polygon_tag, box_tag, false
>
{
typedef typename distance_result
<
Polygon, Box, Strategy
>::type distance_type;
static inline distance_type apply(Polygon const& polygon,
Box const& box,
Strategy const& strategy)
{
return geometry::distance(box, polygon, strategy);
}
};
//========================================================================
template
<
typename MultiPoint1,
typename MultiPoint2,
typename Strategy
>
struct distance_brute_force
<
MultiPoint1, MultiPoint2, Strategy,
multi_point_tag, multi_point_tag, false
>
{
typedef typename distance_result
<
MultiPoint1, MultiPoint2, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint1 const& mp1,
MultiPoint2 const& mp2,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
MultiPoint1,
typename boost::range_value<MultiPoint2>::type,
Strategy
>
>::apply(mp1, boost::begin(mp2), boost::end(mp2), strategy);
}
};
template
<
typename MultiPoint,
typename Linear,
typename Strategy
>
struct distance_brute_force
<
MultiPoint, Linear, Strategy,
multi_point_tag, linear_tag, false
>
{
typedef typename distance_result
<
MultiPoint, Linear, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint const& mp,
Linear const& l,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
MultiPoint,
typename boost::range_value<Linear>::type,
Strategy
>
>::apply(mp, boost::begin(l), boost::end(l), strategy);
}
};
template
<
typename MultiPoint,
typename MultiPolygon,
typename Strategy
>
struct distance_brute_force
<
MultiPoint, MultiPolygon, Strategy,
multi_point_tag, multi_polygon_tag, false
>
{
typedef typename distance_result
<
MultiPoint, MultiPolygon, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint const& mp,
MultiPolygon const& mpl,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
MultiPoint,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(mp, boost::begin(mpl), boost::end(mpl), strategy);
}
};
template
<
typename MultiPoint,
typename Segment,
typename Strategy
>
struct distance_brute_force
<
MultiPoint, Segment, Strategy,
multi_point_tag, segment_tag, false
>
{
typedef typename distance_result
<
MultiPoint, Segment, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint const& mp,
Segment const& segment,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
detail::distance_brute_force::distance_from_bg
>::apply(segment, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename MultiPoint,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
MultiPoint, Ring, Strategy,
multi_point_tag, ring_tag, false
>
{
typedef typename distance_result
<
MultiPoint, Ring, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint const& mp,
Ring const& ring,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
MultiPoint,
typename std::iterator_traits
<
segment_iterator<Ring const>
>::value_type,
Strategy
>
>::apply(mp,
geometry::segments_begin(ring),
geometry::segments_end(ring),
strategy);
}
};
template
<
typename MultiPoint,
typename Box,
typename Strategy
>
struct distance_brute_force
<
MultiPoint, Box, Strategy,
multi_point_tag, box_tag, false
>
{
typedef typename distance_result
<
MultiPoint, Box, Strategy
>::type distance_type;
static inline distance_type apply(MultiPoint const& mp,
Box const& box,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Box,
typename boost::range_value<MultiPoint>::type,
Strategy
>
>::apply(box, boost::begin(mp), boost::end(mp), strategy);
}
};
//=====================================================================
template
<
typename MultiPolygon1,
typename MultiPolygon2,
typename Strategy
>
struct distance_brute_force
<
MultiPolygon1, MultiPolygon2, Strategy,
multi_polygon_tag, multi_polygon_tag, false
>
{
typedef typename distance_result
<
MultiPolygon1, MultiPolygon2, Strategy
>::type distance_type;
static inline distance_type apply(MultiPolygon1 const& mp1,
MultiPolygon2 const& mp2,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
MultiPolygon1,
typename boost::range_value<MultiPolygon2>::type,
Strategy
>
>::apply(mp1, boost::begin(mp2), boost::end(mp2), strategy);
}
};
template
<
typename MultiPolygon,
typename Segment,
typename Strategy
>
struct distance_brute_force
<
MultiPolygon, Segment, Strategy,
multi_polygon_tag, segment_tag, false
>
{
typedef typename distance_result
<
MultiPolygon, Segment, Strategy
>::type distance_type;
static inline distance_type apply(MultiPolygon const& mp,
Segment const& segment,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Segment,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(segment, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename MultiPolygon,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
MultiPolygon, Ring, Strategy,
multi_polygon_tag, ring_tag, false
>
{
typedef typename distance_result
<
MultiPolygon, Ring, Strategy
>::type distance_type;
static inline distance_type apply(MultiPolygon const& mp,
Ring const& ring,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Ring,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(ring, boost::begin(mp), boost::end(mp), strategy);
}
};
template
<
typename MultiPolygon,
typename Box,
typename Strategy
>
struct distance_brute_force
<
MultiPolygon, Box, Strategy,
multi_polygon_tag, box_tag, false
>
{
typedef typename distance_result
<
MultiPolygon, Box, Strategy
>::type distance_type;
static inline distance_type apply(MultiPolygon const& mp,
Box const& box,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Box,
typename boost::range_value<MultiPolygon>::type,
Strategy
>
>::apply(box, boost::begin(mp), boost::end(mp), strategy);
}
};
//========================================================================
template
<
typename Ring,
typename Box,
typename Strategy
>
struct distance_brute_force
<
Ring, Box, Strategy,
ring_tag, box_tag, false
>
{
typedef typename distance_result
<
Ring, Box, Strategy
>::type distance_type;
static inline distance_type apply(Ring const& ring,
Box const& box,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Box,
typename std::iterator_traits
<
segment_iterator<Ring const>
>::value_type,
Strategy
>
>::apply(box,
geometry::segments_begin(ring),
geometry::segments_end(ring),
strategy);
}
};
template
<
typename Ring1,
typename Ring2,
typename Strategy
>
struct distance_brute_force
<
Ring1, Ring2, Strategy,
ring_tag, ring_tag, false
>
{
typedef typename distance_result
<
Ring1, Ring2, Strategy
>::type distance_type;
static inline distance_type apply(Ring1 const& ring1,
Ring2 const& ring2,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Ring1,
typename std::iterator_traits
<
segment_iterator<Ring2 const>
>::value_type,
Strategy
>
>::apply(ring1,
geometry::segments_begin(ring2),
geometry::segments_end(ring2),
strategy);
}
};
//========================================================================
template
<
typename Segment1,
typename Segment2,
typename Strategy
>
struct distance_brute_force
<
Segment1, Segment2, Strategy,
segment_tag, segment_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
template
<
typename Segment,
typename Ring,
typename Strategy
>
struct distance_brute_force
<
Segment, Ring, Strategy,
segment_tag, ring_tag, false
>
{
typedef typename distance_result
<
Segment, Ring, Strategy
>::type distance_type;
static inline distance_type apply(Segment const& segment,
Ring const& ring,
Strategy const& strategy)
{
return detail::distance_brute_force::one_to_many
<
distance_brute_force
<
Segment,
typename std::iterator_traits
<
segment_iterator<Ring const>
>::value_type,
Strategy
>
>::apply(segment,
geometry::segments_begin(ring),
geometry::segments_end(ring),
strategy);
}
};
template
<
typename Segment,
typename Box,
typename Strategy
>
struct distance_brute_force
<
Segment, Box, Strategy,
segment_tag, box_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
//====================================================================
template
<
typename Box1,
typename Box2,
typename Strategy
>
struct distance_brute_force
<
Box1, Box2, Strategy,
box_tag, box_tag, false
> : detail::distance_brute_force::distance_from_bg
{};
} // namespace dispatch
template <typename Geometry1, typename Geometry2, typename Strategy>
inline typename distance_result<Geometry1, Geometry2, Strategy>::type
distance_brute_force(Geometry1 const& geometry1,
Geometry2 const& geometry2,
Strategy const& strategy)
{
return dispatch::distance_brute_force
<
Geometry1, Geometry2, Strategy
>::apply(geometry1, geometry2, strategy);
}
} // namespace unit_test
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_TEST_DISTANCE_BRUTE_FORCE_HPP
| nawawi/poedit | deps/boost/libs/geometry/test/algorithms/distance/distance_brute_force.hpp | C++ | mit | 34,417 |