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
<?php /** * Redirect * * HTTP redirection commands. * * @package core * @author stefano.azzolini@caffeinalab.com * @copyright Caffeina srl - 2015 - http://caffeina.it */ class Redirect { use Module; public static function to($url, $status=302){ if ($link = Filter::with('core.redirect',$url)) { Response::clean(); Response::status($status); Response::header('Location', $link); Response::send(); exit; } } public static function back(){ if ($link = Filter::with('core.redirect', (empty($_SERVER['HTTP_REFERER']) ? Request::get('redirect_uri',false) : $_SERVER['HTTP_REFERER']) )){ Response::clean(); Response::header('Location', $link); Response::send(); exit; } } public static function viaJavaScript($url, $parent=false){ if ($link = Filter::with('core.redirect', $url)){ Response::type('text/html'); Response::add('<script>'.($parent?'parent.':'').'location.href="'.addslashes($link).'"</script>'); Response::send(); exit; } } }
caffeina-core/core
classes/Redirect.php
PHP
mit
1,140
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class Conversations < Domain class V1 < Version class ServiceContext < InstanceContext class ConfigurationContext < InstanceContext class NotificationList < ListResource ## # Initialize the NotificationList # @param [Version] version Version that contains the resource # @param [String] chat_service_sid The unique string that we created to identify # the Service configuration resource. # @return [NotificationList] NotificationList def initialize(version, chat_service_sid: nil) super(version) # Path Solution @solution = {chat_service_sid: chat_service_sid} end ## # Provide a user friendly representation def to_s '#<Twilio.Conversations.V1.NotificationList>' end end class NotificationPage < Page ## # Initialize the NotificationPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [NotificationPage] NotificationPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of NotificationInstance # @param [Hash] payload Payload response from the API # @return [NotificationInstance] NotificationInstance def get_instance(payload) NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], ) end ## # Provide a user friendly representation def to_s '<Twilio.Conversations.V1.NotificationPage>' end end class NotificationContext < InstanceContext ## # Initialize the NotificationContext # @param [Version] version Version that contains the resource # @param [String] chat_service_sid The SID of the {Conversation # Service}[https://www.twilio.com/docs/conversations/api/service-resource] the # Configuration applies to. # @return [NotificationContext] NotificationContext def initialize(version, chat_service_sid) super(version) # Path Solution @solution = {chat_service_sid: chat_service_sid, } @uri = "/Services/#{@solution[:chat_service_sid]}/Configuration/Notifications" end ## # Update the NotificationInstance # @param [Boolean] log_enabled Weather the notification logging is enabled. # @param [Boolean] new_message_enabled Whether to send a notification when a new # message is added to a conversation. The default is `false`. # @param [String] new_message_template The template to use to create the # notification text displayed when a new message is added to a conversation and # `new_message.enabled` is `true`. # @param [String] new_message_sound The name of the sound to play when a new # message is added to a conversation and `new_message.enabled` is `true`. # @param [Boolean] new_message_badge_count_enabled Whether the new message badge # is enabled. The default is `false`. # @param [Boolean] added_to_conversation_enabled Whether to send a notification # when a participant is added to a conversation. The default is `false`. # @param [String] added_to_conversation_template The template to use to create the # notification text displayed when a participant is added to a conversation and # `added_to_conversation.enabled` is `true`. # @param [String] added_to_conversation_sound The name of the sound to play when a # participant is added to a conversation and `added_to_conversation.enabled` is # `true`. # @param [Boolean] removed_from_conversation_enabled Whether to send a # notification to a user when they are removed from a conversation. The default is # `false`. # @param [String] removed_from_conversation_template The template to use to create # the notification text displayed to a user when they are removed from a # conversation and `removed_from_conversation.enabled` is `true`. # @param [String] removed_from_conversation_sound The name of the sound to play to # a user when they are removed from a conversation and # `removed_from_conversation.enabled` is `true`. # @param [Boolean] new_message_with_media_enabled Whether to send a notification # when a new message with media/file attachments is added to a conversation. The # default is `false`. # @param [String] new_message_with_media_template The template to use to create # the notification text displayed when a new message with media/file attachments # is added to a conversation and `new_message.attachments.enabled` is `true`. # @return [NotificationInstance] Updated NotificationInstance def update(log_enabled: :unset, new_message_enabled: :unset, new_message_template: :unset, new_message_sound: :unset, new_message_badge_count_enabled: :unset, added_to_conversation_enabled: :unset, added_to_conversation_template: :unset, added_to_conversation_sound: :unset, removed_from_conversation_enabled: :unset, removed_from_conversation_template: :unset, removed_from_conversation_sound: :unset, new_message_with_media_enabled: :unset, new_message_with_media_template: :unset) data = Twilio::Values.of({ 'LogEnabled' => log_enabled, 'NewMessage.Enabled' => new_message_enabled, 'NewMessage.Template' => new_message_template, 'NewMessage.Sound' => new_message_sound, 'NewMessage.BadgeCountEnabled' => new_message_badge_count_enabled, 'AddedToConversation.Enabled' => added_to_conversation_enabled, 'AddedToConversation.Template' => added_to_conversation_template, 'AddedToConversation.Sound' => added_to_conversation_sound, 'RemovedFromConversation.Enabled' => removed_from_conversation_enabled, 'RemovedFromConversation.Template' => removed_from_conversation_template, 'RemovedFromConversation.Sound' => removed_from_conversation_sound, 'NewMessage.WithMedia.Enabled' => new_message_with_media_enabled, 'NewMessage.WithMedia.Template' => new_message_with_media_template, }) payload = @version.update('POST', @uri, data: data) NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], ) end ## # Fetch the NotificationInstance # @return [NotificationInstance] Fetched NotificationInstance def fetch payload = @version.fetch('GET', @uri) NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], ) end ## # Provide a user friendly representation def to_s context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Conversations.V1.NotificationContext #{context}>" end ## # Provide a detailed, user friendly representation def inspect context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.Conversations.V1.NotificationContext #{context}>" end end class NotificationInstance < InstanceResource ## # Initialize the NotificationInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] chat_service_sid The unique string that we created to identify # the Service configuration resource. # @return [NotificationInstance] NotificationInstance def initialize(version, payload, chat_service_sid: nil) super(version) # Marshaled Properties @properties = { 'account_sid' => payload['account_sid'], 'chat_service_sid' => payload['chat_service_sid'], 'new_message' => payload['new_message'], 'added_to_conversation' => payload['added_to_conversation'], 'removed_from_conversation' => payload['removed_from_conversation'], 'log_enabled' => payload['log_enabled'], 'url' => payload['url'], } # Context @instance_context = nil @params = {'chat_service_sid' => chat_service_sid, } end ## # Generate an instance context for the instance, the context is capable of # performing various actions. All instance actions are proxied to the context # @return [NotificationContext] NotificationContext for this NotificationInstance def context unless @instance_context @instance_context = NotificationContext.new(@version, @params['chat_service_sid'], ) end @instance_context end ## # @return [String] The unique ID of the Account responsible for this configuration. def account_sid @properties['account_sid'] end ## # @return [String] The SID of the Conversation Service that the Configuration applies to. def chat_service_sid @properties['chat_service_sid'] end ## # @return [Hash] The Push Notification configuration for New Messages. def new_message @properties['new_message'] end ## # @return [Hash] The Push Notification configuration for being added to a Conversation. def added_to_conversation @properties['added_to_conversation'] end ## # @return [Hash] The Push Notification configuration for being removed from a Conversation. def removed_from_conversation @properties['removed_from_conversation'] end ## # @return [Boolean] Weather the notification logging is enabled. def log_enabled @properties['log_enabled'] end ## # @return [String] An absolute URL for this configuration. def url @properties['url'] end ## # Update the NotificationInstance # @param [Boolean] log_enabled Weather the notification logging is enabled. # @param [Boolean] new_message_enabled Whether to send a notification when a new # message is added to a conversation. The default is `false`. # @param [String] new_message_template The template to use to create the # notification text displayed when a new message is added to a conversation and # `new_message.enabled` is `true`. # @param [String] new_message_sound The name of the sound to play when a new # message is added to a conversation and `new_message.enabled` is `true`. # @param [Boolean] new_message_badge_count_enabled Whether the new message badge # is enabled. The default is `false`. # @param [Boolean] added_to_conversation_enabled Whether to send a notification # when a participant is added to a conversation. The default is `false`. # @param [String] added_to_conversation_template The template to use to create the # notification text displayed when a participant is added to a conversation and # `added_to_conversation.enabled` is `true`. # @param [String] added_to_conversation_sound The name of the sound to play when a # participant is added to a conversation and `added_to_conversation.enabled` is # `true`. # @param [Boolean] removed_from_conversation_enabled Whether to send a # notification to a user when they are removed from a conversation. The default is # `false`. # @param [String] removed_from_conversation_template The template to use to create # the notification text displayed to a user when they are removed from a # conversation and `removed_from_conversation.enabled` is `true`. # @param [String] removed_from_conversation_sound The name of the sound to play to # a user when they are removed from a conversation and # `removed_from_conversation.enabled` is `true`. # @param [Boolean] new_message_with_media_enabled Whether to send a notification # when a new message with media/file attachments is added to a conversation. The # default is `false`. # @param [String] new_message_with_media_template The template to use to create # the notification text displayed when a new message with media/file attachments # is added to a conversation and `new_message.attachments.enabled` is `true`. # @return [NotificationInstance] Updated NotificationInstance def update(log_enabled: :unset, new_message_enabled: :unset, new_message_template: :unset, new_message_sound: :unset, new_message_badge_count_enabled: :unset, added_to_conversation_enabled: :unset, added_to_conversation_template: :unset, added_to_conversation_sound: :unset, removed_from_conversation_enabled: :unset, removed_from_conversation_template: :unset, removed_from_conversation_sound: :unset, new_message_with_media_enabled: :unset, new_message_with_media_template: :unset) context.update( log_enabled: log_enabled, new_message_enabled: new_message_enabled, new_message_template: new_message_template, new_message_sound: new_message_sound, new_message_badge_count_enabled: new_message_badge_count_enabled, added_to_conversation_enabled: added_to_conversation_enabled, added_to_conversation_template: added_to_conversation_template, added_to_conversation_sound: added_to_conversation_sound, removed_from_conversation_enabled: removed_from_conversation_enabled, removed_from_conversation_template: removed_from_conversation_template, removed_from_conversation_sound: removed_from_conversation_sound, new_message_with_media_enabled: new_message_with_media_enabled, new_message_with_media_template: new_message_with_media_template, ) end ## # Fetch the NotificationInstance # @return [NotificationInstance] Fetched NotificationInstance def fetch context.fetch end ## # Provide a user friendly representation def to_s values = @params.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Conversations.V1.NotificationInstance #{values}>" end ## # Provide a detailed, user friendly representation def inspect values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.Conversations.V1.NotificationInstance #{values}>" end end end end end end end end
philnash/twilio-ruby
lib/twilio-ruby/rest/conversations/v1/service/configuration/notification.rb
Ruby
mit
17,122
<?php namespace REBELinBLUE\Deployer\Presenters; use Illuminate\Support\Facades\Lang; use REBELinBLUE\Deployer\Command; use Robbo\Presenter\Presenter; /** * The view presenter for a command class. */ class CommandPresenter extends Presenter { /** * Gets the readable list of before clone commands. * * @return string * @see self::commandNames() */ public function presentBeforeClone() { return $this->commandNames(Command::BEFORE_CLONE); } /** * Gets the readable list of after clone commands. * * @return string * @see self::commandNames() */ public function presentAfterClone() { return $this->commandNames(Command::AFTER_CLONE); } /** * Gets the readable list of before install commands. * * @return string * @see self::commandNames() */ public function presentBeforeInstall() { return $this->commandNames(Command::BEFORE_INSTALL); } /** * Gets the readable list of after install commands. * * @return string * @see self::commandNames() */ public function presentAfterInstall() { return $this->commandNames(Command::AFTER_INSTALL); } /** * Gets the readable list of before activate commands. * * @return string * @see self::commandNames() */ public function presentBeforeActivate() { return $this->commandNames(Command::BEFORE_ACTIVATE); } /** * Gets the readable list of after activate commands. * * @return string * @see self::commandNames() */ public function presentAfterActivate() { return $this->commandNames(Command::AFTER_ACTIVATE); } /** * Gets the readable list of before purge commands. * * @return string * @see self::commandNames() */ public function presentBeforePurge() { return $this->commandNames(Command::BEFORE_PURGE); } /** * Gets the readable list of after purge commands. * * @return string * @see self::commandNames() */ public function presentAfterPurge() { return $this->commandNames(Command::AFTER_PURGE); } /** * Gets the readable list of commands. * * @param int $stage * @return string */ private function commandNames($stage) { $commands = []; foreach ($this->object->commands as $command) { if ($command->step === $stage) { $commands[] = $command->name; } } if (count($commands)) { return implode(', ', $commands); } return Lang::get('app.none'); } }
iflamed/deployer
app/Presenters/CommandPresenter.php
PHP
mit
2,738
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); /** @typedef {import("../MainTemplate")} MainTemplate */ class CompatRuntimePlugin extends RuntimeModule { constructor() { super("compat", 10); } /** * @returns {string} runtime code */ generate() { const { chunk, compilation } = this; const { chunkGraph, runtimeTemplate, mainTemplate, moduleTemplates, dependencyTemplates } = compilation; const bootstrap = mainTemplate.hooks.bootstrap.call( "", chunk, compilation.hash || "XXXX", moduleTemplates.javascript, dependencyTemplates ); const localVars = mainTemplate.hooks.localVars.call( "", chunk, compilation.hash || "XXXX" ); const requireExtensions = mainTemplate.hooks.requireExtensions.call( "", chunk, compilation.hash || "XXXX" ); const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); let requireEnsure = ""; if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( "", chunk, compilation.hash || "XXXX", "chunkId" ); if (requireEnsureHandler) { requireEnsure = `${ RuntimeGlobals.ensureChunkHandlers }.compat = ${runtimeTemplate.basicFunction( "chunkId, promises", requireEnsureHandler )};`; } } return [bootstrap, localVars, requireEnsure, requireExtensions] .filter(Boolean) .join("\n"); } } module.exports = CompatRuntimePlugin;
EliteScientist/webpack
lib/runtime/CompatRuntimePlugin.js
JavaScript
mit
1,622
module Sequel module Plugins # The composition plugin allows you to easily define a virtual # attribute where the backing data is composed of other columns. # # There are two ways to use the plugin. One way is with the # :mapping option. A simple example of this is when you have a # database table with separate columns for year, month, and day, # but where you want to deal with Date objects in your ruby code. # This can be handled with: # # Album.plugin :composition # Album.composition :date, :mapping=>[:year, :month, :day] # # With the :mapping option, you can provide a :class option # that gives the class to use, but if that is not provided, it # is inferred from the name of the composition (e.g. :date -> Date). # When the <tt>date</tt> method is called, it will return a # Date object by calling: # # Date.new(year, month, day) # # When saving the object, if the date composition has been used # (by calling either the getter or setter method), it will # populate the related columns of the object before saving: # # self.year = date.year # self.month = date.month # self.day = date.day # # The :mapping option is just a shortcut that works in particular # cases. To handle any case, you can define a custom :composer # and :decomposer procs. The :composer proc will be instance_evaled # the first time the getter is called, and the :decomposer proc # will be instance_evaled before saving. The above example could # also be implemented as: # # Album.composition :date, # :composer=>proc{Date.new(year, month, day) if year || month || day}, # :decomposer=>(proc do # if d = compositions[:date] # self.year = d.year # self.month = d.month # self.day = d.day # else # self.year = nil # self.month = nil # self.day = nil # end # end) # # Note that when using the composition object, you should not # modify the underlying columns if you are also instantiating # the composition, as otherwise the composition object values # will override any underlying columns when the object is saved. module Composition # Define the necessary class instance variables. def self.apply(model) model.instance_eval{@compositions = {}} end module ClassMethods # A hash with composition name keys and composition reflection # hash values. attr_reader :compositions # A module included in the class holding the composition # getter and setter methods. attr_reader :composition_module # Define a composition for this model, with name being the name of the composition. # You must provide either a :mapping option or both the :composer and :decomposer options. # # Options: # * :class - if using the :mapping option, the class to use, as a Class, String or Symbol. # * :composer - A proc that is instance evaled when the composition getter method is called # to create the composition. # * :decomposer - A proc that is instance evaled before saving the model object, # if the composition object exists, which sets the columns in the model object # based on the value of the composition object. # * :mapping - An array where each element is either a symbol or an array of two symbols. # A symbol is treated like an array of two symbols where both symbols are the same. # The first symbol represents the getter method in the model, and the second symbol # represents the getter method in the composition object. Example: # # Uses columns year, month, and day in the current model # # Uses year, month, and day methods in the composition object # :mapping=>[:year, :month, :day] # # Uses columns year, month, and day in the current model # # Uses y, m, and d methods in the composition object where # # for example y in the composition object represents year # # in the model object. # :mapping=>[[:year, :y], [:month, :m], [:day, :d]] def composition(name, opts={}) opts = opts.dup compositions[name] = opts if mapping = opts[:mapping] keys = mapping.map{|k| k.is_a?(Array) ? k.first : k} if !opts[:composer] late_binding_class_option(opts, name) klass = opts[:class] class_proc = proc{klass || constantize(opts[:class_name])} opts[:composer] = proc do if values = keys.map{|k| send(k)} and values.any?{|v| !v.nil?} class_proc.call.new(*values) else nil end end end if !opts[:decomposer] setter_meths = keys.map{|k| :"#{k}="} cov_methods = mapping.map{|k| k.is_a?(Array) ? k.last : k} setters = setter_meths.zip(cov_methods) opts[:decomposer] = proc do if (o = compositions[name]).nil? setter_meths.each{|sm| send(sm, nil)} else setters.each{|sm, cm| send(sm, o.send(cm))} end end end end raise(Error, "Must provide :composer and :decomposer options, or :mapping option") unless opts[:composer] && opts[:decomposer] define_composition_accessor(name, opts) end # Copy the necessary class instance variables to the subclass. def inherited(subclass) super c = compositions.dup subclass.instance_eval{@compositions = c} end # Define getter and setter methods for the composition object. def define_composition_accessor(name, opts={}) include(@composition_module ||= Module.new) unless composition_module composer = opts[:composer] composition_module.class_eval do define_method(name) do compositions.include?(name) ? compositions[name] : (compositions[name] = instance_eval(&composer)) end define_method("#{name}=") do |v| modified! compositions[name] = v end end end end module InstanceMethods # Clear the cached compositions when refreshing. def _refresh(ds) super compositions.clear end # For each composition, set the columns in the model class based # on the composition object. def before_save @compositions.keys.each{|n| instance_eval(&model.compositions[n][:decomposer])} if @compositions super end # Cache of composition objects for this class. def compositions @compositions ||= {} end end end end end
saadullahsaeed/chai.io
vendor/bundle/ruby/1.9.1/gems/sequel-3.41.0/lib/sequel/plugins/composition.rb
Ruby
mit
7,178
(function () { var defs = {}; // id -> {dependencies, definition, instance (possibly undefined)} // Used when there is no 'main' module. // The name is probably (hopefully) unique so minification removes for releases. var register_3795 = function (id) { var module = dem(id); var fragments = id.split('.'); var target = Function('return this;')(); for (var i = 0; i < fragments.length - 1; ++i) { if (target[fragments[i]] === undefined) target[fragments[i]] = {}; target = target[fragments[i]]; } target[fragments[fragments.length - 1]] = module; }; var instantiate = function (id) { var actual = defs[id]; var dependencies = actual.deps; var definition = actual.defn; var len = dependencies.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances[i] = dem(dependencies[i]); var defResult = definition.apply(null, instances); if (defResult === undefined) throw 'module [' + id + '] returned undefined'; actual.instance = defResult; }; var def = function (id, dependencies, definition) { if (typeof id !== 'string') throw 'module id must be a string'; else if (dependencies === undefined) throw 'no dependencies for ' + id; else if (definition === undefined) throw 'no definition function for ' + id; defs[id] = { deps: dependencies, defn: definition, instance: undefined }; }; var dem = function (id) { var actual = defs[id]; if (actual === undefined) throw 'module [' + id + '] was undefined'; else if (actual.instance === undefined) instantiate(id); return actual.instance; }; var req = function (ids, callback) { var len = ids.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances.push(dem(ids[i])); callback.apply(null, callback); }; var ephox = {}; ephox.bolt = { module: { api: { define: def, require: req, demand: dem } } }; var define = def; var require = req; var demand = dem; // this helps with minificiation when using a lot of global references var defineGlobal = function (id, ref) { define(id, [], function () { return ref; }); }; /*jsc ["tinymce.themes.modern.Theme","global!window","tinymce.core.AddOnManager","tinymce.core.EditorManager","tinymce.core.Env","tinymce.core.ui.Api","tinymce.themes.modern.modes.Iframe","tinymce.themes.modern.modes.Inline","tinymce.themes.modern.ui.ProgressState","tinymce.themes.modern.ui.Resize","global!tinymce.util.Tools.resolve","tinymce.core.dom.DOMUtils","tinymce.core.ui.Factory","tinymce.core.util.Tools","tinymce.themes.modern.ui.A11y","tinymce.themes.modern.ui.Branding","tinymce.themes.modern.ui.ContextToolbars","tinymce.themes.modern.ui.Menubar","tinymce.themes.modern.ui.Sidebar","tinymce.themes.modern.ui.SkinLoaded","tinymce.themes.modern.ui.Toolbar","tinymce.core.ui.FloatPanel","tinymce.core.ui.Throbber","tinymce.core.util.Delay","tinymce.core.geom.Rect"] jsc*/ defineGlobal("global!window", window); defineGlobal("global!tinymce.util.Tools.resolve", tinymce.util.Tools.resolve); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.AddOnManager', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.AddOnManager'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.EditorManager', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.EditorManager'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.Env', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.Env'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Api', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Api'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.dom.DOMUtils', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.dom.DOMUtils'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Factory', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Factory'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.util.Tools', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.util.Tools'); } ); /** * A11y.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.A11y', [ ], function () { var focus = function (panel, type) { return function () { var item = panel.find(type)[0]; if (item) { item.focus(true); } }; }; var addKeys = function (editor, panel) { editor.shortcuts.add('Alt+F9', '', focus(panel, 'menubar')); editor.shortcuts.add('Alt+F10,F10', '', focus(panel, 'toolbar')); editor.shortcuts.add('Alt+F11', '', focus(panel, 'elementpath')); panel.on('cancel', function () { editor.focus(); }); }; return { addKeys: addKeys }; } ); /** * Branding.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Branding', [ 'tinymce.core.dom.DOMUtils' ], function (DOMUtils) { var DOM = DOMUtils.DOM; var reposition = function (editor, poweredByElm) { return function () { var iframeWidth = editor.getContentAreaContainer().querySelector('iframe').offsetWidth; var scrollbarWidth = Math.max(iframeWidth - editor.getDoc().documentElement.offsetWidth, 0); var statusbarElm = editor.getContainer().querySelector('.mce-statusbar'); var statusbarHeight = statusbarElm ? statusbarElm.offsetHeight : 1; DOM.setStyles(poweredByElm, { right: scrollbarWidth + 'px', bottom: statusbarHeight + 'px' }); }; }; var hide = function (poweredByElm) { return function () { DOM.hide(poweredByElm); }; }; var setupEventListeners = function (editor) { editor.on('SkinLoaded', function () { var poweredByElm = DOM.create('div', { 'class': 'mce-branding-powered-by' }); editor.getContainer().appendChild(poweredByElm); DOM.bind(poweredByElm, 'click', hide(poweredByElm)); editor.on('NodeChange ResizeEditor', reposition(editor, poweredByElm)); }); }; var setup = function (editor) { if (editor.settings.branding !== false) { setupEventListeners(editor); } }; return { setup: setup }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.util.Delay', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.util.Delay'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.geom.Rect', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.geom.Rect'); } ); /** * Toolbar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Toolbar', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory' ], function (Tools, Factory) { var defaultToolbar = "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | " + "bullist numlist outdent indent | link image"; var createToolbar = function (editor, items, size) { var toolbarItems = [], buttonGroup; if (!items) { return; } Tools.each(items.split(/[ ,]/), function (item) { var itemName; var bindSelectorChanged = function () { var selection = editor.selection; if (item.settings.stateSelector) { selection.selectorChanged(item.settings.stateSelector, function (state) { item.active(state); }, true); } if (item.settings.disabledStateSelector) { selection.selectorChanged(item.settings.disabledStateSelector, function (state) { item.disabled(state); }); } }; if (item == "|") { buttonGroup = null; } else { if (!buttonGroup) { buttonGroup = { type: 'buttongroup', items: [] }; toolbarItems.push(buttonGroup); } if (editor.buttons[item]) { // TODO: Move control creation to some UI class itemName = item; item = editor.buttons[itemName]; if (typeof item == "function") { item = item(); } item.type = item.type || 'button'; item.size = size; item = Factory.create(item); buttonGroup.items.push(item); if (editor.initialized) { bindSelectorChanged(); } else { editor.on('init', bindSelectorChanged); } } } }); return { type: 'toolbar', layout: 'flow', items: toolbarItems }; }; /** * Creates the toolbars from config and returns a toolbar array. * * @param {String} size Optional toolbar item size. * @return {Array} Array with toolbars. */ var createToolbars = function (editor, size) { var toolbars = [], settings = editor.settings; var addToolbar = function (items) { if (items) { toolbars.push(createToolbar(editor, items, size)); return true; } }; // Convert toolbar array to multiple options if (Tools.isArray(settings.toolbar)) { // Empty toolbar array is the same as a disabled toolbar if (settings.toolbar.length === 0) { return; } Tools.each(settings.toolbar, function (toolbar, i) { settings["toolbar" + (i + 1)] = toolbar; }); delete settings.toolbar; } // Generate toolbar<n> for (var i = 1; i < 10; i++) { if (!addToolbar(settings["toolbar" + i])) { break; } } // Generate toolbar or default toolbar unless it's disabled if (!toolbars.length && settings.toolbar !== false) { addToolbar(settings.toolbar || defaultToolbar); } if (toolbars.length) { return { type: 'panel', layout: 'stack', classes: "toolbar-grp", ariaRoot: true, ariaRemember: true, items: toolbars }; } }; return { createToolbar: createToolbar, createToolbars: createToolbars }; } ); /** * ContextToolbars.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.ContextToolbars', [ 'tinymce.core.dom.DOMUtils', 'tinymce.core.util.Tools', 'tinymce.core.util.Delay', 'tinymce.core.ui.Factory', 'tinymce.core.geom.Rect', 'tinymce.themes.modern.ui.Toolbar' ], function (DOMUtils, Tools, Delay, Factory, Rect, Toolbar) { var DOM = DOMUtils.DOM; var toClientRect = function (geomRect) { return { left: geomRect.x, top: geomRect.y, width: geomRect.w, height: geomRect.h, right: geomRect.x + geomRect.w, bottom: geomRect.y + geomRect.h }; }; var hideAllFloatingPanels = function (editor) { Tools.each(editor.contextToolbars, function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var movePanelTo = function (panel, pos) { panel.moveTo(pos.left, pos.top); }; var togglePositionClass = function (panel, relPos, predicate) { relPos = relPos ? relPos.substr(0, 2) : ''; Tools.each({ t: 'down', b: 'up' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(0, 1))); }); Tools.each({ l: 'left', r: 'right' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(1, 1))); }); }; var userConstrain = function (handler, x, y, elementRect, contentAreaRect, panelRect) { panelRect = toClientRect({ x: x, y: y, w: panelRect.w, h: panelRect.h }); if (handler) { panelRect = handler({ elementRect: toClientRect(elementRect), contentAreaRect: toClientRect(contentAreaRect), panelRect: panelRect }); } return panelRect; }; var addContextualToolbars = function (editor) { var scrollContainer, settings = editor.settings; var getContextToolbars = function () { return editor.contextToolbars || []; }; var getElementRect = function (elm) { var pos, targetRect, root; pos = DOM.getPos(editor.getContentAreaContainer()); targetRect = editor.dom.getRect(elm); root = editor.dom.getRoot(); // Adjust targetPos for scrolling in the editor if (root.nodeName === 'BODY') { targetRect.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft; targetRect.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop; } targetRect.x += pos.x; targetRect.y += pos.y; return targetRect; }; var reposition = function (match, shouldShow) { var relPos, panelRect, elementRect, contentAreaRect, panel, relRect, testPositions, smallElementWidthThreshold; var handler = settings.inline_toolbar_position_handler; if (editor.removed) { return; } if (!match || !match.toolbar.panel) { hideAllFloatingPanels(editor); return; } testPositions = [ 'bc-tc', 'tc-bc', 'tl-bl', 'bl-tl', 'tr-br', 'br-tr' ]; panel = match.toolbar.panel; // Only show the panel on some events not for example nodeChange since that fires when context menu is opened if (shouldShow) { panel.show(); } elementRect = getElementRect(match.element); panelRect = DOM.getRect(panel.getEl()); contentAreaRect = DOM.getRect(editor.getContentAreaContainer() || editor.getBody()); smallElementWidthThreshold = 25; if (DOM.getStyle(match.element, 'display', true) !== 'inline') { // We need to use these instead of the rect values since the style // size properites might not be the same as the real size for a table elementRect.w = match.element.clientWidth; elementRect.h = match.element.clientHeight; } if (!editor.inline) { contentAreaRect.w = editor.getDoc().documentElement.offsetWidth; } // Inflate the elementRect so it doesn't get placed above resize handles if (editor.selection.controlSelection.isResizable(match.element) && elementRect.w < smallElementWidthThreshold) { elementRect = Rect.inflate(elementRect, 0, 8); } relPos = Rect.findBestRelativePosition(panelRect, elementRect, contentAreaRect, testPositions); elementRect = Rect.clamp(elementRect, contentAreaRect); if (relPos) { relRect = Rect.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { // Allow overflow below the editor to avoid placing toolbars ontop of tables contentAreaRect.h += panelRect.h; elementRect = Rect.intersect(contentAreaRect, elementRect); if (elementRect) { relPos = Rect.findBestRelativePosition(panelRect, elementRect, contentAreaRect, [ 'bc-tc', 'bl-tl', 'br-tr' ]); if (relPos) { relRect = Rect.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { movePanelTo(panel, userConstrain(handler, elementRect.x, elementRect.y, elementRect, contentAreaRect, panelRect)); } } else { panel.hide(); } } togglePositionClass(panel, relPos, function (pos1, pos2) { return pos1 === pos2; }); //drawRect(contentAreaRect, 'blue'); //drawRect(elementRect, 'red'); //drawRect(panelRect, 'green'); }; var repositionHandler = function (show) { return function () { var execute = function () { if (editor.selection) { reposition(findFrontMostMatch(editor.selection.getNode()), show); } }; Delay.requestAnimationFrame(execute); }; }; var bindScrollEvent = function () { if (!scrollContainer) { scrollContainer = editor.selection.getScrollContainer() || editor.getWin(); DOM.bind(scrollContainer, 'scroll', repositionHandler(true)); editor.on('remove', function () { DOM.unbind(scrollContainer, 'scroll'); }); } }; var showContextToolbar = function (match) { var panel; if (match.toolbar.panel) { match.toolbar.panel.show(); reposition(match); return; } bindScrollEvent(); panel = Factory.create({ type: 'floatpanel', role: 'dialog', classes: 'tinymce tinymce-inline arrow', ariaLabel: 'Inline toolbar', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: true, border: 1, items: Toolbar.createToolbar(editor, match.toolbar.items), oncancel: function () { editor.focus(); } }); match.toolbar.panel = panel; panel.renderTo(document.body).reflow(); reposition(match); }; var hideAllContextToolbars = function () { Tools.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var findFrontMostMatch = function (targetElm) { var i, y, parentsAndSelf, toolbars = getContextToolbars(); parentsAndSelf = editor.$(targetElm).parents().add(targetElm); for (i = parentsAndSelf.length - 1; i >= 0; i--) { for (y = toolbars.length - 1; y >= 0; y--) { if (toolbars[y].predicate(parentsAndSelf[i])) { return { toolbar: toolbars[y], element: parentsAndSelf[i] }; } } } return null; }; editor.on('click keyup setContent ObjectResized', function (e) { // Only act on partial inserts if (e.type === 'setcontent' && !e.selection) { return; } // Needs to be delayed to avoid Chrome img focus out bug Delay.setEditorTimeout(editor, function () { var match; match = findFrontMostMatch(editor.selection.getNode()); if (match) { hideAllContextToolbars(); showContextToolbar(match); } else { hideAllContextToolbars(); } }); }); editor.on('blur hide contextmenu', hideAllContextToolbars); editor.on('ObjectResizeStart', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.hide(); } }); editor.on('ResizeEditor ResizeWindow', repositionHandler(true)); editor.on('nodeChange', repositionHandler(false)); editor.on('remove', function () { Tools.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.remove(); } }); editor.contextToolbars = {}; }); editor.shortcuts.add('ctrl+shift+e > ctrl+shift+p', '', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.items()[0].focus(); } }); }; return { addContextualToolbars: addContextualToolbars }; } ); /** * Menubar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Menubar', [ 'tinymce.core.util.Tools' ], function (Tools) { var defaultMenus = { file: { title: 'File', items: 'newdocument' }, edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' }, insert: { title: 'Insert', items: '|' }, view: { title: 'View', items: 'visualaid |' }, format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat' }, table: { title: 'Table' }, tools: { title: 'Tools' } }; var createMenuItem = function (menuItems, name) { var menuItem; if (name == '|') { return { text: '|' }; } menuItem = menuItems[name]; return menuItem; }; var createMenu = function (editorMenuItems, settings, context) { var menuButton, menu, menuItems, isUserDefined, removedMenuItems; removedMenuItems = Tools.makeMap((settings.removed_menuitems || '').split(/[ ,]/)); // User defined menu if (settings.menu) { menu = settings.menu[context]; isUserDefined = true; } else { menu = defaultMenus[context]; } if (menu) { menuButton = { text: menu.title }; menuItems = []; // Default/user defined items Tools.each((menu.items || '').split(/[ ,]/), function (item) { var menuItem = createMenuItem(editorMenuItems, item); if (menuItem && !removedMenuItems[item]) { menuItems.push(createMenuItem(editorMenuItems, item)); } }); // Added though context if (!isUserDefined) { Tools.each(editorMenuItems, function (menuItem) { if (menuItem.context == context) { if (menuItem.separator == 'before') { menuItems.push({ text: '|' }); } if (menuItem.prependToContext) { menuItems.unshift(menuItem); } else { menuItems.push(menuItem); } if (menuItem.separator == 'after') { menuItems.push({ text: '|' }); } } }); } for (var i = 0; i < menuItems.length; i++) { if (menuItems[i].text == '|') { if (i === 0 || i == menuItems.length - 1) { menuItems.splice(i, 1); } } } menuButton.menu = menuItems; if (!menuButton.menu.length) { return null; } } return menuButton; }; var createMenuButtons = function (editor) { var name, menuButtons = [], settings = editor.settings; var defaultMenuBar = []; if (settings.menu) { for (name in settings.menu) { defaultMenuBar.push(name); } } else { for (name in defaultMenus) { defaultMenuBar.push(name); } } var enabledMenuNames = typeof settings.menubar == "string" ? settings.menubar.split(/[ ,]/) : defaultMenuBar; for (var i = 0; i < enabledMenuNames.length; i++) { var menu = enabledMenuNames[i]; menu = createMenu(editor.menuItems, editor.settings, menu); if (menu) { menuButtons.push(menu); } } return menuButtons; }; return { createMenuButtons: createMenuButtons }; } ); /** * Resize.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Resize', [ 'tinymce.core.dom.DOMUtils' ], function (DOMUtils) { var DOM = DOMUtils.DOM; var getSize = function (elm) { return { width: elm.clientWidth, height: elm.clientHeight }; }; var resizeTo = function (editor, width, height) { var containerElm, iframeElm, containerSize, iframeSize, settings = editor.settings; containerElm = editor.getContainer(); iframeElm = editor.getContentAreaContainer().firstChild; containerSize = getSize(containerElm); iframeSize = getSize(iframeElm); if (width !== null) { width = Math.max(settings.min_width || 100, width); width = Math.min(settings.max_width || 0xFFFF, width); DOM.setStyle(containerElm, 'width', width + (containerSize.width - iframeSize.width)); DOM.setStyle(iframeElm, 'width', width); } height = Math.max(settings.min_height || 100, height); height = Math.min(settings.max_height || 0xFFFF, height); DOM.setStyle(iframeElm, 'height', height); editor.fire('ResizeEditor'); }; var resizeBy = function (editor, dw, dh) { var elm = editor.getContentAreaContainer(); resizeTo(editor, elm.clientWidth + dw, elm.clientHeight + dh); }; return { resizeTo: resizeTo, resizeBy: resizeBy }; } ); /** * Sidebar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Sidebar', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory', 'tinymce.core.Env' ], function (Tools, Factory, Env) { var api = function (elm) { return { element: function () { return elm; } }; }; var trigger = function (sidebar, panel, callbackName) { var callback = sidebar.settings[callbackName]; if (callback) { callback(api(panel.getEl('body'))); } }; var hidePanels = function (name, container, sidebars) { Tools.each(sidebars, function (sidebar) { var panel = container.items().filter('#' + sidebar.name)[0]; if (panel && panel.visible() && sidebar.name !== name) { trigger(sidebar, panel, 'onhide'); panel.visible(false); } }); }; var deactivateButtons = function (toolbar) { toolbar.items().each(function (ctrl) { ctrl.active(false); }); }; var findSidebar = function (sidebars, name) { return Tools.grep(sidebars, function (sidebar) { return sidebar.name === name; })[0]; }; var showPanel = function (editor, name, sidebars) { return function (e) { var btnCtrl = e.control; var container = btnCtrl.parents().filter('panel')[0]; var panel = container.find('#' + name)[0]; var sidebar = findSidebar(sidebars, name); hidePanels(name, container, sidebars); deactivateButtons(btnCtrl.parent()); if (panel && panel.visible()) { trigger(sidebar, panel, 'onhide'); panel.hide(); btnCtrl.active(false); } else { if (panel) { panel.show(); trigger(sidebar, panel, 'onshow'); } else { panel = Factory.create({ type: 'container', name: name, layout: 'stack', classes: 'sidebar-panel', html: '' }); container.prepend(panel); trigger(sidebar, panel, 'onrender'); trigger(sidebar, panel, 'onshow'); } btnCtrl.active(true); } editor.fire('ResizeEditor'); }; }; var isModernBrowser = function () { return !Env.ie || Env.ie >= 11; }; var hasSidebar = function (editor) { return isModernBrowser() && editor.sidebars ? editor.sidebars.length > 0 : false; }; var createSidebar = function (editor) { var buttons = Tools.map(editor.sidebars, function (sidebar) { var settings = sidebar.settings; return { type: 'button', icon: settings.icon, image: settings.image, tooltip: settings.tooltip, onclick: showPanel(editor, sidebar.name, editor.sidebars) }; }); return { type: 'panel', name: 'sidebar', layout: 'stack', classes: 'sidebar', items: [ { type: 'toolbar', layout: 'stack', classes: 'sidebar-toolbar', items: buttons } ] }; }; return { hasSidebar: hasSidebar, createSidebar: createSidebar }; } ); /** * SkinLoaded.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.SkinLoaded', [ ], function () { var fireSkinLoaded = function (editor) { var done = function () { editor._skinLoaded = true; editor.fire('SkinLoaded'); }; return function () { if (editor.initialized) { done(); } else { editor.on('init', done); } }; }; return { fireSkinLoaded: fireSkinLoaded }; } ); /** * Iframe.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.modes.Iframe', [ 'tinymce.core.dom.DOMUtils', 'tinymce.core.ui.Factory', 'tinymce.core.util.Tools', 'tinymce.themes.modern.ui.A11y', 'tinymce.themes.modern.ui.Branding', 'tinymce.themes.modern.ui.ContextToolbars', 'tinymce.themes.modern.ui.Menubar', 'tinymce.themes.modern.ui.Resize', 'tinymce.themes.modern.ui.Sidebar', 'tinymce.themes.modern.ui.SkinLoaded', 'tinymce.themes.modern.ui.Toolbar' ], function (DOMUtils, Factory, Tools, A11y, Branding, ContextToolbars, Menubar, Resize, Sidebar, SkinLoaded, Toolbar) { var DOM = DOMUtils.DOM; var switchMode = function (panel) { return function (e) { panel.find('*').disabled(e.mode === 'readonly'); }; }; var editArea = function (border) { return { type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', border: border, html: '' }; }; var editAreaContainer = function (editor) { return { type: 'panel', layout: 'stack', classes: 'edit-aria-container', border: '1 0 0 0', items: [ editArea('0'), Sidebar.createSidebar(editor) ] }; }; var render = function (editor, theme, args) { var panel, resizeHandleCtrl, startSize, settings = editor.settings; if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, SkinLoaded.fireSkinLoaded(editor)); } panel = theme.panel = Factory.create({ type: 'panel', role: 'application', classes: 'tinymce', style: 'visibility: hidden', layout: 'stack', border: 1, items: [ settings.menubar === false ? null : { type: 'menubar', border: '0 0 1 0', items: Menubar.createMenuButtons(editor) }, Toolbar.createToolbars(editor, settings.toolbar_items_size), Sidebar.hasSidebar(editor) ? editAreaContainer(editor) : editArea('1 0 0 0') ] }); if (settings.resize !== false) { resizeHandleCtrl = { type: 'resizehandle', direction: settings.resize, onResizeStart: function () { var elm = editor.getContentAreaContainer().firstChild; startSize = { width: elm.clientWidth, height: elm.clientHeight }; }, onResize: function (e) { if (settings.resize === 'both') { Resize.resizeTo(editor, startSize.width + e.deltaX, startSize.height + e.deltaY); } else { Resize.resizeTo(editor, null, startSize.height + e.deltaY); } } }; } // Add statusbar if needed if (settings.statusbar !== false) { panel.add({ type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', ariaRoot: true, items: [ { type: 'elementpath', editor: editor }, resizeHandleCtrl ] }); } editor.fire('BeforeRenderUI'); editor.on('SwitchMode', switchMode(panel)); panel.renderBefore(args.targetNode).reflow(); if (settings.readonly) { editor.setMode('readonly'); } if (args.width) { DOM.setStyle(panel.getEl(), 'width', args.width); } // Remove the panel when the editor is removed editor.on('remove', function () { panel.remove(); panel = null; }); // Add accesibility shortcuts A11y.addKeys(editor, panel); ContextToolbars.addContextualToolbars(editor); Branding.setup(editor); return { iframeContainer: panel.find('#iframe')[0].getEl(), editorContainer: panel.getEl() }; }; return { render: render }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.FloatPanel', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.FloatPanel'); } ); /** * Inline.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.modes.Inline', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory', 'tinymce.core.dom.DOMUtils', 'tinymce.core.ui.FloatPanel', 'tinymce.themes.modern.ui.Toolbar', 'tinymce.themes.modern.ui.Menubar', 'tinymce.themes.modern.ui.ContextToolbars', 'tinymce.themes.modern.ui.A11y', 'tinymce.themes.modern.ui.SkinLoaded' ], function (Tools, Factory, DOMUtils, FloatPanel, Toolbar, Menubar, ContextToolbars, A11y, SkinLoaded) { var render = function (editor, theme, args) { var panel, inlineToolbarContainer, settings = editor.settings; var DOM = DOMUtils.DOM; if (settings.fixed_toolbar_container) { inlineToolbarContainer = DOM.select(settings.fixed_toolbar_container)[0]; } var reposition = function () { if (panel && panel.moveRel && panel.visible() && !panel._fixed) { // TODO: This is kind of ugly and doesn't handle multiple scrollable elements var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody(); var deltaX = 0, deltaY = 0; if (scrollContainer) { var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer); deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x); deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y); } panel.fixed(false).moveRel(body, editor.rtl ? ['tr-br', 'br-tr'] : ['tl-bl', 'bl-tl', 'tr-br']).moveBy(deltaX, deltaY); } }; var show = function () { if (panel) { panel.show(); reposition(); DOM.addClass(editor.getBody(), 'mce-edit-focus'); } }; var hide = function () { if (panel) { // We require two events as the inline float panel based toolbar does not have autohide=true panel.hide(); // All other autohidden float panels will be closed below. FloatPanel.hideAll(); DOM.removeClass(editor.getBody(), 'mce-edit-focus'); } }; var render = function () { if (panel) { if (!panel.visible()) { show(); } return; } // Render a plain panel inside the inlineToolbarContainer if it's defined panel = theme.panel = Factory.create({ type: inlineToolbarContainer ? 'panel' : 'floatpanel', role: 'application', classes: 'tinymce tinymce-inline', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: !!inlineToolbarContainer, border: 1, items: [ settings.menubar === false ? null : { type: 'menubar', border: '0 0 1 0', items: Menubar.createMenuButtons(editor) }, Toolbar.createToolbars(editor, settings.toolbar_items_size) ] }); // Add statusbar /*if (settings.statusbar !== false) { panel.add({type: 'panel', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', items: [ {type: 'elementpath'} ]}); }*/ editor.fire('BeforeRenderUI'); panel.renderTo(inlineToolbarContainer || document.body).reflow(); A11y.addKeys(editor, panel); show(); ContextToolbars.addContextualToolbars(editor); editor.on('nodeChange', reposition); editor.on('activate', show); editor.on('deactivate', hide); editor.nodeChanged(); }; settings.content_editable = true; editor.on('focus', function () { // Render only when the CSS file has been loaded if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, render, render); } else { render(); } }); editor.on('blur hide', hide); // Remove the panel when the editor is removed editor.on('remove', function () { if (panel) { panel.remove(); panel = null; } }); // Preload skin css if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, SkinLoaded.fireSkinLoaded(editor)); } return {}; }; return { render: render }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Throbber', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Throbber'); } ); /** * ProgressState.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.ProgressState', [ 'tinymce.core.ui.Throbber' ], function (Throbber) { var setup = function (editor, theme) { var throbber; editor.on('ProgressState', function (e) { throbber = throbber || new Throbber(theme.panel.getEl('body')); if (e.state) { throbber.show(e.time); } else { throbber.hide(); } }); }; return { setup: setup }; } ); /** * Theme.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.Theme', [ 'global!window', 'tinymce.core.AddOnManager', 'tinymce.core.EditorManager', 'tinymce.core.Env', 'tinymce.core.ui.Api', 'tinymce.themes.modern.modes.Iframe', 'tinymce.themes.modern.modes.Inline', 'tinymce.themes.modern.ui.ProgressState', 'tinymce.themes.modern.ui.Resize' ], function (window, AddOnManager, EditorManager, Env, Api, Iframe, Inline, ProgressState, Resize) { var ThemeManager = AddOnManager.ThemeManager; Api.appendTo(window.tinymce ? window.tinymce : {}); var renderUI = function (editor, theme, args) { var settings = editor.settings; var skin = settings.skin !== false ? settings.skin || 'lightgray' : false; if (skin) { var skinUrl = settings.skin_url; if (skinUrl) { skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); } else { skinUrl = EditorManager.baseURL + '/skins/' + skin; } args.skinUiCss = skinUrl + '/skin.min.css'; // Load content.min.css or content.inline.min.css editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css'); } ProgressState.setup(editor, theme); if (settings.inline) { return Inline.render(editor, theme, args); } return Iframe.render(editor, theme, args); }; ThemeManager.add('modern', function (editor) { return { renderUI: function (args) { return renderUI(editor, this, args); }, resizeTo: function (w, h) { return Resize.resizeTo(editor, w, h); }, resizeBy: function (dw, dh) { return Resize.resizeBy(editor, dw, dh); } }; }); return function () { }; } ); dem('tinymce.themes.modern.Theme')(); })();
g0otgahp/number-energy
theme/tinymce/tinymce/themes/modern/theme.js
JavaScript
mit
44,251
package test; /* * 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 org.apache.giraph.Algorithm; import org.apache.giraph.conf.LongConfOption; import org.apache.giraph.edge.Edge; import org.apache.giraph.graph.Vertex; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.LongWritable; import org.apache.log4j.Logger; /** * Demonstrates the basic Pregel shortest paths implementation. */ @Algorithm( name = "Shortest paths", description = "Finds all shortest paths from a selected vertex" ) public class SimpleShortestPathsVertex extends Vertex<LongWritable, DoubleWritable, FloatWritable, DoubleWritable> { /** The shortest paths id */ public static final LongConfOption SOURCE_ID = new LongConfOption("SimpleShortestPathsVertex.sourceId", 1); /** Class logger */ private static final Logger LOG = Logger.getLogger(SimpleShortestPathsVertex.class); /** * Is this vertex the source id? * * @return True if the source id */ private boolean isSource() { return getId().get() == SOURCE_ID.get(getConf()); } @Override public void compute(Iterable<DoubleWritable> messages) { if (getSuperstep() == 0) { setValue(new DoubleWritable(Double.MAX_VALUE)); } double minDist = isSource() ? 0d : Double.MAX_VALUE; for (DoubleWritable message : messages) { minDist = Math.min(minDist, message.get()); } if (LOG.isDebugEnabled()) { LOG.debug("Vertex " + getId() + " got minDist = " + minDist + " vertex value = " + getValue()); } if (minDist < getValue().get()) { setValue(new DoubleWritable(minDist)); for (Edge<LongWritable, FloatWritable> edge : getEdges()) { double distance = minDist + edge.getValue().get(); if (LOG.isDebugEnabled()) { LOG.debug("Vertex " + getId() + " sent to " + edge.getTargetVertexId() + " = " + distance); } sendMessage(edge.getTargetVertexId(), new DoubleWritable(distance)); } } voteToHalt(); } }
mitdbg/asciiclass
labs/lab7/code/src/test/SimpleShortestPathsVertex.java
Java
mit
2,846
module.exports = function(sequelize, DataTypes) { var Product = sequelize.define('Product', { ProductId: { type: DataTypes.BIGINT, primaryKey:true, allowNull: false, autoIncrement: true }, ProductTypeId:{ type:DataTypes.BIGINT, allowNull: false, references : 'ProductType', referencesKey:'ProductTypeId', comment: "references对应的是表名" } , productName:{ type:DataTypes.STRING, allowNull: false }, productDesc:{ type:DataTypes.STRING }, mount:{ type:DataTypes.BIGINT }, price:{ type:DataTypes.DECIMAL(10,2) }, isSale:{ type:DataTypes.BOOLEAN }, isVailed:{ type:DataTypes.BOOLEAN } }); return Product; };
coolicer/shopshop
models/Product.js
JavaScript
mit
807
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("GifToGomez")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("maik")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
0x0ade/GifToGomez
Properties/AssemblyInfo.cs
C#
mit
981
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Web.Api.Auth { using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Principal; using System.Text; using System.Threading; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Membership; using DotNetNuke.Web.ConfigSection; public class BasicAuthMessageHandler : AuthMessageHandlerBase { private readonly Encoding _encoding = Encoding.GetEncoding("iso-8859-1"); public BasicAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } public override string AuthScheme => "Basic"; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) { if (this.NeedsAuthentication(request)) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (portalSettings != null) { this.TryToAuthenticate(request, portalSettings.PortalId); } } return base.OnInboundRequest(request, cancellationToken); } public override HttpResponseMessage OnOutboundResponse(HttpResponseMessage response, CancellationToken cancellationToken) { if (response.StatusCode == HttpStatusCode.Unauthorized && this.SupportsBasicAuth(response.RequestMessage)) { response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(this.AuthScheme, "realm=\"DNNAPI\"")); } return base.OnOutboundResponse(response, cancellationToken); } private bool SupportsBasicAuth(HttpRequestMessage request) { return !IsXmlHttpRequest(request); } private void TryToAuthenticate(HttpRequestMessage request, int portalId) { UserCredentials credentials = this.GetCredentials(request); if (credentials == null) { return; } var status = UserLoginStatus.LOGIN_FAILURE; string ipAddress = request.GetIPAddress(); UserInfo user = UserController.ValidateUser(portalId, credentials.UserName, credentials.Password, "DNN", string.Empty, "a portal", ipAddress ?? string.Empty, ref status); if (user != null) { SetCurrentPrincipal(new GenericPrincipal(new GenericIdentity(credentials.UserName, this.AuthScheme), null), request); } } private UserCredentials GetCredentials(HttpRequestMessage request) { if (request?.Headers.Authorization == null) { return null; } if (request?.Headers.Authorization.Scheme.ToLower() != this.AuthScheme.ToLower()) { return null; } string authorization = request?.Headers.Authorization.Parameter; if (string.IsNullOrEmpty(authorization)) { return null; } string decoded = this._encoding.GetString(Convert.FromBase64String(authorization)); string[] parts = decoded.Split(new[] { ':' }, 2); if (parts.Length < 2) { return null; } return new UserCredentials(parts[0], parts[1]); } internal class UserCredentials { public UserCredentials(string userName, string password) { this.UserName = userName; this.Password = password; } public string Password { get; set; } public string UserName { get; set; } } } }
nvisionative/Dnn.Platform
DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs
C#
mit
4,146
namespace Microsoft.ApplicationInsights.WindowsServer.Mock { using System; using System.Collections.Generic; using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing; internal class HeartbeatProviderMock : IHeartbeatPropertyManager { public bool Enabled = true; public TimeSpan Interval = TimeSpan.FromMinutes(15); public List<string> ExcludedProps = new List<string>(); public List<string> ExcludedPropProviders = new List<string>(); public Dictionary<string, string> HbeatProps = new Dictionary<string, string>(); public Dictionary<string, bool> HbeatHealth = new Dictionary<string, bool>(); public bool IsHeartbeatEnabled { get => this.Enabled; set => this.Enabled = value; } public TimeSpan HeartbeatInterval { get => this.Interval; set => this.Interval = value; } public IList<string> ExcludedHeartbeatProperties => this.ExcludedProps; public IList<string> ExcludedHeartbeatPropertyProviders => this.ExcludedPropProviders; public bool AddHeartbeatProperty(string propertyName, string propertyValue, bool isHealthy) { if (!this.HbeatProps.ContainsKey(propertyName)) { this.HbeatProps.Add(propertyName, propertyValue); this.HbeatHealth.Add(propertyName, isHealthy); return true; } return false; } public bool SetHeartbeatProperty(string propertyName, string propertyValue = null, bool? isHealthy = null) { if (!string.IsNullOrEmpty(propertyName) && this.HbeatProps.ContainsKey(propertyName)) { if (!string.IsNullOrEmpty(propertyValue)) { this.HbeatProps[propertyName] = propertyValue; } if (isHealthy.HasValue) { this.HbeatHealth[propertyName] = isHealthy.GetValueOrDefault(false); } return true; } return false; } } }
pharring/ApplicationInsights-dotnet
WEB/Src/WindowsServer/WindowsServer.Tests/Mock/HeartbeatProviderMock.cs
C#
mit
2,100
import bootstrap # noqa import pytest from modviz.cli import parse_arguments, validate_path, validate_fold_paths def test_argument_parsing(): with pytest.raises(SystemExit): parse_arguments([]) namespace = parse_arguments(["foo"]) assert namespace.path == "foo" assert namespace.target is None assert namespace.fold_paths is None assert namespace.exclude_paths is None namespace = parse_arguments(["foo", "-o", "test.html"]) assert namespace.path == "foo" assert namespace.target is "test.html" assert namespace.fold_paths is None assert namespace.exclude_paths is None namespace = parse_arguments(["foo", "-o", "test.html", "-e", "foo", "bar"]) assert namespace.path == "foo" assert namespace.target is "test.html" assert namespace.fold_paths is None assert namespace.exclude_paths == ["foo", "bar"] namespace = parse_arguments(["foo", "-o", "test.html", "-f", "foo", "bar"]) assert namespace.path == "foo" assert namespace.target is "test.html" assert namespace.fold_paths == ["foo", "bar"] assert namespace.exclude_paths is None def test_validate_path(): assert validate_path("/") assert not validate_path("/imprettysureidontexist") def test_validate_fold_paths(): root = "/" assert validate_fold_paths(root, []) assert validate_fold_paths(root, ["/a", "/b"]) with pytest.raises(ValueError): validate_fold_paths(root, ["foo"])
Bogdanp/modviz
tests/test_cli.py
Python
mit
1,467
<?php /** * SwpmMemberUtils * All the utility functions related to member records should be added to this class */ class SwpmMemberUtils { public static function is_member_logged_in() { $auth = SwpmAuth::get_instance(); if ($auth->is_logged_in()) { return true; } else { return false; } } public static function get_logged_in_members_id() { $auth = SwpmAuth::get_instance(); if (!$auth->is_logged_in()) { return SwpmUtils::_("User is not logged in."); } return $auth->get('member_id'); } public static function get_logged_in_members_username() { $auth = SwpmAuth::get_instance(); if (!$auth->is_logged_in()) { return SwpmUtils::_("User is not logged in."); } return $auth->get('user_name'); } public static function get_logged_in_members_level() { $auth = SwpmAuth::get_instance(); if (!$auth->is_logged_in()) { return SwpmUtils::_("User is not logged in."); } return $auth->get('membership_level'); } public static function get_logged_in_members_level_name() { $auth = SwpmAuth::get_instance(); if ($auth->is_logged_in()) { return $auth->get('alias'); } return SwpmUtils::_("User is not logged in."); } public static function get_member_field_by_id($id, $field, $default = '') { global $wpdb; $query = "SELECT * FROM " . $wpdb->prefix . "swpm_members_tbl WHERE member_id = %d"; $userData = $wpdb->get_row($wpdb->prepare($query, $id)); if (isset($userData->$field)) { return $userData->$field; } return apply_filters('swpm_get_member_field_by_id', $default, $id, $field); } public static function get_user_by_id($swpm_id) { //Retrieves the SWPM user record for the given member ID global $wpdb; $query = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}swpm_members_tbl WHERE member_id = %d", $swpm_id); $result = $wpdb->get_row($query); return $result; } public static function get_user_by_user_name($swpm_user_name) { //Retrieves the SWPM user record for the given member username global $wpdb; $query = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}swpm_members_tbl WHERE user_name = %s", $swpm_user_name); $result = $wpdb->get_row($query); return $result; } public static function get_user_by_email($swpm_email) { //Retrieves the SWPM user record for the given member email address global $wpdb; $query = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}swpm_members_tbl WHERE email = %s", $swpm_email); $result = $wpdb->get_row($query); return $result; } public static function is_valid_user_name($user_name){ return preg_match("/^[a-zA-Z0-9!@#$%&+\/=?^_`{|}~\.-]+$/", $user_name)== 1; } }
924ge/xpoint21
www/wordpress/wordpress/wp-content/plugins/simple-membership/classes/class.swpm-utils-member.php
PHP
mit
3,017
#region Copyright // // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice 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. #endregion #region Usings using Telerik.Web.UI; #endregion namespace DotNetNuke.Web.UI.WebControls { public class DnnListViewItem : RadListViewItem { public DnnListViewItem(RadListViewItemType itemType, RadListView ownerView) : base(itemType, ownerView) { } } }
RichardHowells/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs
C#
mit
1,498
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\KDCIFD; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class SerialNumber extends AbstractTag { protected $Id = 64000; protected $Name = 'SerialNumber'; protected $FullName = 'Kodak::KDC_IFD'; protected $GroupName = 'KDC_IFD'; protected $g0 = 'MakerNotes'; protected $g1 = 'KDC_IFD'; protected $g2 = 'Image'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Serial Number'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/KDCIFD/SerialNumber.php
PHP
mit
838
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Qualcomm; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class R2TL84Tbl27 extends AbstractTag { protected $Id = 'r2_tl84_tbl[27]'; protected $Name = 'R2TL84Tbl27'; protected $FullName = 'Qualcomm::Main'; protected $GroupName = 'Qualcomm'; protected $g0 = 'MakerNotes'; protected $g1 = 'Qualcomm'; protected $g2 = 'Camera'; protected $Type = '?'; protected $Writable = false; protected $Description = 'R2 TL84 Tbl 27'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Qualcomm/R2TL84Tbl27.php
PHP
mit
850
<?php /** * This file is part of Railt package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Railt\SDL; use GraphQL\Contracts\TypeSystem\SchemaInterface; use Phplrt\Contracts\Source\ReadableInterface; /** * Interface CompilerInterface */ interface CompilerInterface { /** * Loads GraphQL source into the compiler. * * @param ReadableInterface|string|resource|mixed $source * @param array $variables * @return CompilerInterface|$this */ public function preload($source, array $variables = []): self; /** * Compiles the sources and all previously loaded types * into the final document. * * @param ReadableInterface|string|resource|mixed $source * @param array $variables * @return SchemaInterface */ public function compile($source, array $variables = []): SchemaInterface; }
railt/railt
packages/SDL/src/CompilerInterface.php
PHP
mit
989
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M17 4h-3V2h-4v2H7v18h10V4z" }), 'BatteryStdSharp'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/BatteryStdSharp.js
JavaScript
mit
497
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createConfig; var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _jsYaml = require('js-yaml'); var _jsYaml2 = _interopRequireDefault(_jsYaml); var _stripJsonComments = require('strip-json-comments'); var _stripJsonComments2 = _interopRequireDefault(_stripJsonComments); var _fileExists = require('./utils/fileExists'); var _fileExists2 = _interopRequireDefault(_fileExists); var _selectModules = require('./utils/selectModules'); var _selectModules2 = _interopRequireDefault(_selectModules); var _selectUserModules = require('./utils/selectUserModules'); var _selectUserModules2 = _interopRequireDefault(_selectUserModules); var _getEnvProp = require('./utils/getEnvProp'); var _getEnvProp2 = _interopRequireDefault(_getEnvProp); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* ======= Fetching config */ var DEFAULT_VERSION = 3; var SUPPORTED_VERSIONS = [3, 4]; var CONFIG_FILE = '.bootstraprc'; function resolveDefaultConfigPath(bootstrapVersion) { return _path2.default.resolve(__dirname, '../' + CONFIG_FILE + '-' + bootstrapVersion + '-default'); } function parseConfigFile(configFilePath) { var configContent = (0, _stripJsonComments2.default)(_fs2.default.readFileSync(configFilePath, 'utf8')); try { return _jsYaml2.default.safeLoad(configContent); } catch (YAMLException) { throw new Error('Config file cannot be parsed: ' + configFilePath + '\''); } } function readDefaultConfig() { var configFilePath = resolveDefaultConfigPath(DEFAULT_VERSION); var defaultConfig = parseConfigFile(configFilePath); return { defaultConfig: defaultConfig, configFilePath: configFilePath }; } // default location .bootstraprc function defaultUserConfigPath() { return _path2.default.resolve(__dirname, '../../../' + CONFIG_FILE); } function readUserConfig(customConfigFilePath) { var userConfig = parseConfigFile(customConfigFilePath); var bootstrapVersion = userConfig.bootstrapVersion; if (!bootstrapVersion) { throw new Error('\nBootstrap version not found in your \'.bootstraprc\'.\nMake sure it\'s set to 3 or 4. Like this:\n bootstrapVersion: 4\n '); } if (SUPPORTED_VERSIONS.indexOf(parseInt(bootstrapVersion, 10)) === -1) { throw new Error('\nUnsupported Bootstrap version in your \'.bootstraprc\'.\nMake sure it\'s set to 3 or 4. Like this:\n bootstrapVersion: 4\n '); } var defaultConfigFilePath = resolveDefaultConfigPath(bootstrapVersion); var defaultConfig = parseConfigFile(defaultConfigFilePath); return { userConfig: userConfig, defaultConfig: defaultConfig }; } /* ======= Exports */ function createConfig(_ref) { var extractStyles = _ref.extractStyles, customConfigFilePath = _ref.customConfigFilePath; // .bootstraprc-{3,4}-default, per the DEFAULT_VERSION // otherwise read user provided config file var userConfigFilePath = null; if (customConfigFilePath) { userConfigFilePath = _path2.default.resolve(__dirname, customConfigFilePath); } else { var defaultLocationUserConfigPath = defaultUserConfigPath(); if ((0, _fileExists2.default)(defaultLocationUserConfigPath)) { userConfigFilePath = defaultLocationUserConfigPath; } } if (!userConfigFilePath) { var _readDefaultConfig = readDefaultConfig(), _defaultConfig = _readDefaultConfig.defaultConfig, _configFilePath = _readDefaultConfig.configFilePath; return { bootstrapVersion: parseInt(_defaultConfig.bootstrapVersion, 10), loglevel: _defaultConfig.loglevel, useFlexbox: _defaultConfig.useFlexbox, preBootstrapCustomizations: _defaultConfig.preBootstrapCustomizations, bootstrapCustomizations: _defaultConfig.bootstrapCustomizations, appStyles: _defaultConfig.appStyles, useCustomIconFontPath: _defaultConfig.useCustomIconFontPath, extractStyles: extractStyles || (0, _getEnvProp2.default)('extractStyles', _defaultConfig), styleLoaders: (0, _getEnvProp2.default)('styleLoaders', _defaultConfig), styles: (0, _selectModules2.default)(_defaultConfig.styles), scripts: (0, _selectModules2.default)(_defaultConfig.scripts), configFilePath: _configFilePath }; } var configFilePath = userConfigFilePath; var _readUserConfig = readUserConfig(configFilePath), userConfig = _readUserConfig.userConfig, defaultConfig = _readUserConfig.defaultConfig; var configDir = _path2.default.dirname(configFilePath); var preBootstrapCustomizations = userConfig.preBootstrapCustomizations && _path2.default.resolve(configDir, userConfig.preBootstrapCustomizations); var bootstrapCustomizations = userConfig.bootstrapCustomizations && _path2.default.resolve(configDir, userConfig.bootstrapCustomizations); var appStyles = userConfig.appStyles && _path2.default.resolve(configDir, userConfig.appStyles); return { bootstrapVersion: parseInt(userConfig.bootstrapVersion, 10), loglevel: userConfig.loglevel, preBootstrapCustomizations: preBootstrapCustomizations, bootstrapCustomizations: bootstrapCustomizations, appStyles: appStyles, disableSassSourceMap: userConfig.disableSassSourceMap, disableResolveUrlLoader: userConfig.disableResolveUrlLoader, useFlexbox: userConfig.useFlexbox, useCustomIconFontPath: userConfig.useCustomIconFontPath, extractStyles: extractStyles || (0, _getEnvProp2.default)('extractStyles', userConfig), styleLoaders: (0, _getEnvProp2.default)('styleLoaders', userConfig), styles: (0, _selectUserModules2.default)(userConfig.styles, defaultConfig.styles), scripts: (0, _selectUserModules2.default)(userConfig.scripts, defaultConfig.scripts), configFilePath: configFilePath }; }
Dackng/eh-unmsm-client
node_modules/bootstrap-loader/lib/bootstrap.config.js
JavaScript
mit
5,934
<?php /** * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Catalog\Model\Product\Gallery; use Magento\Framework\Model\AbstractExtensibleModel; use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionInterface; /** * @codeCoverageIgnore */ class Entry extends AbstractExtensibleModel implements ProductAttributeMediaGalleryEntryInterface { /** * Retrieve gallery entry ID * * @return int */ public function getId() { return $this->getData(self::ID); } /** * Get media type * * @return string */ public function getMediaType() { return $this->getData(self::MEDIA_TYPE); } /** * Retrieve gallery entry alternative text * * @return string */ public function getLabel() { return $this->getData(self::LABEL); } /** * Retrieve gallery entry position (sort order) * * @return int */ public function getPosition() { return $this->getData(self::POSITION); } /** * Check if gallery entry is hidden from product page * * @return bool */ public function isDisabled() { return $this->getData(self::DISABLED); } /** * Retrieve gallery entry image types (thumbnail, image, small_image etc) * * @return string[] */ public function getTypes() { return $this->getData(self::TYPES); } /** * Get file path * * @return string */ public function getFile() { return $this->getData(self::FILE); } /** * @return \Magento\Framework\Api\Data\ImageContentInterface|null */ public function getContent() { return $this->getData(self::CONTENT); } /** * Set media type * * @param string $mediaType * @return $this */ public function setMediaType($mediaType) { return $this->setData(self::MEDIA_TYPE, $mediaType); } /** * Set gallery entry alternative text * * @param string $label * @return $this */ public function setLabel($label) { return $this->setData(self::LABEL, $label); } /** * Set gallery entry position (sort order) * * @param int $position * @return $this */ public function setPosition($position) { return $this->setData(self::POSITION, $position); } /** * Set whether gallery entry is hidden from product page * * @param bool $disabled * @return $this */ public function setDisabled($disabled) { return $this->setData(self::DISABLED, $disabled); } /** * Set gallery entry image types (thumbnail, image, small_image etc) * * @param string[] $types * @return $this */ public function setTypes(array $types = null) { return $this->setData(self::TYPES, $types); } /** * Set file path * * @param string $file * @return $this */ public function setFile($file) { return $this->setData(self::FILE, $file); } /** * Set media gallery content * * @param $content \Magento\Framework\Api\Data\ImageContentInterface * @return $this */ public function setContent($content) { return $this->setData(self::CONTENT, $content); } /** * {@inheritdoc} * * @return ProductAttributeMediaGalleryEntryExtensionInterface|null */ public function getExtensionAttributes() { return $this->_getExtensionAttributes(); } /** * {@inheritdoc} * * @param ProductAttributeMediaGalleryEntryExtensionInterface $extensionAttributes * @return $this */ public function setExtensionAttributes(ProductAttributeMediaGalleryEntryExtensionInterface $extensionAttributes) { return $this->_setExtensionAttributes($extensionAttributes); } }
j-froehlich/magento2_wk
vendor/magento/module-catalog/Model/Product/Gallery/Entry.php
PHP
mit
4,135
# Retain for backward compatibility. Methods are now included in Class. module ClassInheritableAttributes # :nodoc: end # Allows attributes to be shared within an inheritance hierarchy, but where each descendant gets a copy of # their parents' attributes, instead of just a pointer to the same. This means that the child can add elements # to, for example, an array without those additions being shared with either their parent, siblings, or # children, which is unlike the regular class-level attributes that are shared across the entire hierarchy. class Class # :nodoc: def class_inheritable_reader(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym} read_inheritable_attribute(:#{sym}) end def #{sym} self.class.#{sym} end EOS end end def class_inheritable_writer(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym}=(obj) write_inheritable_attribute(:#{sym}, obj) end def #{sym}=(obj) self.class.#{sym} = obj end EOS end end def class_inheritable_array_writer(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym}=(obj) write_inheritable_array(:#{sym}, obj) end def #{sym}=(obj) self.class.#{sym} = obj end EOS end end def class_inheritable_hash_writer(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym}=(obj) write_inheritable_hash(:#{sym}, obj) end def #{sym}=(obj) self.class.#{sym} = obj end EOS end end def class_inheritable_accessor(*syms) class_inheritable_reader(*syms) class_inheritable_writer(*syms) end def class_inheritable_array(*syms) class_inheritable_reader(*syms) class_inheritable_array_writer(*syms) end def class_inheritable_hash(*syms) class_inheritable_reader(*syms) class_inheritable_hash_writer(*syms) end def inheritable_attributes @inheritable_attributes ||= {} end def write_inheritable_attribute(key, value) inheritable_attributes[key] = value end def write_inheritable_array(key, elements) write_inheritable_attribute(key, []) if read_inheritable_attribute(key).nil? write_inheritable_attribute(key, read_inheritable_attribute(key) + elements) end def write_inheritable_hash(key, hash) write_inheritable_attribute(key, {}) if read_inheritable_attribute(key).nil? write_inheritable_attribute(key, read_inheritable_attribute(key).merge(hash)) end def read_inheritable_attribute(key) inheritable_attributes[key] end def reset_inheritable_attributes inheritable_attributes.clear end private def inherited_with_inheritable_attributes(child) inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes) new_inheritable_attributes = inheritable_attributes.inject({}) do |memo, (key, value)| memo.update(key => (value.dup rescue value)) end child.instance_variable_set('@inheritable_attributes', new_inheritable_attributes) end alias inherited_without_inheritable_attributes inherited alias inherited inherited_with_inheritable_attributes end
madridonrails/StrategyMOR
vendor/rails/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb
Ruby
mit
3,330
<?php namespace XarismaBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ImportType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('importTime') ->add('filename') ->add('md5') ->add('status') ->add('recs') ->add('errors') ->add('customerNew') ->add('customerUpdate') ->add('orderNew') ->add('orderUpdate') ->add('datecreated') ->add('dateupdated') ->add('deleted') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'XarismaBundle\Entity\Import' )); } /** * @return string */ public function getName() { return 'xarismabundle_import'; } }
mightydonbriggs/xarisma
src/XarismaBundle/Form/ImportType.php
PHP
mit
1,220
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.servicebus.v2017_04_01.implementation; import com.microsoft.azure.management.servicebus.v2017_04_01.MigrationConfigProperties; import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; import rx.Observable; class MigrationConfigPropertiesImpl extends CreatableUpdatableImpl<MigrationConfigProperties, MigrationConfigPropertiesInner, MigrationConfigPropertiesImpl> implements MigrationConfigProperties, MigrationConfigProperties.Definition, MigrationConfigProperties.Update { private final ServiceBusManager manager; private String resourceGroupName; private String namespaceName; MigrationConfigPropertiesImpl(String name, ServiceBusManager manager) { super(name, new MigrationConfigPropertiesInner()); this.manager = manager; // Set resource name this.namespaceName = name; // } MigrationConfigPropertiesImpl(MigrationConfigPropertiesInner inner, ServiceBusManager manager) { super(inner.name(), inner); this.manager = manager; // Set resource name this.namespaceName = inner.name(); // set resource ancestor and positional variables this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); this.namespaceName = IdParsingUtils.getValueFromIdByName(inner.id(), "namespaces"); // } @Override public ServiceBusManager manager() { return this.manager; } @Override public Observable<MigrationConfigProperties> createResourceAsync() { MigrationConfigsInner client = this.manager().inner().migrationConfigs(); return client.createAndStartMigrationAsync(this.resourceGroupName, this.namespaceName, this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<MigrationConfigProperties> updateResourceAsync() { MigrationConfigsInner client = this.manager().inner().migrationConfigs(); return client.createAndStartMigrationAsync(this.resourceGroupName, this.namespaceName, this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<MigrationConfigPropertiesInner> getInnerAsync() { MigrationConfigsInner client = this.manager().inner().migrationConfigs(); return client.getAsync(this.resourceGroupName, this.namespaceName); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public String id() { return this.inner().id(); } @Override public String migrationState() { return this.inner().migrationState(); } @Override public String name() { return this.inner().name(); } @Override public Long pendingReplicationOperationsCount() { return this.inner().pendingReplicationOperationsCount(); } @Override public String postMigrationName() { return this.inner().postMigrationName(); } @Override public String provisioningState() { return this.inner().provisioningState(); } @Override public String targetNamespace() { return this.inner().targetNamespace(); } @Override public String type() { return this.inner().type(); } @Override public MigrationConfigPropertiesImpl withExistingNamespace(String resourceGroupName, String namespaceName) { this.resourceGroupName = resourceGroupName; this.namespaceName = namespaceName; return this; } @Override public MigrationConfigPropertiesImpl withPostMigrationName(String postMigrationName) { this.inner().withPostMigrationName(postMigrationName); return this; } @Override public MigrationConfigPropertiesImpl withTargetNamespace(String targetNamespace) { this.inner().withTargetNamespace(targetNamespace); return this; } }
selvasingh/azure-sdk-for-java
sdk/servicebus/mgmt-v2017_04_01/src/main/java/com/microsoft/azure/management/servicebus/v2017_04_01/implementation/MigrationConfigPropertiesImpl.java
Java
mit
4,198
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.machinelearningservices.v2019_05_01.implementation; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.azure.Page; import java.util.List; /** * An instance of this class defines a page of Azure resources and a link to * get the next page of resources, if any. * * @param <T> type of Azure resource */ public class PageImpl1<T> implements Page<T> { /** * The link to the next page. */ @JsonProperty("nextLink") private String nextPageLink; /** * The list of items. */ @JsonProperty("value") private List<T> items; /** * Gets the link to the next page. * * @return the link to the next page. */ @Override public String nextPageLink() { return this.nextPageLink; } /** * Gets the list of items. * * @return the list of items in {@link List}. */ @Override public List<T> items() { return items; } /** * Sets the link to the next page. * * @param nextPageLink the link to the next page. * @return this Page object itself. */ public PageImpl1<T> setNextPageLink(String nextPageLink) { this.nextPageLink = nextPageLink; return this; } /** * Sets the list of items. * * @param items the list of items in {@link List}. * @return this Page object itself. */ public PageImpl1<T> setItems(List<T> items) { this.items = items; return this; } }
selvasingh/azure-sdk-for-java
sdk/machinelearningservices/mgmt-v2019_05_01/src/main/java/com/microsoft/azure/management/machinelearningservices/v2019_05_01/implementation/PageImpl1.java
Java
mit
1,776
<?php namespace Acacha\AdminLTETemplateLaravel\Console\Routes; /** * Interface GeneratesCode. * * @package Acacha\AdminLTETemplateLaravel\Console\Routes */ interface GeneratesCode { /** * Generates route code * * @return mixed */ public function code(); /** * Set replacements. * * @param $replacements * @return mixed */ public function setReplacements($replacements); }
acacha/adminlte-laravel
src/Console/Routes/GeneratesCode.php
PHP
mit
440
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* DISPLAY_DEVICE.cs -- Ars Magna project, http://arsmagna.ru */ #region Using directives using System; using System.Runtime.InteropServices; using JetBrains.Annotations; #endregion // ReSharper disable InconsistentNaming namespace AM.Win32 { /// <summary> /// Receives information about the display device specified /// by the iDevNum parameter of the EnumDisplayDevices function. /// </summary> /// <remarks> /// The four string members are set based on the parameters passed /// to EnumDisplayDevices. If the lpDevice param is NULL, then DISPLAY_DEVICE is filled in with information about the display adapter(s). If it is a valid device name, then it is filled in with information about the monitor(s) for that device. /// </remarks> // Не фурычит, падла! [PublicAPI] [Serializable] [StructLayout(LayoutKind.Sequential, Size = SIZE, CharSet = CharSet.Unicode)] public struct DISPLAY_DEVICEW { /// <summary> /// Size of structure in bytes. /// </summary> public const int SIZE = 840; /// <summary> /// Size, in bytes, of the DISPLAY_DEVICE structure. /// This must be initialized prior to calling EnumDisplayDevices. /// </summary> //[FieldOffset ( 0 )] public int cb; /// <summary> /// An array of characters identifying the device name. /// This is either the adapter device or the monitor device. /// </summary> //[FieldOffset ( 4 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DeviceName; /// <summary> /// An array of characters containing the device context string. /// This is either a description of the display adapter or of the /// display monitor. /// </summary> //[FieldOffset ( 68 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceString; /// <summary> /// /// </summary> //[FieldOffset ( 324 )] public DeviceStateFlags StateFlags; /// <summary> /// Windows 98/Me: A string that uniquely identifies the hardware /// adapter or the monitor. This is the Plug and Play identifier. /// </summary> //[FieldOffset ( 328 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceID; /// <summary> /// Reserved. /// </summary> //[FieldOffset ( 584 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceKey; } /// <summary> /// Receives information about the display device specified /// by the iDevNum parameter of the EnumDisplayDevices function. /// </summary> /// <remarks> /// The four string members are set based on the parameters passed /// to EnumDisplayDevices. If the lpDevice param is NULL, then DISPLAY_DEVICE is filled in with information about the display adapter(s). If it is a valid device name, then it is filled in with information about the monitor(s) for that device. /// </remarks> [Serializable] [StructLayout(LayoutKind.Sequential, Size = SIZE)] public struct DISPLAY_DEVICEA { /// <summary> /// Size of structure in bytes. /// </summary> public const int SIZE = 424; /// <summary> /// Size, in bytes, of the DISPLAY_DEVICE structure. /// This must be initialized prior to calling EnumDisplayDevices. /// </summary> //[FieldOffset ( 0 )] public int cb; /// <summary> /// An array of characters identifying the device name. /// This is either the adapter device or the monitor device. /// </summary> //[FieldOffset ( 4 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DeviceName; /// <summary> /// An array of characters containing the device context string. /// This is either a description of the display adapter or of the /// display monitor. /// </summary> //[FieldOffset ( 68 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceString; /// <summary> /// /// </summary> //[FieldOffset ( 324 )] public DeviceStateFlags StateFlags; /// <summary> /// Windows 98/Me: A string that uniquely identifies the hardware /// adapter or the monitor. This is the Plug and Play identifier. /// </summary> //[FieldOffset ( 328 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceID; /// <summary> /// Reserved. /// </summary> //[FieldOffset ( 584 )] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string DeviceKey; } }
amironov73/ManagedIrbis
Source/Classic/Libs/AM.Win32/AM/Win32/Gdi32/DISPLAY_DEVICE.cs
C#
mit
5,145
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Loader; use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException; use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException; use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Config\Resource\FileExistenceResource; use Symfony\Component\Config\Resource\GlobResource; /** * FileLoader is the abstract class used by all built-in loaders that are file based. * * @author Fabien Potencier <fabien@symfony.com> */ abstract class FileLoader extends Loader { protected static $loading = []; protected $locator; private $currentDir; public function __construct(FileLocatorInterface $locator) { $this->locator = $locator; } /** * Sets the current directory. */ public function setCurrentDir(string $dir) { $this->currentDir = $dir; } /** * Returns the file locator used by this loader. * * @return FileLocatorInterface */ public function getLocator() { return $this->locator; } /** * Imports a resource. * * @param mixed $resource A Resource * @param string|null $type The resource type or null if unknown * @param bool $ignoreErrors Whether to ignore import errors or not * @param string|null $sourceResource The original resource importing the new resource * * @return mixed * * @throws LoaderLoadException * @throws FileLoaderImportCircularReferenceException * @throws FileLocatorFileNotFoundException */ public function import($resource, string $type = null, bool $ignoreErrors = false, string $sourceResource = null) { if (\is_string($resource) && \strlen($resource) !== $i = strcspn($resource, '*?{[')) { $ret = []; $isSubpath = 0 !== $i && false !== strpos(substr($resource, 0, $i), '/'); foreach ($this->glob($resource, false, $_, $ignoreErrors || !$isSubpath) as $path => $info) { if (null !== $res = $this->doImport($path, $type, $ignoreErrors, $sourceResource)) { $ret[] = $res; } $isSubpath = true; } if ($isSubpath) { return isset($ret[1]) ? $ret : (isset($ret[0]) ? $ret[0] : null); } } return $this->doImport($resource, $type, $ignoreErrors, $sourceResource); } /** * @internal */ protected function glob(string $pattern, bool $recursive, &$resource = null, bool $ignoreErrors = false, bool $forExclusion = false, array $excluded = []) { if (\strlen($pattern) === $i = strcspn($pattern, '*?{[')) { $prefix = $pattern; $pattern = ''; } elseif (0 === $i || false === strpos(substr($pattern, 0, $i), '/')) { $prefix = '.'; $pattern = '/'.$pattern; } else { $prefix = \dirname(substr($pattern, 0, 1 + $i)); $pattern = substr($pattern, \strlen($prefix)); } try { $prefix = $this->locator->locate($prefix, $this->currentDir, true); } catch (FileLocatorFileNotFoundException $e) { if (!$ignoreErrors) { throw $e; } $resource = []; foreach ($e->getPaths() as $path) { $resource[] = new FileExistenceResource($path); } return; } $resource = new GlobResource($prefix, $pattern, $recursive, $forExclusion, $excluded); yield from $resource; } private function doImport($resource, string $type = null, bool $ignoreErrors = false, string $sourceResource = null) { try { $loader = $this->resolve($resource, $type); if ($loader instanceof self && null !== $this->currentDir) { $resource = $loader->getLocator()->locate($resource, $this->currentDir, false); } $resources = \is_array($resource) ? $resource : [$resource]; for ($i = 0; $i < $resourcesCount = \count($resources); ++$i) { if (isset(self::$loading[$resources[$i]])) { if ($i == $resourcesCount - 1) { throw new FileLoaderImportCircularReferenceException(array_keys(self::$loading)); } } else { $resource = $resources[$i]; break; } } self::$loading[$resource] = true; try { $ret = $loader->load($resource, $type); } finally { unset(self::$loading[$resource]); } return $ret; } catch (FileLoaderImportCircularReferenceException $e) { throw $e; } catch (\Exception $e) { if (!$ignoreErrors) { // prevent embedded imports from nesting multiple exceptions if ($e instanceof LoaderLoadException) { throw $e; } throw new LoaderLoadException($resource, $sourceResource, null, $e, $type); } } } }
teohhanhui/symfony
src/Symfony/Component/Config/Loader/FileLoader.php
PHP
mit
5,542
<?php /** * Created by IntelliJ IDEA. * User: emcnaughton * Date: 5/4/17 * Time: 10:35 AM */ namespace Omnimail\Common; /** * Interface CredentialsInterface * * @package Omnimail */ interface CredentialsInterface { /** * Set credentials. * * @param array $credentials */ public function setCredentials($credentials); /** * @param $parameter * @return mixed */ public function get($parameter); }
gabrielbull/php-sitesearch
src/Common/CredentialsInterface.php
PHP
mit
458
package com.nirima.jenkins.plugins.docker.builder; import com.nirima.docker.client.DockerException; import com.nirima.jenkins.plugins.docker.action.DockerLaunchAction; import hudson.model.AbstractBuild; import hudson.model.Describable; import hudson.model.Descriptor; import jenkins.model.Jenkins; import java.io.IOException; import java.io.Serializable; import java.util.List; import java.util.logging.Logger; /** * Created by magnayn on 30/01/2014. */ public abstract class DockerBuilderControlOption implements Describable<DockerBuilderControlOption>, Serializable { protected static final Logger LOGGER = Logger.getLogger(DockerBuilderControl.class.getName()); public abstract void execute(AbstractBuild<?, ?> build) throws DockerException, IOException; protected DockerLaunchAction getLaunchAction(AbstractBuild<?, ?> build) { List<DockerLaunchAction> launchActionList = build.getActions(DockerLaunchAction.class); DockerLaunchAction launchAction; if( launchActionList.size() > 0 ) { launchAction = launchActionList.get(0); } else { launchAction = new DockerLaunchAction(); build.addAction(launchAction); } return launchAction; } public Descriptor<DockerBuilderControlOption> getDescriptor() { return Jenkins.getInstance().getDescriptorOrDie(getClass()); } }
pcas/docker-plugin
src/main/java/com/nirima/jenkins/plugins/docker/builder/DockerBuilderControlOption.java
Java
mit
1,388
var allTestFiles = []; var TEST_REGEXP = /test\.js$/; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { // Normalize paths to RequireJS module names. allTestFiles.push(pathToModule(file)); } }); require.config({ // Karma serves files under /base, which is the basePath from your config file baseUrl: '/base', // example of using shim, to load non AMD libraries (such as underscore and jquery) paths: { 'angular': 'bower_components/angular/angular', 'text': 'bower_components/requirejs-text/text', '_': 'bower_components/underscore/underscore-min' }, shim: { 'angular': { exports: 'angular' }, }, // dynamically load all test files deps: allTestFiles, // we have to kickoff jasmine, as it is asynchronous callback: window.__karma__.start });
Antonio-Lopez/angularjs-requirejs-typescript
app/tests/require-config.js
JavaScript
mit
1,010
/*global blogCategories, $ */ function BlogCategory(blogCategoryElement) { this.element = $vic(blogCategoryElement); if ($vic(blogCategoryElement).data('index')) { this.index = $vic(blogCategoryElement).data('index'); } else { this.index = $vic(blogCategoryElement).children('[data-init="true"]').length; } var lastMaxId = 0; $vic('[data-init=true]').each(function(index, el) { if (!isNaN($vic(el).attr('data-blog-category')) && $vic(el).attr('data-blog-category') > lastMaxId) { lastMaxId = parseInt($vic(el).attr('data-blog-category')); } }); this.id = lastMaxId + 1; this.parentId = $vic(blogCategoryElement).parents('li[role="blogCategory"]').first().data('blog-category'); //get the parent by its id if (this.parentId == null || this.parentId == 0) { this.parent = null; this.parentId = 0; } else { this.parent = blogCategories[this.parentId]; } blogCategories[this.id] = this; } function addBlogCategoryRootItem(el) { var blogCategoryElement = $vic(el).parents('div').first().prev('ul'); // var parentBlogCategory = $vic('#blogCategory-children'); var blogCategory = new BlogCategory(blogCategoryElement); blogCategory.init(); blogCategory.append(); } function addBlogCategoryRow(el) { var blogCategoryElement = $vic(el).parents('span.add_blogCategory_link-container').first().next('ul'); // var parentBlogCategory = $vic(el).parents('[role="blogCategory-item"]').first(); var blogCategory = new BlogCategory(blogCategoryElement); blogCategory.init(); blogCategory.append(); } function deleteBlogCategoryRow(el) { var blogCategory = $vic(el).parents('li[role="blogCategory"]').first(); blogCategories[blogCategory.data('blog-category')] = undefined; blogCategory.remove(); } function initBlogCategories() { var links = $vic('.add_blogCategory_link'); var blogCategory = {id: 0}; //we want the links from the bottom to the top $vic.each(links, function (index, link) { var blogCategoryElement = $vic(link).parents('li[role="blogCategory"]').first(); if (blogCategoryElement.length > 0) { blogCategory = new BlogCategory(blogCategoryElement); blogCategory.update(); } }); //This is exactly the same loop as the one just before //We need to close the previous loop and iterate on a new one because //we operated on the DOM that is updated only when the loop ends. $vic.each(links, function (index, link) { var blogCategoryElement = $vic(link).parents('li[role="blogCategory"]').first(); var blogCategory = blogCategories[blogCategoryElement.attr('data-blog-category')]; var parentBlogCategoryElement = $vic(blogCategoryElement).parents('li[role="blogCategory"]').first(); var parentBlogCategory = blogCategories[parentBlogCategoryElement.attr('data-blog-category')]; if (parentBlogCategory != undefined) { blogCategory.parentId = parentBlogCategory.id; blogCategory.parent = parentBlogCategory; blogCategories[blogCategory.id] = blogCategory; } }); } BlogCategory.prototype.init = function () { var currentBlogCategory = this; var name = '[' + currentBlogCategory.index + ']'; var i = 0; do { i++; if (currentBlogCategory.parent != null) { name = '[' + currentBlogCategory.parent.index + '][children]' + name; } currentBlogCategory = currentBlogCategory.parent; } while (currentBlogCategory != null && i < 10); var newForm = prototype.replace(/\[__name__\]/g, name); var name = name.replace(/\]\[/g, '_'); var name = name.replace(/\]/g, '_'); var name = name.replace(/\[/g, '_'); var newForm = newForm.replace(/__name__/g, name); var newForm = newForm.replace(/__blogCategory_id__/g, this.id); var newForm = newForm.replace(/__blogCategory_index__/g, this.index); this.newForm = $vic.parseHTML(newForm); $vic(this.newForm).attr('data-init', "true"); }; BlogCategory.prototype.update = function () { $vic(this.element).replaceWith(this.element); $vic(this.element).attr('data-blog-category', this.id); $vic(this.element).attr('data-init', "true"); }; BlogCategory.prototype.append = function () { $vic('[data-blog-category="' + this.parentId + '"]').children('[role="blogCategory-container"]').first().append(this.newForm); }; function attachSubmitEventToForm(formSelector, container) { $vic(document).on('submit', formSelector, function(event) { event.preventDefault(); var form = $vic(this); var formData = $vic(form).serializeArray(); formData = $vic.param(formData); if ($vic(form).attr('enctype') == 'multipart/form-data') { var formData = new FormData($vic(form)[0]); var contentType = false; } $vic.ajax({ url : $vic(form).attr('action'), context : document.body, data : formData, type : $vic(form).attr('method'), contentType : 'application/x-www-form-urlencoded; charset=UTF-8', processData : false, async : true, cache : false, success : function(jsonResponse) { if (jsonResponse.hasOwnProperty("url")) { congrat(jsonResponse.message, 10000); window.location.replace(jsonResponse.url); }else{ $vic(container).html(jsonResponse.html); warn(jsonResponse.message, 10000); } } }); }); } attachSubmitEventToForm('#victoire_blog_settings_form', '#victoire-blog-settings'); attachSubmitEventToForm('#victoire_blog_category_form', '#victoire-blog-category');
alexislefebvre/victoire
Bundle/BlogBundle/Resources/public/js/blog.js
JavaScript
mit
5,952
'use strict' const isDirectory = require('is-directory').sync const isFile = require('is-file') function getFarmArgs (args, fileIndex) { const start = 0 const end = fileIndex + 1 return args.slice(start, end) } function getFileArgs (args, fileIndex) { const start = fileIndex + 1 const end = args[args.length] return args.slice(start, end) } function parseArgs (args) { const fileIndex = args.findIndex(arg => isFile(arg) || isDirectory(arg)) return { farm: getFarmArgs(args, fileIndex), file: getFileArgs(args, fileIndex) } } module.exports = parseArgs
Kikobeats/worker-farm-cli
bin/parse-args/index.js
JavaScript
mit
586
using System; namespace IntegrationTests.WebApp.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
pharring/ApplicationInsights-dotnet
NETCORE/test/IntegrationTests.WebApp/Models/ErrorViewModel.cs
C#
mit
221
/** */ package gluemodel.CIM.IEC61970.Informative.InfWork.impl; import gluemodel.CIM.IEC61968.Common.impl.DocumentImpl; import gluemodel.CIM.IEC61968.Work.Work; import gluemodel.CIM.IEC61968.Work.WorkPackage; import gluemodel.CIM.IEC61970.Informative.InfERPSupport.ErpBOM; import gluemodel.CIM.IEC61970.Informative.InfERPSupport.ErpQuoteLineItem; import gluemodel.CIM.IEC61970.Informative.InfERPSupport.InfERPSupportPackage; import gluemodel.CIM.IEC61970.Informative.InfWork.ConditionFactor; import gluemodel.CIM.IEC61970.Informative.InfWork.Design; import gluemodel.CIM.IEC61970.Informative.InfWork.DesignKind; import gluemodel.CIM.IEC61970.Informative.InfWork.DesignLocation; import gluemodel.CIM.IEC61970.Informative.InfWork.DesignLocationCU; import gluemodel.CIM.IEC61970.Informative.InfWork.InfWorkPackage; import gluemodel.CIM.IEC61970.Informative.InfWork.WorkCostDetail; import gluemodel.CIM.IEC61970.Informative.InfWork.WorkTask; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Design</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getCostEstimate <em>Cost Estimate</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getDesignLocations <em>Design Locations</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getDesignLocationsCUs <em>Design Locations CUs</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getWork <em>Work</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getWorkCostDetails <em>Work Cost Details</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getErpBOMs <em>Erp BO Ms</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getErpQuoteLineItem <em>Erp Quote Line Item</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getConditionFactors <em>Condition Factors</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getKind <em>Kind</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getPrice <em>Price</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.InfWork.impl.DesignImpl#getWorkTasks <em>Work Tasks</em>}</li> * </ul> * * @generated */ public class DesignImpl extends DocumentImpl implements Design { /** * The default value of the '{@link #getCostEstimate() <em>Cost Estimate</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCostEstimate() * @generated * @ordered */ protected static final float COST_ESTIMATE_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getCostEstimate() <em>Cost Estimate</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCostEstimate() * @generated * @ordered */ protected float costEstimate = COST_ESTIMATE_EDEFAULT; /** * The cached value of the '{@link #getDesignLocations() <em>Design Locations</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDesignLocations() * @generated * @ordered */ protected EList<DesignLocation> designLocations; /** * The cached value of the '{@link #getDesignLocationsCUs() <em>Design Locations CUs</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDesignLocationsCUs() * @generated * @ordered */ protected EList<DesignLocationCU> designLocationsCUs; /** * The cached value of the '{@link #getWork() <em>Work</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWork() * @generated * @ordered */ protected Work work; /** * The cached value of the '{@link #getWorkCostDetails() <em>Work Cost Details</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWorkCostDetails() * @generated * @ordered */ protected EList<WorkCostDetail> workCostDetails; /** * The cached value of the '{@link #getErpBOMs() <em>Erp BO Ms</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getErpBOMs() * @generated * @ordered */ protected EList<ErpBOM> erpBOMs; /** * The cached value of the '{@link #getErpQuoteLineItem() <em>Erp Quote Line Item</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getErpQuoteLineItem() * @generated * @ordered */ protected ErpQuoteLineItem erpQuoteLineItem; /** * The cached value of the '{@link #getConditionFactors() <em>Condition Factors</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getConditionFactors() * @generated * @ordered */ protected EList<ConditionFactor> conditionFactors; /** * The default value of the '{@link #getKind() <em>Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKind() * @generated * @ordered */ protected static final DesignKind KIND_EDEFAULT = DesignKind.ESTIMATED; /** * The cached value of the '{@link #getKind() <em>Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKind() * @generated * @ordered */ protected DesignKind kind = KIND_EDEFAULT; /** * The default value of the '{@link #getPrice() <em>Price</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPrice() * @generated * @ordered */ protected static final float PRICE_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getPrice() <em>Price</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPrice() * @generated * @ordered */ protected float price = PRICE_EDEFAULT; /** * The cached value of the '{@link #getWorkTasks() <em>Work Tasks</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWorkTasks() * @generated * @ordered */ protected EList<WorkTask> workTasks; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DesignImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return InfWorkPackage.Literals.DESIGN; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getCostEstimate() { return costEstimate; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCostEstimate(float newCostEstimate) { float oldCostEstimate = costEstimate; costEstimate = newCostEstimate; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__COST_ESTIMATE, oldCostEstimate, costEstimate)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DesignLocation> getDesignLocations() { if (designLocations == null) { designLocations = new EObjectWithInverseResolvingEList.ManyInverse<DesignLocation>(DesignLocation.class, this, InfWorkPackage.DESIGN__DESIGN_LOCATIONS, InfWorkPackage.DESIGN_LOCATION__DESIGNS); } return designLocations; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DesignLocationCU> getDesignLocationsCUs() { if (designLocationsCUs == null) { designLocationsCUs = new EObjectWithInverseResolvingEList.ManyInverse<DesignLocationCU>(DesignLocationCU.class, this, InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS, InfWorkPackage.DESIGN_LOCATION_CU__DESIGNS); } return designLocationsCUs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Work getWork() { if (work != null && work.eIsProxy()) { InternalEObject oldWork = (InternalEObject)work; work = (Work)eResolveProxy(oldWork); if (work != oldWork) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, InfWorkPackage.DESIGN__WORK, oldWork, work)); } } return work; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Work basicGetWork() { return work; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetWork(Work newWork, NotificationChain msgs) { Work oldWork = work; work = newWork; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__WORK, oldWork, newWork); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWork(Work newWork) { if (newWork != work) { NotificationChain msgs = null; if (work != null) msgs = ((InternalEObject)work).eInverseRemove(this, WorkPackage.WORK__DESIGNS, Work.class, msgs); if (newWork != null) msgs = ((InternalEObject)newWork).eInverseAdd(this, WorkPackage.WORK__DESIGNS, Work.class, msgs); msgs = basicSetWork(newWork, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__WORK, newWork, newWork)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<WorkCostDetail> getWorkCostDetails() { if (workCostDetails == null) { workCostDetails = new EObjectWithInverseResolvingEList<WorkCostDetail>(WorkCostDetail.class, this, InfWorkPackage.DESIGN__WORK_COST_DETAILS, InfWorkPackage.WORK_COST_DETAIL__DESIGN); } return workCostDetails; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ErpBOM> getErpBOMs() { if (erpBOMs == null) { erpBOMs = new EObjectWithInverseResolvingEList<ErpBOM>(ErpBOM.class, this, InfWorkPackage.DESIGN__ERP_BO_MS, InfERPSupportPackage.ERP_BOM__DESIGN); } return erpBOMs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ErpQuoteLineItem getErpQuoteLineItem() { if (erpQuoteLineItem != null && erpQuoteLineItem.eIsProxy()) { InternalEObject oldErpQuoteLineItem = (InternalEObject)erpQuoteLineItem; erpQuoteLineItem = (ErpQuoteLineItem)eResolveProxy(oldErpQuoteLineItem); if (erpQuoteLineItem != oldErpQuoteLineItem) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM, oldErpQuoteLineItem, erpQuoteLineItem)); } } return erpQuoteLineItem; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ErpQuoteLineItem basicGetErpQuoteLineItem() { return erpQuoteLineItem; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetErpQuoteLineItem(ErpQuoteLineItem newErpQuoteLineItem, NotificationChain msgs) { ErpQuoteLineItem oldErpQuoteLineItem = erpQuoteLineItem; erpQuoteLineItem = newErpQuoteLineItem; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM, oldErpQuoteLineItem, newErpQuoteLineItem); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setErpQuoteLineItem(ErpQuoteLineItem newErpQuoteLineItem) { if (newErpQuoteLineItem != erpQuoteLineItem) { NotificationChain msgs = null; if (erpQuoteLineItem != null) msgs = ((InternalEObject)erpQuoteLineItem).eInverseRemove(this, InfERPSupportPackage.ERP_QUOTE_LINE_ITEM__DESIGN, ErpQuoteLineItem.class, msgs); if (newErpQuoteLineItem != null) msgs = ((InternalEObject)newErpQuoteLineItem).eInverseAdd(this, InfERPSupportPackage.ERP_QUOTE_LINE_ITEM__DESIGN, ErpQuoteLineItem.class, msgs); msgs = basicSetErpQuoteLineItem(newErpQuoteLineItem, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM, newErpQuoteLineItem, newErpQuoteLineItem)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ConditionFactor> getConditionFactors() { if (conditionFactors == null) { conditionFactors = new EObjectWithInverseResolvingEList.ManyInverse<ConditionFactor>(ConditionFactor.class, this, InfWorkPackage.DESIGN__CONDITION_FACTORS, InfWorkPackage.CONDITION_FACTOR__DESIGNS); } return conditionFactors; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DesignKind getKind() { return kind; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setKind(DesignKind newKind) { DesignKind oldKind = kind; kind = newKind == null ? KIND_EDEFAULT : newKind; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__KIND, oldKind, kind)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getPrice() { return price; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPrice(float newPrice) { float oldPrice = price; price = newPrice; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, InfWorkPackage.DESIGN__PRICE, oldPrice, price)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<WorkTask> getWorkTasks() { if (workTasks == null) { workTasks = new EObjectWithInverseResolvingEList<WorkTask>(WorkTask.class, this, InfWorkPackage.DESIGN__WORK_TASKS, InfWorkPackage.WORK_TASK__DESIGN); } return workTasks; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDesignLocations()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDesignLocationsCUs()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN__WORK: if (work != null) msgs = ((InternalEObject)work).eInverseRemove(this, WorkPackage.WORK__DESIGNS, Work.class, msgs); return basicSetWork((Work)otherEnd, msgs); case InfWorkPackage.DESIGN__WORK_COST_DETAILS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getWorkCostDetails()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN__ERP_BO_MS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getErpBOMs()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: if (erpQuoteLineItem != null) msgs = ((InternalEObject)erpQuoteLineItem).eInverseRemove(this, InfERPSupportPackage.ERP_QUOTE_LINE_ITEM__DESIGN, ErpQuoteLineItem.class, msgs); return basicSetErpQuoteLineItem((ErpQuoteLineItem)otherEnd, msgs); case InfWorkPackage.DESIGN__CONDITION_FACTORS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getConditionFactors()).basicAdd(otherEnd, msgs); case InfWorkPackage.DESIGN__WORK_TASKS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getWorkTasks()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: return ((InternalEList<?>)getDesignLocations()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: return ((InternalEList<?>)getDesignLocationsCUs()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN__WORK: return basicSetWork(null, msgs); case InfWorkPackage.DESIGN__WORK_COST_DETAILS: return ((InternalEList<?>)getWorkCostDetails()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN__ERP_BO_MS: return ((InternalEList<?>)getErpBOMs()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: return basicSetErpQuoteLineItem(null, msgs); case InfWorkPackage.DESIGN__CONDITION_FACTORS: return ((InternalEList<?>)getConditionFactors()).basicRemove(otherEnd, msgs); case InfWorkPackage.DESIGN__WORK_TASKS: return ((InternalEList<?>)getWorkTasks()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case InfWorkPackage.DESIGN__COST_ESTIMATE: return getCostEstimate(); case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: return getDesignLocations(); case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: return getDesignLocationsCUs(); case InfWorkPackage.DESIGN__WORK: if (resolve) return getWork(); return basicGetWork(); case InfWorkPackage.DESIGN__WORK_COST_DETAILS: return getWorkCostDetails(); case InfWorkPackage.DESIGN__ERP_BO_MS: return getErpBOMs(); case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: if (resolve) return getErpQuoteLineItem(); return basicGetErpQuoteLineItem(); case InfWorkPackage.DESIGN__CONDITION_FACTORS: return getConditionFactors(); case InfWorkPackage.DESIGN__KIND: return getKind(); case InfWorkPackage.DESIGN__PRICE: return getPrice(); case InfWorkPackage.DESIGN__WORK_TASKS: return getWorkTasks(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case InfWorkPackage.DESIGN__COST_ESTIMATE: setCostEstimate((Float)newValue); return; case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: getDesignLocations().clear(); getDesignLocations().addAll((Collection<? extends DesignLocation>)newValue); return; case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: getDesignLocationsCUs().clear(); getDesignLocationsCUs().addAll((Collection<? extends DesignLocationCU>)newValue); return; case InfWorkPackage.DESIGN__WORK: setWork((Work)newValue); return; case InfWorkPackage.DESIGN__WORK_COST_DETAILS: getWorkCostDetails().clear(); getWorkCostDetails().addAll((Collection<? extends WorkCostDetail>)newValue); return; case InfWorkPackage.DESIGN__ERP_BO_MS: getErpBOMs().clear(); getErpBOMs().addAll((Collection<? extends ErpBOM>)newValue); return; case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: setErpQuoteLineItem((ErpQuoteLineItem)newValue); return; case InfWorkPackage.DESIGN__CONDITION_FACTORS: getConditionFactors().clear(); getConditionFactors().addAll((Collection<? extends ConditionFactor>)newValue); return; case InfWorkPackage.DESIGN__KIND: setKind((DesignKind)newValue); return; case InfWorkPackage.DESIGN__PRICE: setPrice((Float)newValue); return; case InfWorkPackage.DESIGN__WORK_TASKS: getWorkTasks().clear(); getWorkTasks().addAll((Collection<? extends WorkTask>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case InfWorkPackage.DESIGN__COST_ESTIMATE: setCostEstimate(COST_ESTIMATE_EDEFAULT); return; case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: getDesignLocations().clear(); return; case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: getDesignLocationsCUs().clear(); return; case InfWorkPackage.DESIGN__WORK: setWork((Work)null); return; case InfWorkPackage.DESIGN__WORK_COST_DETAILS: getWorkCostDetails().clear(); return; case InfWorkPackage.DESIGN__ERP_BO_MS: getErpBOMs().clear(); return; case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: setErpQuoteLineItem((ErpQuoteLineItem)null); return; case InfWorkPackage.DESIGN__CONDITION_FACTORS: getConditionFactors().clear(); return; case InfWorkPackage.DESIGN__KIND: setKind(KIND_EDEFAULT); return; case InfWorkPackage.DESIGN__PRICE: setPrice(PRICE_EDEFAULT); return; case InfWorkPackage.DESIGN__WORK_TASKS: getWorkTasks().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case InfWorkPackage.DESIGN__COST_ESTIMATE: return costEstimate != COST_ESTIMATE_EDEFAULT; case InfWorkPackage.DESIGN__DESIGN_LOCATIONS: return designLocations != null && !designLocations.isEmpty(); case InfWorkPackage.DESIGN__DESIGN_LOCATIONS_CUS: return designLocationsCUs != null && !designLocationsCUs.isEmpty(); case InfWorkPackage.DESIGN__WORK: return work != null; case InfWorkPackage.DESIGN__WORK_COST_DETAILS: return workCostDetails != null && !workCostDetails.isEmpty(); case InfWorkPackage.DESIGN__ERP_BO_MS: return erpBOMs != null && !erpBOMs.isEmpty(); case InfWorkPackage.DESIGN__ERP_QUOTE_LINE_ITEM: return erpQuoteLineItem != null; case InfWorkPackage.DESIGN__CONDITION_FACTORS: return conditionFactors != null && !conditionFactors.isEmpty(); case InfWorkPackage.DESIGN__KIND: return kind != KIND_EDEFAULT; case InfWorkPackage.DESIGN__PRICE: return price != PRICE_EDEFAULT; case InfWorkPackage.DESIGN__WORK_TASKS: return workTasks != null && !workTasks.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (costEstimate: "); result.append(costEstimate); result.append(", kind: "); result.append(kind); result.append(", price: "); result.append(price); result.append(')'); return result.toString(); } } //DesignImpl
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/InfWork/impl/DesignImpl.java
Java
mit
23,208
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "Backend.h" /* =================================================================================== * TempTracker runs the mark temp algorithm. The template parameter provides information * what are valid temp use, temp transfer, or temp producing operations and what bit to * set once a symbol def can be marked temp. * * NumberTemp mark temp JavascriptNumber creation for math operations, run during deadstore * * ObjectTemp mark temp object allocations, run during backward pass so that it can provide * information to the globopt to install pre op bailout on implicit call while during stack * allocation objects. * * ObjectTempVerify runs a similar mark temp during deadstore in debug mode to assert * that globopt have install the pre op necessary and a marked temp def is still valid * as a mark temp * * The basic of the mark temp algorithm is very simple: we keep track if we have seen * any use of a symbol that is not a valid mark temp (the nonTempSyms bitvector) * and on definition of the symbol, if the all the use allow temp object (not in nonTempSyms * bitvector) then it is mark them able. * * However, the complication comes when the stack object is transferred to another symbol * and we are in a loop. We need to make sure that the stack object isn't still referred * by another symbol when we allocate the number/object in the next iteration * * For example: * Loop top: * s1 = NewScObject * = s6 * s6 = s1 * Goto Loop top * * We cannot mark them this case because when s1 is created, the object might still be * referred to by s6 from previous iteration, and thus if we mark them we would have * change the content of s6 as well. * * To detect this dependency, we conservatively collect "all" transfers in the pre pass * of the loop. We have to be conservative to detect reverse dependencies without * iterating more than 2 times for the loop. * =================================================================================== */ JitArenaAllocator * TempTrackerBase::GetAllocator() const { return nonTempSyms.GetAllocator(); } TempTrackerBase::TempTrackerBase(JitArenaAllocator * alloc, bool inLoop) : nonTempSyms(alloc), tempTransferredSyms(alloc) { if (inLoop) { tempTransferDependencies = HashTable<BVSparse<JitArenaAllocator> *>::New(alloc, 16); } else { tempTransferDependencies = nullptr; } } TempTrackerBase::~TempTrackerBase() { if (this->tempTransferDependencies != nullptr) { JitArenaAllocator * alloc = this->GetAllocator(); FOREACH_HASHTABLE_ENTRY(BVSparse<JitArenaAllocator> *, bucket, this->tempTransferDependencies) { JitAdelete(alloc, bucket.element); } NEXT_HASHTABLE_ENTRY; this->tempTransferDependencies->Delete(); } } void TempTrackerBase::MergeData(TempTrackerBase * fromData, bool deleteData) { this->nonTempSyms.Or(&fromData->nonTempSyms); this->tempTransferredSyms.Or(&fromData->tempTransferredSyms); this->MergeDependencies(this->tempTransferDependencies, fromData->tempTransferDependencies, deleteData); if (this->tempTransferDependencies) { FOREACH_HASHTABLE_ENTRY(BVSparse<JitArenaAllocator> *, bucket, this->tempTransferDependencies) { if (bucket.element->Test(&this->nonTempSyms)) { this->nonTempSyms.Set(bucket.value); } } NEXT_HASHTABLE_ENTRY; } } void TempTrackerBase::AddTransferDependencies(int sourceId, SymID dstSymID, HashTable<BVSparse<JitArenaAllocator> *> * dependencies) { // Add to the transfer dependencies set BVSparse<JitArenaAllocator> ** pBVSparse = dependencies->FindOrInsertNew(sourceId); if (*pBVSparse == nullptr) { *pBVSparse = JitAnew(this->GetAllocator(), BVSparse<JitArenaAllocator>, this->GetAllocator()); } AddTransferDependencies(*pBVSparse, dstSymID); } void TempTrackerBase::AddTransferDependencies(BVSparse<JitArenaAllocator> * bv, SymID dstSymID) { bv->Set(dstSymID); // Add the indirect transfers (always from tempTransferDependencies) BVSparse<JitArenaAllocator> *dstBVSparse = this->tempTransferDependencies->GetAndClear(dstSymID); if (dstBVSparse != nullptr) { bv->Or(dstBVSparse); JitAdelete(this->GetAllocator(), dstBVSparse); } } template <typename T> TempTracker<T>::TempTracker(JitArenaAllocator * alloc, bool inLoop): T(alloc, inLoop) { } template <typename T> void TempTracker<T>::MergeData(TempTracker<T> * fromData, bool deleteData) { TempTrackerBase::MergeData(fromData, deleteData); T::MergeData(fromData, deleteData); if (deleteData) { JitAdelete(this->GetAllocator(), fromData); } } void TempTrackerBase::OrHashTableOfBitVector(HashTable<BVSparse<JitArenaAllocator> *> * toData, HashTable<BVSparse<JitArenaAllocator> *> *& fromData, bool deleteData) { Assert(toData != nullptr); Assert(fromData != nullptr); toData->Or(fromData, [=](BVSparse<JitArenaAllocator> * bv1, BVSparse<JitArenaAllocator> * bv2) -> BVSparse<JitArenaAllocator> * { if (bv1 == nullptr) { if (deleteData) { return bv2; } return bv2->CopyNew(this->GetAllocator()); } bv1->Or(bv2); if (deleteData) { JitAdelete(this->GetAllocator(), bv2); } return bv1; }); if (deleteData) { fromData->Delete(); fromData = nullptr; } } void TempTrackerBase::MergeDependencies(HashTable<BVSparse<JitArenaAllocator> *> * toData, HashTable<BVSparse<JitArenaAllocator> *> *& fromData, bool deleteData) { if (fromData != nullptr) { if (toData != nullptr) { OrHashTableOfBitVector(toData, fromData, deleteData); } else if (deleteData) { FOREACH_HASHTABLE_ENTRY(BVSparse<JitArenaAllocator> *, bucket, fromData) { JitAdelete(this->GetAllocator(), bucket.element); } NEXT_HASHTABLE_ENTRY; fromData->Delete(); fromData = nullptr; } } } #if DBG_DUMP void TempTrackerBase::Dump(char16 const * traceName) { Output::Print(_u("%s: Non temp syms:"), traceName); this->nonTempSyms.Dump(); Output::Print(_u("%s: Temp transferred syms:"), traceName); this->tempTransferredSyms.Dump(); if (this->tempTransferDependencies != nullptr) { Output::Print(_u("%s: Temp transfer dependencies:\n"), traceName); this->tempTransferDependencies->Dump(); } } #endif template <typename T> void TempTracker<T>::ProcessUse(StackSym * sym, BackwardPass * backwardPass) { // Don't care about type specialized syms if (!sym->IsVar()) { return; } IR::Instr * instr = backwardPass->currentInstr; SymID usedSymID = sym->m_id; bool isTempPropertyTransferStore = T::IsTempPropertyTransferStore(instr, backwardPass); bool isTempUse = isTempPropertyTransferStore || T::IsTempUse(instr, sym, backwardPass); if (!isTempUse) { this->nonTempSyms.Set(usedSymID); } #if DBG if (T::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s%4sTemp Use (s%-3d): "), T::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), isTempUse ? _u("") : _u("Non "), usedSymID); instr->DumpSimple(); Output::Flush(); } #endif if (T::IsTempTransfer(instr)) { this->tempTransferredSyms.Set(usedSymID); // Track dependencies if we are in loop only if (this->tempTransferDependencies != nullptr) { IR::Opnd * dstOpnd = instr->GetDst(); if (dstOpnd->IsRegOpnd()) { SymID dstSymID = dstOpnd->AsRegOpnd()->m_sym->m_id; if (dstSymID != usedSymID) { // Record that the usedSymID may propagate to dstSymID and all the symbols // that it may propagate to as well this->AddTransferDependencies(usedSymID, dstSymID, this->tempTransferDependencies); #if DBG_DUMP if (T::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s s%d -> s%d: "), T::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), dstSymID, usedSymID); (*this->tempTransferDependencies->Get(usedSymID))->Dump(); } #endif } } } } if (isTempPropertyTransferStore) { this->tempTransferredSyms.Set(usedSymID); PropertySym * propertySym = instr->GetDst()->AsSymOpnd()->m_sym->AsPropertySym(); this->PropagateTempPropertyTransferStoreDependencies(usedSymID, propertySym, backwardPass); #if DBG_DUMP if (T::DoTrace(backwardPass) && this->tempTransferDependencies) { Output::Print(_u("%s: %8s (PropId:%d)+[] -> s%d: "), T::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), propertySym->m_propertyId, usedSymID); BVSparse<JitArenaAllocator> ** transferDependencies = this->tempTransferDependencies->Get(usedSymID); if (transferDependencies) { (*transferDependencies)->Dump(); } else { Output::Print(_u("[]\n")); } } #endif } }; template <typename T> void TempTracker<T>::DisallowMarkTempAcrossYield(BVSparse<JitArenaAllocator>* bytecodeUpwardExposed) { if (bytecodeUpwardExposed != nullptr) { this->nonTempSyms.Or(bytecodeUpwardExposed); } } template <typename T> void TempTracker<T>::MarkTemp(StackSym * sym, BackwardPass * backwardPass) { // Don't care about type specialized syms Assert(sym->IsVar()); IR::Instr * instr = backwardPass->currentInstr; BOOLEAN nonTemp = this->nonTempSyms.TestAndClear(sym->m_id); BOOLEAN isTempTransferred; BVSparse<JitArenaAllocator> * bvTempTransferDependencies = nullptr; bool const isTransferOperation = T::IsTempTransfer(instr) || T::IsTempPropertyTransferLoad(instr, backwardPass) || T::IsTempIndirTransferLoad(instr, backwardPass); if (this->tempTransferDependencies != nullptr) { // Since we don't iterate "while (!changed)" in loops, we don't have complete accurate dataflow // for loop carried dependencies. So don't clear the dependency transfer info. WOOB:1121525 // Check if this dst is transferred (assigned) to another symbol if (isTransferOperation) { isTempTransferred = this->tempTransferredSyms.Test(sym->m_id); } else { isTempTransferred = this->tempTransferredSyms.TestAndClear(sym->m_id); } // We only need to look at the dependencies if we are in a loop because of the back edge // Also we don't need to if we are in pre pass if (isTempTransferred) { if (!backwardPass->IsPrePass()) { if (isTransferOperation) { // Transfer operation, load but not clear the information BVSparse<JitArenaAllocator> **pBv = this->tempTransferDependencies->Get(sym->m_id); if (pBv) { bvTempTransferDependencies = *pBv; } } else { // Non transfer operation, load and clear the information and the dst value is replaced bvTempTransferDependencies = this->tempTransferDependencies->GetAndClear(sym->m_id); } } else if (!isTransferOperation) { // In pre pass, and not a transfer operation (just an assign). We can clear the dependency info // and not look at it. this->tempTransferDependencies->Clear(sym->m_id); } } } else { isTempTransferred = this->tempTransferredSyms.TestAndClear(sym->m_id); } // Reset the dst is temp bit (we set it optimistically on the loop pre pass) bool dstIsTemp = false; bool dstIsTempTransferred = false; if (nonTemp) { #if DBG_DUMP if (T::DoTrace(backwardPass) && !backwardPass->IsPrePass() && T::CanMarkTemp(instr, backwardPass)) { Output::Print(_u("%s: Not temp (s%-03d):"), T::GetTraceName(), sym->m_id); instr->DumpSimple(); } #endif } else if (backwardPass->IsPrePass()) { // On pre pass, we don't have complete information about whether it is tempable or // not from the back edge. If we already discovered that it is not a temp (above), then // we don't mark it, other wise, assume that it is okay to be tempable and have the // second pass set the bit correctly. The only works on dependency chain that is in order // e.g. // s1 = Add // s2 = s1 // s3 = s2 // The dependencies tracking to catch the case whether the dependency chain is out of order // e.g // s1 = Add // s3 = s2 // s2 = s3 Assert(isTransferOperation == T::IsTempTransfer(instr) || T::IsTempPropertyTransferLoad(instr, backwardPass) || T::IsTempIndirTransferLoad(instr, backwardPass)); if (isTransferOperation) { dstIsTemp = true; } } else if (T::CanMarkTemp(instr, backwardPass)) { dstIsTemp = true; if (isTempTransferred) { // Track whether the dst is transferred or not, and allocate separate stack slot for them // so that another dst will not overrides the value dstIsTempTransferred = true; // The temp is aliased, need to trace if there is another use of the set of aliased // sym that is still live so that we won't mark them this symbol and destroy the value if (bvTempTransferDependencies != nullptr) { // Inside a loop we need to track if any of the reg that we transferred to is still live // s1 = Add // = s2 // s2 = s1 // Since s2 is still live on the next iteration when we reassign s1, making s1 a temp // will cause the value of s2 to change before it's use. // The upwardExposedUses are the live regs, check if it intersect with the set // of dependency or not. #if DBG_DUMP if (T::DoTrace(backwardPass) && Js::Configuration::Global.flags.Verbose) { Output::Print(_u("%s: Loop mark temp check instr:\n"), T::GetTraceName()); instr->DumpSimple(); Output::Print(_u("Transfer dependencies: ")); bvTempTransferDependencies->Dump(); Output::Print(_u("Upward exposed Uses : ")); backwardPass->currentBlock->upwardExposedUses->Dump(); Output::Print(_u("\n")); } #endif BVSparse<JitArenaAllocator> * upwardExposedUses = backwardPass->currentBlock->upwardExposedUses; bool hasExposedDependencies = bvTempTransferDependencies->Test(upwardExposedUses) || T::HasExposedFieldDependencies(bvTempTransferDependencies, backwardPass); if (hasExposedDependencies) { #if DBG_DUMP if (T::DoTrace(backwardPass)) { Output::Print(_u("%s: Not temp (s%-03d): "), T::GetTraceName(), sym->m_id); instr->DumpSimple(); Output::Print(_u(" Transferred exposed uses: ")); JitArenaAllocator tempAllocator(_u("temp"), this->GetAllocator()->GetPageAllocator(), Js::Throw::OutOfMemory); bvTempTransferDependencies->AndNew(upwardExposedUses, &tempAllocator)->Dump(); } #endif dstIsTemp = false; dstIsTempTransferred = false; #if DBG if (IsObjectTempVerify<T>()) { dstIsTemp = ObjectTempVerify::DependencyCheck(instr, bvTempTransferDependencies, backwardPass); } #endif // Only ObjectTmepVerify would do the do anything here. All other returns false } } } } T::SetDstIsTemp(dstIsTemp, dstIsTempTransferred, instr, backwardPass); } NumberTemp::NumberTemp(JitArenaAllocator * alloc, bool inLoop) : TempTrackerBase(alloc, inLoop), elemLoadDependencies(alloc), nonTempElemLoad(false), upwardExposedMarkTempObjectLiveFields(alloc), upwardExposedMarkTempObjectSymsProperties(nullptr) { propertyIdsTempTransferDependencies = inLoop ? HashTable<BVSparse<JitArenaAllocator> *>::New(alloc, 16) : nullptr; } void NumberTemp::MergeData(NumberTemp * fromData, bool deleteData) { nonTempElemLoad = nonTempElemLoad || fromData->nonTempElemLoad; if (!nonTempElemLoad) // Don't bother merging other data if we already have a nonTempElemLoad { if (IsInLoop()) { // in loop elemLoadDependencies.Or(&fromData->elemLoadDependencies); } MergeDependencies(propertyIdsTempTransferDependencies, fromData->propertyIdsTempTransferDependencies, deleteData); if (fromData->upwardExposedMarkTempObjectSymsProperties) { if (upwardExposedMarkTempObjectSymsProperties) { OrHashTableOfBitVector(upwardExposedMarkTempObjectSymsProperties, fromData->upwardExposedMarkTempObjectSymsProperties, deleteData); } else if (deleteData) { upwardExposedMarkTempObjectSymsProperties = fromData->upwardExposedMarkTempObjectSymsProperties; fromData->upwardExposedMarkTempObjectSymsProperties = nullptr; } else { upwardExposedMarkTempObjectSymsProperties = HashTable<BVSparse<JitArenaAllocator> *>::New(this->GetAllocator(), 16); OrHashTableOfBitVector(upwardExposedMarkTempObjectSymsProperties, fromData->upwardExposedMarkTempObjectSymsProperties, deleteData); } } upwardExposedMarkTempObjectLiveFields.Or(&fromData->upwardExposedMarkTempObjectLiveFields); } } bool NumberTemp::IsTempUse(IR::Instr * instr, Sym * sym, BackwardPass * backwardPass) { Js::OpCode opcode = instr->m_opcode; if (OpCodeAttr::NonTempNumberSources(opcode) || (OpCodeAttr::TempNumberTransfer(opcode) && !instr->dstIsTempNumber)) { // For TypedArray stores, we don't store the Var object, so MarkTemp is valid if (opcode != Js::OpCode::StElemI_A || !instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyOptimizedTypedArray()) { // Mark the symbol as non-tempable if the instruction doesn't allow temp sources, // or it is transferred to a non-temp dst return false; } } return true; } bool NumberTemp::IsTempTransfer(IR::Instr * instr) { return OpCodeAttr::TempNumberTransfer(instr->m_opcode); } bool NumberTemp::IsTempProducing(IR::Instr * instr) { Js::OpCode opcode = instr->m_opcode; if (OpCodeAttr::TempNumberProducing(opcode)) { return true; } // Loads from float typedArrays usually require a conversion to Var, which we can MarkTemp. if (opcode == Js::OpCode::LdElemI_A) { const ValueType baseValueType(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType()); if (baseValueType.IsLikelyObject() && (baseValueType.GetObjectType() == ObjectType::Float32Array || baseValueType.GetObjectType() == ObjectType::Float64Array)) { return true; } } return false; } bool NumberTemp::CanMarkTemp(IR::Instr * instr, BackwardPass * backwardPass) { if (IsTempTransfer(instr) || IsTempProducing(instr)) { return true; } // REVIEW: this is added a long time ago, and I am not sure what this is for any more. if (OpCodeAttr::InlineCallInstr(instr->m_opcode)) { return true; } if (NumberTemp::IsTempIndirTransferLoad(instr, backwardPass) || NumberTemp::IsTempPropertyTransferLoad(instr, backwardPass)) { return true; } // the opcode is not temp producing or a transfer, this is not a tmp // Also mark calls which may get inlined. return false; } void NumberTemp::ProcessInstr(IR::Instr * instr, BackwardPass * backwardPass) { #if DBG if (instr->m_opcode == Js::OpCode::BailOnNoProfile) { // If we see BailOnNoProfile, we shouldn't have any successor to have any non temp syms Assert(!this->nonTempElemLoad); Assert(this->nonTempSyms.IsEmpty()); Assert(this->tempTransferredSyms.IsEmpty()); Assert(this->elemLoadDependencies.IsEmpty()); Assert(this->upwardExposedMarkTempObjectLiveFields.IsEmpty()); } #endif // We don't get to process all dst in MarkTemp. Do it here for the upwardExposedMarkTempObjectLiveFields if (!this->DoMarkTempNumbersOnTempObjects(backwardPass)) { return; } IR::Opnd * dst = instr->GetDst(); if (dst == nullptr || !dst->IsRegOpnd()) { return; } StackSym * dstSym = dst->AsRegOpnd()->m_sym; if (!dstSym->IsVar()) { dstSym = dstSym->GetVarEquivSym(nullptr); if (dstSym == nullptr) { return; } } SymID dstSymId = dstSym->m_id; if (this->upwardExposedMarkTempObjectSymsProperties) { // We are assigning to dstSym, it no longer has upward exposed use, get the information and clear it from the hash table BVSparse<JitArenaAllocator> * dstBv = this->upwardExposedMarkTempObjectSymsProperties->GetAndClear(dstSymId); if (dstBv) { // Clear the upward exposed live fields of all the property sym id associated to dstSym this->upwardExposedMarkTempObjectLiveFields.Minus(dstBv); if (ObjectTemp::IsTempTransfer(instr) && instr->GetSrc1()->IsRegOpnd()) { // If it is transfer, copy the dst info to the src SymID srcStackSymId = instr->GetSrc1()->AsRegOpnd()->m_sym->AsStackSym()->m_id; SymTable * symTable = backwardPass->func->m_symTable; FOREACH_BITSET_IN_SPARSEBV(index, dstBv) { PropertySym * propertySym = symTable->FindPropertySym(srcStackSymId, index); if (propertySym) { this->upwardExposedMarkTempObjectLiveFields.Set(propertySym->m_id); } } NEXT_BITSET_IN_SPARSEBV; BVSparse<JitArenaAllocator> ** srcBv = this->upwardExposedMarkTempObjectSymsProperties->FindOrInsert(dstBv, srcStackSymId); if (srcBv) { (*srcBv)->Or(dstBv); JitAdelete(this->GetAllocator(), dstBv); } } else { JitAdelete(this->GetAllocator(), dstBv); } } } } void NumberTemp::SetDstIsTemp(bool dstIsTemp, bool dstIsTempTransferred, IR::Instr * instr, BackwardPass * backwardPass) { Assert(dstIsTemp || !dstIsTempTransferred); Assert(!instr->dstIsTempNumberTransferred); instr->dstIsTempNumber = dstIsTemp; instr->dstIsTempNumberTransferred = dstIsTempTransferred; #if DBG_DUMP if (!backwardPass->IsPrePass() && IsTempProducing(instr)) { backwardPass->numMarkTempNumber += dstIsTemp; backwardPass->numMarkTempNumberTransferred += dstIsTempTransferred; } #endif } bool NumberTemp::IsTempPropertyTransferLoad(IR::Instr * instr, BackwardPass * backwardPass) { if (DoMarkTempNumbersOnTempObjects(backwardPass)) { switch (instr->m_opcode) { case Js::OpCode::LdFld: case Js::OpCode::LdFldForTypeOf: case Js::OpCode::LdMethodFld: case Js::OpCode::LdFldForCallApplyTarget: case Js::OpCode::LdMethodFromFlags: { // Only care about load from possible stack allocated object. return instr->GetSrc1()->CanStoreTemp(); } }; // All other opcode shouldn't have sym opnd that can store temp, See ObjectTemp::IsTempUseOpCodeSym. Assert(instr->GetSrc1() == nullptr || instr->GetDst() == nullptr // this isn't a value loading instruction || instr->GetSrc1()->IsIndirOpnd() // this is detected in IsTempIndirTransferLoad || !instr->GetSrc1()->CanStoreTemp()); } return false; } bool NumberTemp::IsTempPropertyTransferStore(IR::Instr * instr, BackwardPass * backwardPass) { if (DoMarkTempNumbersOnTempObjects(backwardPass)) { switch (instr->m_opcode) { case Js::OpCode::InitFld: case Js::OpCode::StFld: case Js::OpCode::StFldStrict: { IR::Opnd * dst = instr->GetDst(); Assert(dst->IsSymOpnd()); if (!dst->CanStoreTemp()) { return false; } // We don't mark temp store of numeric properties (e.g. object literal { 86: foo }); // This should only happen for InitFld, as StFld should have changed to StElem PropertySym *propertySym = dst->AsSymOpnd()->m_sym->AsPropertySym(); SymID propertySymId = this->GetRepresentativePropertySymId(propertySym, backwardPass); return !this->nonTempSyms.Test(propertySymId) && !instr->m_func->GetThreadContextInfo()->IsNumericProperty(propertySym->m_propertyId); } }; // All other opcode shouldn't have sym opnd that can store temp, see ObjectTemp::IsTempUseOpCodeSym. // We also never mark the dst indir as can store temp for StElemI_A because we don't know what property // it is storing in (or it could be an array index). Assert(instr->GetDst() == nullptr || !instr->GetDst()->CanStoreTemp()); } return false; } bool NumberTemp::IsTempIndirTransferLoad(IR::Instr * instr, BackwardPass * backwardPass) { if (DoMarkTempNumbersOnTempObjects(backwardPass)) { if (instr->m_opcode == Js::OpCode::LdElemI_A) { // If the index is an int, then we don't care about the non-temp use IR::Opnd * src1Opnd = instr->GetSrc1(); IR::RegOpnd * indexOpnd = src1Opnd->AsIndirOpnd()->GetIndexOpnd(); if (indexOpnd && (indexOpnd->m_sym->m_isNotNumber || !indexOpnd->GetValueType().IsInt())) { return src1Opnd->CanStoreTemp(); } } else { // All other opcode shouldn't have sym opnd that can store temp, See ObjectTemp::IsTempUseOpCodeSym. Assert(instr->GetSrc1() == nullptr || instr->GetSrc1()->IsSymOpnd() || !instr->GetSrc1()->CanStoreTemp()); } } return false; } void NumberTemp::PropagateTempPropertyTransferStoreDependencies(SymID usedSymID, PropertySym * propertySym, BackwardPass * backwardPass) { Assert(!this->nonTempElemLoad); upwardExposedMarkTempObjectLiveFields.Clear(propertySym->m_id); if (!this->IsInLoop()) { // Don't need to track dependencies outside of loop, as we already marked the // use as temp transfer already and we won't have a case where the "dst" is reused again (outside of loop) return; } Assert(this->tempTransferDependencies != nullptr); SymID dstSymID = this->GetRepresentativePropertySymId(propertySym, backwardPass); AddTransferDependencies(usedSymID, dstSymID, this->tempTransferDependencies); Js::PropertyId storedPropertyId = propertySym->m_propertyId; // The symbol this properties are transferred to BVSparse<JitArenaAllocator> ** pPropertyTransferDependencies = this->propertyIdsTempTransferDependencies->Get(storedPropertyId); BVSparse<JitArenaAllocator> * transferDependencies = nullptr; if (pPropertyTransferDependencies == nullptr) { if (elemLoadDependencies.IsEmpty()) { // No dependencies to transfer return; } transferDependencies = &elemLoadDependencies; } else { transferDependencies = *pPropertyTransferDependencies; } BVSparse<JitArenaAllocator> ** pBVSparse = this->tempTransferDependencies->FindOrInsertNew(usedSymID); if (*pBVSparse == nullptr) { *pBVSparse = transferDependencies->CopyNew(this->GetAllocator()); } else { (*pBVSparse)->Or(transferDependencies); } if (transferDependencies != &elemLoadDependencies) { // Always include the element load dependencies as well (*pBVSparse)->Or(&elemLoadDependencies); } // Track the propertySym as well for the case where the dependence is not carried by the use // Loop1 // o.x = e // Loop2 // f = o.x // = f // e = e + blah // Here, although we can detect that e and f has dependent relationship, f's life time doesn't cross with e's. // But o.x will keep the value of e alive, so e can't be mark temp because o.x is still in use (not f) // We will add the property sym int he dependency set and check with the upward exposed mark temp object live fields // that we keep track of in NumberTemp (*pBVSparse)->Set(propertySym->m_id); } SymID NumberTemp::GetRepresentativePropertySymId(PropertySym * propertySym, BackwardPass * backwardPass) { // Since we don't track alias with objects, all property accesses are all grouped together. // Use a single property sym id to represent a propertyId to track dependencies. SymID symId = SymID_Invalid; Js::PropertyId propertyId = propertySym->m_propertyId; if (!backwardPass->numberTempRepresentativePropertySym->TryGetValue(propertyId, &symId)) { symId = propertySym->m_id; backwardPass->numberTempRepresentativePropertySym->Add(propertyId, symId); } return symId; } void NumberTemp::ProcessIndirUse(IR::IndirOpnd * indirOpnd, IR::Instr * instr, BackwardPass * backwardPass) { Assert(backwardPass->DoMarkTempNumbersOnTempObjects()); if (!NumberTemp::IsTempIndirTransferLoad(instr, backwardPass)) { return; } bool isTempUse = instr->dstIsTempNumber; if (!isTempUse) { nonTempElemLoad = true; } else if (this->IsInLoop()) { // We didn't already detect non temp use of this property id. so we should track the dependencies in loops IR::Opnd * dstOpnd = instr->GetDst(); Assert(dstOpnd->IsRegOpnd()); SymID dstSymID = dstOpnd->AsRegOpnd()->m_sym->m_id; // Use the no property id as a place holder for elem dependencies AddTransferDependencies(&elemLoadDependencies, dstSymID); #if DBG_DUMP if (NumberTemp::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s s%d -> []: "), NumberTemp::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), dstSymID); elemLoadDependencies.Dump(); } #endif } #if DBG_DUMP if (NumberTemp::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s%4sTemp Use ([] )"), NumberTemp::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), isTempUse ? _u("") : _u("Non ")); instr->DumpSimple(); } #endif } void NumberTemp::ProcessPropertySymUse(IR::SymOpnd * symOpnd, IR::Instr * instr, BackwardPass * backwardPass) { Assert(backwardPass->DoMarkTempNumbersOnTempObjects()); // We only care about instruction that may transfer the property value if (!NumberTemp::IsTempPropertyTransferLoad(instr, backwardPass)) { return; } PropertySym * propertySym = symOpnd->m_sym->AsPropertySym(); upwardExposedMarkTempObjectLiveFields.Set(propertySym->m_id); if (upwardExposedMarkTempObjectSymsProperties == nullptr) { upwardExposedMarkTempObjectSymsProperties = HashTable<BVSparse<JitArenaAllocator> *>::New(this->GetAllocator(), 16); } BVSparse<JitArenaAllocator> ** bv = upwardExposedMarkTempObjectSymsProperties->FindOrInsertNew(propertySym->m_stackSym->m_id); if (*bv == nullptr) { *bv = JitAnew(this->GetAllocator(), BVSparse<JitArenaAllocator>, this->GetAllocator()); } (*bv)->Set(propertySym->m_propertyId); SymID propertySymId = this->GetRepresentativePropertySymId(propertySym, backwardPass); bool isTempUse = instr->dstIsTempNumber; if (!isTempUse) { // Use of the value is non temp, track the property ID's property representative sym so we don't mark temp // assignment to this property on stack objects. this->nonTempSyms.Set(propertySymId); } else if (this->IsInLoop() && !this->nonTempSyms.Test(propertySymId)) { // We didn't already detect non temp use of this property id. so we should track the dependencies in loops IR::Opnd * dstOpnd = instr->GetDst(); Assert(dstOpnd->IsRegOpnd()); SymID dstSymID = dstOpnd->AsRegOpnd()->m_sym->m_id; AddTransferDependencies(propertySym->m_propertyId, dstSymID, this->propertyIdsTempTransferDependencies); #if DBG_DUMP if (NumberTemp::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s s%d -> PropId:%d: "), NumberTemp::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), dstSymID, propertySym->m_propertyId); (*this->propertyIdsTempTransferDependencies->Get(propertySym->m_propertyId))->Dump(); } #endif } #if DBG_DUMP if (NumberTemp::DoTrace(backwardPass)) { Output::Print(_u("%s: %8s%4sTemp Use (PropId:%d)"), NumberTemp::GetTraceName(), backwardPass->IsPrePass() ? _u("Prepass ") : _u(""), isTempUse ? _u("") : _u("Non "), propertySym->m_propertyId); instr->DumpSimple(); } #endif } bool NumberTemp::HasExposedFieldDependencies(BVSparse<JitArenaAllocator> * bvTempTransferDependencies, BackwardPass * backwardPass) { if (!DoMarkTempNumbersOnTempObjects(backwardPass)) { return false; } return bvTempTransferDependencies->Test(&upwardExposedMarkTempObjectLiveFields); } bool NumberTemp::DoMarkTempNumbersOnTempObjects(BackwardPass * backwardPass) const { return backwardPass->DoMarkTempNumbersOnTempObjects() && !this->nonTempElemLoad; } #if DBG void NumberTemp::Dump(char16 const * traceName) { if (nonTempElemLoad) { Output::Print(_u("%s: Has Non Temp Elem Load\n"), traceName); } else { Output::Print(_u("%s: Non Temp Syms"), traceName); this->nonTempSyms.Dump(); if (this->propertyIdsTempTransferDependencies != nullptr) { Output::Print(_u("%s: Temp transfer propertyId dependencies:\n"), traceName); this->propertyIdsTempTransferDependencies->Dump(); } } } #endif //================================================================================================= // ObjectTemp //================================================================================================= bool ObjectTemp::IsTempUse(IR::Instr * instr, Sym * sym, BackwardPass * backwardPass) { Js::OpCode opcode = instr->m_opcode; // If the opcode has implicit call and the profile say we have implicit call, then it is not a temp use // TODO: More precise implicit call tracking if (instr->HasAnyImplicitCalls() && ((backwardPass->currentBlock->loop != nullptr ? !GlobOpt::ImplicitCallFlagsAllowOpts(backwardPass->currentBlock->loop) : !GlobOpt::ImplicitCallFlagsAllowOpts(backwardPass->func)) || instr->CallsAccessor()) ) { return false; } return IsTempUseOpCodeSym(instr, opcode, sym); } bool ObjectTemp::IsTempUseOpCodeSym(IR::Instr * instr, Js::OpCode opcode, Sym * sym) { // Special case ArgOut_A which communicate information about CallDirect switch (opcode) { case Js::OpCode::ArgOut_A: return instr->dstIsTempObject; case Js::OpCode::LdLen_A: if (instr->GetSrc1()->IsRegOpnd()) { return instr->GetSrc1()->AsRegOpnd()->GetStackSym() == sym; } // fall through case Js::OpCode::LdFld: case Js::OpCode::LdFldForTypeOf: case Js::OpCode::LdMethodFld: case Js::OpCode::LdFldForCallApplyTarget: case Js::OpCode::LdMethodFromFlags: return instr->GetSrc1()->AsPropertySymOpnd()->GetObjectSym() == sym; case Js::OpCode::InitFld: if (Js::PropertyRecord::DefaultAttributesForPropertyId( instr->GetDst()->AsPropertySymOpnd()->GetPropertySym()->m_propertyId, true) & PropertyDeleted) { // If the property record is marked PropertyDeleted, the InitFld will cause a type handler conversion, // which may result in creation of a weak reference to the object itself. return false; } // Fall through case Js::OpCode::StFld: case Js::OpCode::StFldStrict: return !(instr->GetSrc1() && instr->GetSrc1()->GetStackSym() == sym) && !(instr->GetSrc2() && instr->GetSrc2()->GetStackSym() == sym) && instr->GetDst()->AsPropertySymOpnd()->GetObjectSym() == sym; case Js::OpCode::LdElemI_A: return instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym == sym; case Js::OpCode::StElemI_A: case Js::OpCode::StElemI_A_Strict: return instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->m_sym == sym && instr->GetSrc1()->GetStackSym() != sym; case Js::OpCode::Memset: return instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->m_sym == sym || (instr->GetSrc1()->IsRegOpnd() && instr->GetSrc1()->AsRegOpnd()->m_sym == sym); case Js::OpCode::Memcopy: return instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->m_sym == sym || instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym == sym; // Special case FromVar for now until we can allow CallsValueOf opcode to be accept temp use case Js::OpCode::FromVar: return true; } // TODO: Currently, when we disable implicit call, we still don't allow valueOf/toString that has no side effects // So we shouldn't mark them if we have use of the sym on opcode that does OpndHasImplicitCall yet. if (OpCodeAttr::OpndHasImplicitCall(opcode)) { return false; } // Mark the symbol as non-tempable if the instruction doesn't allow temp sources, // or it is transferred to a non-temp dst return (OpCodeAttr::TempObjectSources(opcode) && (!OpCodeAttr::TempObjectTransfer(opcode) || instr->dstIsTempObject)); } bool ObjectTemp::IsTempTransfer(IR::Instr * instr) { return OpCodeAttr::TempObjectTransfer(instr->m_opcode); } bool ObjectTemp::IsTempProducing(IR::Instr * instr) { Js::OpCode opcode = instr->m_opcode; if (OpCodeAttr::TempObjectProducing(opcode)) { if (instr->m_opcode == Js::OpCode::CallDirect) { IR::HelperCallOpnd* helper = instr->GetSrc1()->AsHelperCallOpnd(); return HelperMethodAttributes::TempObjectProducing(helper->m_fnHelper); } else { return true; } } // TODO: Process NewScObject and CallI with isCtorCall when the ctor is fixed return false; } bool ObjectTemp::CanStoreTemp(IR::Instr * instr) { // In order to allow storing temp number on temp objects, // We have to make sure that if the instr is marked as dstIsTempObject // we will always generate the code to allocate the object on the stack (so no helper call). // Currently, we only do this for NewRegEx, NewScObjectSimple, NewScObjectLiteral and // NewScObjectNoCtor (where the ctor is inlined). // CONSIDER: review lowering of other TempObjectProducing opcode and see if we can always allocate on the stack // (for example, NewScArray should be able to, but plain NewScObject can't because the size depends on the // number inline slots) Js::OpCode opcode = instr->m_opcode; if (OpCodeAttr::TempObjectCanStoreTemp(opcode)) { // Special cases where stack allocation doesn't happen #if ENABLE_REGEX_CONFIG_OPTIONS if (opcode == Js::OpCode::NewRegEx && REGEX_CONFIG_FLAG(RegexTracing)) { return false; } #endif if (opcode == Js::OpCode::NewScObjectNoCtor) { if (PHASE_OFF(Js::FixedNewObjPhase, instr->m_func) && PHASE_OFF(Js::ObjTypeSpecNewObjPhase, instr->m_func->GetTopFunc())) { return false; } // Only if we have BailOutFailedCtorGuardCheck would we generate a stack object. // Otherwise we will call the helper, which will not generate stack object. return instr->HasBailOutInfo(); } return true; } return false; } bool ObjectTemp::CanMarkTemp(IR::Instr * instr, BackwardPass * backwardPass) { // We mark the ArgOut with the call in ProcessInstr, no need to do it here return IsTempProducing(instr) || IsTempTransfer(instr); } void ObjectTemp::ProcessBailOnNoProfile(IR::Instr * instr) { Assert(instr->m_opcode == Js::OpCode::BailOnNoProfile); // ObjectTemp is done during Backward pass, which hasn't change all succ to BailOnNoProfile // to dead yet, so we need to manually clear all the information this->nonTempSyms.ClearAll(); this->tempTransferredSyms.ClearAll(); if (this->tempTransferDependencies) { this->tempTransferDependencies->ClearAll(); } } void ObjectTemp::ProcessInstr(IR::Instr * instr) { if (instr->m_opcode != Js::OpCode::CallDirect) { return; } IR::HelperCallOpnd * helper = instr->GetSrc1()->AsHelperCallOpnd(); switch (helper->m_fnHelper) { case IR::JnHelperMethod::HelperString_Match: case IR::JnHelperMethod::HelperString_Replace: { // First (non-this) parameter is either a regexp or search string. // It doesn't escape. IR::Instr * instrArgDef = nullptr; instr->FindCallArgumentOpnd(2, &instrArgDef); instrArgDef->dstIsTempObject = true; break; } case IR::JnHelperMethod::HelperRegExp_Exec: { IR::Instr * instrArgDef = nullptr; instr->FindCallArgumentOpnd(1, &instrArgDef); instrArgDef->dstIsTempObject = true; break; } }; } void ObjectTemp::SetDstIsTemp(bool dstIsTemp, bool dstIsTempTransferred, IR::Instr * instr, BackwardPass * backwardPass) { Assert(dstIsTemp || !dstIsTempTransferred); // ArgOut_A are marked by CallDirect and don't need to be set if (instr->m_opcode == Js::OpCode::ArgOut_A) { return; } instr->dstIsTempObject = dstIsTemp; if (!backwardPass->IsPrePass()) { if (OpCodeAttr::TempObjectProducing(instr->m_opcode)) { backwardPass->func->SetHasMarkTempObjects(); #if DBG_DUMP backwardPass->numMarkTempObject += dstIsTemp; #endif } } } StackSym * ObjectTemp::GetStackSym(IR::Opnd * opnd, IR::PropertySymOpnd ** pPropertySymOpnd) { StackSym * stackSym = nullptr; switch (opnd->GetKind()) { case IR::OpndKindReg: stackSym = opnd->AsRegOpnd()->m_sym; break; case IR::OpndKindSym: { IR::SymOpnd * symOpnd = opnd->AsSymOpnd(); if (symOpnd->IsPropertySymOpnd()) { IR::PropertySymOpnd * propertySymOpnd = symOpnd->AsPropertySymOpnd(); *pPropertySymOpnd = propertySymOpnd; stackSym = propertySymOpnd->GetObjectSym(); } else if (symOpnd->m_sym->IsPropertySym()) { stackSym = symOpnd->m_sym->AsPropertySym()->m_stackSym; } break; } case IR::OpndKindIndir: stackSym = opnd->AsIndirOpnd()->GetBaseOpnd()->m_sym; break; case IR::OpndKindList: Assert(UNREACHED); break; }; return stackSym; } #if DBG //================================================================================================= // ObjectTempVerify //================================================================================================= ObjectTempVerify::ObjectTempVerify(JitArenaAllocator * alloc, bool inLoop) : TempTrackerBase(alloc, inLoop), removedUpwardExposedUse(alloc) { } bool ObjectTempVerify::IsTempUse(IR::Instr * instr, Sym * sym, BackwardPass * backwardPass) { Js::OpCode opcode = instr->m_opcode; // If the opcode has implicit call and the profile say we have implicit call, then it is not a temp use. // TODO: More precise implicit call tracking bool isLandingPad = backwardPass->currentBlock->IsLandingPad(); if (OpCodeAttr::HasImplicitCall(opcode) && !isLandingPad && ((backwardPass->currentBlock->loop != nullptr ? !GlobOpt::ImplicitCallFlagsAllowOpts(backwardPass->currentBlock->loop) : !GlobOpt::ImplicitCallFlagsAllowOpts(backwardPass->func)) || instr->CallsAccessor()) ) { return false; } if (!ObjectTemp::IsTempUseOpCodeSym(instr, opcode, sym)) { // the opcode and sym is not a temp use, just return return false; } // In the backward pass, this would have been a temp use already. Continue to verify // if we have install sufficient bailout on implicit call if (isLandingPad || !GlobOpt::MayNeedBailOnImplicitCall(instr, nullptr, nullptr)) { // Implicit call would not happen, or we are in the landing pad where implicit call is disabled. return true; } if (instr->HasBailOutInfo()) { // make sure we have mark the bailout for mark temp object, // so that we won't optimize it away in DeadStoreImplicitCalls return ((instr->GetBailOutKind() & IR::BailOutMarkTempObject) != 0); } // Review (ObjTypeSpec): This is a bit conservative now that we don't revert from obj type specialized operations to live cache // access even if the operation is isolated. Once we decide a given instruction is an object type spec candidate, we know it // will never need an implicit call, so we could basically do opnd->IsObjTypeSpecOptimized() here, instead. if (GlobOpt::IsTypeCheckProtected(instr)) { return true; } return false; } bool ObjectTempVerify::IsTempTransfer(IR::Instr * instr) { if (ObjectTemp::IsTempTransfer(instr) // Add the Ld_I4, and LdC_A_I4 as the forward pass might have changed Ld_A to these || instr->m_opcode == Js::OpCode::Ld_I4 || instr->m_opcode == Js::OpCode::LdC_A_I4) { if (!instr->dstIsTempObject && instr->GetDst() && instr->GetDst()->IsRegOpnd() && instr->GetDst()->AsRegOpnd()->GetValueType().IsNotObject()) { // Globopt has proved that dst is not an object, so this is not really an object transfer. // This prevents the case where glob opt turned a Conv_Num to Ld_A and expose additional // transfer. return false; } return true; } return false; } bool ObjectTempVerify::CanMarkTemp(IR::Instr * instr, BackwardPass * backwardPass) { // We mark the ArgOut with the call in ProcessInstr, no need to do it here return ObjectTemp::IsTempProducing(instr) || IsTempTransfer(instr); } void ObjectTempVerify::ProcessInstr(IR::Instr * instr, BackwardPass * backwardPass) { if (instr->m_opcode == Js::OpCode::InlineThrow) { // We cannot accurately track mark temp for any upward exposed symbol here this->removedUpwardExposedUse.Or(backwardPass->currentBlock->byteCodeUpwardExposedUsed); return; } if (instr->m_opcode != Js::OpCode::CallDirect) { return; } IR::HelperCallOpnd * helper = instr->GetSrc1()->AsHelperCallOpnd(); switch (helper->m_fnHelper) { case IR::JnHelperMethod::HelperString_Match: case IR::JnHelperMethod::HelperString_Replace: { // First (non-this) parameter is either a regexp or search string // It doesn't escape IR::Instr * instrArgDef; instr->FindCallArgumentOpnd(2, &instrArgDef); Assert(instrArgDef->dstIsTempObject); break; } case IR::JnHelperMethod::HelperRegExp_Exec: { IR::Instr * instrArgDef; instr->FindCallArgumentOpnd(1, &instrArgDef); Assert(instrArgDef->dstIsTempObject); break; } }; } void ObjectTempVerify::SetDstIsTemp(bool dstIsTemp, bool dstIsTempTransferred, IR::Instr * instr, BackwardPass * backwardPass) { Assert(dstIsTemp || !dstIsTempTransferred); // ArgOut_A are marked by CallDirect and don't need to be set if (instr->m_opcode == Js::OpCode::ArgOut_A) { return; } if (OpCodeAttr::TempObjectProducing(instr->m_opcode)) { if (!backwardPass->IsPrePass()) { if (dstIsTemp) { // Don't assert if we have detected a removed upward exposed use that could // expose a new mark temp object. Don't assert if it is set in removedUpwardExposedUse bool isBailOnNoProfileUpwardExposedUse = !!this->removedUpwardExposedUse.Test(instr->GetDst()->AsRegOpnd()->m_sym->m_id); #if DBG if (DoTrace(backwardPass) && !instr->dstIsTempObject && !isBailOnNoProfileUpwardExposedUse) { Output::Print(_u("%s: Missed Mark Temp Object: "), GetTraceName()); instr->DumpSimple(); Output::Flush(); } #endif // TODO: Unfortunately we still hit this a lot as we are not accounting for some of the globopt changes // to the IR. It is just reporting that we have missed mark temp object opportunity, so it doesn't // indicate a functional failure. Disable for now. // Assert(instr->dstIsTempObject || isBailOnNoProfileUpwardExposedUse); } else { // If we have marked the dst is temp in the backward pass, the globopt // should have maintained it, and it will be wrong to have detect that it is not // temp now in the deadstore pass (whether there is BailOnNoProfile or not) #if DBG if (DoTrace(backwardPass) && instr->dstIsTempObject) { Output::Print(_u("%s: Invalid Mark Temp Object: "), GetTraceName()); instr->DumpSimple(); Output::Flush(); } #endif // In a generator function, we don't allow marking temp across yields. Since this assert makes // sure that all instructions whose destinations produce temps are marked, it is not // applicable for generators Assert(instr->m_func->GetJITFunctionBody()->IsCoroutine() || !instr->dstIsTempObject); } } } else if (IsTempTransfer(instr)) { // Only set the transfer instr->dstIsTempObject = dstIsTemp; } else { Assert(!dstIsTemp); Assert(!instr->dstIsTempObject); } // clear or transfer the bailOnNoProfile upward exposed use if (this->removedUpwardExposedUse.TestAndClear(instr->GetDst()->AsRegOpnd()->m_sym->m_id) && IsTempTransfer(instr) && instr->GetSrc1()->IsRegOpnd()) { this->removedUpwardExposedUse.Set(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id); } } void ObjectTempVerify::MergeData(ObjectTempVerify * fromData, bool deleteData) { this->removedUpwardExposedUse.Or(&fromData->removedUpwardExposedUse); } void ObjectTempVerify::MergeDeadData(BasicBlock * block) { MergeData(block->tempObjectVerifyTracker, false); if (!block->isDead) { // If there was dead flow to a block that is not dead, it might expose // new mark temp object, so all its current used (upwardExposedUsed) and optimized // use (byteCodeupwardExposedUsed) might not be trace for "missed" mark temp object this->removedUpwardExposedUse.Or(block->upwardExposedUses); if (block->byteCodeUpwardExposedUsed) { this->removedUpwardExposedUse.Or(block->byteCodeUpwardExposedUsed); } } } void ObjectTempVerify::NotifyBailOutRemoval(IR:: Instr * instr, BackwardPass * backwardPass) { Js::OpCode opcode = instr->m_opcode; switch (opcode) { case Js::OpCode::LdFld: case Js::OpCode::LdFldForTypeOf: case Js::OpCode::LdMethodFld: ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(instr->GetSrc1()->AsPropertySymOpnd()->GetObjectSym(), backwardPass); break; case Js::OpCode::InitFld: case Js::OpCode::StFld: case Js::OpCode::StFldStrict: ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(instr->GetDst()->AsPropertySymOpnd()->GetObjectSym(), backwardPass); break; case Js::OpCode::LdElemI_A: ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym, backwardPass); break; case Js::OpCode::StElemI_A: ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->m_sym, backwardPass); break; } } void ObjectTempVerify::NotifyReverseCopyProp(IR::Instr * instr) { Assert(instr->GetDst()); SymID symId = instr->GetDst()->AsRegOpnd()->m_sym->m_id; this->removedUpwardExposedUse.Clear(symId); this->nonTempSyms.Clear(symId); } void ObjectTempVerify::NotifyDeadStore(IR::Instr * instr, BackwardPass * backwardPass) { // Even if we dead store, simulate the uses IR::Opnd * src1 = instr->GetSrc1(); if (src1) { IR::PropertySymOpnd * propertySymOpnd; StackSym * stackSym = ObjectTemp::GetStackSym(src1, &propertySymOpnd); if (stackSym) { ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(stackSym, backwardPass); } IR::Opnd * src2 = instr->GetSrc2(); if (src2) { stackSym = ObjectTemp::GetStackSym(src2, &propertySymOpnd); if (stackSym) { ((TempTracker<ObjectTempVerify> *)this)->ProcessUse(stackSym, backwardPass); } } } } void ObjectTempVerify::NotifyDeadByteCodeUses(IR::Instr * instr) { if (instr->GetDst()) { SymID symId = instr->GetDst()->AsRegOpnd()->m_sym->m_id; this->removedUpwardExposedUse.Clear(symId); this->nonTempSyms.Clear(symId); } IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr(); const BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = byteCodeUsesInstr->GetByteCodeUpwardExposedUsed(); if (byteCodeUpwardExposedUsed != nullptr) { this->removedUpwardExposedUse.Or(byteCodeUpwardExposedUsed); } } bool ObjectTempVerify::DependencyCheck(IR::Instr * instr, BVSparse<JitArenaAllocator> * bvTempTransferDependencies, BackwardPass * backwardPass) { if (!instr->dstIsTempObject) { // The instruction is not marked as temp object anyway, no need to do extra check return false; } // Since our algorithm is conservative, there are cases where even though two defs are unrelated, the use will still // seem like overlapping and not mark-temp-able // For example: // = s6.blah // s1 = LdRootFld // s6 = s1 // s1 = NewScObject // s1 is dependent of s6, and s6 is upward exposed. // = s6.blah // s6 = s1 // Here, although s1 is mark temp able because the s6.blah use is not related, we only know that s1 is dependent of s6 // so it looks like s1 may overlap through the iterations. The backward pass will be able to catch that and not mark temp them // However, the globopt may create situation like the above while it wasn't there in the backward phase // For example: // = s6.blah // s1 = LdRootFld g // s6 = s1 // s1 = NewScObject // s7 = LdRootFld g // = s7.blah // Globopt copy prop s7 -> s6, creating the example above. // s6 = s1 // This make it impossible to verify whether we did the right thing using the conservative algorithm. // Luckily, this case is very rare (ExprGen didn't hit it with > 100K test cases) // So we can use this rather expensive algorithm to find out if any of upward exposed used that we think overlaps // really get their value from the marked temp sym or not. // See unittest\Object\stackobject_dependency.js (with -maxinterpretcount:1 -off:inline) BasicBlock * currentBlock = backwardPass->currentBlock; BVSparse<JitArenaAllocator> * upwardExposedUses = currentBlock->upwardExposedUses; JitArenaAllocator tempAllocator(_u("temp"), instr->m_func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory); BVSparse<JitArenaAllocator> * dependentSyms = bvTempTransferDependencies->AndNew(upwardExposedUses, &tempAllocator); BVSparse<JitArenaAllocator> * initialDependentSyms = dependentSyms->CopyNew(); Assert(!dependentSyms->IsEmpty()); struct BlockRecord { BasicBlock * block; BVSparse<JitArenaAllocator> * dependentSyms; }; SList<BlockRecord> blockStack(&tempAllocator); JsUtil::BaseDictionary<BasicBlock *, BVSparse<JitArenaAllocator> *, JitArenaAllocator> processedSyms(&tempAllocator); IR::Instr * currentInstr = instr; Assert(instr->GetDst()->AsRegOpnd()->m_sym->IsVar()); SymID markTempSymId = instr->GetDst()->AsRegOpnd()->m_sym->m_id; bool initial = true; while (true) { while (currentInstr != currentBlock->GetFirstInstr()) { if (initial) { initial = false; } else if (currentInstr == instr) { if (dependentSyms->Test(markTempSymId)) { // One of the dependent sym from the original set get it's value from the current marked temp dst. // The dst definitely cannot be temp because it's lifetime overlaps across iterations. return false; } // If we have already check the same dependent sym, no need to do it again. // It will produce the same result anyway. dependentSyms->Minus(initialDependentSyms); if (dependentSyms->IsEmpty()) { break; } // Add in newly discovered dependentSym so we won't do it again when it come back here. initialDependentSyms->Or(dependentSyms); } if (currentInstr->GetDst() && currentInstr->GetDst()->IsRegOpnd()) { // Clear the def and mark the src if it is transferred. // If the dst sym is a type specialized sym, clear the var sym instead. StackSym * dstSym = currentInstr->GetDst()->AsRegOpnd()->m_sym; if (!dstSym->IsVar()) { dstSym = dstSym->GetVarEquivSym(nullptr); } if (dstSym && dependentSyms->TestAndClear(dstSym->m_id) && IsTempTransfer(currentInstr) && currentInstr->GetSrc1()->IsRegOpnd()) { // We only really care about var syms uses for object temp. StackSym * srcSym = currentInstr->GetSrc1()->AsRegOpnd()->m_sym; if (srcSym->IsVar()) { dependentSyms->Set(srcSym->m_id); } } if (dependentSyms->IsEmpty()) { // No more dependent sym, we found the def of all of them we can move on to the next block. break; } } currentInstr = currentInstr->m_prev; } if (currentBlock->isLoopHeader && !dependentSyms->IsEmpty()) { Assert(currentInstr == currentBlock->GetFirstInstr()); // If we have try to propagate the symbol through the loop before, we don't need to propagate it again. BVSparse<JitArenaAllocator> * currentLoopProcessedSyms = processedSyms.Lookup(currentBlock, nullptr); if (currentLoopProcessedSyms == nullptr) { processedSyms.Add(currentBlock, dependentSyms->CopyNew()); } else { dependentSyms->Minus(currentLoopProcessedSyms); currentLoopProcessedSyms->Or(dependentSyms); } } if (!dependentSyms->IsEmpty()) { Assert(currentInstr == currentBlock->GetFirstInstr()); FOREACH_PREDECESSOR_BLOCK(predBlock, currentBlock) { if (predBlock->loop == nullptr) { // No need to track outside of loops. continue; } BlockRecord record; record.block = predBlock; record.dependentSyms = dependentSyms->CopyNew(); blockStack.Prepend(record); } NEXT_PREDECESSOR_BLOCK; } JitAdelete(&tempAllocator, dependentSyms); if (blockStack.Empty()) { // No more blocks. We are done. break; } currentBlock = blockStack.Head().block; dependentSyms = blockStack.Head().dependentSyms; blockStack.RemoveHead(); currentInstr = currentBlock->GetLastInstr(); } // All the dependent sym doesn't get their value from the marked temp def, so it can really be marked temp. #if DBG if (DoTrace(backwardPass)) { Output::Print(_u("%s: Unrelated overlap mark temp (s%-3d): "), GetTraceName(), markTempSymId); instr->DumpSimple(); Output::Flush(); } #endif return true; } #endif #if DBG bool NumberTemp::DoTrace(BackwardPass * backwardPass) { return PHASE_TRACE(Js::MarkTempNumberPhase, backwardPass->func); } bool ObjectTemp::DoTrace(BackwardPass * backwardPass) { return PHASE_TRACE(Js::MarkTempObjectPhase, backwardPass->func); } bool ObjectTempVerify::DoTrace(BackwardPass * backwardPass) { return PHASE_TRACE(Js::MarkTempObjectPhase, backwardPass->func); } #endif // explicit instantiation template class TempTracker<NumberTemp>; template class TempTracker<ObjectTemp>; #if DBG template class TempTracker<ObjectTempVerify>; #endif
Microsoft/ChakraCore
lib/Backend/TempTracker.cpp
C++
mit
64,404
<?php /** * @link https://github.com/ManifestWebDesign/DABL * @link http://manifestwebdesign.com/redmine/projects/dabl * @author Manifest Web Design * @license MIT License */ /** * Convert a value to JSON * * This function returns a JSON representation of $param. It uses json_encode * to accomplish this, but converts objects and arrays containing objects to * associative arrays first. This way, objects that do not expose (all) their * properties directly but only through an Iterator interface are also encoded * correctly. */ function json_encode_all(&$param) { if (is_object($param) || is_array($param)) { return json_encode(object_to_array($param)); } return json_encode($param); }
davidstelter/dabl-mvc
src/helpers/json_encode_all.php
PHP
mit
713
package com.cs.moose.ui.controls.memorytable; public class MemoryTableRow { private final short[] values; private final int row; public MemoryTableRow(short[] values, int row) { this.values = values; this.row = row; } public int getColumn0() { return row; } public short getColumn1() { return values[0]; } public short getColumn2() { return values[1]; } public short getColumn3() { return values[2]; } public short getColumn4() { return values[3]; } public short getColumn5() { return values[4]; } public short getColumn6() { return values[5]; } public short getColumn7() { return values[6]; } public short getColumn8() { return values[7]; } public short getColumn9() { return values[8]; } public short getColumn10() { return values[9]; } public static MemoryTableRow[] getRows(short[] memory) { int rest = memory.length % 10, count = memory.length / 10; if (rest > 0) { count++; } MemoryTableRow[] rows = new MemoryTableRow[count]; for (int i = 0; i < count; i++) { short[] values = new short[10]; for (int j = 0; j < 10; j++) { int index = i * 10 + j; if (index < memory.length) { values[j] = memory[index]; } } MemoryTableRow row = new MemoryTableRow(values, i * 10); rows[i] = row; } return rows; } }
michaelneu/MooseMachine
src/com/cs/moose/ui/controls/memorytable/MemoryTableRow.java
Java
mit
1,331
(function ($) { $.extend(Backbone.View.prototype, { parse: function(objName) { var self = this, recurse_form = function(object, objName) { $.each(object, function(v,k) { if (k instanceof Object) { object[v] = recurse_form(k, objName + '[' + v + ']'); } else { object[v] = self.$('[name="'+ objName + '[' + v + ']"]').val(); } }); return object; }; this.model.attributes = recurse_form(this.model.attributes, objName); }, populate: function(objName) { var self = this, recurse_obj = function(object, objName) { $.each(object, function (v,k) { if (v instanceof Object) { recurse_obj(v, k); } else if (_.isString(v)) { self.$('[name="'+ objName + '[' + v + ']"]').val(k); } }); }; recurse_obj(this.model.attributes, objName); } }); })(jQuery);
teampl4y4/j2-exchange
web/bundles/j2exchange/js/backbone/form.js
JavaScript
mit
1,175
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Cache { using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Web.Caching; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Instrumentation; public class FBCachingProvider : CachingProvider { internal const string CacheFileExtension = ".resources"; internal static string CachingDirectory = "Cache\\"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FBCachingProvider)); public override void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { // initialize cache dependency DNNCacheDependency d = dependency; // if web farm is enabled if (this.IsWebFarm()) { // get hashed file name var f = new string[1]; f[0] = GetFileName(cacheKey); // create a cache file for item CreateCacheFile(f[0], cacheKey); // create a cache dependency on the cache file d = new DNNCacheDependency(f, null, dependency); } // Call base class method to add obect to cache base.Insert(cacheKey, itemToCache, d, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); } public override bool IsWebFarm() { bool _IsWebFarm = Null.NullBoolean; if (!string.IsNullOrEmpty(Config.GetSetting("IsWebFarm"))) { _IsWebFarm = bool.Parse(Config.GetSetting("IsWebFarm")); } return _IsWebFarm; } public override string PurgeCache() { // called by scheduled job to remove cache files which are no longer active return this.PurgeCacheFiles(Globals.HostMapPath + CachingDirectory); } public override void Remove(string Key) { base.Remove(Key); // if web farm is enabled in config file if (this.IsWebFarm()) { // get hashed filename string f = GetFileName(Key); // delete cache file - this synchronizes the cache across servers in the farm DeleteCacheFile(f); } } private static string ByteArrayToString(byte[] arrInput) { int i; var sOutput = new StringBuilder(arrInput.Length); for (i = 0; i <= arrInput.Length - 1; i++) { sOutput.Append(arrInput[i].ToString("X2")); } return sOutput.ToString(); } private static void CreateCacheFile(string FileName, string CacheKey) { // declare stream StreamWriter s = null; try { // if the cache file does not already exist if (!File.Exists(FileName)) { // create the cache file s = File.CreateText(FileName); // write the CacheKey to the file to provide a documented link between cache item and cache file s.Write(CacheKey); // close the stream } } catch (Exception ex) { // permissions issue creating cache file or more than one thread may have been trying to write the cache file simultaneously Exceptions.Exceptions.LogException(ex); } finally { if (s != null) { s.Close(); } } } private static void DeleteCacheFile(string FileName) { try { if (File.Exists(FileName)) { File.Delete(FileName); } } catch (Exception ex) { // an error occurred when trying to delete the cache file - this is serious as it means that the cache will not be synchronized Exceptions.Exceptions.LogException(ex); } } private static string GetFileName(string CacheKey) { // cache key may contain characters invalid for a filename - this method creates a valid filename byte[] FileNameBytes = Encoding.ASCII.GetBytes(CacheKey); using (var sha256 = new SHA256CryptoServiceProvider()) { FileNameBytes = sha256.ComputeHash(FileNameBytes); string FinalFileName = ByteArrayToString(FileNameBytes); return Path.GetFullPath(Globals.HostMapPath + CachingDirectory + FinalFileName + CacheFileExtension); } } private string PurgeCacheFiles(string Folder) { // declare counters int PurgedFiles = 0; int PurgeErrors = 0; int i; // get list of cache files string[] f; f = Directory.GetFiles(Folder); // loop through cache files for (i = 0; i <= f.Length - 1; i++) { // get last write time for file DateTime dtLastWrite; dtLastWrite = File.GetLastWriteTime(f[i]); // if the cache file is more than 2 hours old ( no point in checking most recent cache files ) if (dtLastWrite < DateTime.Now.Subtract(new TimeSpan(2, 0, 0))) { // get cachekey string strCacheKey = Path.GetFileNameWithoutExtension(f[i]); // if the cache key does not exist in memory if (DataCache.GetCache(strCacheKey) == null) { try { // delete the file File.Delete(f[i]); PurgedFiles += 1; } catch (Exception exc) { // an error occurred Logger.Error(exc); PurgeErrors += 1; } } } } // return a summary message for the job return string.Format("Cache Synchronization Files Processed: " + f.Length + ", Purged: " + PurgedFiles + ", Errors: " + PurgeErrors); } } }
nvisionative/Dnn.Platform
DNN Platform/Library/Services/Cache/FBCachingProvider.cs
C#
mit
7,037
const getShows = require('./lib/getShows'); module.exports = { getShows };
oliverviljamaa/markus-cinema-client
index.js
JavaScript
mit
76
package rogue import ( "testing" "github.com/stretchr/testify/assert" ) func TestParseSpritesetDefinitionCharacters(t *testing.T) { ss, err := ParseSpritesetDefinition("resources/assets/tilesets/oddball/characters.yml") assert.Equal(t, nil, err) assert.Equal(t, true, len(ss.Tiles) > 2) } func TestParseSpritesetDefinitionItems(t *testing.T) { ss, err := ParseSpritesetDefinition("resources/assets/tilesets/oddball/items.yml") assert.Equal(t, nil, err) assert.Equal(t, true, len(ss.Tiles) > 2) } func TestGenerateTexturePacker(t *testing.T) { ss, err := ParseSpritesetDefinition("resources/assets/tilesets/oddball/characters.yml") assert.Equal(t, nil, err) assert.Equal(t, true, len(ss.Tiles) > 2) tp := GenerateTexturePacker(ss) assert.Equal(t, true, len(tp.Frames) > 2) }
martinlindhe/rogue
spriteset_test.go
GO
mit
796
// TYPE_CHECKING public class J1_castarrayaccess { public J1_castarrayaccess() {} public static int test() { String[] s = new String[5]; Object o = (Object)s[1]; return 123; } }
gregwym/joos-compiler-java
testcases/a3/J1_castarrayaccess.java
Java
mit
197
# frozen_string_literal: true require 'fast_spec_helper' RSpec.describe Gitlab::RequestProfiler::Profile do let(:profile) { described_class.new(filename) } describe '.new' do context 'using old filename' do let(:filename) { '|api|v4|version.txt_1562854738.html' } it 'returns valid data' do expect(profile).to be_valid expect(profile.request_path).to eq('/api/v4/version.txt') expect(profile.time).to eq(Time.at(1562854738).utc) expect(profile.type).to eq('html') end end context 'using new filename' do let(:filename) { '|api|v4|version.txt_1563547949_execution.html' } it 'returns valid data' do expect(profile).to be_valid expect(profile.request_path).to eq('/api/v4/version.txt') expect(profile.profile_mode).to eq('execution') expect(profile.time).to eq(Time.at(1563547949).utc) expect(profile.type).to eq('html') end end end describe '#content_type' do context 'when using html file' do let(:filename) { '|api|v4|version.txt_1562854738_memory.html' } it 'returns valid data' do expect(profile).to be_valid expect(profile.content_type).to eq('text/html') end end context 'when using text file' do let(:filename) { '|api|v4|version.txt_1562854738_memory.txt' } it 'returns valid data' do expect(profile).to be_valid expect(profile.content_type).to eq('text/plain') end end context 'when file is unknown' do let(:filename) { '|api|v4|version.txt_1562854738_memory.xxx' } it 'returns valid data' do expect(profile).not_to be_valid expect(profile.content_type).to be_nil end end end end
mmkassem/gitlabhq
spec/lib/gitlab/request_profiler/profile_spec.rb
Ruby
mit
1,760
<?php /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup Russian Russian language * @ingroup UnaModules * * @{ */ $aConfig = array( /** * Main Section. */ 'type' => BX_DOL_MODULE_TYPE_LANGUAGE, 'name' => 'bx_ru', 'title' => 'Russian', 'note' => 'Language file', 'version' => '9.0.12.DEV', 'vendor' => 'Boonex', 'help_url' => 'http://feed.una.io/?section={module_name}', 'compatible_with' => array( '9.0.x' ), /** * 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars. */ 'home_dir' => 'boonex/russian/', 'home_uri' => 'ru', 'db_prefix' => 'bx_rsn_', 'class_prefix' => 'BxRsn', /** * Category for language keys. */ 'language_category' => 'BoonEx Russian', /** * Installation/Uninstallation Section. * NOTE. The sequence of actions is critical. Don't change the order. */ 'install' => array( 'execute_sql' => 1, 'update_languages' => 1, 'install_language' => 1, 'clear_db_cache' => 1 ), 'uninstall' => array ( 'update_languages' => 1, 'execute_sql' => 1, 'clear_db_cache' => 1 ), 'enable' => array( 'execute_sql' => 1 ), 'disable' => array( 'execute_sql' => 1 ), /** * Dependencies Section */ 'dependencies' => array(), ); /** @} */
camperjz/trident
modules/boonex/russian/install/config.php
PHP
mit
1,513
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Game.Beatmaps; using osu.Game.Overlays.Settings; namespace osu.Game.Rulesets.Mods { public class DifficultyAdjustSettingsControl : SettingsItem<float?> { [Resolved] private IBindable<WorkingBeatmap> beatmap { get; set; } /// <summary> /// Used to track the display value on the setting slider. /// </summary> /// <remarks> /// When the mod is overriding a default, this will match the value of <see cref="Current"/>. /// When there is no override (ie. <see cref="Current"/> is null), this value will match the beatmap provided default via <see cref="updateCurrentFromSlider"/>. /// </remarks> private readonly BindableNumber<float> sliderDisplayCurrent = new BindableNumber<float>(); protected override Drawable CreateControl() => new SliderControl(sliderDisplayCurrent); /// <summary> /// Guards against beatmap values displayed on slider bars being transferred to user override. /// </summary> private bool isInternalChange; private DifficultyBindable difficultyBindable; public override Bindable<float?> Current { get => base.Current; set { // Intercept and extract the internal number bindable from DifficultyBindable. // This will provide bounds and precision specifications for the slider bar. difficultyBindable = (DifficultyBindable)value.GetBoundCopy(); sliderDisplayCurrent.BindTo(difficultyBindable.CurrentNumber); base.Current = difficultyBindable; } } protected override void LoadComplete() { base.LoadComplete(); Current.BindValueChanged(current => updateCurrentFromSlider()); beatmap.BindValueChanged(b => updateCurrentFromSlider(), true); sliderDisplayCurrent.BindValueChanged(number => { // this handles the transfer of the slider value to the main bindable. // as such, should be skipped if the slider is being updated via updateFromDifficulty(). if (!isInternalChange) Current.Value = number.NewValue; }); } private void updateCurrentFromSlider() { if (Current.Value != null) { // a user override has been added or updated. sliderDisplayCurrent.Value = Current.Value.Value; return; } var difficulty = beatmap.Value.BeatmapInfo.Difficulty; // generally should always be implemented, else the slider will have a zero default. if (difficultyBindable.ReadCurrentFromDifficulty == null) return; isInternalChange = true; sliderDisplayCurrent.Value = difficultyBindable.ReadCurrentFromDifficulty(difficulty); isInternalChange = false; } private class SliderControl : CompositeDrawable, IHasCurrentValue<float?> { // This is required as SettingsItem relies heavily on this bindable for internal use. // The actual update flow is done via the bindable provided in the constructor. private readonly DifficultyBindableWithCurrent current = new DifficultyBindableWithCurrent(); public Bindable<float?> Current { get => current.Current; set => current.Current = value; } public SliderControl(BindableNumber<float> currentNumber) { InternalChildren = new Drawable[] { new SettingsSlider<float> { ShowsDefaultIndicator = false, Current = currentNumber, KeyboardStep = 0.1f, } }; AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; } } private class DifficultyBindableWithCurrent : DifficultyBindable, IHasCurrentValue<float?> { private Bindable<float?> currentBound; public Bindable<float?> Current { get => this; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (currentBound != null) UnbindFrom(currentBound); BindTo(currentBound = value); } } public DifficultyBindableWithCurrent(float? defaultValue = default) : base(defaultValue) { } protected override Bindable<float?> CreateInstance() => new DifficultyBindableWithCurrent(); } } }
peppy/osu
osu.Game/Rulesets/Mods/DifficultyAdjustSettingsControl.cs
C#
mit
5,254
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOnlineShop.Models.ShopingCartModels { public class OrderDetail { public int OrderDetailId { get; set; } public int OrderId { get; set; } public int ProductId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public virtual Product Product { get; set; } public virtual Order Order { get; set; } } }
didimitrov/Shop
MyOnlineShop/MyOnlineShop.Models/ShopingCartModels/OrderDetail.cs
C#
mit
505
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Casio; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class SpecialEffectLevel extends AbstractTag { protected $Id = 12336; protected $Name = 'SpecialEffectLevel'; protected $FullName = 'Casio::Type2'; protected $GroupName = 'Casio'; protected $g0 = 'MakerNotes'; protected $g1 = 'Casio'; protected $g2 = 'Camera'; protected $Type = 'int16u'; protected $Writable = true; protected $Description = 'Special Effect Level'; protected $flag_Permanent = true; }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Casio/SpecialEffectLevel.php
PHP
mit
851
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2018_07_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Class to specify which protocols are enabled. */ public class EnabledProtocols { /** * Enable Download protocol or not. */ @JsonProperty(value = "download", required = true) private boolean download; /** * Enable DASH protocol or not. */ @JsonProperty(value = "dash", required = true) private boolean dash; /** * Enable HLS protocol or not. */ @JsonProperty(value = "hls", required = true) private boolean hls; /** * Enable SmoothStreaming protocol or not. */ @JsonProperty(value = "smoothStreaming", required = true) private boolean smoothStreaming; /** * Get enable Download protocol or not. * * @return the download value */ public boolean download() { return this.download; } /** * Set enable Download protocol or not. * * @param download the download value to set * @return the EnabledProtocols object itself. */ public EnabledProtocols withDownload(boolean download) { this.download = download; return this; } /** * Get enable DASH protocol or not. * * @return the dash value */ public boolean dash() { return this.dash; } /** * Set enable DASH protocol or not. * * @param dash the dash value to set * @return the EnabledProtocols object itself. */ public EnabledProtocols withDash(boolean dash) { this.dash = dash; return this; } /** * Get enable HLS protocol or not. * * @return the hls value */ public boolean hls() { return this.hls; } /** * Set enable HLS protocol or not. * * @param hls the hls value to set * @return the EnabledProtocols object itself. */ public EnabledProtocols withHls(boolean hls) { this.hls = hls; return this; } /** * Get enable SmoothStreaming protocol or not. * * @return the smoothStreaming value */ public boolean smoothStreaming() { return this.smoothStreaming; } /** * Set enable SmoothStreaming protocol or not. * * @param smoothStreaming the smoothStreaming value to set * @return the EnabledProtocols object itself. */ public EnabledProtocols withSmoothStreaming(boolean smoothStreaming) { this.smoothStreaming = smoothStreaming; return this; } }
selvasingh/azure-sdk-for-java
sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EnabledProtocols.java
Java
mit
2,825
import functools from ...drivers.spi_interfaces import SPI_INTERFACES USAGE = """ A spi_interface is represented by a string. Possible values are """ + ', '.join(sorted(SPI_INTERFACES.__members__)) @functools.singledispatch def make(c): raise ValueError("Don't understand type %s" % type(c), USAGE) @make.register(SPI_INTERFACES) def _(c): return c @make.register(str) def _(c): return SPI_INTERFACES[c]
ManiacalLabs/BiblioPixel
bibliopixel/project/types/spi_interface.py
Python
mit
424
#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include "tangram.h" #include "tile/labels/label.h" #include "glm/gtc/matrix_transform.hpp" #define EPSILON 0.00001 glm::mat4 mvp; glm::vec2 screen; TEST_CASE( "Ensure the transition from wait -> sleep when occlusion happens", "[Core][Label]" ) { Label l({}, "label", 0, Label::Type::LINE); REQUIRE(l.getState() == Label::State::WAIT_OCC); l.setOcclusion(true); l.update(mvp, screen, 0); REQUIRE(l.getState() != Label::State::SLEEP); REQUIRE(l.getState() == Label::State::WAIT_OCC); REQUIRE(l.canOcclude()); l.setOcclusion(true); l.occlusionSolved(); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::SLEEP); REQUIRE(!l.canOcclude()); } TEST_CASE( "Ensure the transition from wait -> visible when no occlusion happens", "[Core][Label]" ) { Label l({}, "label", 0, Label::Type::LINE); REQUIRE(l.getState() == Label::State::WAIT_OCC); l.setOcclusion(false); l.update(mvp, screen, 0); REQUIRE(l.getState() != Label::State::SLEEP); REQUIRE(l.getState() == Label::State::WAIT_OCC); l.setOcclusion(false); l.occlusionSolved(); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::FADING_IN); REQUIRE(l.canOcclude()); l.update(mvp, screen, 1.0); REQUIRE(l.getState() == Label::State::VISIBLE); REQUIRE(l.canOcclude()); } TEST_CASE( "Ensure the end state after occlusion is leep state", "[Core][Label]" ) { Label l({}, "label", 0, Label::Type::LINE); l.setOcclusion(false); l.occlusionSolved(); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::FADING_IN); REQUIRE(l.canOcclude()); l.setOcclusion(true); l.occlusionSolved(); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::SLEEP); REQUIRE(!l.canOcclude()); } TEST_CASE( "Ensure the out of screen state transition", "[Core][Label]" ) { Label l({ glm::vec2(500.0) }, "label", 0, Label::Type::POINT); REQUIRE(l.getState() == Label::State::WAIT_OCC); double screenWidth = 250.0, screenHeight = 250.0; glm::mat4 p = glm::ortho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1000.0); l.update(p, glm::vec2(screenWidth, screenHeight), 0); REQUIRE(l.getState() == Label::State::OUT_OF_SCREEN); REQUIRE(!l.canOcclude()); p = glm::ortho(0.0, screenWidth * 4.0, screenHeight * 4.0, 0.0, 0.0, 1000.0); l.update(p, glm::vec2(screenWidth * 4.0, screenHeight * 4.0), 0); REQUIRE(l.getState() == Label::State::WAIT_OCC); REQUIRE(l.canOcclude()); l.setOcclusion(false); l.occlusionSolved(); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::FADING_IN); REQUIRE(l.canOcclude()); l.update(mvp, screen, 1.0); REQUIRE(l.getState() == Label::State::VISIBLE); REQUIRE(l.canOcclude()); } TEST_CASE( "Ensure debug labels are always visible and cannot occlude", "[Core][Label]" ) { Label l({}, "label", 0, Label::Type::DEBUG); REQUIRE(l.getState() == Label::State::VISIBLE); REQUIRE(!l.canOcclude()); l.update(mvp, screen, 0); REQUIRE(l.getState() == Label::State::VISIBLE); REQUIRE(!l.canOcclude()); } TEST_CASE( "Linear interpolation", "[Core][Label][Fade]" ) { FadeEffect fadeOut(false, FadeEffect::Interpolation::LINEAR, 1.0); REQUIRE(fadeOut.update(0.0) == 1.0); REQUIRE(fadeOut.update(0.5) == 0.5); REQUIRE(fadeOut.update(0.5) == 0.0); fadeOut.update(0.01); REQUIRE(fadeOut.isFinished()); FadeEffect fadeIn(true, FadeEffect::Interpolation::LINEAR, 1.0); REQUIRE(fadeIn.update(0.0) == 0.0); REQUIRE(fadeIn.update(0.5) == 0.5); REQUIRE(fadeIn.update(0.5) == 1.0); fadeIn.update(0.01); REQUIRE(fadeIn.isFinished()); } TEST_CASE( "Pow interpolation", "[Core][Label][Fade]" ) { FadeEffect fadeOut(false, FadeEffect::Interpolation::POW, 1.0); REQUIRE(fadeOut.update(0.0) == 1.0); REQUIRE(fadeOut.update(0.5) == 0.75); REQUIRE(fadeOut.update(0.5) == 0.0); fadeOut.update(0.01); REQUIRE(fadeOut.isFinished()); FadeEffect fadeIn(true, FadeEffect::Interpolation::POW, 1.0); REQUIRE(fadeIn.update(0.0) == 0.0); REQUIRE(fadeIn.update(0.5) == 0.25); REQUIRE(fadeIn.update(0.5) == 1.0); fadeIn.update(0.01); REQUIRE(fadeIn.isFinished()); } TEST_CASE( "Sine interpolation", "[Core][Label][Fade]" ) { FadeEffect fadeOut(false, FadeEffect::Interpolation::SINE, 1.0); REQUIRE(abs(fadeOut.update(0.0) - 1.0) < EPSILON); REQUIRE(abs(fadeOut.update(1.0) - 0.0) < EPSILON); fadeOut.update(0.01); REQUIRE(fadeOut.isFinished()); FadeEffect fadeIn(true, FadeEffect::Interpolation::SINE, 1.0); REQUIRE(abs(fadeIn.update(0.0) - 0.0) < EPSILON); REQUIRE(abs(fadeIn.update(1.0) - 1.0) < EPSILON); fadeIn.update(0.01); REQUIRE(fadeIn.isFinished()); }
karimnaaji/tangram-es
tests/unit/labelTests.cpp
C++
mit
4,905
#include "lexer/token.h" #include <iostream> Token::Token(int t) { tag = t; } //For unknown tokens Token::Token(std::string t) { //Get ascii for each character for(int i = 0; i < t.length(); i++) { //Give the tag some arbitrary value tag = -1; asciiValuesTag.push_back(t[i]); } unknownToken = t; } std::string Token::getString() { std::stringstream ss; if(asciiValuesTag.size() > 0) { ss << "TOKEN: Tag is "; std::list<int>::iterator it; for(it = asciiValuesTag.begin(); it != asciiValuesTag.end(); it++) { ss << static_cast<char>(*it); } } else ss << "TOKEN: Tag is " << static_cast<char>(tag); return ss.str(); } std::string Token::toString() { std::stringstream ss; ss << (char)tag; return ss.str(); } std::string Token::getName() { std::stringstream ss; if(asciiValuesTag.size() > 0) { std::list<int>::iterator it; for(it = asciiValuesTag.begin(); it != asciiValuesTag.end(); it++) { ss << static_cast<char>(*it); } } else ss << static_cast<char>(tag); return ss.str(); }
cruzj6/orderUpCompiler
compiler_back/source/lexer/token.cpp
C++
mit
1,085
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations # Some initial, primary places. PLACES = [ ('Work', 'work'), ('Home', 'home'), ('School', 'school'), ] def create_primary_place(apps, schema_editor=None): Place = apps.get_model("userprofile", "Place") for name, slug in PLACES: Place.objects.create(name=name, slug=slug, primary=True) class Migration(migrations.Migration): dependencies = [ ('userprofile', '0010_auto_20150908_2010'), ] operations = [ migrations.RunPython(create_primary_place), ]
izzyalonso/tndata_backend
tndata_backend/userprofile/migrations/0011_create_places.py
Python
mit
622
// Node.js env expect = require('expect.js'); sha1 = require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // Webpack browser env JS_SHA1_NO_NODE_JS = true; window = global; sha1 = require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // browser env JS_SHA1_NO_NODE_JS = true; JS_SHA1_NO_COMMON_JS = true; window = global; require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // browser AMD JS_SHA1_NO_NODE_JS = true; JS_SHA1_NO_COMMON_JS = true; window = global; define = function (func) { sha1 = func(); require('./test.js'); }; define.amd = true; require('../src/sha1.js');
emn178/js-sha1
tests/node-test.js
JavaScript
mit
940
import {IFunctionLookupTable} from "../../function/function-lookup-table"; import {ParallelWorkerFunctionIds} from "./parallel-worker-functions"; import {identity} from "../../util/identity"; import {filterIterator} from "./filter-iterator"; import {mapIterator} from "./map-iterator"; import {parallelJobExecutor} from "./parallel-job-executor"; import {rangeIterator} from "./range-iterator"; import {reduceIterator} from "./reduce-iterator"; import {toIterator} from "../../util/arrays"; /** * Registers the static parallel functions * @param lookupTable the table into which the function should be registered */ export function registerStaticParallelFunctions(lookupTable: IFunctionLookupTable) { lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.IDENTITY, identity); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.FILTER, filterIterator); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.MAP, mapIterator); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.PARALLEL_JOB_EXECUTOR, parallelJobExecutor); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.RANGE, rangeIterator); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.REDUCE, reduceIterator); lookupTable.registerStaticFunction(ParallelWorkerFunctionIds.TO_ITERATOR, toIterator); }
DatenMetzgerX/parallel.es
src/common/parallel/slave/register-parallel-worker-functions.ts
TypeScript
mit
1,346
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common; import com.google.inject.Inject; import net.minecraft.server.dedicated.DedicatedServer; import org.spongepowered.api.Platform; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.service.ServiceManager; import org.spongepowered.api.service.ban.BanService; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.service.permission.PermissionService; import org.spongepowered.api.service.rcon.RconService; import org.spongepowered.api.service.sql.SqlService; import org.spongepowered.api.service.user.UserStorageService; import org.spongepowered.api.service.whitelist.WhitelistService; import org.spongepowered.api.util.annotation.NonnullByDefault; import org.spongepowered.common.command.SpongeCommands; import org.spongepowered.common.service.ban.SpongeBanService; import org.spongepowered.common.service.pagination.SpongePaginationService; import org.spongepowered.common.service.rcon.MinecraftRconService; import org.spongepowered.common.service.sql.SqlServiceImpl; import org.spongepowered.common.service.user.SpongeUserStorageService; import org.spongepowered.common.service.whitelist.SpongeWhitelistService; import org.spongepowered.common.text.action.SpongeCallbackHolder; import org.spongepowered.common.util.SpongeUsernameCache; /** * Used to setup the ecosystem. */ @NonnullByDefault public final class SpongeBootstrap { @Inject private static ServiceManager serviceManager; @Inject private static CommandManager commandManager; public static void initializeServices() { registerService(SqlService.class, new SqlServiceImpl()); registerService(PaginationService.class, new SpongePaginationService()); if (SpongeImpl.getGame().getPlatform().getType() == Platform.Type.SERVER) { registerService(RconService.class, new MinecraftRconService((DedicatedServer) Sponge.getServer())); } registerService(UserStorageService.class, new SpongeUserStorageService()); registerService(BanService.class, new SpongeBanService()); registerService(WhitelistService.class, new SpongeWhitelistService()); SpongeInternalListeners.getInstance().registerServiceCallback(PermissionService.class, input -> SpongeImpl.getGame().getServer().getConsole().getContainingCollection()); SpongeUsernameCache.load(); } public static void initializeCommands() { commandManager.register(SpongeImpl.getPlugin(), SpongeCommands.createSpongeCommand(), "sponge", "sp"); commandManager.register(SpongeImpl.getPlugin(), SpongeCommands.createHelpCommand(), "help", "?"); commandManager.register(SpongeImpl.getPlugin(), SpongeCallbackHolder.getInstance().createCommand(), SpongeCallbackHolder.CALLBACK_COMMAND); } private static <T> void registerService(Class<T> serviceClass, T serviceImpl) { serviceManager.setProvider(SpongeImpl.getPlugin(), serviceClass, serviceImpl); } }
Grinch/SpongeCommon
src/main/java/org/spongepowered/common/SpongeBootstrap.java
Java
mit
4,287
import { Farmbot } from "farmbot"; import { createTransferCert } from "./create_transfer_cert"; import { toPairs } from "../../util"; import { getDevice } from "../../device"; export interface TransferProps { email: string; password: string; device: Farmbot; } /** Pass control of your device over to another user. */ export async function transferOwnership(input: TransferProps): Promise<void> { const { email, device } = input; try { const secret = await createTransferCert(input); const body = toPairs({ email, secret }); await device.send(getDevice().rpcShim([{ kind: "change_ownership", args: {}, body }])); return Promise.resolve(); } catch (error) { return Promise.reject(error); } }
gabrielburnworth/Farmbot-Web-App
frontend/settings/transfer_ownership/transfer_ownership.ts
TypeScript
mit
737
'use strict'; var expect = require('chai').expect; var stub = require('../../helpers/stub').stub; var commandOptions = require('../../factories/command-options'); var UninstallCommand = require('../../../lib/commands/uninstall-npm'); var Task = require('../../../lib/models/task'); describe('uninstall:npm command', function() { var command, options, tasks, npmInstance; beforeEach(function() { tasks = { NpmUninstall: Task.extend({ init: function() { npmInstance = this; } }) }; options = commandOptions({ settings: {}, project: { name: function() { return 'some-random-name'; }, isEmberCLIProject: function() { return true; } }, tasks: tasks }); stub(tasks.NpmUninstall.prototype, 'run'); command = new UninstallCommand(options); }); afterEach(function() { tasks.NpmUninstall.prototype.run.restore(); }); it('initializes npm task with ui, project and analytics', function() { return command.validateAndRun([]).then(function() { expect(npmInstance.ui, 'ui was set'); expect(npmInstance.project, 'project was set'); expect(npmInstance.analytics, 'analytics was set'); }); }); describe('with no args', function() { it('runs the npm uninstall task with no packages, save-dev true and save-exact true', function() { return command.validateAndRun([]).then(function() { var npmRun = tasks.NpmUninstall.prototype.run; expect(npmRun.called).to.equal(1, 'expected npm uninstall run was called once'); expect(npmRun.calledWith[0][0]).to.deep.equal({ packages: [], 'save-dev': true, 'save-exact': true }, 'expected npm uninstall called with no packages, save-dev true, and save-exact true'); }); }); }); describe('with args', function() { it('runs the npm uninstall task with given packages', function() { return command.validateAndRun(['moment', 'lodash']).then(function() { var npmRun = tasks.NpmUninstall.prototype.run; expect(npmRun.called).to.equal(1, 'expected npm uninstall run was called once'); expect(npmRun.calledWith[0][0]).to.deep.equal({ packages: ['moment', 'lodash'], 'save-dev': true, 'save-exact': true }, 'expected npm uninstall called with given packages, save-dev true, and save-exact true'); }); }); }); });
zanemayo/ember-cli
tests/unit/commands/uninstall-npm-test.js
JavaScript
mit
2,523
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace NetOffice.DeveloperToolbox.Controls.Painter { /// <summary> /// Support Painter to create a paint event which is possible to use as overlayer /// </summary> public partial class OverlayPainter : Component { #region Fields private Form _form; #endregion #region Ctor /// <summary> /// Creates an instance of the class /// </summary> public OverlayPainter() { InitializeComponent(); this.Disposed += new EventHandler(OverlayPainter_Disposed); } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="container">parent container</param> public OverlayPainter(IContainer container) { container.Add(this); InitializeComponent(); this.Disposed += new EventHandler(OverlayPainter_Disposed); } #endregion #region Events /// <summary> /// Paint event to draw on top as overlayer /// </summary> public event EventHandler<PaintEventArgs> Paint; #endregion #region Properties /// <summary> /// Top level window /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Form Owner { get { return _form; } set { if (value == null) throw new ArgumentNullException(); if (_form != null) throw new InvalidOperationException(); _form = value; _form.Resize += new EventHandler(Form_Resize); ConnectPaintEventHandlers(_form); } } #endregion #region Methods private void ConnectPaintEventHandlers(Control control) { control.Paint -= new PaintEventHandler(Control_Paint); control.Paint += new PaintEventHandler(Control_Paint); control.ControlAdded -= new ControlEventHandler(Control_ControlAdded); control.ControlAdded += new ControlEventHandler(Control_ControlAdded); foreach (Control child in control.Controls) ConnectPaintEventHandlers(child); } private void DisconnectPaintEventHandlers(Control control) { control.Paint -= new PaintEventHandler(Control_Paint); control.ControlAdded -= new ControlEventHandler(Control_ControlAdded); foreach (Control child in control.Controls) DisconnectPaintEventHandlers(child); } private void OnPaint(object sender, PaintEventArgs e) { if (Paint != null) Paint(sender, e); } #endregion #region Trigger private void OverlayPainter_Disposed(object sender, EventArgs e) { if (null != _form) DisconnectPaintEventHandlers(_form); } private void Form_Resize(object sender, EventArgs e) { if(null != _form) _form.Invalidate(true); } private void Control_ControlAdded(object sender, ControlEventArgs e) { ConnectPaintEventHandlers(e.Control); } private void Control_Paint(object sender, PaintEventArgs e) { if (null == _form || _form.IsDisposed) return; Control control = sender as Control; Point location; if (control == _form) location = control.Location; else { location = _form.PointToClient(control.Parent.PointToScreen(control.Location)); location += new Size((control.Width - control.ClientSize.Width) / 2, (control.Height - control.ClientSize.Height) / 2); } if (control != _form) e.Graphics.TranslateTransform(-location.X, -location.Y); OnPaint(sender, e); } #endregion } } namespace System.Windows.Forms { using System.Drawing; public static class Extensions { /// <summary> /// Coordinates from control on toplevel control or desktop /// </summary> /// <param name="control">target control</param> /// <returns>coordinates</returns> public static Rectangle Coordinates(this Control control) { Rectangle coordinates; Form form = control.TopLevelControl as Form; if (control == form) coordinates = form.ClientRectangle; else coordinates = form.RectangleToClient(control.Parent.RectangleToScreen(control.Bounds)); return coordinates; } } }
NetOfficeFw/NetOffice
Toolbox/Toolbox/Controls/Painter/OverlayPainter.cs
C#
mit
4,964
using System; using System.Diagnostics; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.I2c; namespace Lesson_203V2 { public class BME280_CalibrationData { //BME280 Registers public UInt16 dig_T1 { get; set; } public Int16 dig_T2 { get; set; } public Int16 dig_T3 { get; set; } public UInt16 dig_P1 { get; set; } public Int16 dig_P2 { get; set; } public Int16 dig_P3 { get; set; } public Int16 dig_P4 { get; set; } public Int16 dig_P5 { get; set; } public Int16 dig_P6 { get; set; } public Int16 dig_P7 { get; set; } public Int16 dig_P8 { get; set; } public Int16 dig_P9 { get; set; } public byte dig_H1 { get; set; } public Int16 dig_H2 { get; set; } public byte dig_H3 { get; set; } public Int16 dig_H4 { get; set; } public Int16 dig_H5 { get; set; } public SByte dig_H6 { get; set; } } public class BME280Sensor { //The BME280 register addresses according the the datasheet: http://www.adafruit.com/datasheets/BST-BME280-DS001-11.pdf const byte BME280_Address = 0x77; const byte BME280_Signature = 0x60; enum eRegisters : byte { BME280_REGISTER_DIG_T1 = 0x88, BME280_REGISTER_DIG_T2 = 0x8A, BME280_REGISTER_DIG_T3 = 0x8C, BME280_REGISTER_DIG_P1 = 0x8E, BME280_REGISTER_DIG_P2 = 0x90, BME280_REGISTER_DIG_P3 = 0x92, BME280_REGISTER_DIG_P4 = 0x94, BME280_REGISTER_DIG_P5 = 0x96, BME280_REGISTER_DIG_P6 = 0x98, BME280_REGISTER_DIG_P7 = 0x9A, BME280_REGISTER_DIG_P8 = 0x9C, BME280_REGISTER_DIG_P9 = 0x9E, BME280_REGISTER_DIG_H1 = 0xA1, BME280_REGISTER_DIG_H2 = 0xE1, BME280_REGISTER_DIG_H3 = 0xE3, BME280_REGISTER_DIG_H4 = 0xE4, BME280_REGISTER_DIG_H5 = 0xE5, BME280_REGISTER_DIG_H6 = 0xE7, BME280_REGISTER_CHIPID = 0xD0, BME280_REGISTER_VERSION = 0xD1, BME280_REGISTER_SOFTRESET = 0xE0, BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0 BME280_REGISTER_CONTROLHUMID = 0xF2, BME280_REGISTER_CONTROL = 0xF4, BME280_REGISTER_CONFIG = 0xF5, BME280_REGISTER_PRESSUREDATA_MSB = 0xF7, BME280_REGISTER_PRESSUREDATA_LSB = 0xF8, BME280_REGISTER_PRESSUREDATA_XLSB = 0xF9, // bits <7:4> BME280_REGISTER_TEMPDATA_MSB = 0xFA, BME280_REGISTER_TEMPDATA_LSB = 0xFB, BME280_REGISTER_TEMPDATA_XLSB = 0xFC, // bits <7:4> BME280_REGISTER_HUMIDDATA_MSB = 0xFD, BME280_REGISTER_HUMIDDATA_LSB = 0xFE, }; //String for the friendly name of the I2C bus const string I2CControllerName = "I2C1"; //Create an I2C device private I2cDevice bme280 = null; //Create new calibration data for the sensor BME280_CalibrationData CalibrationData; //Variable to check if device is initialized bool init = false; //Method to initialize the BME280 sensor public async Task Initialize() { Debug.WriteLine("BME280::Initialize"); try { //Instantiate the I2CConnectionSettings using the device address of the BME280 I2cConnectionSettings settings = new I2cConnectionSettings(BME280_Address); //Set the I2C bus speed of connection to fast mode settings.BusSpeed = I2cBusSpeed.FastMode; //Use the I2CBus device selector to create an advanced query syntax string string aqs = I2cDevice.GetDeviceSelector(I2CControllerName); //Use the Windows.Devices.Enumeration.DeviceInformation class to create a collection using the advanced query syntax string DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs); //Instantiate the the BME280 I2C device using the device id of the I2CBus and the I2CConnectionSettings bme280 = await I2cDevice.FromIdAsync(dis[0].Id, settings); //Check if device was found if (bme280 == null) { Debug.WriteLine("Device not found"); } } catch (Exception e) { Debug.WriteLine("Exception: " + e.Message + "\n" + e.StackTrace); throw; } } private async Task Begin() { Debug.WriteLine("BME280::Begin"); byte[] WriteBuffer = new byte[] { (byte)eRegisters.BME280_REGISTER_CHIPID }; byte[] ReadBuffer = new byte[] { 0xFF }; //Read the device signature bme280.WriteRead(WriteBuffer, ReadBuffer); Debug.WriteLine("BME280 Signature: " + ReadBuffer[0].ToString()); //Verify the device signature if (ReadBuffer[0] != BME280_Signature) { Debug.WriteLine("BME280::Begin Signature Mismatch."); return; } //Set the initialize variable to true init = true; //Read the coefficients table CalibrationData = await ReadCoefficeints(); //Write control register await WriteControlRegister(); //Write humidity control register await WriteControlRegisterHumidity(); } //Method to write 0x03 to the humidity control register private async Task WriteControlRegisterHumidity() { byte[] WriteBuffer = new byte[] { (byte)eRegisters.BME280_REGISTER_CONTROLHUMID, 0x03 }; bme280.Write(WriteBuffer); await Task.Delay(1); return; } //Method to write 0x3F to the control register private async Task WriteControlRegister() { byte[] WriteBuffer = new byte[] { (byte)eRegisters.BME280_REGISTER_CONTROL, 0x3F }; bme280.Write(WriteBuffer); await Task.Delay(1); return; } //Method to read a 16-bit value from a register and return it in little endian format private UInt16 ReadUInt16_LittleEndian(byte register) { UInt16 value = 0; byte[] writeBuffer = new byte[] { 0x00 }; byte[] readBuffer = new byte[] { 0x00, 0x00 }; writeBuffer[0] = register; bme280.WriteRead(writeBuffer, readBuffer); int h = readBuffer[1] << 8; int l = readBuffer[0]; value = (UInt16)(h + l); return value; } //Method to read an 8-bit value from a register private byte ReadByte(byte register) { byte value = 0; byte[] writeBuffer = new byte[] { 0x00 }; byte[] readBuffer = new byte[] { 0x00 }; writeBuffer[0] = register; bme280.WriteRead(writeBuffer, readBuffer); value = readBuffer[0]; return value; } //Method to read the calibration data from the registers private async Task<BME280_CalibrationData> ReadCoefficeints() { // 16 bit calibration data is stored as Little Endian, the helper method will do the byte swap. CalibrationData = new BME280_CalibrationData(); // Read temperature calibration data CalibrationData.dig_T1 = ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_T1); CalibrationData.dig_T2 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_T2); CalibrationData.dig_T3 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_T3); // Read presure calibration data CalibrationData.dig_P1 = ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P1); CalibrationData.dig_P2 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P2); CalibrationData.dig_P3 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P3); CalibrationData.dig_P4 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P4); CalibrationData.dig_P5 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P5); CalibrationData.dig_P6 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P6); CalibrationData.dig_P7 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P7); CalibrationData.dig_P8 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P8); CalibrationData.dig_P9 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_P9); // Read humidity calibration data CalibrationData.dig_H1 = ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H1); CalibrationData.dig_H2 = (Int16)ReadUInt16_LittleEndian((byte)eRegisters.BME280_REGISTER_DIG_H2); CalibrationData.dig_H3 = ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H3); CalibrationData.dig_H4 = (Int16)((ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H4) << 4) | (ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H4 + 1) & 0xF)); CalibrationData.dig_H5 = (Int16)((ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H5 + 1) << 4) | (ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H5) >> 4)); CalibrationData.dig_H6 = (sbyte)ReadByte((byte)eRegisters.BME280_REGISTER_DIG_H6); await Task.Delay(1); return CalibrationData; } //t_fine carries fine temperature as global value Int32 t_fine = Int32.MinValue; //Method to return the temperature in DegC. Resolution is 0.01 DegC. Output value of “5123” equals 51.23 DegC. private double BME280_compensate_T_double(Int32 adc_T) { double var1, var2, T; //The temperature is calculated using the compensation formula in the BME280 datasheet var1 = ((adc_T / 16384.0) - (CalibrationData.dig_T1 / 1024.0)) * CalibrationData.dig_T2; var2 = ((adc_T / 131072.0) - (CalibrationData.dig_T1 / 8192.0)) * CalibrationData.dig_T3; t_fine = (Int32)(var1 + var2); T = (var1 + var2) / 5120.0; return T; } //Method to returns the pressure in Pa, in Q24.8 format (24 integer bits and 8 fractional bits). //Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa private Int64 BME280_compensate_P_Int64(Int32 adc_P) { Int64 var1, var2, p; //The pressure is calculated using the compensation formula in the BME280 datasheet var1 = t_fine - 128000; var2 = var1 * var1 * (Int64)CalibrationData.dig_P6; var2 = var2 + ((var1 * (Int64)CalibrationData.dig_P5) << 17); var2 = var2 + ((Int64)CalibrationData.dig_P4 << 35); var1 = ((var1 * var1 * (Int64)CalibrationData.dig_P3) >> 8) + ((var1 * (Int64)CalibrationData.dig_P2) << 12); var1 = (((((Int64)1 << 47) + var1)) * (Int64)CalibrationData.dig_P1) >> 33; if (var1 == 0) { Debug.WriteLine("BME280_compensate_P_Int64 Jump out to avoid / 0"); return 0; //Avoid exception caused by division by zero } //Perform calibration operations as per datasheet: http://www.adafruit.com/datasheets/BST-BME280-DS001-11.pdf p = 1048576 - adc_P; p = (((p << 31) - var2) * 3125) / var1; var1 = ((Int64)CalibrationData.dig_P9 * (p >> 13) * (p >> 13)) >> 25; var2 = ((Int64)CalibrationData.dig_P8 * p) >> 19; p = ((p + var1 + var2) >> 8) + ((Int64)CalibrationData.dig_P7 << 4); return p; } // Returns humidity in %RH as unsigned 32 bit integer in Q22.10 format (22 integer and 10 fractional bits). // Output value of “47445” represents 47445/1024 = 46.333 %RH UInt32 bme280_compensate_H_int32(Int32 adc_H) { Int32 v_x1_u32r; v_x1_u32r = (t_fine - ((Int32)76800)); v_x1_u32r = (((((adc_H << 14) - (((Int32)CalibrationData.dig_H4) << 20) - (((Int32)CalibrationData.dig_H5) * v_x1_u32r)) + ((Int32)16384)) >> 15) * (((((((v_x1_u32r * ((Int32)CalibrationData.dig_H6)) >> 10) * (((v_x1_u32r * ((Int32)CalibrationData.dig_H3)) >> 11) + ((Int32)32768))) >> 10) + ((Int32)2097152)) * ((Int32)CalibrationData.dig_H2) + 8192) >> 14)); v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((Int32)CalibrationData.dig_H1)) >> 4)); v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r); v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r); return (UInt32)(v_x1_u32r >> 12); } public async Task<float> ReadTemperature() { //Make sure the I2C device is initialized if (!init) await Begin(); //Read the MSB, LSB and bits 7:4 (XLSB) of the temperature from the BME280 registers byte tmsb = ReadByte((byte)eRegisters.BME280_REGISTER_TEMPDATA_MSB); byte tlsb = ReadByte((byte)eRegisters.BME280_REGISTER_TEMPDATA_LSB); byte txlsb = ReadByte((byte)eRegisters.BME280_REGISTER_TEMPDATA_XLSB); // bits 7:4 //Combine the values into a 32-bit integer Int32 t = (tmsb << 12) + (tlsb << 4) + (txlsb >> 4); //Convert the raw value to the temperature in degC double temp = BME280_compensate_T_double(t); //Return the temperature as a float value return (float)temp; } public async Task<float> ReadPreasure() { //Make sure the I2C device is initialized if (!init) await Begin(); //Read the temperature first to load the t_fine value for compensation if (t_fine == Int32.MinValue) { await ReadTemperature(); } //Read the MSB, LSB and bits 7:4 (XLSB) of the pressure from the BME280 registers byte tmsb = ReadByte((byte)eRegisters.BME280_REGISTER_PRESSUREDATA_MSB); byte tlsb = ReadByte((byte)eRegisters.BME280_REGISTER_PRESSUREDATA_LSB); byte txlsb = ReadByte((byte)eRegisters.BME280_REGISTER_PRESSUREDATA_XLSB); // bits 7:4 //Combine the values into a 32-bit integer Int32 t = (tmsb << 12) + (tlsb << 4) + (txlsb >> 4); //Convert the raw value to the pressure in Pa Int64 pres = BME280_compensate_P_Int64(t); //Return the temperature as a float value return ((float)pres) / 256; } public async Task<float> ReadHumidity() { if (!init) await Begin(); byte tmsb = ReadByte((byte)eRegisters.BME280_REGISTER_HUMIDDATA_MSB); byte tlsb = ReadByte((byte)eRegisters.BME280_REGISTER_HUMIDDATA_LSB); Int32 uncompensated = (tmsb << 8) + tlsb; UInt32 humidity = bme280_compensate_H_int32(uncompensated); return ((float)humidity) / 1000; } //Method to take the sea level pressure in Hectopascals(hPa) as a parameter and calculate the altitude using current pressure. public async Task<float> ReadAltitude(float seaLevel) { //Make sure the I2C device is initialized if (!init) await Begin(); //Read the pressure first float pressure = await ReadPreasure(); //Convert the pressure to Hectopascals(hPa) pressure /= 100; //Calculate and return the altitude using the international barometric formula return 44330.0f * (1.0f - (float)Math.Pow((pressure / seaLevel), 0.1903f)); } } }
DavidShoe/adafruitsample
Lesson_203V2/FullSolution/BME280.cs
C#
mit
16,192
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Braintree\Gateway\Response; use Magento\Payment\Gateway\Response\HandlerInterface; use Magento\Braintree\Gateway\Helper\SubjectReader; use Magento\Sales\Api\Data\OrderPaymentInterface; /** * Class PayPalDetailsHandler */ class PayPalDetailsHandler implements HandlerInterface { const PAYMENT_ID = 'paymentId'; const PAYER_EMAIL = 'payerEmail'; /** * @var SubjectReader */ private $subjectReader; /** * Constructor * * @param SubjectReader $subjectReader */ public function __construct(SubjectReader $subjectReader) { $this->subjectReader = $subjectReader; } /** * @inheritdoc */ public function handle(array $handlingSubject, array $response) { $paymentDO = $this->subjectReader->readPayment($handlingSubject); /** @var \Braintree\Transaction $transaction */ $transaction = $this->subjectReader->readTransaction($response); /** @var OrderPaymentInterface $payment */ $payment = $paymentDO->getPayment(); $payPal = $this->subjectReader->readPayPal($transaction); $payment->setAdditionalInformation(self::PAYMENT_ID, $payPal[self::PAYMENT_ID]); $payment->setAdditionalInformation(self::PAYER_EMAIL, $payPal[self::PAYER_EMAIL]); } }
j-froehlich/magento2_wk
vendor/magento/module-braintree/Gateway/Response/PayPalDetailsHandler.php
PHP
mit
1,434
<?php namespace PROCERGS\LoginCidadao\CoreBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\EntityManager; use PROCERGS\LoginCidadao\NotificationBundle\Entity\Category; use PROCERGS\OAuthBundle\Entity\Client; use Symfony\Component\HttpFoundation\File\File; class PopulateDatabaseCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('login-cidadao:database:populate') ->setDescription('Populates the database.') ->addArgument('dump_folder', InputArgument::REQUIRED, 'Where are the dumps?'); } protected function execute(InputInterface $input, OutputInterface $output) { $dir = realpath($input->getArgument('dump_folder')); $this->loadDumpFiles($dir, $output); $this->createDefaultOAuthClient($dir, $output); $this->createCategories($output); } private function loadDumpFiles($dir, OutputInterface $output) { $em = $this->getManager(); $db = $em->getConnection(); $db->beginTransaction(); try { $db->exec('DELETE FROM city;'); $db->exec('DELETE FROM state;'); $db->exec('DELETE FROM country;'); $countryInsert = 'INSERT INTO country (id, name, iso2, postal_format, postal_name, reviewed, iso3, iso_num) VALUES (:id, :name, :iso2, :postal_format, :postal_name, :reviewed, :iso3, :iso_num)'; $countryQuery = $db->prepare($countryInsert); $countries = $this->loopInsert($dir, 'country_dump.csv', $countryQuery, array($this, 'prepareCountryData')); $statesInsert = 'INSERT INTO state (id, name, acronym, country_id, iso6, fips, stat, class, reviewed) VALUES (:id, :name, :acronym, :country_id, :iso6, :fips, :stat, :class, :reviewed)'; $statesQuery = $db->prepare($statesInsert); $states = $this->loopInsert($dir, 'state_dump.csv', $statesQuery, array($this, 'prepareStateData')); $citiesInsert = 'INSERT INTO city (id, name, state_id, stat, reviewed) VALUES (:id, :name, :state_id, :stat, :reviewed)'; $citiesQuery = $db->prepare($citiesInsert); $cities = $this->loopInsert($dir, 'city_dump.csv', $citiesQuery, array($this, 'prepareCityData')); $db->commit(); } catch (Exception $e) { $db->rollBack(); } $output->writeln("Added $countries countries, $states states and $cities cities."); } /** * * @return EntityManager */ private function getManager() { return $this->getContainer()->get('doctrine')->getManager(); } protected function prepareCountryData($row) { list($id, $name, $iso2, $postal_format, $postal_name, $reviewed, $iso3, $iso_num) = $row; $vars = compact('id', 'name', 'iso2', 'postal_format', 'postal_name', 'reviewed', 'iso3', 'iso_num'); foreach ($vars as $k => $v) { if ($v === "") { $vars[$k] = null; } } return $vars; } protected function prepareStateData($row) { list($id, $name, $acronym, $country_id, $iso6, $fips, $stat, $class, $reviewed) = $row; return compact('id', 'name', 'acronym', 'country_id', 'iso6', 'fips', 'stat', 'class', 'reviewed'); } protected function prepareCityData($row) { list($id, $name, $state_id, $stat, $reviewed) = $row; return compact('id', 'name', 'state_id', 'stat', 'reviewed'); } private function loopInsert($dir, $fileName, $query, $prepareFunction, $debug = false) { $entries = 0; $file = $dir . DIRECTORY_SEPARATOR . $fileName; if (($handle = fopen($file, 'r')) !== false) { while (($row = fgetcsv($handle)) !== false) { $data = $prepareFunction($row); if ($debug) { var_dump($data); } $query->execute($data); $entries++; } fclose($handle); } return $entries; } protected function createDefaultOAuthClient($dir, OutputInterface $output) { if (!($this->getDefaultOAuthClient() instanceof Client)) { $uid = $this->getContainer()->getParameter('oauth_default_client.uid'); $pictureName = 'meurs_logo.png'; $picture = new File($dir . DIRECTORY_SEPARATOR . $pictureName); $domain = $this->getContainer()->getParameter('site_domain'); $url = "//$domain"; $grantTypes = array( "authorization_code", "token", "password", "client_credentials", "refresh_token", "extensions" ); $clientManager = $this->getContainer()->get('fos_oauth_server.client_manager'); $client = $clientManager->createClient(); $client->setName('Login Cidadão'); $client->setDescription('Login Cidadão'); $client->setSiteUrl($url); $client->setRedirectUris(array($url)); $client->setAllowedGrantTypes($grantTypes); $client->setTermsOfUseUrl($url); $client->setPublished(true); $client->setVisible(false); $client->setUid($uid); $client->setPictureFile($picture); $clientManager->updateClient($client); $output->writeln('Default Client created.'); } } protected function createCategories(OutputInterface $output) { $em = $this->getManager(); $categories = $em->getRepository('PROCERGSLoginCidadaoNotificationBundle:Category'); $alertCategoryUid = $this->getContainer()->getParameter('notifications_categories_alert.uid'); $alertCategory = $categories->findOneByUid($alertCategoryUid); if (!($alertCategory instanceof Category)) { $alertCategory = new Category(); $alertCategory->setClient($this->getDefaultOAuthClient()) ->setDefaultShortText('Alert') ->setDefaultTitle('Alert') ->setDefaultIcon('alert') ->setMarkdownTemplate('%shorttext%') ->setEmailable(false) ->setName('Alerts') ->setUid($alertCategoryUid); $em->persist($alertCategory); $em->flush(); $output->writeln('Alert category created.'); } } /** * @return Client */ private function getDefaultOAuthClient() { $em = $this->getManager(); $uid = $this->getContainer()->getParameter('oauth_default_client.uid'); $client = $em->getRepository('PROCERGSOAuthBundle:Client')->findOneByUid($uid); return $client; } }
gilsondev/login-cidadao
src/PROCERGS/LoginCidadao/CoreBundle/Command/PopulateDatabaseCommand.php
PHP
mit
7,080
(function($) { // Some vars var template = '/field/link'; // Tabs $(document).on('click', '.adminContext .tabs li', function() { // Some vars var $admincontext = $(this).parents('.adminContext'); var $tabs = $admincontext.find('.tabs'); var $panels = $admincontext.find('.panels'); var currentTab = $(this).data('tab'); // Close all tabs & panels $tabs.find('>li').attr('class', 'off'); $panels.find('>div').attr('class', 'off'); // Open the right one $tabs.find('>li[data-tab="'+currentTab+'"]').attr('class', 'on'); $panel = $panels.find('>div[data-panel="'+currentTab+'"]'); $panel.attr('class', 'on'); // Init the panel (cameltoe function initCurrenttab) var function_name = 'init'+currentTab.charAt(0).toUpperCase() + currentTab.slice(1); window[function_name]($panel); }); // Init internal linking initInternal = function(panel) { // restore selection when blur input $('.adminContext').on('blur', 'input[type="search"]', function() { restoreSelection(selRange); // selRange = false; }); // Send Internal link $(document).on('click', '.adminContext[data-template="/field/link"] [data-panel="internal"] [data-item] button', function(e) { if (selRange !== null) { restoreSelection(selRange); var link = $(this).parent().data('item'); // console.log(link) document.execCommand('CreateLink', false, link); closeContext(template); selRange = null; }; }); // Refine item lists $('.adminContext[data-template="/field/link"] [data-panel="internal"] input[type="search"]').each(function() { // Some vars var $input = $(this); var item = $input.data('item'); var $target = $(this).next('ul'); // Search as you type $input.searchasyoutype( { app:'sirtrevor', template:'/field/link.internal', param:'{"item":"'+item+'"}', target:$target, }) // Start with something .trigger('input'); }); } // Init external linking initExternal = function(panel) { // Send external link $(document).on('click', '.adminContext[data-template="/field/link"] [data-panel="external"] button.done', function() { // Get the value from the iframe var link = $(this).parent().find('iframe').contents().find('input').val(); // Good link if(link && link.length > 0) { var link_regex = /(ftp|http|https):\/\/./; if (!link_regex.test(link)) link = "http://" + link; document.execCommand('CreateLink', false, link); closeContext(template); } // Bad link else console.log('That is not a valid URL, buddy'); }); } // Init media linking initMedia = function(panel) { panel.ajx( { app:'media', template:'admin', }, { done:function() { // Override "Edit a media"... $('#mediaLibrary').off('click', 'a.file'); // ...with "send the link" $(document).on('click', '.adminContext[data-template="/field/link"] #mediaLibrary a.file', function() { url = $(this).parent().data('url'); // Send link document.execCommand('CreateLink', false, url); closeContext(template); }); } }); } // Open one by default $('.adminContext .tabs li[data-tab="internal"]').trigger('click'); })(jQuery);
hands-agency/grandcentral
grandcentral/sirtrevor/template/field/js/link.js
JavaScript
mit
3,216
class JobsController < ApplicationController before_action :load_job def show if @job.completed? show_completed_job elsif @job.errored? show_errored_job else show_submitted_job end end protected def publicly_accessible? true end private def load_job @job ||= TrackableJob::Job.find(params[:id]) end def show_completed_job redirect_to @job.redirect_to if @job.redirect_to.present? end def show_errored_job if @job.redirect_to.present? redirect_to @job.redirect_to else response.status = :internal_server_error end end def show_submitted_job response.status = :accepted end end
BenMQ/coursemology2
app/controllers/jobs_controller.rb
Ruby
mit
688
<!-- DataTables --> <script src="<?php echo base_url(); ?>assets/plugins/datatables/jquery.dataTables.min.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.min.js"></script> <script type="text/javascript"> $(function () { $('#tableOrnamenAtas,#tableOrnamenKonten,#tableOrnamenBawah').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": false, // "scrollX":"400px", "scrollCollapse": true, "info": false, "autoWidth": false, "pageLength":5 }); }); $('#editOrnamen').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var id = button.data('id') // Extract info from data-* attributes var image = button.data('image') // Extract info from data-* attributes var type = button.data('type') // Extract info from data-* attributes var kode = button.data('kode') // Extract info from data-* attributes var gambarTemp = button.data('gambartemp') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) // modal.find('.modal-title').text('New message to ' + recipient) // modal.find('.modal-body input').val(recipient) modal.find('#gambarTemp').attr('src',image) modal.find('#idUpdate').attr('value',id) modal.find('#typeUpdate').attr('value',type) modal.find('#kodeUpdate').attr('value',kode) modal.find('#gambarTempUpdate').attr('value',gambarTemp) }) $('#deleteOrnamen').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var link = button.data('link') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) // modal.find('.modal-title').text('New message to ' + recipient) // modal.find('.modal-body input').val(recipient) modal.find('#linkDeleteOrnamen').attr('href',link) }) $('#addOrnamen').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var type = button.data('type') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) // modal.find('.modal-title').text('New message to ' + recipient) // modal.find('.modal-body input').val(recipient) modal.find('#typeAdd').attr('value',type) }) </script>
reeganaga/SI-lelang
application/views/back/ornamen/custom_js.php
PHP
mit
3,029
from __future__ import unicode_literals, division, absolute_import import argparse import logging import re import time from copy import copy from datetime import datetime, timedelta from sqlalchemy import (Column, Integer, String, Unicode, DateTime, Boolean, desc, select, update, delete, ForeignKey, Index, func, and_, not_, UniqueConstraint) from sqlalchemy.orm import relation, backref from sqlalchemy.ext.hybrid import Comparator, hybrid_property from sqlalchemy.exc import OperationalError, IntegrityError from flexget import db_schema, options, plugin from flexget.config_schema import one_or_more from flexget.event import event from flexget.manager import Session from flexget.utils import qualities from flexget.utils.log import log_once from flexget.plugins.parsers import ParseWarning, SERIES_ID_TYPES from flexget.plugin import get_plugin_by_name from flexget.utils.sqlalchemy_utils import (table_columns, table_exists, drop_tables, table_schema, table_add_column, create_index) from flexget.utils.tools import merge_dict_from_to, parse_timedelta from flexget.utils.database import quality_property SCHEMA_VER = 12 log = logging.getLogger('series') Base = db_schema.versioned_base('series', SCHEMA_VER) @db_schema.upgrade('series') def upgrade(ver, session): if ver is None: if table_exists('episode_qualities', session): log.info('Series database format is too old to upgrade, dropping and recreating tables.') # Drop the deprecated data drop_tables(['series', 'series_episodes', 'episode_qualities'], session) # Create new tables from the current models Base.metadata.create_all(bind=session.bind) # Upgrade episode_releases table to have a proper count and seed it with appropriate numbers columns = table_columns('episode_releases', session) if not 'proper_count' in columns: log.info('Upgrading episode_releases table to have proper_count column') table_add_column('episode_releases', 'proper_count', Integer, session) release_table = table_schema('episode_releases', session) for row in session.execute(select([release_table.c.id, release_table.c.title])): # Recalculate the proper_count from title for old episodes proper_count = get_plugin_by_name('parsing').parse_series(row['title']).proper_count session.execute(update(release_table, release_table.c.id == row['id'], {'proper_count': proper_count})) ver = 0 if ver == 0: log.info('Migrating first_seen column from series_episodes to episode_releases table.') # Create the column in episode_releases table_add_column('episode_releases', 'first_seen', DateTime, session) # Seed the first_seen value for all the past releases with the first_seen of their episode. episode_table = table_schema('series_episodes', session) release_table = table_schema('episode_releases', session) for row in session.execute(select([episode_table.c.id, episode_table.c.first_seen])): session.execute(update(release_table, release_table.c.episode_id == row['id'], {'first_seen': row['first_seen']})) ver = 1 if ver == 1: log.info('Adding `identified_by` column to series table.') table_add_column('series', 'identified_by', String, session) ver = 2 if ver == 2: log.info('Creating index on episode_releases table.') create_index('episode_releases', session, 'episode_id') ver = 3 if ver == 3: # Remove index on Series.name try: Index('ix_series_name').drop(bind=session.bind) except OperationalError: log.debug('There was no ix_series_name index to remove.') # Add Series.name_lower column log.info('Adding `name_lower` column to series table.') table_add_column('series', 'name_lower', Unicode, session) series_table = table_schema('series', session) create_index('series', session, 'name_lower') # Fill in lower case name column session.execute(update(series_table, values={'name_lower': func.lower(series_table.c.name)})) ver = 4 if ver == 4: log.info('Adding `identified_by` column to episodes table.') table_add_column('series_episodes', 'identified_by', String, session) series_table = table_schema('series', session) # Clear out identified_by id series so that they can be auto detected again session.execute(update(series_table, series_table.c.identified_by != 'ep', {'identified_by': None})) # Warn users about a possible config change needed. log.warning('If you are using `identified_by: id` option for the series plugin for date, ' 'or abolute numbered series, you will need to update your config. Two new identified_by modes have ' 'been added, `date` and `sequence`. In addition, if you are using auto identified_by, it will' 'be relearned based on upcoming episodes.') ver = 5 if ver == 5: # Episode advancement now relies on identified_by being filled for the episodes. # This action retroactively marks 'ep' mode for all episodes where the series is already in 'ep' mode. series_table = table_schema('series', session) ep_table = table_schema('series_episodes', session) ep_mode_series = select([series_table.c.id], series_table.c.identified_by == 'ep') where_clause = and_(ep_table.c.series_id.in_(ep_mode_series), ep_table.c.season != None, ep_table.c.number != None, ep_table.c.identified_by == None) session.execute(update(ep_table, where_clause, {'identified_by': 'ep'})) ver = 6 if ver == 6: # Translate old qualities into new quality requirements release_table = table_schema('episode_releases', session) for row in session.execute(select([release_table.c.id, release_table.c.quality])): # Webdl quality no longer has dash new_qual = row['quality'].replace('web-dl', 'webdl') if row['quality'] != new_qual: session.execute(update(release_table, release_table.c.id == row['id'], {'quality': new_qual})) ver = 7 # Normalization rules changed for 7 and 8, but only run this once if ver in [7, 8]: # Merge series that qualify as duplicates with new normalization scheme series_table = table_schema('series', session) ep_table = table_schema('series_episodes', session) all_series = session.execute(select([series_table.c.name, series_table.c.id])) unique_series = {} for row in all_series: unique_series.setdefault(normalize_series_name(row['name']), []).append(row['id']) for series, ids in unique_series.iteritems(): session.execute(update(ep_table, ep_table.c.series_id.in_(ids), {'series_id': ids[0]})) if len(ids) > 1: session.execute(delete(series_table, series_table.c.id.in_(ids[1:]))) session.execute(update(series_table, series_table.c.id == ids[0], {'name_lower': series})) ver = 9 if ver == 9: table_add_column('series', 'begin_episode_id', Integer, session) ver = 10 if ver == 10: # Due to bad db cleanups there may be invalid entries in series_tasks table series_tasks = table_schema('series_tasks', session) series_table = table_schema('series', session) log.verbose('Repairing series_tasks table data') session.execute(delete(series_tasks, ~series_tasks.c.series_id.in_(select([series_table.c.id])))) ver = 11 if ver == 11: # SeriesTasks was cleared out due to a bug, make sure they get recalculated next run #2772 from flexget.task import config_changed config_changed() ver = 12 return ver @event('manager.db_cleanup') def db_cleanup(session): # Clean up old undownloaded releases result = session.query(Release).\ filter(Release.downloaded == False).\ filter(Release.first_seen < datetime.now() - timedelta(days=120)).delete(False) if result: log.verbose('Removed %d undownloaded episode releases.', result) # Clean up episodes without releases result = session.query(Episode).filter(~Episode.releases.any()).filter(~Episode.begins_series.any()).delete(False) if result: log.verbose('Removed %d episodes without releases.', result) # Clean up series without episodes that aren't in any tasks result = session.query(Series).filter(~Series.episodes.any()).filter(~Series.in_tasks.any()).delete(False) if result: log.verbose('Removed %d series without episodes.', result) @event('manager.lock_acquired') def repair(manager): # Perform database repairing and upgrading at startup. if not manager.persist.get('series_repaired', False): session = Session() try: # For some reason at least I have some releases in database which don't belong to any episode. for release in session.query(Release).filter(Release.episode == None).all(): log.info('Purging orphan release %s from database', release.title) session.delete(release) session.commit() finally: session.close() manager.persist['series_repaired'] = True # Run clean_series the first time we get a database lock, since we won't have had one the first time the config # got loaded. clean_series(manager) @event('manager.config_updated') def clean_series(manager): # Unmark series from tasks which have been deleted. if not manager.has_lock: return with Session() as session: removed_tasks = session.query(SeriesTask) if manager.tasks: removed_tasks = removed_tasks.filter(not_(SeriesTask.name.in_(manager.tasks))) deleted = removed_tasks.delete(synchronize_session=False) if deleted: session.commit() TRANSLATE_MAP = {ord(u'&'): u' and '} for char in u'\'\\': TRANSLATE_MAP[ord(char)] = u'' for char in u'_./-,[]():': TRANSLATE_MAP[ord(char)] = u' ' def normalize_series_name(name): """Returns a normalized version of the series name.""" name = name.lower() name = name.replace('&amp;', ' and ') name = name.translate(TRANSLATE_MAP) # Replaced some symbols with spaces name = u' '.join(name.split()) return name class NormalizedComparator(Comparator): def operate(self, op, other): return op(self.__clause_element__(), normalize_series_name(other)) class AlternateNames(Base): """ Similar to Series. Name is handled case insensitively transparently. """ __tablename__ = 'series_alternate_names' id = Column(Integer, primary_key=True) _alt_name = Column('alt_name', Unicode) _alt_name_normalized = Column('alt_name_normalized', Unicode, index=True, unique=True) series_id = Column(Integer, ForeignKey('series.id'), nullable=False) def name_setter(self, value): self._alt_name = value self._alt_name_normalized = normalize_series_name(value) def name_getter(self): return self._alt_name def name_comparator(self): return NormalizedComparator(self._alt_name_normalized) alt_name = hybrid_property(name_getter, name_setter) alt_name.comparator(name_comparator) def __init__(self, name): self.alt_name = name def __unicode__(self): return '<SeriesAlternateName(series_id=%s, alt_name=%s)>' % (self.series_id, self.alt_name) def __repr__(self): return unicode(self).encode('ascii', 'replace') #Index('alternatenames_series_name', AlternateNames.alt_name, unique=True) class Series(Base): """ Name is handled case insensitively transparently """ __tablename__ = 'series' id = Column(Integer, primary_key=True) _name = Column('name', Unicode) _name_normalized = Column('name_lower', Unicode, index=True, unique=True) identified_by = Column(String) begin_episode_id = Column(Integer, ForeignKey('series_episodes.id', name='begin_episode_id', use_alter=True)) begin = relation('Episode', uselist=False, primaryjoin="Series.begin_episode_id == Episode.id", foreign_keys=[begin_episode_id], post_update=True, backref='begins_series') episodes = relation('Episode', backref='series', cascade='all, delete, delete-orphan', primaryjoin='Series.id == Episode.series_id') in_tasks = relation('SeriesTask', backref=backref('series', uselist=False), cascade='all, delete, delete-orphan') alternate_names = relation('AlternateNames', backref='series', primaryjoin='Series.id == AlternateNames.series_id', cascade='all, delete, delete-orphan') # Make a special property that does indexed case insensitive lookups on name, but stores/returns specified case def name_getter(self): return self._name def name_setter(self, value): self._name = value self._name_normalized = normalize_series_name(value) def name_comparator(self): return NormalizedComparator(self._name_normalized) name = hybrid_property(name_getter, name_setter) name.comparator(name_comparator) def __unicode__(self): return '<Series(id=%s,name=%s)>' % (self.id, self.name) def __repr__(self): return unicode(self).encode('ascii', 'replace') class Episode(Base): __tablename__ = 'series_episodes' id = Column(Integer, primary_key=True) identifier = Column(String) season = Column(Integer) number = Column(Integer) identified_by = Column(String) series_id = Column(Integer, ForeignKey('series.id'), nullable=False) releases = relation('Release', backref='episode', cascade='all, delete, delete-orphan') @hybrid_property def first_seen(self): if not self.releases: return None return min(release.first_seen for release in self.releases) @first_seen.expression def first_seen(cls): return select([func.min(Release.first_seen)]).where(Release.episode_id == cls.id).\ correlate(Episode.__table__).label('first_seen') @property def age(self): """ :return: Pretty string representing age of episode. eg "23d 12h" or "No releases seen" """ if not self.first_seen: return 'No releases seen' diff = datetime.now() - self.first_seen age_days = diff.days age_hours = diff.seconds // 60 // 60 age = '' if age_days: age += '%sd ' % age_days age += '%sh' % age_hours return age @property def is_premiere(self): if self.season == 1 and self.number in (0, 1): return 'Series Premiere' elif self.number in (0, 1): return 'Season Premiere' return False @property def downloaded_releases(self): return [release for release in self.releases if release.downloaded] def __unicode__(self): return '<Episode(id=%s,identifier=%s,season=%s,number=%s)>' % \ (self.id, self.identifier, self.season, self.number) def __repr__(self): return unicode(self).encode('ascii', 'replace') def __eq__(self, other): if not isinstance(other, Episode): return NotImplemented if self.identified_by != other.identified_by: return NotImplemented return self.identifier == other.identifier def __lt__(self, other): if not isinstance(other, Episode): return NotImplemented if self.identified_by != other.identified_by: return NotImplemented if self.identified_by in ['ep', 'sequence']: return self.season < other.season or (self.season == other.season and self.number < other.number) if self.identified_by == 'date': return self.identifier < other.identifier # Can't compare id type identifiers return NotImplemented Index('episode_series_identifier', Episode.series_id, Episode.identifier) class Release(Base): __tablename__ = 'episode_releases' id = Column(Integer, primary_key=True) episode_id = Column(Integer, ForeignKey('series_episodes.id'), nullable=False, index=True) _quality = Column('quality', String) quality = quality_property('_quality') downloaded = Column(Boolean, default=False) proper_count = Column(Integer, default=0) title = Column(Unicode) first_seen = Column(DateTime) def __init__(self): self.first_seen = datetime.now() @property def proper(self): # TODO: TEMP import warnings warnings.warn("accessing deprecated release.proper, use release.proper_count instead") return self.proper_count > 0 def __unicode__(self): return '<Release(id=%s,quality=%s,downloaded=%s,proper_count=%s,title=%s)>' % \ (self.id, self.quality, self.downloaded, self.proper_count, self.title) def __repr__(self): return unicode(self).encode('ascii', 'replace') class SeriesTask(Base): __tablename__ = 'series_tasks' id = Column(Integer, primary_key=True) series_id = Column(Integer, ForeignKey('series.id'), nullable=False) name = Column(Unicode, index=True) def __init__(self, name): self.name = name def get_latest_episode(series): """Return latest known identifier in dict (season, episode, name) for series name""" session = Session.object_session(series) episode = session.query(Episode).join(Episode.series).\ filter(Series.id == series.id).\ filter(Episode.season != None).\ order_by(desc(Episode.season)).\ order_by(desc(Episode.number)).first() if not episode: # log.trace('get_latest_info: no info available for %s', name) return False # log.trace('get_latest_info, series: %s season: %s episode: %s' % \ # (name, episode.season, episode.number)) return episode def auto_identified_by(series): """ Determine if series `name` should be considered identified by episode or id format Returns 'ep', 'sequence', 'date' or 'id' if enough history is present to identify the series' id type. Returns 'auto' if there is not enough history to determine the format yet """ session = Session.object_session(series) type_totals = dict(session.query(Episode.identified_by, func.count(Episode.identified_by)).join(Episode.series). filter(Series.id == series.id).group_by(Episode.identified_by).all()) # Remove None and specials from the dict, # we are only considering episodes that we know the type of (parsed with new parser) type_totals.pop(None, None) type_totals.pop('special', None) if not type_totals: return 'auto' log.debug('%s episode type totals: %r', series.name, type_totals) # Find total number of parsed episodes total = sum(type_totals.itervalues()) # See which type has the most best = max(type_totals, key=lambda x: type_totals[x]) # Ep mode locks in faster than the rest. At 2 seen episodes. if type_totals.get('ep', 0) >= 2 and type_totals['ep'] > total / 3: log.info('identified_by has locked in to type `ep` for %s', series.name) return 'ep' # If we have over 3 episodes all of the same type, lock in if len(type_totals) == 1 and total >= 3: return best # Otherwise wait until 5 episodes to lock in if total >= 5: log.info('identified_by has locked in to type `%s` for %s', best, series.name) return best log.verbose('identified by is currently on `auto` for %s. ' 'Multiple id types may be accepted until it locks in on the appropriate type.', series.name) return 'auto' def get_latest_release(series, downloaded=True, season=None): """ :param Series series: SQLAlchemy session :param Downloaded: find only downloaded releases :param Season: season to find newest release for :return: Instance of Episode or None if not found. """ session = Session.object_session(series) releases = session.query(Episode).join(Episode.releases, Episode.series).filter(Series.id == series.id) if downloaded: releases = releases.filter(Release.downloaded == True) if season is not None: releases = releases.filter(Episode.season == season) if series.identified_by and series.identified_by != 'auto': releases = releases.filter(Episode.identified_by == series.identified_by) if series.identified_by in ['ep', 'sequence']: latest_release = releases.order_by(desc(Episode.season), desc(Episode.number)).first() elif series.identified_by == 'date': latest_release = releases.order_by(desc(Episode.identifier)).first() else: latest_release = releases.order_by(desc(Episode.first_seen)).first() if not latest_release: log.debug('get_latest_release returning None, no downloaded episodes found for: %s', series.name) return return latest_release def new_eps_after(since_ep): """ :param since_ep: Episode instance :return: Number of episodes since then """ session = Session.object_session(since_ep) series = since_ep.series series_eps = session.query(Episode).join(Episode.series).\ filter(Series.id == series.id) if series.identified_by == 'ep': if since_ep.season is None or since_ep.number is None: log.debug('new_eps_after for %s falling back to timestamp because latest dl in non-ep format' % series.name) return series_eps.filter(Episode.first_seen > since_ep.first_seen).count() return series_eps.filter((Episode.identified_by == 'ep') & (((Episode.season == since_ep.season) & (Episode.number > since_ep.number)) | (Episode.season > since_ep.season))).count() elif series.identified_by == 'seq': return series_eps.filter(Episode.number > since_ep.number).count() elif series.identified_by == 'id': return series_eps.filter(Episode.first_seen > since_ep.first_seen).count() else: log.debug('unsupported identified_by %s', series.identified_by) return 0 def store_parser(session, parser, series=None): """ Push series information into database. Returns added/existing release. :param session: Database session to use :param parser: parser for release that should be added to database :param series: Series in database to add release to. Will be looked up if not provided. :return: List of Releases """ if not series: # if series does not exist in database, add new series = session.query(Series).\ filter(Series.name == parser.name).\ filter(Series.id != None).first() if not series: log.debug('adding series %s into db', parser.name) series = Series() series.name = parser.name session.add(series) log.debug('-> added %s' % series) releases = [] for ix, identifier in enumerate(parser.identifiers): # if episode does not exist in series, add new episode = session.query(Episode).filter(Episode.series_id == series.id).\ filter(Episode.identifier == identifier).\ filter(Episode.series_id != None).first() if not episode: log.debug('adding episode %s into series %s', identifier, parser.name) episode = Episode() episode.identifier = identifier episode.identified_by = parser.id_type # if episodic format if parser.id_type == 'ep': episode.season = parser.season episode.number = parser.episode + ix elif parser.id_type == 'sequence': episode.season = 0 episode.number = parser.id + ix series.episodes.append(episode) # pylint:disable=E1103 log.debug('-> added %s' % episode) # if release does not exists in episode, add new # # NOTE: # # filter(Release.episode_id != None) fixes weird bug where release had/has been added # to database but doesn't have episode_id, this causes all kinds of havoc with the plugin. # perhaps a bug in sqlalchemy? release = session.query(Release).filter(Release.episode_id == episode.id).\ filter(Release.title == parser.data).\ filter(Release.quality == parser.quality).\ filter(Release.proper_count == parser.proper_count).\ filter(Release.episode_id != None).first() if not release: log.debug('adding release %s into episode', parser) release = Release() release.quality = parser.quality release.proper_count = parser.proper_count release.title = parser.data episode.releases.append(release) # pylint:disable=E1103 log.debug('-> added %s' % release) releases.append(release) session.flush() # Make sure autonumber ids are populated return releases def set_series_begin(series, ep_id): """ Set beginning for series :param Series series: Series instance :param ep_id: Integer for sequence mode, SxxEyy for episodic and yyyy-mm-dd for date. :raises ValueError: If malformed ep_id or series in different mode """ # If identified_by is not explicitly specified, auto-detect it based on begin identifier # TODO: use some method of series parser to do the identifier parsing session = Session.object_session(series) if isinstance(ep_id, int): identified_by = 'sequence' elif re.match(r'(?i)^S\d{1,4}E\d{1,2}$', ep_id): identified_by = 'ep' ep_id = ep_id.upper() elif re.match(r'\d{4}-\d{2}-\d{2}', ep_id): identified_by = 'date' else: # Check if a sequence identifier was passed as a string try: ep_id = int(ep_id) identified_by = 'sequence' except ValueError: raise ValueError('`%s` is not a valid episode identifier' % ep_id) if series.identified_by not in ['auto', '', None]: if identified_by != series.identified_by: raise ValueError('`begin` value `%s` does not match identifier type for identified_by `%s`' % (ep_id, series.identified_by)) series.identified_by = identified_by episode = (session.query(Episode).filter(Episode.series_id == series.id). filter(Episode.identified_by == series.identified_by). filter(Episode.identifier == str(ep_id)).first()) if not episode: # TODO: Don't duplicate code from self.store method episode = Episode() episode.identifier = ep_id episode.identified_by = identified_by if identified_by == 'ep': match = re.match(r'S(\d+)E(\d+)', ep_id) episode.season = int(match.group(1)) episode.number = int(match.group(2)) elif identified_by == 'sequence': episode.season = 0 episode.number = ep_id series.episodes.append(episode) # Need to flush to get an id on new Episode before assigning it as series begin session.flush() series.begin = episode def forget_series(name): """Remove a whole series `name` from database.""" session = Session() try: series = session.query(Series).filter(Series.name == name).all() if series: for s in series: session.delete(s) session.commit() log.debug('Removed series %s from database.', name) else: raise ValueError('Unknown series %s' % name) finally: session.close() def forget_series_episode(name, identifier): """Remove all episodes by `identifier` from series `name` from database.""" session = Session() try: series = session.query(Series).filter(Series.name == name).first() if series: episode = session.query(Episode).filter(Episode.identifier == identifier).\ filter(Episode.series_id == series.id).first() if episode: series.identified_by = '' # reset identified_by flag so that it will be recalculated session.delete(episode) session.commit() log.debug('Episode %s from series %s removed from database.', identifier, name) else: raise ValueError('Unknown identifier %s for series %s' % (identifier, name.capitalize())) else: raise ValueError('Unknown series %s' % name) finally: session.close() def populate_entry_fields(entry, parser): entry['series_parser'] = copy(parser) # add series, season and episode to entry entry['series_name'] = parser.name if 'quality' in entry and entry['quality'] != parser.quality: log.verbose('Found different quality for %s. Was %s, overriding with %s.' % (entry['title'], entry['quality'], parser.quality)) entry['quality'] = parser.quality entry['proper'] = parser.proper entry['proper_count'] = parser.proper_count if parser.id_type == 'ep': entry['series_season'] = parser.season entry['series_episode'] = parser.episode elif parser.id_type == 'date': entry['series_date'] = parser.id entry['series_season'] = parser.id.year else: entry['series_season'] = time.gmtime().tm_year entry['series_episodes'] = parser.episodes entry['series_id'] = parser.pack_identifier entry['series_id_type'] = parser.id_type class FilterSeriesBase(object): """ Class that contains helper methods for both filter.series as well as plugins that configure it, such as all_series, series_premiere and configure_series. """ @property def settings_schema(self): return { 'title': 'series options', 'type': 'object', 'properties': { 'path': {'type': 'string'}, 'set': {'type': 'object'}, 'alternate_name': one_or_more({'type': 'string'}), # Custom regexp options 'name_regexp': one_or_more({'type': 'string', 'format': 'regex'}), 'ep_regexp': one_or_more({'type': 'string', 'format': 'regex'}), 'date_regexp': one_or_more({'type': 'string', 'format': 'regex'}), 'sequence_regexp': one_or_more({'type': 'string', 'format': 'regex'}), 'id_regexp': one_or_more({'type': 'string', 'format': 'regex'}), # Date parsing options 'date_yearfirst': {'type': 'boolean'}, 'date_dayfirst': {'type': 'boolean'}, # Quality options 'quality': {'type': 'string', 'format': 'quality_requirements'}, 'qualities': {'type': 'array', 'items': {'type': 'string', 'format': 'quality_requirements'}}, 'timeframe': {'type': 'string', 'format': 'interval'}, 'upgrade': {'type': 'boolean'}, 'target': {'type': 'string', 'format': 'quality_requirements'}, # Specials 'specials': {'type': 'boolean'}, # Propers (can be boolean, or an interval string) 'propers': {'type': ['boolean', 'string'], 'format': 'interval'}, # Identified by 'identified_by': { 'type': 'string', 'enum': ['ep', 'date', 'sequence', 'id', 'auto'] }, # Strict naming 'exact': {'type': 'boolean'}, # Begin takes an ep, sequence or date identifier 'begin': { 'oneOf': [ {'name': 'ep identifier', 'type': 'string', 'pattern': r'(?i)^S\d{2,4}E\d{2,3}$', 'error_pattern': 'episode identifiers should be in the form `SxxEyy`'}, {'name': 'date identifier', 'type': 'string', 'pattern': r'^\d{4}-\d{2}-\d{2}$', 'error_pattern': 'date identifiers must be in the form `YYYY-MM-DD`'}, {'name': 'sequence identifier', 'type': 'integer', 'minimum': 0} ] }, 'from_group': one_or_more({'type': 'string'}), 'parse_only': {'type': 'boolean'}, 'special_ids': one_or_more({'type': 'string'}), 'prefer_specials': {'type': 'boolean'}, 'assume_special': {'type': 'boolean'}, 'tracking': {'type': ['boolean', 'string'], 'enum': [True, False, 'backfill']} }, 'additionalProperties': False } def make_grouped_config(self, config): """Turns a simple series list into grouped format with a empty settings dict""" if not isinstance(config, dict): # convert simplest configuration internally grouped format config = {'simple': config, 'settings': {}} else: # already in grouped format, just make sure there's settings config.setdefault('settings', {}) return config def apply_group_options(self, config): """Applies group settings to each item in series group and removes settings dict.""" # Make sure config is in grouped format first config = self.make_grouped_config(config) for group_name in config: if group_name == 'settings': continue group_series = [] if isinstance(group_name, basestring): # if group name is known quality, convenience create settings with that quality try: qualities.Requirements(group_name) config['settings'].setdefault(group_name, {}).setdefault('target', group_name) except ValueError: # If group name is not a valid quality requirement string, do nothing. pass for series in config[group_name]: # convert into dict-form if necessary series_settings = {} group_settings = config['settings'].get(group_name, {}) if isinstance(series, dict): series, series_settings = series.items()[0] if series_settings is None: raise Exception('Series %s has unexpected \':\'' % series) # Make sure this isn't a series with no name if not series: log.warning('Series config contains a series with no name!') continue # make sure series name is a string to accommodate for "24" if not isinstance(series, basestring): series = unicode(series) # if series have given path instead of dict, convert it into a dict if isinstance(series_settings, basestring): series_settings = {'path': series_settings} # merge group settings into this series settings merge_dict_from_to(group_settings, series_settings) # Convert to dict if watched is in SXXEXX format if isinstance(series_settings.get('watched'), basestring): season, episode = series_settings['watched'].upper().split('E') season = season.lstrip('S') series_settings['watched'] = {'season': int(season), 'episode': int(episode)} # Convert enough to target for backwards compatibility if 'enough' in series_settings: log.warning('Series setting `enough` has been renamed to `target` please update your config.') series_settings.setdefault('target', series_settings['enough']) # Add quality: 720p if timeframe is specified with no target if 'timeframe' in series_settings and 'qualities' not in series_settings: series_settings.setdefault('target', '720p hdtv+') group_series.append({series: series_settings}) config[group_name] = group_series del config['settings'] return config def prepare_config(self, config): """Generate a list of unique series from configuration. This way we don't need to handle two different configuration formats in the logic. Applies group settings with advanced form.""" config = self.apply_group_options(config) return self.combine_series_lists(*config.values()) def combine_series_lists(self, *series_lists, **kwargs): """Combines the series from multiple lists, making sure there are no doubles. If keyword argument log_once is set to True, an error message will be printed if a series is listed more than once, otherwise log_once will be used.""" unique_series = {} for series_list in series_lists: for series in series_list: series, series_settings = series.items()[0] if series not in unique_series: unique_series[series] = series_settings else: if kwargs.get('log_once'): log_once('Series %s is already configured in series plugin' % series, log) else: log.warning('Series %s is configured multiple times in series plugin.', series) # Combine the config dicts for both instances of the show unique_series[series].update(series_settings) # Turn our all_series dict back into a list # sort by reverse alpha, so that in the event of 2 series with common prefix, more specific is parsed first return [{series: unique_series[series]} for series in sorted(unique_series, reverse=True)] def merge_config(self, task, config): """Merges another series config dict in with the current one.""" # Make sure we start with both configs as a list of complex series native_series = self.prepare_config(task.config.get('series', {})) merging_series = self.prepare_config(config) task.config['series'] = self.combine_series_lists(merging_series, native_series, log_once=True) return task.config['series'] class FilterSeries(FilterSeriesBase): """ Intelligent filter for tv-series. http://flexget.com/wiki/Plugins/series """ @property def schema(self): return { 'type': ['array', 'object'], # simple format: # - series # - another series 'items': { 'type': ['string', 'number', 'object'], 'additionalProperties': self.settings_schema }, # advanced format: # settings: # group: {...} # group: # {...} 'properties': { 'settings': { 'type': 'object', 'additionalProperties': self.settings_schema } }, 'additionalProperties': { 'type': 'array', 'items': { 'type': ['string', 'number', 'object'], 'additionalProperties': self.settings_schema } } } def __init__(self): try: self.backlog = plugin.get_plugin_by_name('backlog') except plugin.DependencyError: log.warning('Unable utilize backlog plugin, episodes may slip trough timeframe') def auto_exact(self, config): """Automatically enable exact naming option for series that look like a problem""" # generate list of all series in one dict all_series = {} for series_item in config: series_name, series_config = series_item.items()[0] all_series[series_name] = series_config # scan for problematic names, enable exact mode for them for series_name, series_config in all_series.iteritems(): for name in all_series.keys(): if (name.lower().startswith(series_name.lower())) and \ (name.lower() != series_name.lower()): if not 'exact' in series_config: log.verbose('Auto enabling exact matching for series %s (reason %s)', series_name, name) series_config['exact'] = True # Run after metainfo_quality and before metainfo_series @plugin.priority(125) def on_task_metainfo(self, task, config): config = self.prepare_config(config) self.auto_exact(config) for series_item in config: series_name, series_config = series_item.items()[0] log.trace('series_name: %s series_config: %s', series_name, series_config) start_time = time.clock() self.parse_series(task.entries, series_name, series_config) took = time.clock() - start_time log.trace('parsing %s took %s', series_name, took) def on_task_filter(self, task, config): """Filter series""" # Parsing was done in metainfo phase, create the dicts to pass to process_series from the task entries # key: series episode identifier ie. S01E02 # value: seriesparser config = self.prepare_config(config) found_series = {} for entry in task.entries: if entry.get('series_name') and entry.get('series_id') is not None and entry.get('series_parser'): found_series.setdefault(entry['series_name'], []).append(entry) for series_item in config: with Session() as session: series_name, series_config = series_item.items()[0] if series_config.get('parse_only'): log.debug('Skipping filtering of series %s because of parse_only', series_name) continue # Make sure number shows (e.g. 24) are turned into strings series_name = unicode(series_name) db_series = session.query(Series).filter(Series.name == series_name).first() if not db_series: log.debug('adding series %s into db', series_name) db_series = Series() db_series.name = series_name db_series.identified_by = series_config.get('identified_by', 'auto') session.add(db_series) log.debug('-> added %s' % db_series) session.flush() # Flush to get an id on series before adding alternate names. alts = series_config.get('alternate_name', []) if not isinstance(alts, list): alts = [alts] for alt in alts: _add_alt_name(alt, db_series, series_name, session) if not series_name in found_series: continue series_entries = {} for entry in found_series[series_name]: # store found episodes into database and save reference for later use releases = store_parser(session, entry['series_parser'], series=db_series) entry['series_releases'] = [r.id for r in releases] series_entries.setdefault(releases[0].episode, []).append(entry) # TODO: Unfortunately we are setting these again, even though they were set in metanifo. This is # for the benefit of all_series and series_premiere. Figure a better way. # set custom download path if 'path' in series_config: log.debug('setting %s custom path to %s', entry['title'], series_config.get('path')) # Just add this to the 'set' dictionary, so that string replacement is done cleanly series_config.setdefault('set', {}).update(path=series_config['path']) # accept info from set: and place into the entry if 'set' in series_config: set = plugin.get_plugin_by_name('set') # TODO: Could cause lazy lookups. We don't really want to have a transaction open during this. set.instance.modify(entry, series_config.get('set')) # If we didn't find any episodes for this series, continue if not series_entries: log.trace('No entries found for %s this run.', series_name) continue # configuration always overrides everything if series_config.get('identified_by', 'auto') != 'auto': db_series.identified_by = series_config['identified_by'] # if series doesn't have identified_by flag already set, calculate one now that new eps are added to db if not db_series.identified_by or db_series.identified_by == 'auto': db_series.identified_by = auto_identified_by(db_series) log.debug('identified_by set to \'%s\' based on series history', db_series.identified_by) log.trace('series_name: %s series_config: %s', series_name, series_config) import time start_time = time.clock() self.process_series(task, series_entries, series_config) took = time.clock() - start_time log.trace('processing %s took %s', series_name, took) def parse_series(self, entries, series_name, config): """ Search for `series_name` and populate all `series_*` fields in entries when successfully parsed :param session: SQLAlchemy session :param entries: List of entries to process :param series_name: Series name which is being processed :param config: Series config being processed """ def get_as_array(config, key): """Return configuration key as array, even if given as a single string""" v = config.get(key, []) if isinstance(v, basestring): return [v] return v # set parser flags flags based on config / database identified_by = config.get('identified_by', 'auto') if identified_by == 'auto': with Session() as session: series = session.query(Series).filter(Series.name == series_name).first() if series: # set flag from database identified_by = series.identified_by or 'auto' params = dict(identified_by=identified_by, alternate_names=get_as_array(config, 'alternate_name'), name_regexps=get_as_array(config, 'name_regexp'), strict_name=config.get('exact', False), allow_groups=get_as_array(config, 'from_group'), date_yearfirst=config.get('date_yearfirst'), date_dayfirst=config.get('date_dayfirst'), special_ids=get_as_array(config, 'special_ids'), prefer_specials=config.get('prefer_specials'), assume_special=config.get('assume_special')) for id_type in SERIES_ID_TYPES: params[id_type + '_regexps'] = get_as_array(config, id_type + '_regexp') for entry in entries: # skip processed entries if (entry.get('series_parser') and entry['series_parser'].valid and entry['series_parser'].name.lower() != series_name.lower()): continue # Quality field may have been manipulated by e.g. assume_quality. Use quality field from entry if available. parsed = get_plugin_by_name('parsing').instance.parse_series(entry['title'], name=series_name, **params) if not parsed.valid: continue parsed.field = 'title' log.debug('%s detected as %s, field: %s', entry['title'], parsed, parsed.field) populate_entry_fields(entry, parsed) # set custom download path if 'path' in config: log.debug('setting %s custom path to %s', entry['title'], config.get('path')) # Just add this to the 'set' dictionary, so that string replacement is done cleanly config.setdefault('set', {}).update(path=config['path']) # accept info from set: and place into the entry if 'set' in config: set = plugin.get_plugin_by_name('set') set.instance.modify(entry, config.get('set')) def process_series(self, task, series_entries, config): """ Accept or Reject episode from available releases, or postpone choosing. :param task: Current Task :param series_entries: dict mapping Episodes to entries for that episode :param config: Series configuration """ for ep, entries in series_entries.iteritems(): if not entries: continue reason = None # sort episodes in order of quality entries.sort(key=lambda e: e['series_parser'], reverse=True) log.debug('start with episodes: %s', [e['title'] for e in entries]) # reject episodes that have been marked as watched in config file if ep.series.begin: if ep < ep.series.begin: for entry in entries: entry.reject('Episode `%s` is before begin value of `%s`' % (ep.identifier, ep.series.begin.identifier)) continue # skip special episodes if special handling has been turned off if not config.get('specials', True) and ep.identified_by == 'special': log.debug('Skipping special episode as support is turned off.') continue log.debug('current episodes: %s', [e['title'] for e in entries]) # quality filtering if 'quality' in config: entries = self.process_quality(config, entries) if not entries: continue reason = 'matches quality' # Many of the following functions need to know this info. Only look it up once. downloaded = ep.downloaded_releases downloaded_qualities = [rls.quality for rls in downloaded] # proper handling log.debug('-' * 20 + ' process_propers -->') entries = self.process_propers(config, ep, entries) if not entries: continue # Remove any eps we already have from the list for entry in reversed(entries): # Iterate in reverse so we can safely remove from the list while iterating if entry['series_parser'].quality in downloaded_qualities: entry.reject('quality already downloaded') entries.remove(entry) if not entries: continue # Figure out if we need an additional quality for this ep if downloaded: if config.get('upgrade'): # Remove all the qualities lower than what we have for entry in reversed(entries): if entry['series_parser'].quality < max(downloaded_qualities): entry.reject('worse quality than already downloaded.') entries.remove(entry) if not entries: continue if 'target' in config and config.get('upgrade'): # If we haven't grabbed the target yet, allow upgrade to it self.process_timeframe_target(config, entries, downloaded) continue if 'qualities' in config: # Grab any additional wanted qualities log.debug('-' * 20 + ' process_qualities -->') self.process_qualities(config, entries, downloaded) continue elif config.get('upgrade'): entries[0].accept('is an upgrade to existing quality') continue # Reject eps because we have them for entry in entries: entry.reject('episode has already been downloaded') continue best = entries[0] log.debug('continuing w. episodes: %s', [e['title'] for e in entries]) log.debug('best episode is: %s', best['title']) # episode tracking. used only with season and sequence based series if ep.identified_by in ['ep', 'sequence']: if task.options.disable_tracking or not config.get('tracking', True): log.debug('episode tracking disabled') else: log.debug('-' * 20 + ' episode tracking -->') # Grace is number of distinct eps in the task for this series + 2 backfill = config.get('tracking') == 'backfill' if self.process_episode_tracking(ep, entries, grace=len(series_entries)+2, backfill=backfill): continue # quality if 'target' in config or 'qualities' in config: if 'target' in config: if self.process_timeframe_target(config, entries, downloaded): continue elif 'qualities' in config: if self.process_qualities(config, entries, downloaded): continue # We didn't make a quality target match, check timeframe to see # if we should get something anyway if 'timeframe' in config: if self.process_timeframe(task, config, ep, entries): continue reason = 'Timeframe expired, choosing best available' else: # If target or qualities is configured without timeframe, don't accept anything now continue # Just pick the best ep if we get here reason = reason or 'choosing best available quality' best.accept(reason) def process_propers(self, config, episode, entries): """ Accepts needed propers. Nukes episodes from which there exists proper. :returns: A list of episodes to continue processing. """ pass_filter = [] best_propers = [] # Since eps is sorted by quality then proper_count we always see the highest proper for a quality first. (last_qual, best_proper) = (None, 0) for entry in entries: if entry['series_parser'].quality != last_qual: last_qual, best_proper = entry['series_parser'].quality, entry['series_parser'].proper_count best_propers.append(entry) if entry['series_parser'].proper_count < best_proper: # nuke qualities which there is a better proper available entry.reject('nuked') else: pass_filter.append(entry) # If propers support is turned off, or proper timeframe has expired just return the filtered eps list if isinstance(config.get('propers', True), bool): if not config.get('propers', True): return pass_filter else: # propers with timeframe log.debug('proper timeframe: %s', config['propers']) timeframe = parse_timedelta(config['propers']) first_seen = episode.first_seen expires = first_seen + timeframe log.debug('propers timeframe: %s', timeframe) log.debug('first_seen: %s', first_seen) log.debug('propers ignore after: %s', expires) if datetime.now() > expires: log.debug('propers timeframe expired') return pass_filter downloaded_qualities = dict((d.quality, d.proper_count) for d in episode.downloaded_releases) log.debug('propers - downloaded qualities: %s' % downloaded_qualities) # Accept propers we actually need, and remove them from the list of entries to continue processing for entry in best_propers: if (entry['series_parser'].quality in downloaded_qualities and entry['series_parser'].proper_count > downloaded_qualities[entry['series_parser'].quality]): entry.accept('proper') pass_filter.remove(entry) return pass_filter def process_timeframe_target(self, config, entries, downloaded=None): """ Accepts first episode matching the quality configured for the series. :return: True if accepted something """ req = qualities.Requirements(config['target']) if downloaded: if any(req.allows(release.quality) for release in downloaded): log.debug('Target quality already achieved.') return True # scan for quality for entry in entries: if req.allows(entry['series_parser'].quality): log.debug('Series accepting. %s meets quality %s', entry['title'], req) entry.accept('target quality') return True def process_quality(self, config, entries): """ Filters eps that do not fall between within our defined quality standards. :returns: A list of eps that are in the acceptable range """ reqs = qualities.Requirements(config['quality']) log.debug('quality req: %s', reqs) result = [] # see if any of the eps match accepted qualities for entry in entries: if reqs.allows(entry['quality']): result.append(entry) else: log.verbose('Ignored `%s`. Does not meet quality requirement `%s`.', entry['title'], reqs) if not result: log.debug('no quality meets requirements') return result def process_episode_tracking(self, episode, entries, grace, backfill=False): """ Rejects all episodes that are too old or new, return True when this happens. :param episode: Episode model :param list entries: List of entries for given episode. :param int grace: Number of episodes before or after latest download that are allowed. :param bool backfill: If this is True, previous episodes will be allowed, but forward advancement will still be restricted. """ latest = get_latest_release(episode.series) if episode.series.begin and episode.series.begin > latest: latest = episode.series.begin log.debug('latest download: %s' % latest) log.debug('current: %s' % episode) if latest and latest.identified_by == episode.identified_by: # Allow any previous episodes this season, or previous episodes within grace if sequence mode if (not backfill and (episode.season < latest.season or (episode.identified_by == 'sequence' and episode.number < (latest.number - grace)))): log.debug('too old! rejecting all occurrences') for entry in entries: entry.reject('Too much in the past from latest downloaded episode %s' % latest.identifier) return True # Allow future episodes within grace, or first episode of next season if (episode.season > latest.season + 1 or (episode.season > latest.season and episode.number > 1) or (episode.season == latest.season and episode.number > (latest.number + grace))): log.debug('too new! rejecting all occurrences') for entry in entries: entry.reject('Too much in the future from latest downloaded episode %s. ' 'See `--disable-tracking` if this should be downloaded.' % latest.identifier) return True def process_timeframe(self, task, config, episode, entries): """ Runs the timeframe logic to determine if we should wait for a better quality. Saves current best to backlog if timeframe has not expired. :returns: True - if we should keep the quality (or qualities) restriction False - if the quality restriction should be released, due to timeframe expiring """ if 'timeframe' not in config: return True best = entries[0] # parse options log.debug('timeframe: %s', config['timeframe']) timeframe = parse_timedelta(config['timeframe']) if config.get('quality'): req = qualities.Requirements(config['quality']) seen_times = [rls.first_seen for rls in episode.releases if req.allows(rls.quality)] else: seen_times = [rls.first_seen for rls in episode.releases] # Somehow we can get here without having qualifying releases (#2779) make sure min doesn't crash first_seen = min(seen_times) if seen_times else datetime.now() expires = first_seen + timeframe log.debug('timeframe: %s, first_seen: %s, expires: %s', timeframe, first_seen, expires) stop = normalize_series_name(task.options.stop_waiting) == episode.series._name_normalized if expires <= datetime.now() or stop: # Expire timeframe, accept anything log.info('Timeframe expired, releasing quality restriction.') return False else: # verbose waiting, add to backlog diff = expires - datetime.now() hours, remainder = divmod(diff.seconds, 3600) hours += diff.days * 24 minutes, seconds = divmod(remainder, 60) log.info('Timeframe waiting %s for %sh:%smin, currently best is %s' % (episode.series.name, hours, minutes, best['title'])) # add best entry to backlog (backlog is able to handle duplicate adds) if self.backlog: self.backlog.instance.add_backlog(task, best) return True def process_qualities(self, config, entries, downloaded): """ Handles all modes that can accept more than one quality per episode. (qualities, upgrade) :returns: True - if at least one wanted quality has been downloaded or accepted. False - if no wanted qualities have been accepted """ # Get list of already downloaded qualities downloaded_qualities = [r.quality for r in downloaded] log.debug('downloaded_qualities: %s', downloaded_qualities) # If qualities key is configured, we only want qualities defined in it. wanted_qualities = set([qualities.Requirements(name) for name in config.get('qualities', [])]) # Compute the requirements from our set that have not yet been fulfilled still_needed = [req for req in wanted_qualities if not any(req.allows(qual) for qual in downloaded_qualities)] log.debug('Wanted qualities: %s', wanted_qualities) def wanted(quality): """Returns True if we want this quality based on the config options.""" wanted = not wanted_qualities or any(req.allows(quality) for req in wanted_qualities) if config.get('upgrade'): wanted = wanted and quality > max(downloaded_qualities or [qualities.Quality()]) return wanted for entry in entries: quality = entry['series_parser'].quality log.debug('ep: %s quality: %s', entry['title'], quality) if not wanted(quality): log.debug('%s is unwanted quality', quality) continue if any(req.allows(quality) for req in still_needed): # Don't get worse qualities in upgrade mode if config.get('upgrade'): if downloaded_qualities and quality < max(downloaded_qualities): continue entry.accept('quality wanted') downloaded_qualities.append(quality) downloaded.append(entry) # Re-calculate what is still needed still_needed = [req for req in still_needed if not req.allows(quality)] return bool(downloaded_qualities) def on_task_learn(self, task, config): """Learn succeeded episodes""" log.debug('on_task_learn') for entry in task.accepted: if 'series_releases' in entry: with Session() as session: num = (session.query(Release).filter(Release.id.in_(entry['series_releases'])). update({'downloaded': True}, synchronize_session=False)) log.debug('marking %s releases as downloaded for %s', num, entry) else: log.debug('%s is not a series', entry['title']) class SeriesDBManager(FilterSeriesBase): """Update in the database with series info from the config""" @plugin.priority(0) def on_task_start(self, task, config): if not task.config_modified: return # Clear all series from this task with Session() as session: session.query(SeriesTask).filter(SeriesTask.name == task.name).delete() if not task.config.get('series'): return config = self.prepare_config(task.config['series']) for series_item in config: series_name, series_config = series_item.items()[0] # Make sure number shows (e.g. 24) are turned into strings series_name = unicode(series_name) db_series = session.query(Series).filter(Series.name == series_name).first() if db_series: # Update database with capitalization from config db_series.name = series_name alts = series_config.get('alternate_name', []) if not isinstance(alts, list): alts = [alts] # Remove the alternate names not present in current config db_series.alternate_names = [alt for alt in db_series.alternate_names if alt.alt_name in alts] # Add/update the possibly new alternate names for alt in alts: _add_alt_name(alt, db_series, series_name, session) else: log.debug('adding series %s into db', series_name) db_series = Series() db_series.name = series_name session.add(db_series) session.flush() # flush to get id on series before creating alternate names log.debug('-> added %s' % db_series) alts = series_config.get('alternate_name', []) if not isinstance(alts, list): alts = [alts] for alt in alts: _add_alt_name(alt, db_series, series_name, session) db_series.in_tasks.append(SeriesTask(task.name)) if series_config.get('identified_by', 'auto') != 'auto': db_series.identified_by = series_config['identified_by'] # Set the begin episode if series_config.get('begin'): try: set_series_begin(db_series, series_config['begin']) except ValueError as e: raise plugin.PluginError(e) def _add_alt_name(alt, db_series, series_name, session): alt = unicode(alt) db_series_alt = session.query(AlternateNames).join(Series).filter(AlternateNames.alt_name == alt).first() if db_series_alt and db_series_alt.series_id == db_series.id: # Already exists, no need to create it then # TODO is checking the list for duplicates faster/better than querying the DB? db_series_alt.alt_name = alt elif db_series_alt: # Alternate name already exists for another series. Not good. raise plugin.PluginError('Error adding alternate name for %s. %s is already associated with %s. ' 'Check your config.' % (series_name, alt, db_series_alt.series.name) ) else: log.debug('adding alternate name %s for %s into db' % (alt, series_name)) db_series_alt = AlternateNames(alt) db_series.alternate_names.append(db_series_alt) log.debug('-> added %s' % db_series_alt) @event('plugin.register') def register_plugin(): plugin.register(FilterSeries, 'series', api_ver=2) # This is a builtin so that it can update the database for tasks that may have had series plugin removed plugin.register(SeriesDBManager, 'series_db', builtin=True, api_ver=2) @event('options.register') def register_parser_arguments(): exec_parser = options.get_parser('execute') exec_parser.add_argument('--stop-waiting', action='store', dest='stop_waiting', default='', metavar='NAME', help='stop timeframe for a given series') exec_parser.add_argument('--disable-tracking', action='store_true', default=False, help='disable episode advancement for this run') # Backwards compatibility exec_parser.add_argument('--disable-advancement', action='store_true', dest='disable_tracking', help=argparse.SUPPRESS)
tvcsantos/Flexget
flexget/plugins/filter/series.py
Python
mit
70,663
package com.meapsoft; /* * Copyright 2006-2007 Columbia University. * * This file is part of MEAPsoft. * * MEAPsoft is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * MEAPsoft 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 MEAPsoft; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * See the file "COPYING" for the text of the license. */ import com.cosmicsubspace.nerdyaudio.exceptions.FFTException; public class FFT { int n, m; // Lookup tables. Only need to recompute when size of FFT changes. double[] cos; double[] sin; double[] window; public FFT(int n) { this.n = n; this.m = (int)(Math.log(n) / Math.log(2)); // Make sure n is a power of 2 if(n != (1<<m)) throw new RuntimeException("FFT length must be power of 2"); // precompute tables cos = new double[n/2]; sin = new double[n/2]; // for(int i=0; i<n/4; i++) { // cos[i] = Math.cos(-2*Math.PI*i/n); // sin[n/4-i] = cos[i]; // cos[n/2-i] = -cos[i]; // sin[n/4+i] = cos[i]; // cos[n/2+i] = -cos[i]; // sin[n*3/4-i] = -cos[i]; // cos[n-i] = cos[i]; // sin[n*3/4+i] = -cos[i]; // } for(int i=0; i<n/2; i++) { cos[i] = Math.cos(-2*Math.PI*i/n); sin[i] = Math.sin(-2*Math.PI*i/n); } makeWindow(); } public int getFftSize(){return n;} protected void makeWindow() { // Make a blackman window: // w(n)=0.42-0.5cos{(2*PI*n)/(N-1)}+0.08cos{(4*PI*n)/(N-1)}; window = new double[n]; for(int i = 0; i < window.length; i++) window[i] = 0.42 - 0.5 * Math.cos(2*Math.PI*i/(n-1)) + 0.08 * Math.cos(4*Math.PI*i/(n-1)); } public double[] getWindow() { return window; } /*************************************************************** * fft.c * Douglas L. Jones * University of Illinois at Urbana-Champaign * January 19, 1992 * http://cnx.rice.edu/content/m12016/latest/ * * fft: in-place radix-2 DIT DFT of a complex input * * input: * n: length of FFT: must be a power of two * m: n = 2**m * input/output * x: double array of length n with real part of data * y: double array of length n with imag part of data * * Permission to copy and use this program is granted * as long as this header is included. ****************************************************************/ public void fft(double[] x, double[] y) throws FFTException //TODO Maybe I can do with single precision. { if (!(x.length==y.length && x.length==n)) throw new FFTException("FFT Size Mismatch!"); int i,j,k,n1,n2,a; double c,s,e,t1,t2; // Bit-reverse j = 0; n2 = n/2; for (i=1; i < n - 1; i++) { n1 = n2; while ( j >= n1 ) { j = j - n1; n1 = n1/2; } j = j + n1; if (i < j) { t1 = x[i]; x[i] = x[j]; x[j] = t1; t1 = y[i]; y[i] = y[j]; y[j] = t1; } } // FFT n1 = 0; n2 = 1; for (i=0; i < m; i++) { n1 = n2; n2 = n2 + n2; a = 0; for (j=0; j < n1; j++) { c = cos[a]; s = sin[a]; a += 1 << (m-i-1); for (k=j; k < n; k=k+n2) { t1 = c*x[k+n1] - s*y[k+n1]; t2 = s*x[k+n1] + c*y[k+n1]; x[k+n1] = x[k] - t1; y[k+n1] = y[k] - t2; x[k] = x[k] + t1; y[k] = y[k] + t2; } } } } }
CosmicSubspace/NerdyAudio
app/src/main/java/com/meapsoft/FFT.java
Java
mit
4,463
module SS::Model::File extend ActiveSupport::Concern extend SS::Translation include SS::Document include SS::Reference::User attr_accessor :in_file, :in_files, :resizing included do store_in collection: "ss_files" seqid :id field :model, type: String field :state, type: String, default: "closed" field :name, type: String field :filename, type: String field :size, type: Integer field :content_type, type: String belongs_to :site, class_name: "SS::Site" permit_params :state, :name, :filename permit_params :in_file, :in_files, in_files: [] permit_params :resizing before_validation :set_filename, if: ->{ in_file.present? } before_validation :validate_filename, if: ->{ filename.present? } validates :model, presence: true validates :state, presence: true validates :filename, presence: true, if: ->{ in_file.blank? && in_files.blank? } validate :validate_size before_save :rename_file, if: ->{ @db_changes.present? } before_save :save_file before_destroy :remove_file end module ClassMethods def root "#{Rails.root}/private/files" end def resizing_options [ [I18n.t('views.options.resizing.320×240'), "320,240"], [I18n.t('views.options.resizing.240x320'), "240,320"], [I18n.t('views.options.resizing.640x480'), "640,480"], [I18n.t('views.options.resizing.480x640'), "480,640"], [I18n.t('views.options.resizing.800x600'), "800,600"], [I18n.t('views.options.resizing.600x800'), "600,800"], [I18n.t('views.options.resizing.1024×768'), "1024,768"], [I18n.t('views.options.resizing.768x1024'), "768,1024"], [I18n.t('views.options.resizing.1280x720'), "1280,720"], [I18n.t('views.options.resizing.720x1280'), "720,1280"], ] end public def search(params) criteria = self.where({}) return criteria if params.blank? if params[:name].present? criteria = criteria.search_text params[:name] end if params[:keyword].present? criteria = criteria.keyword_in params[:keyword], :name, :filename end criteria end end public def path "#{self.class.root}/ss_files/" + id.to_s.split(//).join("/") + "/_/#{id}" end def public_path "#{site.path}/fs/" + id.to_s.split(//).join("/") + "/_/#{filename}" end def url "/fs/" + id.to_s.split(//).join("/") + "/_/#{filename}" end def thumb_url "/fs/" + id.to_s.split(//).join("/") + "/_/thumb/#{filename}" end def state_options [[I18n.t('views.options.state.public'), 'public']] end def name self[:name].presence || basename end def basename filename.to_s.sub(/.*\//, "") end def extname filename.to_s.sub(/.*\W/, "") end def image? filename =~ /\.(bmp|gif|jpe?g|png)$/i end def resizing (@resizing && @resizing.size == 2) ? @resizing.map(&:to_i) : nil end def resizing=(s) @resizing = (s.class == String) ? s.split(",") : s end def read Fs.exists?(path) ? Fs.binread(path) : nil end def save_files return false unless valid? in_files.each do |file| item = self.class.new(attributes) item.in_file = file item.resizing = resizing next if item.save item.errors.full_messages.each { |m| errors.add :base, m } return false end true end def uploaded_file file = Fs::UploadedFile.new("ss_file") file.binmode file.write(read) file.rewind file.original_filename = basename file.content_type = content_type file end def generate_public_file if site && basename.ascii_only? file = public_path data = self.read return if Fs.exists?(file) && data == Fs.read(file) Fs.binwrite file, data end end def remove_public_file Fs.rm_rf(public_path) if site end private def set_filename self.filename = in_file.original_filename if filename.blank? self.size = in_file.size self.content_type = ::SS::MimeType.find(in_file.original_filename, in_file.content_type) end def validate_filename self.filename = filename.gsub(/[^\w\-\.]/, "_") end def save_file errors.add :in_file, :blank if new_record? && in_file.blank? return false if errors.present? return if in_file.blank? if image? && resizing width, height = resizing image = Magick::Image.from_blob(in_file.read).shift image = image.resize_to_fit width, height if image.columns > width || image.rows > height binary = image.to_blob else binary = in_file.read end dir = ::File.dirname(path) Fs.mkdir_p(dir) unless Fs.exists?(dir) Fs.binwrite(path, binary) end def remove_file Fs.rm_rf(path) remove_public_file end def rename_file return unless @db_changes["filename"] return unless @db_changes["filename"][0] remove_public_file if site end def validate_size validate_limit = lambda do |file| filename = file.original_filename base_limit = SS.config.env.max_filesize ext_limit = SS.config.env.max_filesize_ext[filename.sub(/.*\./, "").downcase] [ ext_limit, base_limit ].each do |limit| if limit.present? && file.size > limit errors.add :base, :too_large_file, filename: filename, size: number_to_human_size(file.size), limit: number_to_human_size(limit) end end end if in_file.present? validate_limit.call(in_file) elsif in_files.present? in_files.each { |file| validate_limit.call(file) } end end def number_to_human_size(size) ApplicationController.helpers.number_to_human_size(size) end end
togusafish/shirasagi-_-shirasagi
app/models/concerns/ss/model/file.rb
Ruby
mit
6,055
using System.Linq.Expressions; namespace Orion.Scripting.Ast { internal class AstGreaterThanOrEqualOperator : AstOperator { public AstGreaterThanOrEqualOperator(string value) : base(value) { } protected override Expression CreateExpression<T>(ParameterExpression parameter, Expression left, Expression right) { return Expression.GreaterThanOrEqual(left, right); } } }
mika-f/Orion
Source/Orion.Scripting/Ast/AstGreaterThanOrEqualOperator.cs
C#
mit
428
from django.dispatch import dispatcher from django.db.models import signals from django.utils.translation import ugettext_noop as _ try: from notification import models as notification def create_notice_types(app, created_models, verbosity, **kwargs): notification.create_notice_type("swaps_proposal", _("New Swap Proposal"), _("someone has proposed a swap for one of your offers"), default=2) notification.create_notice_type("swaps_acceptance", _("Swap Acceptance"), _("someone has accepted a swap that you proposed"), default=2) notification.create_notice_type("swaps_rejection", _("Swap Rejection"), _("someone has rejected a swap that you proposed"), default=2) notification.create_notice_type("swaps_cancellation", _("Swap Cancellation"), _("someone has canceled a proposed swap for one of your offers"), default=2) notification.create_notice_type("swaps_proposing_offer_changed", _("Swap Proposing Offer Changed"), _("someone has changed their proposing offer in a swap for one of your offers"), default=2) notification.create_notice_type("swaps_responding_offer_changed", _("Swap Responding Offer Changed"), _("someone has changed their responding offer in a swap that you proposed"), default=2) notification.create_notice_type("swaps_comment", _("Swap Comment"), _("someone has commented on a swap in which your offer is involved"), default=2) notification.create_notice_type("swaps_conflict", _("Swap Conflict"), _("your swap has lost a conflict to another swap"), default=2) signals.post_syncdb.connect(create_notice_types, sender=notification) except ImportError: print "Skipping creation of NoticeTypes as notification app not found"
indro/t2c
apps/external_apps/swaps/management.py
Python
mit
1,734
require 'rails_admin/config/fields/base' module RailsAdmin module Config module Fields module Types class CodeMirror < RailsAdmin::Config::Fields::Types::Text # Register field type for the type loader RailsAdmin::Config::Fields::Types::register(self) #Pass the theme and mode for Codemirror register_instance_option :config do { :mode => 'css', :theme => 'night' } end #Pass the location of the theme and mode for Codemirror register_instance_option :assets do { :mode => '/assets/codemirror/modes/css.js', :theme => '/assets/codemirror/themes/night.css' } end #Use this if you want to point to a cloud instances of CodeMirror register_instance_option :js_location do '/assets/codemirror.js' end #Use this if you want to point to a cloud instances of CodeMirror register_instance_option :css_location do '/assets/codemirror.css' end register_instance_option :partial do :form_code_mirror end [:assets, :config, :css_location, :js_location].each do |key| register_deprecated_instance_option :"codemirror_#{key}", key end end end end end end
17up/rails_admin
lib/rails_admin/config/fields/types/code_mirror.rb
Ruby
mit
1,419
# encoding: utf-8 require 'logger' require 'socket' require 'spec_helper' require 'girl_friday' require 'redis' require 'active_support/core_ext/object' require 'active_support/json/encoding' begin require 'sucker_punch' require 'sucker_punch/testing/inline' rescue LoadError end describe Rollbar do let(:notifier) { Rollbar.notifier } before do Rollbar.unconfigure configure end context 'when notifier has been used before configure it' do before do Rollbar.unconfigure Rollbar.reset_notifier! end it 'is finally reset' do Rollbar.log_debug('Testing notifier') expect(Rollbar.error('error message')).to be_eql('disabled') reconfigure_notifier expect(Rollbar.error('error message')).not_to be_eql('disabled') end end context 'Notifier' do context 'log' do let(:exception) do begin foo = bar rescue => e e end end let(:configuration) { Rollbar.configuration } context 'executing a Thread before Rollbar is configured', :skip_dummy_rollbar => true do before do Rollbar.reset_notifier! Rollbar.unconfigure Thread.new {} Rollbar.configure do |config| config.access_token = 'my-access-token' end end it 'sets correct configuration for Rollbar.notifier' do expect(Rollbar.notifier.configuration.enabled).to be_truthy end end it 'should report a simple message' do expect(notifier).to receive(:report).with('error', 'test message', nil, nil) notifier.log('error', 'test message') end it 'should report a simple message with extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} expect(notifier).to receive(:report).with('error', 'test message', nil, extra_data) notifier.log('error', 'test message', extra_data) end it 'should report an exception' do expect(notifier).to receive(:report).with('error', nil, exception, nil) notifier.log('error', exception) end it 'should report an exception with extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} expect(notifier).to receive(:report).with('error', nil, exception, extra_data) notifier.log('error', exception, extra_data) end it 'should report an exception with a description' do expect(notifier).to receive(:report).with('error', 'exception description', exception, nil) notifier.log('error', exception, 'exception description') end it 'should report an exception with a description and extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} expect(notifier).to receive(:report).with('error', 'exception description', exception, extra_data) notifier.log('error', exception, extra_data, 'exception description') end end context 'debug/info/warning/error/critical' do let(:exception) do begin foo = bar rescue => e e end end let(:extra_data) { {:key => 'value', :hash => {:inner_key => 'inner_value'}} } it 'should report with a debug level' do expect(notifier).to receive(:report).with('debug', nil, exception, nil) notifier.debug(exception) expect(notifier).to receive(:report).with('debug', 'description', exception, nil) notifier.debug(exception, 'description') expect(notifier).to receive(:report).with('debug', 'description', exception, extra_data) notifier.debug(exception, 'description', extra_data) end it 'should report with an info level' do expect(notifier).to receive(:report).with('info', nil, exception, nil) notifier.info(exception) expect(notifier).to receive(:report).with('info', 'description', exception, nil) notifier.info(exception, 'description') expect(notifier).to receive(:report).with('info', 'description', exception, extra_data) notifier.info(exception, 'description', extra_data) end it 'should report with a warning level' do expect(notifier).to receive(:report).with('warning', nil, exception, nil) notifier.warning(exception) expect(notifier).to receive(:report).with('warning', 'description', exception, nil) notifier.warning(exception, 'description') expect(notifier).to receive(:report).with('warning', 'description', exception, extra_data) notifier.warning(exception, 'description', extra_data) end it 'should report with an error level' do expect(notifier).to receive(:report).with('error', nil, exception, nil) notifier.error(exception) expect(notifier).to receive(:report).with('error', 'description', exception, nil) notifier.error(exception, 'description') expect(notifier).to receive(:report).with('error', 'description', exception, extra_data) notifier.error(exception, 'description', extra_data) end it 'should report with a critical level' do expect(notifier).to receive(:report).with('critical', nil, exception, nil) notifier.critical(exception) expect(notifier).to receive(:report).with('critical', 'description', exception, nil) notifier.critical(exception, 'description') expect(notifier).to receive(:report).with('critical', 'description', exception, extra_data) notifier.critical(exception, 'description', extra_data) end end context 'scope' do it 'should create a new notifier object' do notifier2 = notifier.scope notifier2.should_not eq(notifier) notifier2.should be_instance_of(Rollbar::Notifier) end it 'should create a copy of the parent notifier\'s configuration' do notifier.configure do |config| config.code_version = '123' config.payload_options = { :a => 'a', :b => {:c => 'c'} } end notifier2 = notifier.scope notifier2.configuration.code_version.should == '123' notifier2.configuration.should_not equal(notifier.configuration) notifier2.configuration.payload_options.should_not equal(notifier.configuration.payload_options) notifier2.configuration.payload_options.should == notifier.configuration.payload_options notifier2.configuration.payload_options.should == { :a => 'a', :b => {:c => 'c'} } end it 'should not modify any parent notifier configuration' do configure Rollbar.configuration.code_version.should be_nil Rollbar.configuration.payload_options.should be_empty notifier.configure do |config| config.code_version = '123' config.payload_options = { :a => 'a', :b => {:c => 'c'} } end notifier2 = notifier.scope notifier2.configure do |config| config.payload_options[:c] = 'c' end notifier.configuration.payload_options[:c].should be_nil notifier3 = notifier2.scope({ :b => {:c => 3, :d => 'd'} }) notifier3.configure do |config| config.code_version = '456' end notifier.configuration.code_version.should == '123' notifier.configuration.payload_options.should == { :a => 'a', :b => {:c => 'c'} } notifier2.configuration.code_version.should == '123' notifier2.configuration.payload_options.should == { :a => 'a', :b => {:c => 'c'}, :c => 'c' } notifier3.configuration.code_version.should == '456' notifier3.configuration.payload_options.should == { :a => 'a', :b => {:c => 3, :d => 'd'}, :c => 'c' } Rollbar.configuration.code_version.should be_nil Rollbar.configuration.payload_options.should be_empty end end context 'report' do let(:logger_mock) { double("Rails.logger").as_null_object } before(:each) do configure Rollbar.configure do |config| config.logger = logger_mock end end after(:each) do Rollbar.unconfigure configure end it 'should reject input that doesn\'t contain an exception, message or extra data' do expect(logger_mock).to receive(:error).with('[Rollbar] Tried to send a report with no message, exception or extra data.') expect(notifier).not_to receive(:schedule_payload) result = notifier.send(:report, 'info', nil, nil, nil) result.should == 'error' end it 'should be ignored if the person is ignored' do person_data = { :id => 1, :username => "test", :email => "test@example.com" } notifier.configure do |config| config.ignored_person_ids += [1] config.payload_options = { :person => person_data } end expect(notifier).not_to receive(:schedule_payload) result = notifier.send(:report, 'info', 'message', nil, nil) result.should == 'ignored' end end context 'build_payload' do context 'a basic payload' do let(:extra_data) { {:key => 'value', :hash => {:inner_key => 'inner_value'}} } let(:payload) { notifier.send(:build_payload, 'info', 'message', nil, extra_data) } it 'should have the correct root-level keys' do payload.keys.should match_array(['access_token', 'data']) end it 'should have the correct data keys' do payload['data'].keys.should include(:timestamp, :environment, :level, :language, :framework, :server, :notifier, :body) end it 'should have the correct notifier name and version' do payload['data'][:notifier][:name].should == 'rollbar-gem' payload['data'][:notifier][:version].should == Rollbar::VERSION end it 'should have the correct language and framework' do payload['data'][:language].should == 'ruby' payload['data'][:framework].should == Rollbar.configuration.framework payload['data'][:framework].should match(/^Rails/) end it 'should have the correct server keys' do payload['data'][:server].keys.should match_array([:host, :root, :pid]) end it 'should have the correct level and message body' do payload['data'][:level].should == 'info' payload['data'][:body][:message][:body].should == 'message' end end it 'should merge in a new key from payload_options' do notifier.configure do |config| config.payload_options = { :some_new_key => 'some new value' } end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:some_new_key].should == 'some new value' end it 'should overwrite existing keys from payload_options' do reconfigure_notifier payload_options = { :notifier => 'bad notifier', :server => { :host => 'new host', :new_server_key => 'value' } } notifier.configure do |config| config.payload_options = payload_options end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:notifier].should == 'bad notifier' payload['data'][:server][:host].should == 'new host' payload['data'][:server][:root].should_not be_nil payload['data'][:server][:new_server_key].should == 'value' end it 'should have default environment "unspecified"' do Rollbar.unconfigure payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:environment].should == 'unspecified' end it 'should have an overridden environment' do Rollbar.configure do |config| config.environment = 'overridden' end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:environment].should == 'overridden' end it 'should not have custom data under default configuration' do payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:body][:message][:extra].should be_nil end it 'should have custom message data when custom_data_method is configured' do Rollbar.configure do |config| config.custom_data_method = lambda { {:a => 1, :b => [2, 3, 4]} } end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:body][:message][:extra].should_not be_nil payload['data'][:body][:message][:extra][:a].should == 1 payload['data'][:body][:message][:extra][:b][2].should == 4 end it 'should merge extra data into custom message data' do custom_method = lambda do { :a => 1, :b => [2, 3, 4], :c => { :d => 'd', :e => 'e' }, :f => ['1', '2'] } end Rollbar.configure do |config| config.custom_data_method = custom_method end payload = notifier.send(:build_payload, 'info', 'message', nil, {:c => {:e => 'g'}, :f => 'f'}) payload['data'][:body][:message][:extra].should_not be_nil payload['data'][:body][:message][:extra][:a].should == 1 payload['data'][:body][:message][:extra][:b][2].should == 4 payload['data'][:body][:message][:extra][:c][:d].should == 'd' payload['data'][:body][:message][:extra][:c][:e].should == 'g' payload['data'][:body][:message][:extra][:f].should == 'f' end context 'with custom_data_method crashing' do next unless defined?(SecureRandom) and SecureRandom.respond_to?(:uuid) let(:crashing_exception) { StandardError.new } let(:custom_method) { proc { raise crashing_exception } } let(:extra) { { :foo => :bar } } let(:custom_data_report) do { :_error_in_custom_data_method => SecureRandom.uuid } end let(:expected_extra) { extra.merge(custom_data_report) } before do notifier.configure do |config| config.custom_data_method = custom_method end expect(notifier).to receive(:report_custom_data_error).once.and_return(custom_data_report) end it 'doesnt crash the report' do payload = notifier.send(:build_payload, 'info', 'message', nil, extra) expect(payload['data'][:body][:message][:extra]).to be_eql(expected_extra) end end it 'should include project_gem_paths' do notifier.configure do |config| config.project_gems = ['rails', 'rspec'] end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) expect(payload['data'][:project_package_paths].count).to eq 2 end it 'should include a code_version' do notifier.configure do |config| config.code_version = 'abcdef' end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:code_version].should == 'abcdef' end it 'should have the right hostname' do payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:server][:host].should == Socket.gethostname end it 'should have root and branch set when configured' do configure Rollbar.configure do |config| config.root = '/path/to/root' config.branch = 'master' end payload = notifier.send(:build_payload, 'info', 'message', nil, nil) payload['data'][:server][:root].should == '/path/to/root' payload['data'][:server][:branch].should == 'master' end context "with Redis instance in payload and ActiveSupport is enabled" do let(:redis) { ::Redis.new } let(:payload) do { :key => { :value => redis } } end it 'dumps to JSON correctly' do redis.set('foo', 'bar') json = notifier.send(:dump_payload, payload) expect(json).to be_kind_of(String) end end end context 'build_payload_body' do let(:exception) do begin foo = bar rescue => e e end end it 'should build a message body when no exception is passed in' do body = notifier.send(:build_payload_body, 'message', nil, nil) body[:message][:body].should == 'message' body[:message][:extra].should be_nil body[:trace].should be_nil end it 'should build a message body when no exception and extra data is passed in' do body = notifier.send(:build_payload_body, 'message', nil, {:a => 'b'}) body[:message][:body].should == 'message' body[:message][:extra].should == {:a => 'b'} body[:trace].should be_nil end it 'should build an exception body when one is passed in' do body = notifier.send(:build_payload_body, 'message', exception, nil) body[:message].should be_nil trace = body[:trace] trace.should_not be_nil trace[:extra].should be_nil trace[:exception][:class].should_not be_nil trace[:exception][:message].should_not be_nil end it 'should build an exception body when one is passed in along with extra data' do body = notifier.send(:build_payload_body, 'message', exception, {:a => 'b'}) body[:message].should be_nil trace = body[:trace] trace.should_not be_nil trace[:exception][:class].should_not be_nil trace[:exception][:message].should_not be_nil trace[:extra].should == {:a => 'b'} end end context 'build_payload_body_exception' do let(:exception) do begin foo = bar rescue => e e end end after(:each) do Rollbar.unconfigure configure end it 'should build valid exception data' do body = notifier.send(:build_payload_body_exception, nil, exception, nil) body[:message].should be_nil trace = body[:trace] frames = trace[:frames] frames.should be_a_kind_of(Array) frames.each do |frame| frame[:filename].should be_a_kind_of(String) frame[:lineno].should be_a_kind_of(Fixnum) if frame[:method] frame[:method].should be_a_kind_of(String) end end # should be NameError, but can be NoMethodError sometimes on rubinius 1.8 # http://yehudakatz.com/2010/01/02/the-craziest-fing-bug-ive-ever-seen/ trace[:exception][:class].should match(/^(NameError|NoMethodError)$/) trace[:exception][:message].should match(/^(undefined local variable or method `bar'|undefined method `bar' on an instance of)/) end it 'should build exception data with a description' do body = notifier.send(:build_payload_body_exception, 'exception description', exception, nil) trace = body[:trace] trace[:exception][:message].should match(/^(undefined local variable or method `bar'|undefined method `bar' on an instance of)/) trace[:exception][:description].should == 'exception description' end it 'should build exception data with a description and extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} body = notifier.send(:build_payload_body_exception, 'exception description', exception, extra_data) trace = body[:trace] trace[:exception][:message].should match(/^(undefined local variable or method `bar'|undefined method `bar' on an instance of)/) trace[:exception][:description].should == 'exception description' trace[:extra][:key].should == 'value' trace[:extra][:hash].should == {:inner_key => 'inner_value'} end it 'should build exception data with a extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} body = notifier.send(:build_payload_body_exception, nil, exception, extra_data) trace = body[:trace] trace[:exception][:message].should match(/^(undefined local variable or method `bar'|undefined method `bar' on an instance of)/) trace[:extra][:key].should == 'value' trace[:extra][:hash].should == {:inner_key => 'inner_value'} end context 'with nested exceptions' do let(:crashing_code) do proc do begin begin fail CauseException.new('the cause') rescue fail StandardError.new('the error') end rescue => e e end end end let(:rescued_exception) { crashing_code.call } let(:message) { 'message' } let(:extra) { {} } context 'using ruby >= 2.1' do next unless Exception.instance_methods.include?(:cause) it 'sends the two exceptions in the trace_chain attribute' do body = notifier.send(:build_payload_body_exception, message, rescued_exception, extra) body[:trace].should be_nil body[:trace_chain].should be_kind_of(Array) chain = body[:trace_chain] chain[0][:exception][:class].should match(/StandardError/) chain[0][:exception][:message].should match(/the error/) chain[1][:exception][:class].should match(/CauseException/) chain[1][:exception][:message].should match(/the cause/) end context 'with cyclic nested exceptions' do let(:exception1) { Exception.new('exception1') } let(:exception2) { Exception.new('exception2') } before do allow(exception1).to receive(:cause).and_return(exception2) allow(exception2).to receive(:cause).and_return(exception1) end it 'doesnt loop for ever' do body = notifier.send(:build_payload_body_exception, message, exception1, extra) chain = body[:trace_chain] expect(chain[0][:exception][:message]).to be_eql('exception1') expect(chain[1][:exception][:message]).to be_eql('exception2') end end end context 'using ruby <= 2.1' do next if Exception.instance_methods.include?(:cause) it 'sends only the last exception in the trace attribute' do body = notifier.send(:build_payload_body_exception, message, rescued_exception, extra) body[:trace].should be_kind_of(Hash) body[:trace_chain].should be_nil body[:trace][:exception][:class].should match(/StandardError/) body[:trace][:exception][:message].should match(/the error/) end end end end context 'build_payload_body_message' do it 'should build a message' do body = notifier.send(:build_payload_body_message, 'message', nil) body[:message][:body].should == 'message' body[:trace].should be_nil end it 'should build a message with extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} body = notifier.send(:build_payload_body_message, 'message', extra_data) body[:message][:body].should == 'message' body[:message][:extra][:key].should == 'value' body[:message][:extra][:hash].should == {:inner_key => 'inner_value'} end it 'should build an empty message with extra data' do extra_data = {:key => 'value', :hash => {:inner_key => 'inner_value'}} body = notifier.send(:build_payload_body_message, nil, extra_data) body[:message][:body].should == 'Empty message' body[:message][:extra][:key].should == 'value' body[:message][:extra][:hash].should == {:inner_key => 'inner_value'} end end end context 'reporting' do let(:exception) do begin foo = bar rescue => e e end end let(:logger_mock) { double("Rails.logger").as_null_object } let(:user) { User.create(:email => 'email@example.com', :encrypted_password => '', :created_at => Time.now, :updated_at => Time.now) } before(:each) do configure Rollbar.configure do |config| config.logger = logger_mock end end after(:each) do Rollbar.unconfigure configure end it 'should report exceptions without person or request data' do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.error(exception) end it 'should not report anything when disabled' do logger_mock.should_not_receive(:info).with('[Rollbar] Success') Rollbar.configure do |config| config.enabled = false end Rollbar.error(exception).should == 'disabled' end it 'should report exceptions without person or request data' do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.error(exception) end it 'should be enabled when freshly configured' do Rollbar.configuration.enabled.should == true end it 'should not be enabled when not configured' do Rollbar.unconfigure Rollbar.configuration.enabled.should be_nil Rollbar.error(exception).should == 'disabled' end it 'should stay disabled if configure is called again' do Rollbar.unconfigure # configure once, setting enabled to false. Rollbar.configure do |config| config.enabled = false end # now configure again (perhaps to change some other values) Rollbar.configure do |config| end Rollbar.configuration.enabled.should == false Rollbar.error(exception).should == 'disabled' end context 'using :use_exception_level_filters option as true' do it 'sends the correct filtered level' do Rollbar.configure do |config| config.exception_level_filters = { 'NameError' => 'warning' } end Rollbar.error(exception, :use_exception_level_filters => true) expect(Rollbar.last_report[:level]).to be_eql('warning') end it 'ignore ignored exception classes' do Rollbar.configure do |config| config.exception_level_filters = { 'NameError' => 'ignore' } end logger_mock.should_not_receive(:info) logger_mock.should_not_receive(:warn) logger_mock.should_not_receive(:error) Rollbar.error(exception, :use_exception_level_filters => true) end end context 'if not using :use_exception_level_filters option' do it 'sends the level defined by the used method' do Rollbar.configure do |config| config.exception_level_filters = { 'NameError' => 'warning' } end Rollbar.error(exception) expect(Rollbar.last_report[:level]).to be_eql('error') end it 'ignore ignored exception classes' do Rollbar.configure do |config| config.exception_level_filters = { 'NameError' => 'ignore' } end Rollbar.error(exception) expect(Rollbar.last_report[:level]).to be_eql('error') end end # Skip jruby 1.9+ (https://github.com/jruby/jruby/issues/2373) if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' && (not RUBY_VERSION =~ /^1\.9/) it "should work with an IO object as rack.errors" do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.error(exception, :env => { :"rack.errors" => IO.new(2, File::WRONLY) }) end end it 'should ignore ignored persons' do person_data = { :id => 1, :username => "test", :email => "test@example.com" } Rollbar.configure do |config| config.payload_options = {:person => person_data} config.ignored_person_ids += [1] end logger_mock.should_not_receive(:info) logger_mock.should_not_receive(:warn) logger_mock.should_not_receive(:error) Rollbar.error(exception) end it 'should not ignore non-ignored persons' do person_data = { :id => 1, :username => "test", :email => "test@example.com" } Rollbar.configure do |config| config.payload_options = { :person => person_data } config.ignored_person_ids += [1] end Rollbar.last_report = nil Rollbar.error(exception) Rollbar.last_report.should be_nil person_data = { :id => 2, :username => "test2", :email => "test2@example.com" } new_options = { :person => person_data } Rollbar.scoped(new_options) do Rollbar.error(exception) end Rollbar.last_report.should_not be_nil end it 'should allow callables to set exception filtered level' do callable_mock = double saved_filters = Rollbar.configuration.exception_level_filters Rollbar.configure do |config| config.exception_level_filters = { 'NameError' => callable_mock } end callable_mock.should_receive(:call).with(exception).at_least(:once).and_return("info") logger_mock.should_receive(:info) logger_mock.should_not_receive(:warn) logger_mock.should_not_receive(:error) Rollbar.error(exception, :use_exception_level_filters => true) end it 'should not report exceptions when silenced' do expect_any_instance_of(Rollbar::Notifier).to_not receive(:schedule_payload) begin test_var = 1 Rollbar.silenced do test_var = 2 raise end rescue => e Rollbar.error(e) end test_var.should == 2 end it 'should report exception objects with no backtrace' do payload = nil notifier.stub(:schedule_payload) do |*args| payload = args[0] end Rollbar.error(StandardError.new("oops")) payload["data"][:body][:trace][:frames].should == [] payload["data"][:body][:trace][:exception][:class].should == "StandardError" payload["data"][:body][:trace][:exception][:message].should == "oops" end it 'gets the backtrace from the caller' do Rollbar.configure do |config| config.populate_empty_backtraces = true end exception = Exception.new Rollbar.error(exception) gem_dir = Gem::Specification.find_by_name('rollbar').gem_dir gem_lib_dir = gem_dir + '/lib' last_report = Rollbar.last_report filepaths = last_report[:body][:trace][:frames].map {|frame| frame[:filename] }.reverse expect(filepaths[0]).not_to include(gem_lib_dir) expect(filepaths.any? {|filepath| filepath.include?(gem_dir) }).to eq true end it 'should return the exception data with a uuid, on platforms with SecureRandom' do if defined?(SecureRandom) and SecureRandom.respond_to?(:uuid) exception_data = Rollbar.error(StandardError.new("oops")) exception_data[:uuid].should_not be_nil end end it 'should report exception objects with nonstandard backtraces' do payload = nil notifier.stub(:schedule_payload) do |*args| payload = args[0] end class CustomException < StandardError def backtrace ["custom backtrace line"] end end exception = CustomException.new("oops") notifier.error(exception) payload["data"][:body][:trace][:frames][0][:method].should == "custom backtrace line" end it 'should report exceptions with a custom level' do payload = nil notifier.stub(:schedule_payload) do |*args| payload = args[0] end Rollbar.error(exception) payload['data'][:level].should == 'error' Rollbar.log('debug', exception) payload['data'][:level].should == 'debug' end context 'with invalid utf8 encoding' do let(:extra) do { :extra => force_to_ascii("bad value 1\255") } end it 'removes te invalid characteres' do Rollbar.info('removing invalid chars', extra) extra_value = Rollbar.last_report[:body][:message][:extra][:extra] expect(extra_value).to be_eql('bad value 1') end end end # Backwards context 'report_message' do before(:each) do configure Rollbar.configure do |config| config.logger = logger_mock end end let(:logger_mock) { double("Rails.logger").as_null_object } let(:user) { User.create(:email => 'email@example.com', :encrypted_password => '', :created_at => Time.now, :updated_at => Time.now) } it 'should report simple messages' do logger_mock.should_receive(:info).with('[Rollbar] Scheduling payload') logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.error('Test message') end it 'should not report anything when disabled' do logger_mock.should_not_receive(:info).with('[Rollbar] Success') Rollbar.configure do |config| config.enabled = false end Rollbar.error('Test message that should be ignored') Rollbar.configure do |config| config.enabled = true end end it 'should report messages with extra data' do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.debug('Test message with extra data', 'debug', :foo => "bar", :hash => { :a => 123, :b => "xyz" }) end # END Backwards it 'should not crash with circular extra_data' do a = { :foo => "bar" } b = { :a => a } c = { :b => b } a[:c] = c logger_mock.should_receive(:error).with(/\[Rollbar\] Reporting internal error encountered while sending data to Rollbar./) Rollbar.error("Test message with circular extra data", a) end it 'should be able to report form validation errors when they are present' do logger_mock.should_receive(:info).with('[Rollbar] Success') user.errors.add(:example, "error") user.report_validation_errors_to_rollbar end it 'should not report form validation errors when they are not present' do logger_mock.should_not_receive(:info).with('[Rollbar] Success') user.errors.clear user.report_validation_errors_to_rollbar end it 'should report messages with extra data' do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.info("Test message with extra data", :foo => "bar", :hash => { :a => 123, :b => "xyz" }) end it 'should report messages with request, person data and extra data' do logger_mock.should_receive(:info).with('[Rollbar] Scheduling payload') logger_mock.should_receive(:info).with('[Rollbar] Success') request_data = { :params => {:foo => 'bar'} } person_data = { :id => 123, :username => 'username' } extra_data = { :extra_foo => 'extra_bar' } Rollbar.configure do |config| config.payload_options = { :request => request_data, :person => person_data } end Rollbar.info("Test message", extra_data) Rollbar.last_report[:request].should == request_data Rollbar.last_report[:person].should == person_data Rollbar.last_report[:body][:message][:extra][:extra_foo].should == 'extra_bar' end end context 'payload_destination' do before(:each) do configure Rollbar.configure do |config| config.logger = logger_mock config.filepath = 'test.rollbar' end end after(:each) do Rollbar.unconfigure configure end let(:exception) do begin foo = bar rescue => e e end end let(:logger_mock) { double("Rails.logger").as_null_object } it 'should send the payload over the network by default' do logger_mock.should_not_receive(:info).with('[Rollbar] Writing payload to file') logger_mock.should_receive(:info).with('[Rollbar] Sending payload').once logger_mock.should_receive(:info).with('[Rollbar] Success').once Rollbar.error(exception) end it 'should save the payload to a file if set' do logger_mock.should_not_receive(:info).with('[Rollbar] Sending payload') logger_mock.should_receive(:info).with('[Rollbar] Writing payload to file').once logger_mock.should_receive(:info).with('[Rollbar] Success').once filepath = '' Rollbar.configure do |config| config.write_to_file = true filepath = config.filepath end Rollbar.error(exception) File.exist?(filepath).should == true File.read(filepath).should include test_access_token File.delete(filepath) Rollbar.configure do |config| config.write_to_file = false end end end context 'asynchronous_handling' do before(:each) do configure Rollbar.configure do |config| config.logger = logger_mock end end after(:each) do Rollbar.unconfigure configure end let(:exception) do begin foo = bar rescue => e e end end let(:logger_mock) { double("Rails.logger").as_null_object } it 'should send the payload using the default asynchronous handler girl_friday' do logger_mock.should_receive(:info).with('[Rollbar] Scheduling payload') logger_mock.should_receive(:info).with('[Rollbar] Sending payload') logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.configure do |config| config.use_async = true GirlFriday::WorkQueue.immediate! end Rollbar.error(exception) Rollbar.configure do |config| config.use_async = false GirlFriday::WorkQueue.queue! end end it 'should send the payload using a user-supplied asynchronous handler' do logger_mock.should_receive(:info).with('Custom async handler called') logger_mock.should_receive(:info).with('[Rollbar] Sending payload') logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.configure do |config| config.use_async = true config.async_handler = Proc.new { |payload| logger_mock.info 'Custom async handler called' Rollbar.process_payload(payload) } end Rollbar.error(exception) end # We should be able to send String payloads, generated # by a previous version of the gem. This can happend just # after a deploy with an gem upgrade. context 'with a payload generated as String' do let(:async_handler) do proc do |payload| # simulate previous gem version string_payload = Rollbar::JSON.dump(payload) Rollbar.process_payload(string_payload) end end before do Rollbar.configuration.stub(:use_async).and_return(true) Rollbar.configuration.stub(:async_handler).and_return(async_handler) end it 'sends a payload generated as String, not as a Hash' do logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.error(exception) end context 'with async failover handlers' do before do Rollbar.reconfigure do |config| config.use_async = true config.async_handler = async_handler config.failover_handlers = handlers config.logger = logger_mock end end let(:exception) { StandardError.new('the error') } context 'if the async handler doesnt fail' do let(:async_handler) { proc { |_| 'success' } } let(:handler) { proc { |_| 'success' } } let(:handlers) { [handler] } it 'doesnt call any failover handler' do expect(handler).not_to receive(:call) Rollbar.error(exception) end end context 'if the async handler fails' do let(:async_handler) { proc { |_| fail 'this handler will crash' } } context 'if any failover handlers is configured' do let(:handlers) { [] } let(:log_message) do '[Rollbar] Async handler failed, and there are no failover handlers configured. See the docs for "failover_handlers"' end it 'logs the error but doesnt try to report an internal error' do expect(logger_mock).to receive(:error).with(log_message) Rollbar.error(exception) end end context 'if the first failover handler success' do let(:handler) { proc { |_| 'success' } } let(:handlers) { [handler] } it 'calls the failover handler and doesnt report internal error' do expect(Rollbar).not_to receive(:report_internal_error) expect(handler).to receive(:call) Rollbar.error(exception) end end context 'with two handlers, the first failing' do let(:handler1) { proc { |_| fail 'this handler fails' } } let(:handler2) { proc { |_| 'success' } } let(:handlers) { [handler1, handler2] } it 'calls the second handler and doesnt report internal error' do expect(handler2).to receive(:call) Rollbar.error(exception) end end context 'with two handlers, both failing' do let(:handler1) { proc { |_| fail 'this handler fails' } } let(:handler2) { proc { |_| fail 'this will also fail' } } let(:handlers) { [handler1, handler2] } it 'reports internal error' do expect(logger_mock).to receive(:error) Rollbar.error(exception) end end end end end describe "#use_sucker_punch", :if => defined?(SuckerPunch) do it "should send the payload to sucker_punch delayer" do logger_mock.should_receive(:info).with('[Rollbar] Scheduling payload') logger_mock.should_receive(:info).with('[Rollbar] Sending payload') logger_mock.should_receive(:info).with('[Rollbar] Success') Rollbar.configure do |config| config.use_sucker_punch end Rollbar.error(exception) end end describe "#use_sidekiq", :if => defined?(Sidekiq) do it "should instanciate sidekiq delayer with custom values" do Rollbar::Delay::Sidekiq.should_receive(:new).with('queue' => 'test_queue') config = Rollbar::Configuration.new config.use_sidekiq 'queue' => 'test_queue' end it "should send the payload to sidekiq delayer" do handler = double('sidekiq_handler_mock') handler.should_receive(:call) Rollbar.configure do |config| config.use_sidekiq config.async_handler = handler end Rollbar.error(exception) end end end context 'logger' do before(:each) do reset_configuration end it 'should have use the Rails logger when configured to do so' do configure expect(Rollbar.send(:logger)).to be_kind_of(Rollbar::LoggerProxy) expect(Rollbar.send(:logger).object).to eq ::Rails.logger end it 'should use the default_logger when no logger is set' do logger = Logger.new(STDERR) Rollbar.configure do |config| config.default_logger = lambda { logger } end Rollbar.send(:logger).object.should == logger end it 'should have a default default_logger' do Rollbar.send(:logger).should_not be_nil end after(:each) do reset_configuration end end context 'enforce_valid_utf8' do # TODO(jon): all these tests should be removed since they are in # in spec/rollbar/encoding/encoder.rb. # # This should just check that in payload with simple values and # nested values are each one passed through Rollbar::Encoding.encode context 'with utf8 string and ruby > 1.8' do next unless String.instance_methods.include?(:force_encoding) let(:payload) { { :foo => 'Изменение' } } it 'just returns the same string' do payload_copy = payload.clone notifier.send(:enforce_valid_utf8, payload_copy) expect(payload_copy[:foo]).to be_eql('Изменение') end end it 'should replace invalid utf8 values' do bad_key = force_to_ascii("inner \x92bad key") payload = { :bad_value => force_to_ascii("bad value 1\255"), :bad_value_2 => force_to_ascii("bad\255 value 2"), force_to_ascii("bad\255 key") => "good value", :hash => { :inner_bad_value => force_to_ascii("\255\255bad value 3"), bad_key.to_sym => 'inner good value', force_to_ascii("bad array key\255") => [ 'good array value 1', force_to_ascii("bad\255 array value 1\255"), { :inner_inner_bad => force_to_ascii("bad inner \255inner value") } ] } } payload_copy = payload.clone notifier.send(:enforce_valid_utf8, payload_copy) payload_copy[:bad_value].should == "bad value 1" payload_copy[:bad_value_2].should == "bad value 2" payload_copy["bad key"].should == "good value" payload_copy.keys.should_not include("bad\456 key") payload_copy[:hash][:inner_bad_value].should == "bad value 3" payload_copy[:hash][:"inner bad key"].should == 'inner good value' payload_copy[:hash]["bad array key"].should == [ 'good array value 1', 'bad array value 1', { :inner_inner_bad => 'bad inner inner value' } ] end end context 'truncate_payload' do it 'should truncate all nested strings in the payload' do payload = { :truncated => '1234567', :not_truncated => '123456', :hash => { :inner_truncated => '123456789', :inner_not_truncated => '567', :array => ['12345678', '12', {:inner_inner => '123456789'}] } } payload_copy = payload.clone notifier.send(:truncate_payload, payload_copy, 6) payload_copy[:truncated].should == '123...' payload_copy[:not_truncated].should == '123456' payload_copy[:hash][:inner_truncated].should == '123...' payload_copy[:hash][:inner_not_truncated].should == '567' payload_copy[:hash][:array].should == ['123...', '12', {:inner_inner => '123...'}] end it 'should truncate utf8 strings properly' do payload = { :truncated => 'Ŝǻмρļẻ śţяịņģ', :not_truncated => '123456', } payload_copy = payload.clone notifier.send(:truncate_payload, payload_copy, 6) payload_copy[:truncated].should == "Ŝǻм..." payload_copy[:not_truncated].should == '123456' end end context 'server_data' do it 'should have the right hostname' do notifier.send(:server_data)[:host] == Socket.gethostname end it 'should have root and branch set when configured' do configure Rollbar.configure do |config| config.root = '/path/to/root' config.branch = 'master' end data = notifier.send(:server_data) data[:root].should == '/path/to/root' data[:branch].should == 'master' end end context "project_gems" do it "should include gem paths for specified project gems in the payload" do gems = ['rack', 'rspec-rails'] gem_paths = [] Rollbar.configure do |config| config.project_gems = gems end gems.each {|gem| gem_paths.push(Gem::Specification.find_by_name(gem).gem_dir) } data = notifier.send(:build_payload, 'info', 'test', nil, {})['data'] data[:project_package_paths].kind_of?(Array).should == true data[:project_package_paths].length.should == gem_paths.length data[:project_package_paths].each_with_index{|path, index| path.should == gem_paths[index] } end it "should handle regex gem patterns" do gems = ["rack", /rspec/, /roll/] gem_paths = [] Rollbar.configure do |config| config.project_gems = gems end gem_paths = gems.map{|gem| Gem::Specification.find_all_by_name(gem).map(&:gem_dir) }.flatten.compact.uniq gem_paths.length.should > 1 gem_paths.any?{|path| path.include? 'rollbar-gem'}.should == true gem_paths.any?{|path| path.include? 'rspec-rails'}.should == true data = notifier.send(:build_payload, 'info', 'test', nil, {})['data'] data[:project_package_paths].kind_of?(Array).should == true data[:project_package_paths].length.should == gem_paths.length (data[:project_package_paths] - gem_paths).length.should == 0 end it "should not break on non-existent gems" do gems = ["this_gem_does_not_exist", "rack"] Rollbar.configure do |config| config.project_gems = gems end data = notifier.send(:build_payload, 'info', 'test', nil, {})['data'] data[:project_package_paths].kind_of?(Array).should == true data[:project_package_paths].length.should == 1 end end context 'report_internal_error', :reconfigure_notifier => true do it "should not crash when given an exception object" do begin 1 / 0 rescue => e notifier.send(:report_internal_error, e) end end end context "send_failsafe" do let(:exception) { StandardError.new } it "should not crash when given a message and exception" do sent_payload = notifier.send(:send_failsafe, "test failsafe", exception) expected_message = 'Failsafe from rollbar-gem: StandardError: test failsafe' expect(sent_payload['data'][:body][:message][:body]).to be_eql(expected_message) end it "should not crash when given all nils" do notifier.send(:send_failsafe, nil, nil) end context 'without exception object' do it 'just sends the given message' do sent_payload = notifier.send(:send_failsafe, "test failsafe", nil) expected_message = 'Failsafe from rollbar-gem: test failsafe' expect(sent_payload['data'][:body][:message][:body]).to be_eql(expected_message) end end end context 'when reporting internal error with nil context' do let(:context_proc) { proc {} } let(:scoped_notifier) { notifier.scope(:context => context_proc) } let(:exception) { Exception.new } let(:logger_mock) { double("Rails.logger").as_null_object } it 'reports successfully' do configure Rollbar.configure do |config| config.logger = logger_mock end logger_mock.should_receive(:info).with('[Rollbar] Sending payload').once logger_mock.should_receive(:info).with('[Rollbar] Success').once scoped_notifier.send(:report_internal_error, exception) end end context "request_data_extractor" do before(:each) do class DummyClass end @dummy_class = DummyClass.new @dummy_class.extend(Rollbar::RequestDataExtractor) end context "rollbar_headers" do it "should not include cookies" do env = {"HTTP_USER_AGENT" => "test", "HTTP_COOKIE" => "cookie"} headers = @dummy_class.send(:rollbar_headers, env) headers.should have_key "User-Agent" headers.should_not have_key "Cookie" end end end describe '.scoped' do let(:scope_options) do { :foo => 'bar' } end it 'changes payload options inside the block' do Rollbar.reset_notifier! configure current_notifier_id = Rollbar.notifier.object_id Rollbar.scoped(scope_options) do configuration = Rollbar.notifier.configuration expect(Rollbar.notifier.object_id).not_to be_eql(current_notifier_id) expect(configuration.payload_options).to be_eql(scope_options) end expect(Rollbar.notifier.object_id).to be_eql(current_notifier_id) end context 'if the block fails' do let(:crashing_block) { proc { fail } } it 'restores the old notifier' do notifier = Rollbar.notifier expect { Rollbar.scoped(&crashing_block) }.to raise_error expect(notifier).to be_eql(Rollbar.notifier) end end context 'if the block creates a new thread' do let(:block) do proc do Thread.new do scope = Rollbar.notifier.configuration.payload_options Thread.main[:inner_scope] = scope end.join end end let(:scope) do { :foo => 'bar' } end it 'maintains the parent thread notifier scope' do Rollbar.scoped(scope, &block) expect(Thread.main[:inner_scope]).to be_eql(scope) end end end describe '.scope!' do let(:new_scope) do { :person => { :id => 1 } } end before { reconfigure_notifier } it 'adds the new scope to the payload options' do configuration = Rollbar.notifier.configuration Rollbar.scope!(new_scope) expect(configuration.payload_options).to be_eql(new_scope) end end describe '.reset_notifier' do it 'resets the notifier' do notifier1_id = Rollbar.notifier.object_id Rollbar.reset_notifier! expect(Rollbar.notifier.object_id).not_to be_eql(notifier1_id) end end describe '.process_payload' do context 'if there is an exception sending the payload' do let(:exception) { StandardError.new('error message') } let(:payload) { { :foo => :bar } } it 'logs the error and the payload' do allow(Rollbar.notifier).to receive(:send_payload).and_raise(exception) expect(Rollbar.notifier).to receive(:log_error) expect { Rollbar.notifier.process_payload(payload) }.to raise_error(exception) end end end describe '.process_from_async_handler' do context 'with errors' do let(:exception) { StandardError.new('the error') } it 'raises anything and sends internal error' do allow(Rollbar.notifier).to receive(:process_payload).and_raise(exception) expect(Rollbar.notifier).to receive(:report_internal_error).with(exception) expect do Rollbar.notifier.process_from_async_handler({}) end.to raise_error(exception) rollbar_do_not_report = exception.instance_variable_get(:@_rollbar_do_not_report) expect(rollbar_do_not_report).to be_eql(true) end end end describe '#custom_data' do before do Rollbar.configure do |config| config.custom_data_method = proc { raise 'this-will-raise' } end expect_any_instance_of(Rollbar::Notifier).to receive(:error).and_return(report_data) end context 'with uuid in reported data' do next unless defined?(SecureRandom) and SecureRandom.respond_to?(:uuid) let(:report_data) { { :uuid => SecureRandom.uuid } } let(:expected_url) { "https://rollbar.com/instance/uuid?uuid=#{report_data[:uuid]}" } it 'returns the uuid in :_error_in_custom_data_method' do expect(notifier.custom_data).to be_eql(:_error_in_custom_data_method => expected_url) end end context 'without uuid in reported data' do let(:report_data) { { :some => 'other-data' } } it 'returns the uuid in :_error_in_custom_data_method' do expect(notifier.custom_data).to be_eql({}) end end end # configure with some basic params def configure reconfigure_notifier end end
heshamnaim/rollbar-gem
spec/rollbar_spec.rb
Ruby
mit
56,294
package main /* We often need our programs to perform operations on collections of data, like selecting all items that satisfy a given predicate or mapping all items to a new collection with a custom function. In some languages it’s idiomatic to use generic data structures and algorithms. Go does not support generics; in Go it’s common to provide collection functions if and when they are specifically needed for your program and data types. Here are some example collection functions for slices of strings. You can use these examples to build your own functions. Note that in some cases it may be clearest to just inline the collection-manipulating code directly, instead of creating and calling a helper function. */ import "strings" import "fmt" // Returns the first index of the target string t, or -1 if no match is found. func Index(vs []string, t string) int { for i, v := range vs { if v == t { return i } } return -1 } // Returns true if the target string t is in the slice. func Include(vs []string, t string) bool { return Index(vs, t) >= 0 } // Returns true if one of the strings in the slice satisfies the predicate f. func Any(vs []string, f func(string) bool) bool { for _, v := range vs { if f(v) { return true } } return false } // Returns true if all of the strings in the slice satisfy the predicate f. func All(vs []string, f func(string) bool) bool { for _, v := range vs { if !f(v) { return false } } return true } // Returns a new slice containing all strings in the slice that satisfy the // predicate f. func Filter(vs []string, f func(string) bool) []string { vsf := make([]string, 0) for _, v := range vs { if f(v) { vsf = append(vsf, v) } } return vsf } // Returns a new slice containing the results of applying the function f to // each string in the original slice. func Map(vs []string, f func(string) string) []string { vsm := make([]string, len(vs)) for i, v := range vs { vsm[i] = f(v) } return vsm } func main() { // Here we try out our various collection functions. var strs = []string{"peach", "apple", "pear", "plum"} fmt.Println(Index(strs, "pear")) fmt.Println(Include(strs, "grape")) fmt.Println(Any(strs, func(v string) bool { return strings.HasPrefix(v, "p") })) fmt.Println(All(strs, func(v string) bool { return strings.HasPrefix(v, "p") })) fmt.Println(Filter(strs, func(v string) bool { return strings.Contains(v, "e") })) // The above examples all used anonymous functions, but you can also use // named functions of the correct type. fmt.Println(Map(strs, strings.ToUpper)) }
tsunammis/software-craftsmanship
development/golang/golangbyexample/43-collection-functions/collection-functions.go
GO
mit
2,608
import { Author } from './article/author/author'; import { Extend } from '../core/globals'; import { Deck } from '../decks/deck'; export class Article { id: number; author: Author; title: string; imageURL: string; content: string; game: 'HS' | 'GWENT'; type: 'METAREPORTS' | 'ANNOUNCMENTS' | 'PODCASTS' | 'HIGHLIGHTS' | 'VIEWPOINTS' | 'TEAMS' | 'CARD_REVEALS'; published: boolean; rating: number; date: number; editDate: number; recommended: Array<Article>; similar?: Array<Deck>; constructor(jsonData: any) { Extend(this, jsonData); } }
JB1040/fade2karma
src/app/articles/article.ts
TypeScript
mit
608
package main // CompletionHandler provides possible completions for given input type CompletionHandler func(input string) []string // DefaultCompletionHandler simply returns an empty slice. var DefaultCompletionHandler = func(input string) []string { return make([]string, 0) } var complHandler = DefaultCompletionHandler // SetCompletionHandler sets the CompletionHandler to be used for completion func SetCompletionHandler(c CompletionHandler) { complHandler = c }
sygool/ledisdb
cmd/ledis-cli/complietion.go
GO
mit
473
'use strict'; const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); const setupTestHooks = blueprintHelpers.setupTestHooks; const emberNew = blueprintHelpers.emberNew; const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; const setupPodConfig = blueprintHelpers.setupPodConfig; const expectError = require('../helpers/expect-error'); const EOL = require('os').EOL; const chai = require('ember-cli-blueprint-test-helpers/chai'); const expect = chai.expect; const setupTestEnvironment = require('../helpers/setup-test-environment'); const enableModuleUnification = setupTestEnvironment.enableModuleUnification; describe('Blueprint: mixin', function() { setupTestHooks(this); describe('in app', function() { beforeEach(function() { return emberNew(); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); it('mixin foo --pod', function() { return emberGenerateDestroy(['mixin', 'foo', '--pod'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--pod'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--pod'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); describe('with podModulePrefix', function() { beforeEach(function() { setupPodConfig({ podModulePrefix: true }); }); it('mixin foo --pod', function() { return emberGenerateDestroy(['mixin', 'foo', '--pod'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--pod'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); }); }); describe('in app - module unification', function() { enableModuleUnification(); beforeEach(function() { return emberNew(); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('src/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('src/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); it('mixin foo --pod', function() { return expectError( emberGenerateDestroy(['service', 'foo', '--pod']), "Pods aren't supported within a module unification app" ); }); }); describe('in addon', function() { beforeEach(function() { return emberNew({ target: 'addon' }); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('addon/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); expect(_file('app/mixins/foo.js')).to.not.exist; }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('addon/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); expect(_file('app/mixins/foo/bar.js')).to.not.exist; }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('addon/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); expect(_file('app/mixins/foo/bar/baz.js')).to.not.exist; }); }); it('mixin foo/bar/baz --dummy', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--dummy'], _file => { expect(_file('tests/dummy/app/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('addon/mixins/foo/bar/baz.js')).to.not.exist; }); }); }); describe('in addon - module unification', function() { enableModuleUnification(); beforeEach(function() { return emberNew({ target: 'addon' }); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('src/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('src/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); }); }); it('mixin foo/bar/baz --dummy', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--dummy'], _file => { expect(_file('tests/dummy/src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz.js')).to.not.exist; }); }); }); describe('in in-repo-addon', function() { beforeEach(function() { return emberNew({ target: 'in-repo-addon' }); }); it('mixin foo --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo', '--in-repo-addon=my-addon'], _file => { expect(_file('lib/my-addon/addon/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); }); }); it('mixin foo/bar --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--in-repo-addon=my-addon'], _file => { expect(_file('lib/my-addon/addon/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--in-repo-addon=my-addon'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); }); }); }); });
kellyselden/ember.js
node-tests/blueprints/mixin-test.js
JavaScript
mit
11,394
package com.swmansion.gesturehandler.react; import android.os.Build; import android.view.View; import android.view.ViewGroup; import com.facebook.react.uimanager.PointerEvents; import com.facebook.react.uimanager.ReactPointerEventsView; import com.facebook.react.views.view.ReactViewGroup; import com.swmansion.gesturehandler.PointerEventsConfig; import com.swmansion.gesturehandler.ViewConfigurationHelper; public class RNViewConfigurationHelper implements ViewConfigurationHelper { @Override public PointerEventsConfig getPointerEventsConfigForView(View view) { PointerEvents pointerEvents; pointerEvents = view instanceof ReactPointerEventsView ? ((ReactPointerEventsView) view).getPointerEvents() : PointerEvents.AUTO; // Views that are disabled should never be the target of pointer events. However, their children // can be because some views (SwipeRefreshLayout) use enabled but still have children that can // be valid targets. if (!view.isEnabled()) { if (pointerEvents == PointerEvents.AUTO) { return PointerEventsConfig.BOX_NONE; } else if (pointerEvents == PointerEvents.BOX_ONLY) { return PointerEventsConfig.NONE; } } switch (pointerEvents) { case BOX_ONLY: return PointerEventsConfig.BOX_ONLY; case BOX_NONE: return PointerEventsConfig.BOX_NONE; case NONE: return PointerEventsConfig.NONE; } return PointerEventsConfig.AUTO; } @Override public View getChildInDrawingOrderAtIndex(ViewGroup parent, int index) { if (parent instanceof ReactViewGroup) { return parent.getChildAt(((ReactViewGroup) parent).getZIndexMappedChildIndex(index)); } return parent.getChildAt(index); } @Override public boolean isViewClippingChildren(ViewGroup view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && !view.getClipChildren()) { if (view instanceof ReactViewGroup) { String overflow = ((ReactViewGroup) view).getOverflow(); return "hidden".equals(overflow); } return false; } return true; } }
BranchMetrics/react-native-branch
examples/androidx-deps/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNViewConfigurationHelper.java
Java
mit
2,135
module Extropy.Entity { // State encapsulates the state of a set of entities for a particular frame export class State { public id: number; public tick: number; private _idToEntity: HashTable<EntityState> = Object.create(null); private _entities: EntityState[] = []; public get entities(): EntityState[] { return this._entities; } public containsEntity(id: string): boolean { return !!this._idToEntity[id]; } public pushEntityData(state: EntityState) { var id = state.id; if (this._idToEntity[id]) throw "This case isn't handled yet."; this._idToEntity[id] = state; this._entities.push(state); } } }
extr0py/extropy
src/js/common/Entity/State/State.ts
TypeScript
mit
790
using System; namespace NHamcrest.Tests.TestClasses { public class ClassWithArrayOfClasses { public Guid Id { get; set; } public SimpleFlatClass[] OtherThings { get; set; } } }
nhamcrest/NHamcrest
src/NHamcrest.Tests/TestClasses/ClassWithArrayOfClasses.cs
C#
mit
208
/* * Copyright (c) 2006-2012 Rogério Liesenfeld * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package powermock.examples.simple; import java.io.*; import org.junit.*; import mockit.*; /** * <a href="http://code.google.com/p/powermock/source/browse/trunk/examples/simple/src/test/java/demo/org/powermock/examples/simple/LoggerTest.java">PowerMock version</a> */ public final class Logger_JMockit_Test { @Test(expected = IllegalStateException.class) public void testException() throws Exception { new NonStrictExpectations() { final FileWriter fileWriter; { fileWriter = new FileWriter("target/logger.log"); result = new IOException(); } }; new Logger(); } @Test public void testLogger() throws Exception { new NonStrictExpectations() { FileWriter fileWriter; // can also be final with value "new FileWriter(withAny(""))" PrintWriter printWriter; // can also be final with value "new PrintWriter(fileWriter)" { printWriter.println("qwe"); } }; Logger logger = new Logger(); logger.log("qwe"); } @Test public void testLogger2(final Logger logger) { new Expectations(logger) { PrintWriter printWriter; { setField(logger, printWriter); printWriter.println("qwe"); } }; logger.log("qwe"); } }
borisbrodski/jmockit
samples/powermock/test/powermock/examples/simple/Logger_JMockit_Test.java
Java
mit
1,473
//Controller app.controller('NavbarController', function($scope, $location) { //Set active navigation bar tab $scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; });
Vmlweb/MEAN-AngularJS-1
client/controller.js
JavaScript
mit
218
{ "name": "editor.js", "url": "https://github.com/ktkaushik/editor.git" }
bower/components
packages/editor.js
JavaScript
mit
78
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * CycleDetector.java * ------------------ * (C) Copyright 2004-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: CycleDetector.java,v 1.1 2010/07/14 14:09:02 mkuper Exp $ * * Changes * ------- * 16-Sept-2004 : Initial revision (JVS); * 07-Jun-2005 : Made generic (CH); * */ package ags.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.traverse.*; /** * Performs cycle detection on a graph. The <i>inspected graph</i> is specified * at construction time and cannot be modified. Currently, the detector supports * only directed graphs. * * @author John V. Sichi * @since Sept 16, 2004 */ public class CycleDetector<V, E> { //~ Instance fields -------------------------------------------------------- /** * Graph on which cycle detection is being performed. */ private DirectedGraph<V, E> graph; //~ Constructors ----------------------------------------------------------- /** * Creates a cycle detector for the specified graph. Currently only directed * graphs are supported. * * @param graph the DirectedGraph in which to detect cycles */ public CycleDetector(DirectedGraph<V, E> graph) { this.graph = graph; } //~ Methods ---------------------------------------------------------------- /** * Performs yes/no cycle detection on the entire graph. * * @return true iff the graph contains at least one cycle */ @SuppressWarnings({ "unchecked", "static-access" }) public List<V> detectCycles() { try { execute(null, null); } catch (CycleDetectedException ex) { return ex.path; } return null; } /** * Performs yes/no cycle detection on an individual vertex. * * @param v the vertex to test * * @return true if v is on at least one cycle */ public boolean detectCyclesContainingVertex(V v) { try { execute(null, v); } catch (CycleDetectedException ex) { return true; } return false; } /** * Finds the vertex set for the subgraph of all cycles which contain a * particular vertex. * * <p>REVIEW jvs 25-Aug-2006: This implementation is not guaranteed to cover * all cases. If you want to be absolutely certain that you report vertices * from all cycles containing v, it's safer (but less efficient) to use * StrongConnectivityInspector instead and return the strongly connected * component containing v. * * @param v the vertex to test * * @return set of all vertices reachable from v via at least one cycle */ public Set<V> findCyclesContainingVertex(V v) { Set<V> set = new HashSet<V>(); execute(set, v); return set; } private void execute(Set<V> s, V v) { ProbeIterator iter = new ProbeIterator(s, v); while (iter.hasNext()) { iter.next(); } } //~ Inner Classes ---------------------------------------------------------- /** * Exception thrown internally when a cycle is detected during a yes/no * cycle test. Must be caught by top-level detection method. */ private static class CycleDetectedException extends RuntimeException { @SuppressWarnings({ "unchecked", "static-access" }) public CycleDetectedException(List path) { this.path = path; } private static final long serialVersionUID = 3834305137802950712L; @SuppressWarnings("unchecked") protected static List path; } /** * Version of DFS which maintains a backtracking path used to probe for * cycles. */ private class ProbeIterator extends DepthFirstIterator<V, E> { private List<V> path; private Set<V> cycleSet; private V root; ProbeIterator(Set<V> cycleSet, V startVertex) { super(graph, startVertex); root = startVertex; this.cycleSet = cycleSet; path = new ArrayList<V>(); } /** * {@inheritDoc} */ protected void encounterVertexAgain(V vertex, E edge) { super.encounterVertexAgain(vertex, edge); int i; if (root != null) { // For rooted detection, the path must either // double back to the root, or to a node of a cycle // which has already been detected. if (vertex == root) { i = 0; } else if ((cycleSet != null) && cycleSet.contains(vertex)) { i = 0; } else { return; } } else { i = path.indexOf(vertex); } if (i > -1) { if (cycleSet == null) { // we're doing yes/no cycle detection path.add(vertex); throw new CycleDetectedException(path); } else { for (; i < path.size(); ++i) { cycleSet.add(path.get(i)); } } } } /** * {@inheritDoc} */ protected V provideNextVertex() { V v = super.provideNextVertex(); // backtrack for (int i = path.size() - 1; i >= 0; --i) { if (graph.containsEdge(path.get(i), v)) { break; } path.remove(i); } path.add(v); return v; } } } // End CycleDetector.java
hetmeter/awmm
fender-sb-bdd/src/ags/graph/CycleDetector.java
Java
mit
6,919
#!/usr/bin/env python # coding:utf8 import ctypes from utils import Loader from utils import convert_data import numpy as np import api mv_lib = Loader.get_lib() class TableHandler(object): '''`TableHandler` is an interface to sync different kinds of values. If you are not writing python code based on theano or lasagne, you are supposed to sync models (for initialization) and gradients (during training) so as to let multiverso help you manage the models in distributed environments. Otherwise, you'd better use the classes in `multiverso.theano_ext` or `multiverso.theano_ext.lasagne_ext` ''' def __init__(self, size, init_value=None): raise NotImplementedError("You must implement the __init__ method.") def get(self, size): raise NotImplementedError("You must implement the get method.") def add(self, data, sync=False): raise NotImplementedError("You must implement the add method.") # types C_FLOAT_P = ctypes.POINTER(ctypes.c_float) class ArrayTableHandler(TableHandler): '''`ArrayTableHandler` is used to sync array-like (one-dimensional) value.''' def __init__(self, size, init_value=None): '''Constructor for syncing array-like (one-dimensional) value. The `size` should be a int equal to the size of value we want to sync. If init_value is None, zeros will be used to initialize the table, otherwise the table will be initialized as the init_value. *Notice*: Only the init_value from the master will be used! ''' self._handler = ctypes.c_void_p() self._size = size mv_lib.MV_NewArrayTable(size, ctypes.byref(self._handler)) if init_value is not None: init_value = convert_data(init_value) # sync add is used because we want to make sure that the initial # value has taken effect when the call returns. No matter whether # it is master worker, we should call add to make sure it works in # sync mode self.add(init_value if api.is_master_worker() else np.zeros(init_value.shape), sync=True) def get(self): '''get the latest value from multiverso ArrayTable Data type of return value is numpy.ndarray with one-dimensional ''' data = np.zeros((self._size, ), dtype=np.dtype("float32")) mv_lib.MV_GetArrayTable(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) return data def add(self, data, sync=False): '''add the data to the multiverso ArrayTable Data type of `data` is numpy.ndarray with one-dimensional If sync is True, this call will blocked by IO until the call finish. Otherwise it will return immediately ''' data = convert_data(data) assert(data.size == self._size) if sync: mv_lib.MV_AddArrayTable(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) else: mv_lib.MV_AddAsyncArrayTable(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) class MatrixTableHandler(TableHandler): def __init__(self, num_row, num_col, init_value=None): '''Constructor for syncing matrix-like (two-dimensional) value. The `num_row` should be the number of rows and the `num_col` should be the number of columns. If init_value is None, zeros will be used to initialize the table, otherwise the table will be initialized as the init_value. *Notice*: Only the init_value from the master will be used! ''' self._handler = ctypes.c_void_p() self._num_row = num_row self._num_col = num_col self._size = num_col * num_row mv_lib.MV_NewMatrixTable(num_row, num_col, ctypes.byref(self._handler)) if init_value is not None: init_value = convert_data(init_value) # sync add is used because we want to make sure that the initial # value has taken effect when the call returns. No matter whether # it is master worker, we should call add to make sure it works in # sync mode self.add(init_value if api.is_master_worker() else np.zeros(init_value.shape), sync=True) def get(self, row_ids=None): '''get the latest value from multiverso MatrixTable If row_ids is None, we will return all rows as numpy.narray , e.g. array([[1, 3], [3, 4]]). Otherwise we will return the data according to the row_ids(e.g. you can pass [1] to row_ids to get only the first row, it will return a two-dimensional numpy.ndarray with one row) Data type of return value is numpy.ndarray with two-dimensional ''' if row_ids is None: data = np.zeros((self._num_row, self._num_col), dtype=np.dtype("float32")) mv_lib.MV_GetMatrixTableAll(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) return data else: row_ids_n = len(row_ids) int_array_type = ctypes.c_int * row_ids_n data = np.zeros((row_ids_n, self._num_col), dtype=np.dtype("float32")) mv_lib.MV_GetMatrixTableByRows(self._handler, data.ctypes.data_as(C_FLOAT_P), row_ids_n * self._num_col, int_array_type(*row_ids), row_ids_n) return data def add(self, data=None, row_ids=None, sync=False): '''add the data to the multiverso MatrixTable If row_ids is None, we will add all data, and the data should be a list, e.g. [1, 2, 3, ...] Otherwise we will add the data according to the row_ids Data type of `data` is numpy.ndarray with two-dimensional If sync is True, this call will blocked by IO until the call finish. Otherwise it will return immediately ''' assert(data is not None) data = convert_data(data) if row_ids is None: assert(data.size == self._size) if sync: mv_lib.MV_AddMatrixTableAll(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) else: mv_lib.MV_AddAsyncMatrixTableAll(self._handler, data.ctypes.data_as(C_FLOAT_P), self._size) else: row_ids_n = len(row_ids) assert(data.size == row_ids_n * self._num_col) int_array_type = ctypes.c_int * row_ids_n if sync: mv_lib.MV_AddMatrixTableByRows(self._handler, data.ctypes.data_as(C_FLOAT_P), row_ids_n * self._num_col, int_array_type(*row_ids), row_ids_n) else: mv_lib.MV_AddAsyncMatrixTableByRows(self._handler, data.ctypes.data_as(C_FLOAT_P), row_ids_n * self._num_col, int_array_type(*row_ids), row_ids_n)
you-n-g/multiverso
binding/python/multiverso/tables.py
Python
mit
7,029
<?php namespace Plivo\Exceptions; /** * Class PlivoXMLException * @package Plivo\Exceptions */ class PlivoXMLException extends PlivoRestException { }
plivo/plivo-php
src/Plivo/Exceptions/PlivoXMLException.php
PHP
mit
156
'use strict'; const dotenv = require('dotenv'); dotenv.load(); const express = require('express'); const debug = require('debug')('ways2go:server'); const morgan = require('morgan'); const cors = require('cors'); const mongoose = require('mongoose'); const Promise = require('bluebird'); const apiRouter = require('./route/api-router.js'); const wayRouter = require('./route/way-router.js'); const userRouter = require('./route/user-router.js'); const profileRouter = require('./route/profile-router.js'); const messageRouter = require('./route/message-router.js'); const reviewRouter = require('./route/review-router.js'); const errors = require('./lib/error-middleware.js'); const PORT = process.env.PORT || 3000; const app = express(); mongoose.Promise = Promise; mongoose.connect(process.env.MONGODB_URI); app.use(cors()); app.use(morgan('dev')); app.use(userRouter); app.use(apiRouter); app.use(wayRouter); app.use(profileRouter); app.use(reviewRouter); app.use(messageRouter); app.use(errors); const server = module.exports = app.listen(PORT, () => { debug(`Server's up on PORT: ${PORT}`); }); server.isRunning = true;
dkulp23/ways2goAPI
server.js
JavaScript
mit
1,137
<?php abstract class f_di_shared extends f_di { protected static $_shared = array(); public function __get($name) { if (isset(self::$_shared[$name])) { return $this->{$name} = self::$_shared[$name]; } return parent::__get($name); } }
serafin/fine
src/lib/f/di/shared.php
PHP
mit
295
var conf = require('../config/'); var sha = require('object-hash'); var uuid = require('node-uuid'); var _ = require('underscore'); _.mixin(require('underscore.deep')); var url = require('url'); var db; var env = exports.env = conf.name; var similarFilter = ['type', 'location', 'description.contactnumber']; var readonly = exports.readonly = Number(process.env.KAHA_READONLY) || 0; exports.init = function(dbObj){ db = dbObj; }; /** * Description: mixin for increment * and decrement counter * * @method flagcounter * @param dbQry{Function} query to be performed * @return Function */ var flagcounter = exports.flagcounter = function(dbQry) { return function(req, res, next) { if (enforceReadonly(res)) { return; } var obj = { "uuid": req.params.id, "flag": req.query.flag }; dbQry(req, res, obj); }; }; /** * Description: When the server * needs to enable read-only * mode to stop writing on db * * @method enforceReadonly * @param res{Object} * @return Boolean */ var enforceReadonly = exports.enforceReadonly = function(res) { if (readonly) { res.status(503).send('Service Unavailable'); return true; } return false; }; /** * Description: Standard Callback * To stop duplication across * all page * * @method stdCb * @param err{Boolean}, reply{Array} * @return [Boolean] */ var stdCb = exports.stdCb = function(err, reply) { if (err) { return err; } }; /** * Description: Get Everything * * @method getAllFromDb * @param Function * @return N/A */ exports.getEverything = function(cb) { var results = []; var multi = db.multi(); db.keys('*', function(err, reply) { if (err) { return err; } reply.forEach(function(key) { multi.get(key, stdCb); }); multi.exec(function(err, replies) { if (err) { return err; } var result = _.map(replies, function(rep) { return JSON.parse(rep); }); var keyVals = _.object(reply, result); cb(null, keyVals); }); }); }; /** * Description: DRYing * * @method getAllFromDb * @param cb{Function} * @return n/a */ var getAllFromDb = exports.getAllFromDb = function(cb) { var results = []; var multi = db.multi(); db.keys('*', function(err, reply) { if (err) { return err; } db.keys('*:*', function(err, reply2) { if (err) { return err; } _.each(_.difference(reply, reply2), function(key) { multi.get(key, stdCb); }); multi.exec(function(err, replies) { if (err) { return err; } var result = _.map(replies, function(rep) { return JSON.parse(rep); }); cb(null, result); }); }); }); }; /** * Description: Only for individual * Object * * @method getSha * @param obj{Object}, shaFilters{Array} * @return String */ var getSha = exports.getSha = function(obj, shaFilters) { var key, extract = {}; if (Array.isArray(shaFilters)) { shaFilters.forEach(function(filter) { var selectedObj = _.deepPick(obj, [filter]); _.extend(extract, selectedObj); }); } return sha(extract); }; /** * Description: Similar to getSha * but for array of Objects * * @method getShaAllWithObjs * @param objs{Object} * @return Array */ var getShaAllWithObjs = exports.getShaAllWithObjs = function(objs) { var hashes = []; objs.forEach(function(result) { var tmpObj = {}; tmpObj[getSha(result, similarFilter)] = result; hashes.push(tmpObj); }); return hashes; }; /** * Description: No filter * * @method methodName * @param type * @return type */ var getShaAll = exports.getShaAll = function(objs, similarFilter) { var hashes = []; objs.forEach(function(result) { hashes.push(getSha(result, similarFilter)); }); return hashes; }; /** * Description: * * @method methodName * @param type * @return type */ var getSimilarItems = exports.getSimilarItems = function(arrayObj, shaKey) { return _.map(_.filter(getShaAllWithObjs(arrayObj), function(obj) { return _.keys(obj)[0] === shaKey; }), function(obj) { return _.values(obj)[0]; }); }; var getUniqueUserID = exports.getUniqueUserID = function(req) { var proxies = req.headers['x-forwarded-for'] || ''; var ip = _.last(proxies.split(',')) || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; return ip; }; /** * Description: Does single or bulk post * * @method rootPost * @param req(Object), res(Object), next(Function) * @return n/a */ var rootPost = exports.rootPost = function(req, res, next) { /* give each entry a unique id */ function entry(obj) { var data_uuid = uuid.v4(); obj.uuid = data_uuid; obj = dateEntry(obj); if (typeof obj.verified === 'undefined') { obj.verified = false; } multi.set(data_uuid, JSON.stringify(obj), function(err, reply) { if (err) { return err; } return reply; }); } function dateEntry(obj) { var today = new Date(); if (!(obj.date && obj.date.created)) { obj.date = { 'created': today.toUTCString(), 'modified': today.toUTCString() }; } return obj; } function insertToDb(res) { multi.exec(function(err, replies) { if (err) { console.log(err); res.status(500).send(err); return; } //console.log(JSON.stringify(replies)); if (replies) { res.send(replies); } }); } if (enforceReadonly(res)) { return; } var ref = (req.headers && req.headers.referer) || false; //No POST request allowed from other sources //TODO probably need to fix this for prod docker if (ref) { var u = url.parse(ref); var hostname = u && u.hostname; var environment = env.toLowerCase(); if (hasPostAccess(hostname, environment)) { var okResult = []; var multi = db.multi(); var data = req.body; if (Array.isArray(data)) { data.forEach(function(item, index) { entry(item); insertToDb(res); }); } else { getAllFromDb(function(err, results) { var similarItems = getSimilarItems(results, getSha(data, similarFilter)); var query = req.query.confirm || "no"; if (similarItems.length > 0 && (query.toLowerCase() === "no")) { res.send(similarItems); } else { entry(data); insertToDb(res); } }); } } else { res.status(403).send('Invalid Origin'); } } else { res.status(403).send('Invalid Origin'); } }; function hasPostAccess(currDomain, currEnv){ var allowedDomains= ["kaha.co", "demokaha.herokuapp.com"]; var allowedEnvs = ["dev", "stage"]; return checkDomain(allowedDomains, currDomain) || checkEnvs(allowedEnvs, currEnv); } /** * Description: Checks if it's the right domains * * @method checkDomain * @param {Array}, {String} * @return {Boolean} */ function checkDomain(allowedDomains, currDomain){ //check sub-domains and prefixes like `www` too return allowedDomains.some(function(domain){ return ~currDomain.indexOf(domain); }); } /** * Description: Checks the right environment * for right access * @method checkEnvs * @param {Array}, {String} * @return {Boolean} */ function checkEnvs(allowedEnvs, currEnv){ return ~allowedEnvs.indexOf(currEnv); }
sinkingshriek/kaha
routes/utils.js
JavaScript
mit
7,537
module Kamome class Railtie < Rails::Railtie initializer "kamome.on_load_active_record" do ActiveSupport.on_load(:active_record) do include Kamome::Model end end initializer "kamome.configure" do Kamome.configure do |config| config.config_path = Rails.root.join("config/kamome.yml") end end rake_tasks do Dir[File.join(__dir__, "../tasks/**/*.rake")].each { |f| load f } end end end
t1732/kamome
lib/kamome/railtie.rb
Ruby
mit
459
using PsISEProjectExplorer.Enums; using PsISEProjectExplorer.Model; using PsISEProjectExplorer.Model.DocHierarchy.Nodes; using PsISEProjectExplorer.Services; using PsISEProjectExplorer.UI.IseIntegration; using PsISEProjectExplorer.UI.ViewModel; using System; namespace PsISEProjectExplorer.Commands { [Component] public class OpenItemCommand : Command { private readonly TreeViewModel treeViewModel; private readonly MainViewModel mainViewModel; private readonly IseIntegrator iseIntegrator; private readonly TokenLocator tokenLocator; public OpenItemCommand(TreeViewModel treeViewModel, MainViewModel mainViewModel, IseIntegrator iseIntegrator, TokenLocator tokenLocator) { this.treeViewModel = treeViewModel; this.mainViewModel = mainViewModel; this.iseIntegrator = iseIntegrator; this.tokenLocator = tokenLocator; } public void Execute() { var item = this.treeViewModel.SelectedItem; var searchOptions = this.mainViewModel.SearchOptions; if (item == null) { return; } if (item.Node.NodeType == NodeType.File) { bool wasOpen = (this.iseIntegrator.SelectedFilePath == item.Node.Path); if (!wasOpen) { this.iseIntegrator.GoToFile(item.Node.Path); } else { this.iseIntegrator.SetFocusOnCurrentTab(); } if (searchOptions.SearchText != null && searchOptions.SearchText.Length > 2) { EditorInfo editorInfo = (wasOpen ? this.iseIntegrator.GetCurrentLineWithColumnIndex() : null); TokenPosition tokenPos = this.tokenLocator.LocateNextToken(item.Node.Path, searchOptions, editorInfo); if (tokenPos.MatchLength > 2) { this.iseIntegrator.SelectText(tokenPos.Line, tokenPos.Column, tokenPos.MatchLength); } else if (string.IsNullOrEmpty(this.iseIntegrator.SelectedText)) { tokenPos = this.tokenLocator.LocateSubtoken(item.Node.Path, searchOptions); if (tokenPos.MatchLength > 2) { this.iseIntegrator.SelectText(tokenPos.Line, tokenPos.Column, tokenPos.MatchLength); } } } } else if (item.Node.NodeType == NodeType.Directory) { item.IsExpanded = !item.IsExpanded; } else if (item.Node.NodeType != NodeType.Intermediate) { var node = ((PowershellItemNode)item.Node); this.iseIntegrator.GoToFile(node.FilePath); this.iseIntegrator.SelectText(node.PowershellItem.StartLine, node.PowershellItem.StartColumn, node.PowershellItem.EndColumn - node.PowershellItem.StartColumn); } } } }
mgr32/PsISEProjectExplorer
PsISEProjectExplorer/Commands/OpenItemCommand.cs
C#
mit
3,259
<?php /*==========================================================*/ //This is a model to finally register a user into the database //by creating he or she account on the platform use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\Reminders\RemindableInterface; class RegisterUser extends Eloquent { protected $guarded = array(); protected $table = 'created_users'; // table name public $timestamps = 'true' ; // to disable default timestamp fields // model function to store form data to database public static function saveUserData($data) { DB::table('created_users')->insert($data); } }
ch3nkula/IMS_Soft400
app/models/RegisterUser.php
PHP
mit
739
(function () { angular .module('keylistener') .directive('keylistener', keylistener); function keylistener($document, $rootScope, $ionicPopup) { var directive = { restrict: 'A', link: link }; return directive; function link() { var captured = []; $document.bind('keydown', function (e) { $rootScope.$broadcast('keydown', e); $rootScope.$broadcast('keydown:' + e.which, e); // check nerd captured.push(e.which) if (arrayEndsWith(captured, [38, 38, 40, 40, 37, 39, 37, 39, 66, 65])) nerd(); }); } function arrayEndsWith(a, b) { a = a.slice(a.length - b.length, a.length); if (a.length !== b.length) return; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } function nerd() { captured = []; document.getElementsByTagName('body')[0].className += ' nerd'; $ionicPopup.alert({title: 'You\'re a nerd 🤓', buttons: [{text: 'I know', type: 'button-positive'}]}); } } })();
dank-meme-dealership/foosey
frontend/www/js/keylistener/keylistener.directive.js
JavaScript
mit
1,086
#include "../include/structure/fenwick_tree.cpp" int main() { int n, q, com, x, y; scanf("%d%d", &n, &q); FenwickTree<int> bit(n + 1); while (q--) { scanf("%d%d%d", &com, &x, &y); if (com) printf("%d\n", bit.sum(x, y + 1)); else bit.add(x, y); } return 0; }
asi1024/ContestLibrary
cpp/tests/aoj-DSL_2_B.cpp
C++
mit
295
import { highlight } from "../../../helpers/highlight" import { module, test } from "qunit" module("Unit | Helper | highlight") test("it works", function(assert) { let result result = highlight([], { phrase: "Something", part: "Some" }) assert.equal( result, '<mark class="en-select-option-highlight">Some</mark>thing' ) result = highlight([], { phrase: "No match", part: "Some" }) assert.equal(result, "No match") result = highlight([], { phrase: "John Doe", part: "John D" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">D</mark>oe' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "In a world far away", part: "a" }) assert.equal( result, 'In <mark class="en-select-option-highlight">a</mark> world f<mark class="en-select-option-highlight">a</mark>r <mark class="en-select-option-highlight">a</mark>w<mark class="en-select-option-highlight">a</mark>y' ) result = highlight([], { phrase: "In a world far away", part: "" }) assert.equal( result, 'In a world far away' ) })
swastik/en-select
tests/unit/helpers/highlight-test.js
JavaScript
mit
1,823
u1 = User.new(:email => 'louis.merlin@epfl.ch', :first_name => 'Louis', :last_name => 'Merlin') u1.password = "louis" u1.password_confirmation = "louis" u1.save u2 = User.new(:email => 'patrick.aebischer@epfl.ch', :first_name => 'Patrick', :last_name => 'Aebischer') u2.password = "patrick" u2.password_confirmation = "patrick" u2.save p1 = Pomodoro.new(:h => Time.now()) p1.save u1.add_pomodoro(p1) t1 = Tag.new(:title => "Code") t2 = Tag.new(title: "Analyse") t1.save t2.save u1.add_tag(t1) u1.add_tag(t2) p1.add_tag(t1) #puts User[:id => 1].email #puts p1.user #p1.user = User[:id => 1]
louismerlin/trackodoro
populate.rb
Ruby
mit
594
import pytest from hackathon.constants import VE_PROVIDER, TEMPLATE_STATUS from hackathon.hmongo.models import User, Template, UserHackathon from hackathon.hmongo.database import add_super_user @pytest.fixture(scope="class") def user1(): # return new user named one one = User( name="test_one", nickname="test_one", avatar_url="/static/pic/monkey-32-32px.png", is_super=False) one.set_password("test_password") one.save() return one @pytest.fixture(scope="class") def user2(): # return new user named two two = User( name="test_two", nickname="test_two", avatar_url="/static/pic/monkey-32-32px.png", is_super=False) two.set_password("test_password") two.save() return two @pytest.fixture(scope="class") def admin1(): # return new admin named one admin_one = User( name="admin_one", nickname="admin_one", avatar_url="/static/pic/monkey-32-32px.png", is_super=True) admin_one.set_password("test_password") admin_one.save() return admin_one @pytest.fixture(scope="class") def default_template(user1): tmpl = Template( name="test_default_template", provider=VE_PROVIDER.DOCKER, status=TEMPLATE_STATUS.UNCHECKED, description="old_desc", content="", template_args={}, docker_image="ubuntu", network_configs=[], virtual_environment_count=0, creator=user1, ) tmpl.save() return tmpl
juniwang/open-hackathon
open-hackathon-server/src/tests/conftest.py
Python
mit
1,534
<?php namespace Chamilo\Application\Weblcms\Tool\Action\Component; use Chamilo\Application\Weblcms\Rights\WeblcmsRights; use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication; use Chamilo\Application\Weblcms\Tool\Action\Manager; use Chamilo\Core\Repository\ContentObject\Introduction\Storage\DataClass\Introduction; use Chamilo\Libraries\Architecture\Application\ApplicationConfiguration; use Chamilo\Libraries\Architecture\Application\ApplicationFactory; use Chamilo\Libraries\Architecture\Exceptions\NotAllowedException; use Chamilo\Libraries\Architecture\Interfaces\DelegateComponent; use Chamilo\Libraries\Platform\Session\Session; use Chamilo\Libraries\Platform\Translation; use Chamilo\Libraries\Utilities\Utilities; /** * $Id: introduction_publisher.class.php 216 2009-11-13 14:08:06Z kariboe $ * * @package application.lib.weblcms.tool.component */ class IntroductionPublisherComponent extends Manager implements \Chamilo\Core\Repository\Viewer\ViewerInterface, DelegateComponent { public function run() { if (! $this->is_allowed(WeblcmsRights::ADD_RIGHT)) { throw new NotAllowedException(); } if (! \Chamilo\Core\Repository\Viewer\Manager::is_ready_to_be_published()) { $applicationConfiguration = new ApplicationConfiguration($this->getRequest(), $this->get_user(), $this); $applicationConfiguration->set(\Chamilo\Core\Repository\Viewer\Manager::SETTING_TABS_DISABLED, true); $factory = new ApplicationFactory( \Chamilo\Core\Repository\Viewer\Manager::context(), $applicationConfiguration); $component = $factory->getComponent(); $component->set_maximum_select(\Chamilo\Core\Repository\Viewer\Manager::SELECT_SINGLE); $component->set_parameter( \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION, \Chamilo\Application\Weblcms\Tool\Manager::ACTION_PUBLISH_INTRODUCTION); return $component->run(); } else { $pub = new ContentObjectPublication(); $pub->set_content_object_id(\Chamilo\Core\Repository\Viewer\Manager::get_selected_objects()); $pub->set_course_id($this->get_course_id()); $pub->set_tool($this->get_tool_id()); $pub->set_category_id(0); $pub->set_from_date(0); $pub->set_to_date(0); $pub->set_publisher_id(Session::get_user_id()); $pub->set_publication_date(time()); $pub->set_modified_date(time()); $pub->set_hidden(0); $pub->set_email_sent(0); $pub->set_show_on_homepage(0); $pub->set_allow_collaboration(1); $pub->ignore_display_order(); $pub->create(); $parameters = $this->get_parameters(); $parameters['tool_action'] = null; $this->redirect( Translation::get( 'ObjectPublished', array('OBJECT' => Translation::get('Introduction')), Utilities::COMMON_LIBRARIES), (false), $parameters); } } public function get_allowed_content_object_types() { return array(Introduction::class_name()); } }
cosnicsTHLU/cosnics
src/Chamilo/Application/Weblcms/Tool/Action/Component/IntroductionPublisherComponent.php
PHP
mit
3,460
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.logic.v2018_07_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for WorkflowState. */ public final class WorkflowState extends ExpandableStringEnum<WorkflowState> { /** Static value NotSpecified for WorkflowState. */ public static final WorkflowState NOT_SPECIFIED = fromString("NotSpecified"); /** Static value Completed for WorkflowState. */ public static final WorkflowState COMPLETED = fromString("Completed"); /** Static value Enabled for WorkflowState. */ public static final WorkflowState ENABLED = fromString("Enabled"); /** Static value Disabled for WorkflowState. */ public static final WorkflowState DISABLED = fromString("Disabled"); /** Static value Deleted for WorkflowState. */ public static final WorkflowState DELETED = fromString("Deleted"); /** Static value Suspended for WorkflowState. */ public static final WorkflowState SUSPENDED = fromString("Suspended"); /** * Creates or finds a WorkflowState from its string representation. * @param name a name to look for * @return the corresponding WorkflowState */ @JsonCreator public static WorkflowState fromString(String name) { return fromString(name, WorkflowState.class); } /** * @return known WorkflowState values */ public static Collection<WorkflowState> values() { return values(WorkflowState.class); } }
selvasingh/azure-sdk-for-java
sdk/logic/mgmt-v2018_07_01_preview/src/main/java/com/microsoft/azure/management/logic/v2018_07_01_preview/WorkflowState.java
Java
mit
1,797
var EventUtil = { addHandler: function(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); } else if (element.attachEvent){ element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, getButton: function(event){ if (document.implementation.hasFeature("MouseEvents", "2.0")){ return event.button; } else { switch(event.button){ case 0: case 1: case 3: case 5: case 7: return 0; case 2: case 6: return 2; case 4: return 1; } } }, getCharCode: function(event){ if (typeof event.charCode == "number"){ return event.charCode; } else { return event.keyCode; } }, getClipboardText: function(event){ var clipboardData = (event.clipboardData || window.clipboardData); return clipboardData.getData("text"); }, getEvent: function(event){ return event ? event : window.event; }, getRelatedTarget: function(event){ if (event.relatedTarget){ return event.relatedTarget; } else if (event.toElement){ return event.toElement; } else if (event.fromElement){ return event.fromElement; } else { return null; } }, getTarget: function(event){ if (event.target){ return event.target; } else { return event.srcElement; } }, getWheelDelta: function(event){ if (event.wheelDelta){ return (client.opera && client.opera < 9.5 ? -event.wheelDelta : event.wheelDelta); } else { return -event.detail * 40; } }, preventDefault: function(event){ if (event.preventDefault){ event.preventDefault(); } else { event.returnValue = false; } }, removeHandler: function(element, type, handler){ if (element.removeEventListener){ element.removeEventListener(type, handler, false); } else if (element.detachEvent){ element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } }, setClipboardText: function(event, value){ if (event.clipboardData){ event.clipboardData.setData("text/plain", value); } else if (window.clipboardData){ window.clipboardData.setData("text", value); } }, stopPropagation: function(event){ if (event.stopPropagation){ event.stopPropagation(); } else { event.cancelBubble = true; } } }; //back button function goBack() { window.history.back(); } // yes, this does what you think it does! $( document ).ready(function() { window.setInterval(function(){ $('.blink').toggle(); }, 550); }); // this sets the default sprint number if its not changed on the admin page. var defaultSprint = function() { var sprintNow = JSON.parse(localStorage.getItem('sprint-number')); console.log(sprintNow); if (sprintNow == null) { sprintNow = "programmeTen"; localStorage.setItem("sprint-number", JSON.stringify(sprintNow)); } else { } }; defaultSprint(); // This removes the breadcrumbs from sprint 10 (the navigation version). The breadcrumb on earlier versions is broken var breadyCrumb = function() { var whatSprint = JSON.parse(localStorage.getItem('sprint-number')); console.log('what sprint is ' + whatSprint); if (whatSprint == "sprint10") { $('<style>.breadcrumbs ol li a { display:none;}</style>').appendTo('head'); } else {} }; breadyCrumb(); // This sets a default company name if its not been set on the proto admin page var CompanyName = function() { var compName = JSON.parse(localStorage.getItem('company-name-header')); console.log(compName); if (compName == null) { compName = "Acme Ltd"; localStorage.setItem("company-name-header", JSON.stringify(compName)); } else { } }; CompanyName(); /* To determine if the to do list has been done - only dates works for now - this breaks because of the URl change below if it is in the page...it should live in /sprint11/contracts/new-contract/provider-interface/add-apprenticeship */ //$( document ).ready(function() { //var addedOrNor = function() { // var hasDatesAdded = JSON.parse(localStorage.getItem('apprenticeship-dates-added')); // console.log(hasDatesAdded) // if (hasDatesAdded == "yes") { // $( ".datesComplete" ).removeClass( "rj-dont-display" ); // $( ".datesToDo" ).addClass( "rj-dont-display" ); // var hasDatesAdded = 'no'; // localStorage.setItem("apprenticeship-dates-added", JSON.stringify(hasDatesAdded)); // } else { // $( ".datesComplete" ).addClass( "rj-dont-display" ); // } //}; //addedOrNor(); //}); /* To determine if an apprenticeship has been added to the contract - this breaks because of the URl change below if it is in the page...it should live in /sprint11/contracts/new-contract/provider-interface/individual-contract */ // This has moved to javascripts/das/commitment-1.0.js // $( document ).ready(function() { // var whereNow = function() { // var hasAppAdded = JSON.parse(localStorage.getItem('apprenticeship-added')); // // if (hasAppAdded == "yes") { // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // var isAddedApp = 'no'; // localStorage.setItem("apprenticeship-added", JSON.stringify(isAddedApp)); // // // } else { // $( "#apprenticeships" ).addClass( "rj-dont-display" ); // // } // }; // whereNow(); // // }); // // $( document ).ready(function() { // var bulkUpload = function() { // var hasBulkUpload = JSON.parse(localStorage.getItem('apprenticeship-added.bulk-upload')); // if (hasBulkUpload == "yes") { // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // $( "#apprenticeships-bulk" ).removeClass( "rj-dont-display" ); // var hasBulkUpload = 'no'; // localStorage.setItem("apprenticeship-added.bulk-upload", JSON.stringify(hasBulkUpload)); // } else { // $( "#apprenticeships-bulk" ).addClass( "rj-dont-display" ); // // } // }; // bulkUpload(); // // }); /* To determine whether the commitments in progress page should show the confirmation or not (i.e. have you just completed something) - this breaks because of the URl change below if it is in the page...it should live in /contracts/provider-in-progress? */ $( document ).ready(function() { var showDoneAlert = function() { var isAlertShowing = JSON.parse(localStorage.getItem('commitments.providerAlert')); if (isAlertShowing == "yes") { $( "#showDoneAlert" ).removeClass( "rj-dont-display" ); var isAlertShowing = 'no'; localStorage.setItem("commitments.providerAlert", JSON.stringify(isAlertShowing)); } else { // $( "#showDoneAlert" ).addClass( "rj-dont-display" ); } }; showDoneAlert(); }); //This swaps out the URL to the sprint chosen in the admin tool. The phrase it is searching for and replacing is in includes/sprint-link.html // Want this to run last as it was breaking other things... $(document).ready(function() { var urlToBeChanged = JSON.parse(localStorage.getItem('sprint-number')); $("body").html($("body").html().replace(/change-me-url/g, urlToBeChanged)); });
SkillsFundingAgency/das-alpha-ui
public/javascripts/custom.js
JavaScript
mit
7,807
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7.Exchange_Variable_Values { class Program { static void Main(string[] args) { int a = 5; int b = 10; Console.WriteLine("Before:\na = " + a + "\nb = " + b); int c = a; a = b; b = c; Console.WriteLine("After:\na = " + a + "\nb = " + b); } } }
AlexanderStanev/SoftUni
TechModule/DataTypesVariablesExercises/07. Exchange Variable Values/Program.cs
C#
mit
501
using CubeWorld.World.Generator; using CubeWorld.Tiles; using CubeWorld.World.Lights; using CubeWorld.Configuration; using CubeWorld.Items; using CubeWorld.Avatars; using CubeWorld.Gameplay; namespace CubeWorld.Configuration { public class Config { public ConfigWorldSize worldSize; public ConfigDayInfo dayInfo; public ConfigWorldGenerator worldGenerator; public TileDefinition[] tileDefinitions; public ItemDefinition[] itemDefinitions; public AvatarDefinition[] avatarDefinitions; public ConfigExtraMaterials extraMaterials; public GameplayDefinition gameplay; } }
yizhi401/NoahsArk
CubeWorldUnity/Assets/SourceCode/CubeWorld/Configuration/Config.cs
C#
mit
639