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
/* * Author: Bob Limnor (info@limnor.com) * Project: Limnor Studio * Item: Visual Programming Language Implement * License: GNU General Public License v3.0 */ using System; using System.Collections.Generic; using System.Text; namespace LimnorDesigner.Web { public class HtmlElement_pre : HtmlElement_ItemBase { public HtmlElement_pre(ClassPointer owner) : base(owner) { } public HtmlElement_pre(ClassPointer owner, string id, Guid guid) : base(owner, id, guid) { } public override string tagName { get { return "pre"; } } } }
Limnor/Limnor-Studio-Source-Code
Source/LimnorDesigner/Web/HtmlElement_pre.cs
C#
gpl-3.0
599
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.trade.vendorpay.devicedata.upload response. * * @author auto create * @since 1.0, 2016-12-08 00:51:39 */ public class AlipayTradeVendorpayDevicedataUploadResponse extends AlipayResponse { private static final long serialVersionUID = 5272579554188824387L; }
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/response/AlipayTradeVendorpayDevicedataUploadResponse.java
Java
gpl-3.0
371
<?php /** * User: ed8 * Date: 7/27/14 */ class Shell { /** * Execute a shell command and capture its output * @param null $_ shell command * @param bool $debug * @return mixed */ public static function execute($_ = null, $debug=true) { $_ = "( TERM=screen-256color $_ )"; $_ = $debug ? $_." 2>&1" : $_; # we wrap the commands in a subshell so all stdout is piped to aha exec("$_ | aha --no-header", $output, $exitCode); return $output; } /** * Serialize to string a captured command * @param null $_ */ public static function toString($_ = null) { if (is_array($_ )) { foreach($_ as $k => $line) { echo $line.'<br/>'; } } else { var_dump($_); show_error('Invalid command output in '.basename(__FILE__), 500); } } /** * Shortcut to execute and serialize * @param $_ shell command * @return mixed */ public function run($_) { $ouput = self::execute($_); return self::toString($ouput); } public static function list_channels($_) { $output = self::execute(sprintf("%s %s NAME=%s", MAST_UTILS, "list-channels", $_)); return $output; } }
edouard-lopez/mast-web
application/libraries/Shell.php
PHP
gpl-3.0
1,311
<?php /* * This file is part of Phraseanet * * (c) 2005-2015 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alchemy\Phrasea\Databox; use Alchemy\Phrasea\Application; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class DataboxFactory { /** @var Application */ private $app; public function __construct(Application $app) { $this->app = $app; } /** * @param int $id * @param array $raw * @throws NotFoundHttpException when Databox could not be retrieved from Persistence layer * @return \databox */ public function create($id, array $raw) { return new \databox($this->app, $id, $raw); } /** * @param array $rows * @throws NotFoundHttpException when Databox could not be retrieved from Persistence layer * @return \databox[] */ public function createMany(array $rows) { $databoxes = []; foreach ($rows as $id => $raw) { $databoxes[$id] = new \databox($this->app, $id, $raw); } return $databoxes; } }
mdarse/Phraseanet
lib/Alchemy/Phrasea/Databox/DataboxFactory.php
PHP
gpl-3.0
1,190
package com.chandilsachin.diettracker.io; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Iterator; public final class FontsOverride { public static void populateFonts(Activity activity, HashMap<String, String> fontTable) { if (fontTable != null) { Iterator<String> fonts = fontTable.keySet().iterator(); while (fonts.hasNext()) { String font = fonts.next(); setDefaultFont(activity, font, "fonts/" + fontTable.get(font)); } } } public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) { final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName); replaceFont(staticTypefaceFieldName, regular); } protected static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) { try { final Field staticField = Typeface.class .getDeclaredField(staticTypefaceFieldName); staticField.setAccessible(true); staticField.set(null, newTypeface); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
chandilsachin/DietTracker
app/src/main/java/com/chandilsachin/diettracker/io/FontsOverride.java
Java
gpl-3.0
1,560
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { extract($_POST); extract($_GET); $pdo = conectar(); $query = selectPinEvento(); $stmt = $pdo->prepare($query); $stmt->bindParam(":id", $id); $stmt->bindParam(":pin", $pin); $stmt->execute(); if ($stmt->rowCount() == 1) { if ($a == 'ed') { $pdo = null; $stmt = null; header("Location: ./?p=ev&id=$id"); exit; } elseif ($a == 'ex') { $pdo = null; $stmt = null; header("Location: ./?p=exm&id=$id"); exit; } } else { $pdo = null; $stmt = null; header("Location: ./?p=agv&m=pi"); exit; } } ?>
hardrikk/sitvi
php/model/pinModalModel.php
PHP
gpl-3.0
772
# Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object): """can look up email addresses and realnames for contacts. .. note:: This is an abstract class that leaves :meth:`get_contacts` unspecified. See :class:`AbookAddressBook` and :class:`ExternalAddressbook` for implementations. """ __metaclass__ = abc.ABCMeta def __init__(self, ignorecase=True): self.reflags = re.IGNORECASE if ignorecase else 0 @abc.abstractmethod def get_contacts(self): # pragma no cover """list all contacts tuples in this abook as (name, email) tuples""" return [] def lookup(self, query=''): """looks up all contacts where name or address match query""" res = [] query = re.compile('.*%s.*' % query, self.reflags) for name, email in self.get_contacts(): if query.match(name) or query.match(email): res.append((name, email)) return res
geier/alot
alot/addressbook/__init__.py
Python
gpl-3.0
1,232
import numpy as np from scipy.signal import medfilt import manager.operations.method as method from manager.operations.methodsteps.confirmation import Confirmation from manager.exceptions import VoltPyNotAllowed class MedianFilter(method.ProcessingMethod): can_be_applied = True _steps = [ { 'class': Confirmation, 'title': 'Apply median filter', 'desc': 'Press Forward to apply Median Filter.', }, ] description = """ Median filter is smoothing algorithm similar to the Savitzky-Golay, however instead of fitting of the polynomial, the middle point of the window is moved to the value of median of the points in the window. The median filter is most usefull for removal of spikes from the signal (single point, large amplitude errors). """ @classmethod def __str__(cls): return "Median Filter" def apply(self, user, dataset): if self.model.completed is not True: raise VoltPyNotAllowed('Incomplete procedure.') self.__perform(dataset) def __perform(self, dataset): for cd in dataset.curves_data.all(): yvec = cd.yVector newyvec = medfilt(yvec) dataset.updateCurve(self.model, cd, newyvec) dataset.save() def finalize(self, user): self.__perform(self.model.dataset) self.model.step = None self.model.completed = True self.model.save() return True
efce/voltPy
manager/operations/methods/MedianFilter.py
Python
gpl-3.0
1,485
'use strict'; const { expect } = require('chai'); const kadence = require('..'); const network = require('./fixtures/node-generator'); const trust = require('../lib/plugin-trust'); const sinon = require('sinon'); const async = require('async'); describe('@module kadence/trust + @class UDPTransport', function() { let clock = null; let [node1, node2, node3, node4] = network(4, kadence.UDPTransport); before(function(done) { this.timeout(12000); clock = sinon.useFakeTimers(0); async.eachSeries([node1, node2, node3, node4], (node, next) => { node.listen(node.contact.port, next); }, done); }); after(function() { clock.restore(); process._getActiveHandles().forEach((h) => h.unref()); }) it('should allow the whitelisted contact', function(done) { node2.trust = node2.plugin(trust([ { identity: node1.identity, methods: ['PING'] } ], trust.MODE_WHITELIST)); node1.trust = node1.plugin(trust([ { identity: node2.identity, methods: ['PING'] } ], trust.MODE_WHITELIST)); node1.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], done); }); it('should prevent the blacklisted contact', function(done) { node3.trust = node3.plugin(trust([ { identity: node1.identity, methods: ['PING'] } ], trust.MODE_BLACKLIST)); node1.trust.addTrustPolicy({ identity: node3.identity, methods: ['*'] }) node1.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should allow the non-blacklisted contact', function(done) { node2.trust.addTrustPolicy({ identity: node3.identity.toString('hex'), methods: ['PING'] }) node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], done); }); it('should prevent the non-whitelisted contact', function(done) { node4.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should blacklist all nodes from using PING', function(done) { node3.trust.addTrustPolicy({ identity: '*', methods: ['PING'] }); node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); }); it('should refuse send to node with missing trust policy', function(done) { node1.trust.removeTrustPolicy(node2.identity); node1.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should allow if method is not blacklisted', function(done) { node2.trust.addTrustPolicy({ identity: node3.identity, methods: ['PING'] }); node3.trust.addTrustPolicy({ identity: node2.identity, methods: ['FIND_NODE'] }); node2.send('PING', [], [ node3.identity, node3.contact ], done); }); it('should reject if method is not whitelisted', function(done) { node4.trust = node4.plugin(trust([ { identity: node2.identity, methods: ['FIND_NODE'] } ], trust.MODE_WHITELIST)); node2.trust.addTrustPolicy({ identity: node4.identity, methods: ['PING'] }); node4.send('FIND_NODE', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); });
gordonwritescode/kad
test/plugin-trust.e2e.js
JavaScript
gpl-3.0
3,986
<?php session_start(); $blad = $_SESSION['blad'] ; ?> <!DOCTYPE html> <html lang="pl"> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <head> <title>Gra w słowa</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Najlepsza gra słowna w internecie"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="style/main.css"> <link rel="canonical" href="index.html"> <link rel="alternate" type="application/rss+xml" title="Gra w słowa" href="feed.xml" /> </head> <body> <header class="navbar navbar-default navbar-fixed-top" role="banner"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Pasek nawigacyjny</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="index.html" class="logo-container"> <img src="images/logo2.png" alt="Gra w słowa" height="40"> </a> </div> <nav id="navbar" class="collapse navbar-collapse" role="navigation"> <ul class="nav navbar-nav navbar-right"> <li> <a href="index.html">Strona główna</a> </li> <li> <a href="index.php">Logowanie</a> </li> </ul> </nav> </div> </header> <section class="content"> <section class="container"> <div class="row head-banner-text"> <h1 class="text-center col-md-12 col-xs-12"> Kontakt z administratorem:<br /> </h1> </div> <div class="row head-banner-buttons"> <div class="col-lg-offset-4 col-lg-4 col-xs-12"> <form action="wysylaniemsg.php" method="post"> <div class="input-group input-group-lg btn-block"> <input type="text" name="login" class="form-control" placeholder="Temat wiadomości" aria-describedby="basic-addon1"> </div> <br /> <div class="input-group"> <textarea class="form-control" rows="5" aria-describedby="basic-addon1" placeholder="Treść wiadomości" id="comment"></textarea> </div> <br /> <button type="submit" id="submit" class="btn btn-primary btn-lg btn-block">Wyślij wiadomość</button> </form> </div> </div> </section> </section> <footer class="container text-center small"> Copyright grawslowa.pl 2017 </footer> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </body> </html>
maghostmil/grawslowa.pl
kontakt.php
PHP
gpl-3.0
3,250
<?php /** * Définit le domaine des commentaires. * * @author ybaccala */ class Klee_Model_Domain_DescriptifCourt extends Klee_Model_Domain_Abstract implements Klee_Model_Domain_Interface { /* (non-PHPdoc) * @see Application_Model_Domains_Abstract::initValidators() */ public function initValidators($element) { $options['max']=1024; if (!$element instanceof Zend_Form_Element) { throw new Zend_Exception("$element n'est pas un Zend_Form_Element."); } $element->addValidator('StringLength',true,$options); } /* (non-PHPdoc) * @see Application_Model_Domains_LibelleLong::initOtherDecorators() */ protected function initOtherDecorators($element) { parent::initOtherDecorators($element); $element->setAttrib('maxlength', 1024); } }
Nyaoh/Mz
webapp/library/Klee/Model/Domain/DescriptifCourt.php
PHP
gpl-3.0
795
(function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(this.arguments, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments).rules); match = true; } catch (e) { throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; } } } if (match) { return rules; } else { throw { message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index }; } } } throw { message: this.selector.toCSS().trim() + " is undefined", index: this.index }; } }; tree.mixin.Definition = function (name, params, rules) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (p.name && !p.value) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, eval: function (env, args) { var frame = new(tree.Ruleset)(null, []), context; for (var i = 0, val; i < this.params.length; i++) { if (this.params[i].name) { if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); } else { throw { message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len; if (argsLength < this.required) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('less/tree'));
tfe/cloud9
support/connect/support/less/lib/less/tree/mixin.js
JavaScript
gpl-3.0
3,761
package me.killje.servercaster.core.converter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import me.killje.servercaster.core.ServerCaster; import mkremins.fanciful.FancyMessage; import org.bukkit.entity.Player; /** * * @author Patrick Beuks (killje) and Floris Huizinga (Flexo013) */ public class CodeConverter extends Converter { private static final Map<String, CodeAction> codes = new HashMap<>(); private final ArrayList<CodeAction> actionCode = new ArrayList<>(); private final ArrayList<CodeAction> emptyCodes = new ArrayList<>(); private boolean nextChar = false; private boolean inBracket = false; private final Collection<? extends Player> players; CodeConverter(FancyMessage fm, Collection<? extends Player> players) { super(fm); for (Map.Entry<String, CodeAction> entry : codes.entrySet()) { CodeAction codeAction = entry.getValue(); codeAction.setBuilders(fm, players); } this.players = players; } @Override boolean isEndChar(char c) { return c == ';'; } @Override Converter end() { nextChar = true; String savedString = getSavedString(); if (codes.containsKey(savedString.toLowerCase())) { CodeAction ca = codes.get(savedString.toLowerCase()); if (ca.hasArgumentsLeft()) { actionCode.add(ca); } else { emptyCodes.add(ca); } } else { ServerCaster.getInstance().getLogger().logp( Level.WARNING, this.getClass().getName(), "end()", "Unknown Action Code", new IllegalArgumentException("Code Action Unknown (" + savedString + ")")); } clearSavedString(); return this; } @Override Converter nextChar(char c) { if (fm == null) { throw new NullPointerException("FancyMessage not declared"); } if (inBracket) { if (actionCode.get(0).isEndChar(c)) { if (actionCode.get(0).isEnd(getSavedString())) { actionCode.remove(0); inBracket = false; } } addChar(c); return this; } if (nextChar) { if (c == '{') { if (actionCode.isEmpty()) { return new BracketConverter(fm, emptyCodes, players); } inBracket = true; return this; } else { nextChar = false; return this; } } else { return super.nextChar(c); } } public static void addCodeAction(CodeAction ca) { codes.put(ca.getCode(), ca); } public static void removeCodeAction(CodeAction ca) { codes.remove(ca.getCode()); } }
killje/ServerCasterOld
core/src/main/java/me/killje/servercaster/core/converter/CodeConverter.java
Java
gpl-3.0
2,978
""" Django settings for lwc project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7fm_f66p8e!p%o=sr%d&cue(%+bh@@j_y6*b3d@t^c5%i8)1)2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] #Share url SHARER_URL = "http://127.0.0.1:8000/?ref=" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'joins', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'lwc.middleware.ReferMiddleware', ] ROOT_URLCONF = 'lwc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'lwc.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static', 'static_dirs'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
Phexcom/product-launcher
lwc/settings/base.py
Python
gpl-3.0
3,530
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyGarden.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
pmandr/plant_carer
MyGarden/manage.py
Python
gpl-3.0
806
<?php //////////////////////////////////////////////////////////////////////////////// /// This file contains a few configuration variables that control /// how Moodle uses this theme. //////////////////////////////////////////////////////////////////////////////// $THEME->name = 'skonline_test_wo_SKOParent'; $THEME->sheets = array('base','skonline','browser','ImportedFromMoodle1_9','CoursesSitewide','skonline_test_wo_SKOParent'); /// This variable is an array containing the names of all the /// stylesheet files you want included in this theme, and in what order //////////////////////////////////////////////////////////////////////////////// $THEME->parents = array('base'); // TODO: new themes can not be based on standardold, instead use 'base' as the base /// This variable can be set to the name of a parent theme /// which you want to have included before the current theme. /// This can make it easy to make modifications to another /// theme without having to actually change the files /// If this variable is empty or false then a parent theme /// is not used. //////////////////////////////////////////////////////////////////////////////// $THEME->parents_exclude_sheets = array('base'=>array('styles_moz')); $THEME->resource_mp3player_colors = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&'. 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&'. 'font=Arial&fontColour=3333FF&buffer=10&waitForPlay=no&autoPlay=yes'; /// With this you can control the colours of the "big" MP3 player /// that is used for MP3 resources. $THEME->filter_mediaplugin_colors = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&'. 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&'. 'waitForPlay=yes'; /// ...And this controls the small embedded player $THEME->layouts = array( // Most pages - if we encounter an unknown or a missing page type, this one is used. 'base' => array( 'file' => 'general.php', 'regions' => array() ), 'standard' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'skonline' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), // Course page 'course' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), // Course page 'coursecategory' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'incourse' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'frontpage' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'admin' => array( 'file' => 'general.php', 'regions' => array('side-pre'), 'defaultregion' => 'side-pre' ), 'mydashboard' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'mypublic' => array( 'file' => 'general.php', 'regions' => array('side-pre', 'side-post'), 'defaultregion' => 'side-post' ), 'login' => array( 'file' => 'general.php', 'regions' => array() ), // Pages that appear in pop-up windows - no navigation, no blocks, no header. 'popup' => array( 'file' => 'general.php', 'regions' => array(), 'options' => array('nofooter'=>true, 'nonavbar'=>true, 'noblocks'=>true), ), // No blocks and minimal footer - used for legacy frame layouts only! 'frametop' => array( 'file' => 'general.php', 'regions' => array(), 'options' => array('nofooter', 'noblocks'=>true), ), // Embeded pages, like iframe embeded in moodleform 'embedded' => array( 'file' => 'general.php', 'regions' => array(), 'options' => array('nofooter'=>true, 'nonavbar'=>true, 'noblocks'=>true), ), // Used during upgrade and install, and for the 'This site is undergoing maintenance' message. // This must not have any blocks, and it is good idea if it does not have links to // other places - for example there should not be a home link in the footer... 'maintenance' => array( 'file' => 'general.php', 'regions' => array(), 'options' => array('nofooter'=>true, 'nonavbar'=>true, 'noblocks'=>true), ), // Should display the content and basic headers only. 'print' => array( 'file' => 'general.php', 'regions' => array(), 'options' => array('nofooter'=>true, 'nonavbar'=>false, 'noblocks'=>true), ), 'report' => array( 'file' => 'report.php', 'regions' => array('side-pre'), 'defaultregion' => 'side-pre' ), ); $THEME->rendererfactory = 'theme_overridden_renderer_factory'; $THEME->enable_dock = true; //$THEME->javascripts_footer = array('navigation'); $THEME->editor_sheets = array('editor'); $THEME->javascripts = array('skonline'); //$THEME->javascripts = array('skonline' => array('skonline'));
orvsd/moodle22
theme/skonline_test_wo_SKOParent/config.php
PHP
gpl-3.0
5,583
from osweb.projects.ManageProject import ManageProject from osweb.projects.projects_data import ProjectsData
openshine/osweb
osweb/projects/__init__.py
Python
gpl-3.0
108
/* Copyright (C) 2016, 2017 PISM Authors * * This file is part of PISM. * * PISM is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * PISM 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 PISM; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Initialization.hh" #include "pism/util/pism_utilities.hh" #include "pism/util/io/io_helpers.hh" #include "pism/util/io/PIO.hh" #include "pism/util/pism_options.hh" namespace pism { namespace ocean { InitializationHelper::InitializationHelper(IceGrid::ConstPtr g, OceanModel* in) : OceanModifier(g, in), m_sea_level_metadata("effective_sea_level_elevation", m_config->get_string("time.dimension_name"), m_sys) { m_melange_back_pressure_fraction.create(m_grid, "effective_melange_back_pressure_fraction", WITHOUT_GHOSTS); m_melange_back_pressure_fraction.set_attrs("model_state", "effective melange back pressure fraction," " as seen by the ice dynamics code (for re-starting)", "1", ""); m_shelf_base_temperature.create(m_grid, "effective_shelf_base_temperature", WITHOUT_GHOSTS); m_shelf_base_temperature.set_attrs("model_state", "effective shelf base temperature," " as seen by the ice dynamics code (for re-starting)", "Kelvin", ""); m_shelf_base_mass_flux.create(m_grid, "effective_shelf_base_mass_flux", WITHOUT_GHOSTS); m_shelf_base_mass_flux.set_attrs("model_state", "effective shelf base mass flux" " (positive flux is loss from ice shelf)," " as seen by the ice dynamics code (for re-starting)", "kg m-2 s-1", ""); m_shelf_base_mass_flux.metadata().set_string("glaciological_units", "kg m-2 year-1"); m_sea_level_elevation = 0.0; m_sea_level_metadata.set_string("pism_intent", "model_state"); m_sea_level_metadata.set_string("units", "meters"); m_sea_level_metadata.set_string("long_name", "effective sea level elevation, " "as seen by the ice dynamics code (for re-starting)"); } void InitializationHelper::update_impl(double t, double dt) { m_input_model->update(t, dt); m_input_model->melange_back_pressure_fraction(m_melange_back_pressure_fraction); m_input_model->shelf_base_mass_flux(m_shelf_base_mass_flux); m_input_model->shelf_base_temperature(m_shelf_base_temperature); m_sea_level_elevation = m_input_model->sea_level_elevation(); } void InitializationHelper::init_impl() { m_input_model->init(); InputOptions opts = process_input_options(m_grid->com); if (opts.type == INIT_RESTART) { m_log->message(2, "* Reading effective ocean model outputs from '%s' for re-starting...\n", opts.filename.c_str()); PIO file(m_grid->com, "guess_mode", opts.filename, PISM_READONLY); const unsigned int time_length = file.inq_nrecords(); const unsigned int last_record = time_length > 0 ? time_length - 1 : 0; m_melange_back_pressure_fraction.read(file, last_record); m_shelf_base_mass_flux.read(file, last_record); m_shelf_base_temperature.read(file, last_record); { std::vector<double> data; file.get_1d_var(m_sea_level_metadata.get_name(), last_record, 1, // start, count data); m_sea_level_elevation = data[0]; } file.close(); } else { m_log->message(2, "* Performing a 'fake' ocean model time-step for bootstrapping...\n"); init_step(*this, *m_grid->ctx()->time()); } // Support regridding. This is needed to ensure that initialization using "-i" is equivalent to // "-i ... -bootstrap -regrid_file ..." { regrid("ocean model initialization helper", m_melange_back_pressure_fraction, REGRID_WITHOUT_REGRID_VARS); regrid("ocean model initialization helper", m_shelf_base_mass_flux, REGRID_WITHOUT_REGRID_VARS); regrid("ocean model initialization helper", m_shelf_base_temperature, REGRID_WITHOUT_REGRID_VARS); } // FIXME: fake "regridding" of sea level } void InitializationHelper::melange_back_pressure_fraction_impl(IceModelVec2S &result) const { result.copy_from(m_melange_back_pressure_fraction); } void InitializationHelper::sea_level_elevation_impl(double &result) const { result = m_sea_level_elevation; } void InitializationHelper::shelf_base_temperature_impl(IceModelVec2S &result) const { result.copy_from(m_shelf_base_temperature); } void InitializationHelper::shelf_base_mass_flux_impl(IceModelVec2S &result) const { result.copy_from(m_shelf_base_mass_flux); } void InitializationHelper::define_model_state_impl(const PIO &output) const { m_melange_back_pressure_fraction.define(output); m_shelf_base_mass_flux.define(output); m_shelf_base_temperature.define(output); m_melange_back_pressure_fraction.define(output); io::define_timeseries(m_sea_level_metadata, output, PISM_DOUBLE); m_input_model->define_model_state(output); } void InitializationHelper::write_model_state_impl(const PIO &output) const { m_melange_back_pressure_fraction.write(output); m_shelf_base_mass_flux.write(output); m_shelf_base_temperature.write(output); m_melange_back_pressure_fraction.write(output); const unsigned int time_length = output.inq_dimlen(m_sea_level_metadata.get_dimension_name()), t_start = time_length > 0 ? time_length - 1 : 0; io::write_timeseries(output, m_sea_level_metadata, t_start, m_sea_level_elevation, PISM_DOUBLE); m_input_model->write_model_state(output); } } // end of namespace ocean } // end of namespace pism
talbrecht/pism_pik
src/coupler/ocean/Initialization.cc
C++
gpl-3.0
6,460
/* * This file is part of Log4Jdbc. * * Log4Jdbc is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>. * */ package fr.ms.log4jdbc.lang.reflect; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import fr.ms.log4jdbc.lang.delegate.DefaultStringMakerFactory; import fr.ms.log4jdbc.lang.delegate.DefaultSyncLongFactory; import fr.ms.log4jdbc.lang.delegate.StringMakerFactory; import fr.ms.log4jdbc.lang.delegate.SyncLongFactory; import fr.ms.log4jdbc.lang.stringmaker.impl.StringMaker; import fr.ms.log4jdbc.lang.sync.impl.SyncLong; import fr.ms.log4jdbc.util.logging.Logger; import fr.ms.log4jdbc.util.logging.LoggerManager; /** * * @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a> * * * @author Marco Semiao * */ public class TraceTimeInvocationHandler implements InvocationHandler { public final static Logger LOG = LoggerManager.getLogger(TraceTimeInvocationHandler.class); private final static StringMakerFactory stringFactory = DefaultStringMakerFactory.getInstance(); private final static SyncLongFactory syncLongFactory = DefaultSyncLongFactory.getInstance(); private final InvocationHandler invocationHandler; private static long maxTime; private static String maxMethodName; private static SyncLong averageTime = syncLongFactory.newLong(); private static SyncLong quotient = syncLongFactory.newLong(); public TraceTimeInvocationHandler(final InvocationHandler invocationHandler) { this.invocationHandler = invocationHandler; } public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final long start = System.currentTimeMillis(); final TimeInvocation invokeTime = (TimeInvocation) invocationHandler.invoke(proxy, method, args); final long end = System.currentTimeMillis(); final long time = (end - start) - invokeTime.getExecTime(); final String methodName = getMethodCall(method.getDeclaringClass().getName() + "." + method.getName(), args); if (time > maxTime) { maxTime = time; maxMethodName = methodName; } averageTime.addAndGet(time); final StringMaker sb = stringFactory.newString(); sb.append("Time Process : "); sb.append(time); sb.append(" ms - Average Time : "); sb.append(averageTime.get() / quotient.incrementAndGet()); sb.append(" ms - Method Name : "); sb.append(methodName); sb.append(" - Max Time Process : "); sb.append(maxTime); sb.append(" ms - Max Method Name : "); sb.append(maxMethodName); LOG.debug(sb.toString()); return invokeTime.getWrapInvocation().getInvoke(); } public static String getMethodCall(final String methodName, final Object[] args) { final StringMaker sb = stringFactory.newString(); sb.append(methodName); sb.append("("); if (args != null) { for (int i = 0; i < args.length; i++) { final Object arg = args[i]; if (arg != null) { sb.append(arg.getClass()); if (i < args.length - 1) { sb.append(","); } } } } sb.append(");"); return sb.toString(); } }
marcosemiao/log4jdbc
core/log4jdbc-impl/src/main/java/fr/ms/log4jdbc/lang/reflect/TraceTimeInvocationHandler.java
Java
gpl-3.0
3,606
/* * This file is part of the L2J Mobius project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q00700_CursedLife; import java.util.HashMap; import java.util.Map; import com.l2jmobius.gameserver.enums.QuestSound; import com.l2jmobius.gameserver.model.actor.L2Npc; import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance; import com.l2jmobius.gameserver.model.quest.Quest; import com.l2jmobius.gameserver.model.quest.QuestState; import com.l2jmobius.gameserver.model.quest.State; import quests.Q10273_GoodDayToFly.Q10273_GoodDayToFly; /** * Cursed Life (700) * @author xban1x */ public class Q00700_CursedLife extends Quest { // NPC private static final int ORBYU = 32560; // Monsters private static final int ROK = 25624; private static final Map<Integer, Integer[]> MONSTERS = new HashMap<>(); //@formatter:off static { MONSTERS.put(22602, new Integer[] { 15, 139, 965}); // Mutant Bird lvl 1 MONSTERS.put(22603, new Integer[] { 15, 143, 999}); // Mutant Bird lvl 2 MONSTERS.put(25627, new Integer[] { 14, 125, 993}); // Mutant Bird lvl 3 MONSTERS.put(22604, new Integer[] { 5, 94, 994}); // Dra Hawk lvl 1 MONSTERS.put(22605, new Integer[] { 5, 99, 993}); // Dra Hawk lvl 2 MONSTERS.put(25628, new Integer[] { 3, 73, 991}); // Dra Hawk lvl 3 } //@formatter:on // Items private static final int SWALLOWED_BONES = 13874; private static final int SWALLOWED_STERNUM = 13873; private static final int SWALLOWED_SKULL = 13872; // Misc private static final int MIN_LVL = 75; private static final int SWALLOWED_BONES_ADENA = 500; private static final int SWALLOWED_STERNUM_ADENA = 5000; private static final int SWALLOWED_SKULL_ADENA = 50000; private static final int BONUS = 16670; public Q00700_CursedLife() { super(700, Q00700_CursedLife.class.getSimpleName(), "Cursed Life"); addStartNpc(ORBYU); addTalkId(ORBYU); addKillId(ROK); addKillId(MONSTERS.keySet()); registerQuestItems(SWALLOWED_BONES, SWALLOWED_STERNUM, SWALLOWED_SKULL); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { QuestState st = getQuestState(player, false); String htmltext = null; if (st != null) { switch (event) { case "32560-02.htm": { st = player.getQuestState(Q10273_GoodDayToFly.class.getSimpleName()); htmltext = ((player.getLevel() < MIN_LVL) || (st == null) || (!st.isCompleted())) ? "32560-03.htm" : event; break; } case "32560-04.htm": case "32560-09.html": { htmltext = event; break; } case "32560-05.htm": { st.startQuest(); htmltext = event; break; } case "32560-10.html": { st.exitQuest(true, true); htmltext = event; break; } } } return htmltext; } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, true); String htmltext = getNoQuestMsg(player); if (st != null) { switch (st.getState()) { case State.CREATED: { htmltext = "32560-01.htm"; break; } case State.STARTED: { final long bones = st.getQuestItemsCount(SWALLOWED_BONES); final long ribs = st.getQuestItemsCount(SWALLOWED_STERNUM); final long skulls = st.getQuestItemsCount(SWALLOWED_SKULL); final long sum = bones + ribs + skulls; if (sum > 0) { st.giveAdena(((bones * SWALLOWED_BONES_ADENA) + (ribs * SWALLOWED_STERNUM_ADENA) + (skulls * SWALLOWED_SKULL_ADENA) + (sum >= 10 ? BONUS : 0)), true); takeItems(player, -1, SWALLOWED_BONES, SWALLOWED_STERNUM, SWALLOWED_SKULL); htmltext = sum < 10 ? "32560-07.html" : "32560-08.html"; } else { htmltext = "32560-06.html"; } break; } } } return htmltext; } @Override public String onKill(L2Npc npc, L2PcInstance player, boolean isSummon) { final QuestState st = getQuestState(player, false); if (st != null) { if (npc.getId() == ROK) { int amount = 0, chance = getRandom(1000); if (chance < 700) { amount = 1; } else if (chance < 885) { amount = 2; } else if (chance < 949) { amount = 3; } else if (chance < 966) { amount = getRandom(5) + 4; } else if (chance < 985) { amount = getRandom(9) + 4; } else if (chance < 993) { amount = getRandom(7) + 13; } else if (chance < 997) { amount = getRandom(15) + 9; } else if (chance < 999) { amount = getRandom(23) + 53; } else { amount = getRandom(49) + 76; } st.giveItems(SWALLOWED_BONES, amount); chance = getRandom(1000); if (chance < 520) { amount = 1; } else if (chance < 771) { amount = 2; } else if (chance < 836) { amount = 3; } else if (chance < 985) { amount = getRandom(2) + 4; } else if (chance < 995) { amount = getRandom(4) + 5; } else { amount = getRandom(8) + 6; } st.giveItems(SWALLOWED_STERNUM, amount); chance = getRandom(1000); if (chance < 185) { amount = getRandom(2) + 1; } else if (chance < 370) { amount = getRandom(6) + 2; } else if (chance < 570) { amount = getRandom(6) + 7; } else if (chance < 850) { amount = getRandom(6) + 12; } else { amount = getRandom(6) + 17; } st.giveItems(SWALLOWED_SKULL, amount); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else { final Integer[] chances = MONSTERS.get(npc.getId()); final int chance = getRandom(1000); if (chance < chances[0]) { st.giveItems(SWALLOWED_BONES, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else if (chance < chances[1]) { st.giveItems(SWALLOWED_STERNUM, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else if (chance < chances[2]) { st.giveItems(SWALLOWED_SKULL, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } } } return super.onKill(npc, player, isSummon); } }
karolusw/l2j
game/data/scripts/quests/Q00700_CursedLife/Q00700_CursedLife.java
Java
gpl-3.0
6,753
package com.libertacao.libertacao.manager; import android.support.annotation.Nullable; import com.libertacao.libertacao.persistence.UserPreferences; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; public class LoginManager { private static final LoginManager ourInstance = new LoginManager(); public static LoginManager getInstance() { return ourInstance; } private LoginManager() { } public boolean isLoggedIn(){ return ParseUser.getCurrentUser() != null; } public boolean isSuperAdmin() { if(isLoggedIn()) { int type = ParseUser.getCurrentUser().getInt("type"); if(type == 666) { return true; } } return false; } public boolean isAdmin() { if(isLoggedIn()) { int type = ParseUser.getCurrentUser().getInt("type"); if(type % 66 == 6) { return true; } } return false; } public void logout() { UserPreferences.clearSharedPreferences(); UserManager.getInstance().setCurrentLatLng(null); } @Nullable public String getUsername() { if(isLoggedIn()) { ParseUser currentUser = ParseUser.getCurrentUser(); if(ParseFacebookUtils.isLinked(currentUser)) { return currentUser.getString("name"); } else { return currentUser.getUsername(); } } else { return null; } } }
LibertACAO/libertacao-android
app/src/main/java/com/libertacao/libertacao/manager/LoginManager.java
Java
gpl-3.0
1,546
<?php /** * A two factor authentication module that protects both the admin and customer logins * Copyright (C) 2017 Ross Mitchell * * This file is part of Rossmitchell/Twofactor. * * Rossmitchell/Twofactor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Rossmitchell\Twofactor\Controller\Customerlogin; use Magento\Customer\Api\Data\CustomerInterface; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\Controller\Result\Redirect; use Rossmitchell\Twofactor\Model\Config\Customer as CustomerAdmin; use Rossmitchell\Twofactor\Model\Customer\Attribute\IsUsingTwoFactor; use Rossmitchell\Twofactor\Model\Customer\Customer; use Rossmitchell\Twofactor\Model\Urls\Fetcher; abstract class AbstractController extends Action { /** * @var CustomerAdmin */ private $customerAdmin; /** * @var Customer */ private $customerGetter; /** * @var Redirect */ private $redirectAction; /** * @var CustomerInterface|false */ private $customerModel; /** * @var IsUsingTwoFactor */ private $isUsingTwoFactor; /** * @var Fetcher */ private $fetcher; /** * AbstractController constructor. * * @param Context $context * @param CustomerAdmin $customerAdmin * @param Customer $customerGetter * @param Fetcher $fetcher * @param IsUsingTwoFactor $isUsingTwoFactor */ public function __construct( Context $context, CustomerAdmin $customerAdmin, Customer $customerGetter, Fetcher $fetcher, IsUsingTwoFactor $isUsingTwoFactor ) { parent::__construct($context); $this->customerAdmin = $customerAdmin; $this->customerGetter = $customerGetter; $this->isUsingTwoFactor = $isUsingTwoFactor; $this->fetcher = $fetcher; } /** * The controllers should only be run if the following conditions are met: * * - Two Factor Authentication is enabled for the store * - There is a customer * - That customer is using Two Factor Authentication * * If all of these conditions are met, then the method will return true, otherwise a redirect will be created and * the method will return false * * @return bool */ public function shouldActionBeRun() { if ($this->isEnabled() === false) { $this->redirectAction = $this->handleDisabled(); return false; } if ($this->getCustomer() === false) { $this->redirectAction = $this->handleMissingCustomer(); return false; } if ($this->isCustomerUsingTwoFactor() === false) { $this->redirectAction = $this->handleNonOptInCustomer(); return false; } return true; } /** * Returns the redirect action generated by the shouldActionBeRun method * * @return Redirect */ public function getRedirectAction() { return $this->redirectAction; } /** * Used to create a redirect action to a specific page * * @param string $path - The path the the customer should be redirected to * * @return Redirect */ public function redirect($path) { $redirect = $this->resultRedirectFactory->create(); $redirect->setPath($path); return $redirect; } /** * Used to fetch the customer from the session * * @return CustomerInterface|false */ public function getCustomer() { if (null === $this->customerModel) { $this->customerModel = $this->customerGetter->getCustomer(); } return $this->customerModel; } /** * @return Fetcher */ public function getUrlFetcher() { return $this->fetcher; } /** * A wrapper method around the Customer::isTwoFactorEnabled method * * @return bool */ private function isEnabled() { return ($this->customerAdmin->isTwoFactorEnabled() === true); } /** * A wrapper method around the IsUsingTwoFactor::getValue method * * @return bool */ private function isCustomerUsingTwoFactor() { $customer = $this->getCustomer(); return $this->isUsingTwoFactor->getValue($customer); } /** * If Two Factor Authentication is disabled redirect the customer to the home page * * @return Redirect */ private function handleDisabled() { return $this->redirect('/'); } /** * If there isn't a customer in the session then redirect the user to the login page * * @return Redirect */ private function handleMissingCustomer() { $loginUrl = $this->getUrlFetcher()->getCustomerLogInUrl(); return $this->redirect($loginUrl); } /** * Redirect customers that are not using Two Factor Authentication to the home page * * @return Redirect */ private function handleNonOptInCustomer() { return $this->redirect('/'); } }
rossmitchell/module-twofactor
Controller/Customerlogin/AbstractController.php
PHP
gpl-3.0
5,795
/* * Copyright (C) 2013 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Michael Terry <michael.terry@canonical.com> */ #include "Greeter.h" #include "GreeterPrivate.h" #include <QFuture> #include <QFutureInterface> #include <QFutureWatcher> #include <QQueue> #include <QtConcurrent> #include <QVector> #include <security/pam_appl.h> namespace QLightDM { class GreeterImpl : public QObject { Q_OBJECT struct AppData { GreeterImpl *impl; pam_handle *handle; }; typedef QFutureInterface<QString> ResponseFuture; public: explicit GreeterImpl(Greeter *parent, GreeterPrivate *greeterPrivate) : QObject(parent), greeter(parent), greeterPrivate(greeterPrivate), pamHandle(nullptr) { qRegisterMetaType<QLightDM::GreeterImpl::ResponseFuture>("QLightDM::GreeterImpl::ResponseFuture"); connect(&futureWatcher, &QFutureWatcher<int>::finished, this, &GreeterImpl::finishPam); connect(this, SIGNAL(showMessage(pam_handle *, QString, QLightDM::Greeter::MessageType)), this, SLOT(handleMessage(pam_handle *, QString, QLightDM::Greeter::MessageType))); // This next connect is how we pass ResponseFutures between threads connect(this, SIGNAL(showPrompt(pam_handle *, QString, QLightDM::Greeter::PromptType, QLightDM::GreeterImpl::ResponseFuture)), this, SLOT(handlePrompt(pam_handle *, QString, QLightDM::Greeter::PromptType, QLightDM::GreeterImpl::ResponseFuture)), Qt::BlockingQueuedConnection); } ~GreeterImpl() { cancelPam(); } void start(QString username) { // Clear out any existing PAM interactions first cancelPam(); if (pamHandle != nullptr) { // While we were cancelling pam above, we processed Qt events. // Which may have allowed someone to call start() on us again. // In which case, we'll bail on our current start() call. // This isn't racy because it's all in the same thread. return; } AppData *appData = new AppData(); appData->impl = this; // Now actually start a new conversation with PAM pam_conv conversation; conversation.conv = converseWithPam; conversation.appdata_ptr = static_cast<void*>(appData); if (pam_start("lightdm", username.toUtf8(), &conversation, &pamHandle) == PAM_SUCCESS) { appData->handle = pamHandle; futureWatcher.setFuture(QtConcurrent::mapped(QList<pam_handle*>() << pamHandle, authenticateWithPam)); } else { delete appData; greeterPrivate->authenticated = false; Q_EMIT greeter->showMessage(QStringLiteral("Internal error: could not start PAM authentication"), QLightDM::Greeter::MessageTypeError); Q_EMIT greeter->authenticationComplete(); } } static int authenticateWithPam(pam_handle* const& pamHandle) { int pamStatus = pam_authenticate(pamHandle, 0); if (pamStatus == PAM_SUCCESS) { pamStatus = pam_acct_mgmt(pamHandle, 0); } if (pamStatus == PAM_NEW_AUTHTOK_REQD) { pamStatus = pam_chauthtok(pamHandle, PAM_CHANGE_EXPIRED_AUTHTOK); } if (pamStatus == PAM_SUCCESS) { pam_setcred(pamHandle, PAM_REINITIALIZE_CRED); } return pamStatus; } static int converseWithPam(int num_msg, const pam_message** msg, pam_response** resp, void* appdata_ptr) { if (num_msg <= 0) return PAM_CONV_ERR; auto* tmp_response = static_cast<pam_response*>(calloc(num_msg, sizeof(pam_response))); if (!tmp_response) return PAM_CONV_ERR; AppData *appData = static_cast<AppData*>(appdata_ptr); GreeterImpl *impl = appData->impl; pam_handle *handle = appData->handle; int count; QVector<ResponseFuture> responses; for (count = 0; count < num_msg; ++count) { switch (msg[count]->msg_style) { case PAM_PROMPT_ECHO_ON: { QString message(msg[count]->msg); responses.append(ResponseFuture()); responses.last().reportStarted(); Q_EMIT impl->showPrompt(handle, message, Greeter::PromptTypeQuestion, responses.last()); break; } case PAM_PROMPT_ECHO_OFF: { QString message(msg[count]->msg); responses.append(ResponseFuture()); responses.last().reportStarted(); Q_EMIT impl->showPrompt(handle, message, Greeter::PromptTypeSecret, responses.last()); break; } case PAM_TEXT_INFO: { QString message(msg[count]->msg); Q_EMIT impl->showMessage(handle, message, Greeter::MessageTypeInfo); break; } default: { QString message(msg[count]->msg); Q_EMIT impl->showMessage(handle, message, Greeter::MessageTypeError); break; } } } int i = 0; bool raise_error = false; for (auto &response : responses) { pam_response* resp_item = &tmp_response[i++]; resp_item->resp_retcode = 0; resp_item->resp = strdup(response.future().result().toUtf8()); if (!resp_item->resp) { raise_error = true; break; } } delete appData; if (raise_error) { for (int i = 0; i < count; ++i) free(tmp_response[i].resp); free(tmp_response); return PAM_CONV_ERR; } else { *resp = tmp_response; return PAM_SUCCESS; } } public Q_SLOTS: bool respond(QString response) { if (!futures.isEmpty()) { futures.dequeue().reportFinished(&response); return true; } else { return false; } } void cancelPam() { if (pamHandle != nullptr) { QFuture<int> pamFuture = futureWatcher.future(); pam_handle *handle = pamHandle; pamHandle = nullptr; // to disable normal finishPam() handling pamFuture.cancel(); // Note the empty loop, we just want to clear the futures queue. // Any further prompts from the pam thread will be immediately // responded to/dismissed in handlePrompt(). while (respond(QString())); // Now let signal/slot handling happen so the thread can finish while (!pamFuture.isFinished()) { QCoreApplication::processEvents(); } pam_end(handle, PAM_CONV_ERR); } } Q_SIGNALS: void showMessage(pam_handle *handle, QString text, QLightDM::Greeter::MessageType type); void showPrompt(pam_handle *handle, QString text, QLightDM::Greeter::PromptType type, QLightDM::GreeterImpl::ResponseFuture response); private Q_SLOTS: void finishPam() { if (pamHandle == nullptr) { return; } int pamStatus = futureWatcher.result(); pam_end(pamHandle, pamStatus); pamHandle = nullptr; greeterPrivate->authenticated = (pamStatus == PAM_SUCCESS); Q_EMIT greeter->authenticationComplete(); } void handleMessage(pam_handle *handle, QString text, QLightDM::Greeter::MessageType type) { if (handle != pamHandle) return; Q_EMIT greeter->showMessage(text, type); } void handlePrompt(pam_handle *handle, QString text, QLightDM::Greeter::PromptType type, QLightDM::GreeterImpl::ResponseFuture future) { if (handle != pamHandle) { future.reportResult(QString()); future.reportFinished(); return; } futures.enqueue(future); Q_EMIT greeter->showPrompt(text, type); } private: Greeter *greeter; GreeterPrivate *greeterPrivate; pam_handle* pamHandle; QFutureWatcher<int> futureWatcher; QQueue<ResponseFuture> futures; }; GreeterPrivate::GreeterPrivate(Greeter* parent) : authenticated(false), authenticationUser(), m_impl(new GreeterImpl(parent, this)), q_ptr(parent) { } GreeterPrivate::~GreeterPrivate() { delete m_impl; } void GreeterPrivate::handleAuthenticate() { m_impl->start(authenticationUser); } void GreeterPrivate::handleRespond(const QString &response) { m_impl->respond(response); } void GreeterPrivate::cancelAuthentication() { m_impl->cancelPam(); } } #include "GreeterPrivate.moc"
yunit-io/yunit
plugins/LightDM/IntegratedLightDM/liblightdm/GreeterPrivate.cpp
C++
gpl-3.0
9,466
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; using Renci.SshNet; namespace Luice { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string GetHost() { string host = hostTxt.Text; return host; } public string GetPort() { return portTxt.Text; } public string GetUser() { string user = uidTxt.Text; return user; } public string GetPsw() { string psw = passwordTxt.Text; return psw; } public string GetAuth() { string auth = authTxt.Text; return auth; } public string GetChar() { string characters = charTxt.Text; return characters; } public string GetWorld() { string world = worldTxt.Text; return world; } bool sshconn = false; private void connBtn_Click(object sender, EventArgs e) { if (checkBox1.Checked) { sshconn = true; try { using (var client = new SshClient(hostTxt.Text, uidTxt.Text, passwordTxt.Text)) { client.Connect(); client.Disconnect(); MessageBox.Show("logged in!"); } LuiceEditor editor = new LuiceEditor(this); editor.Show(); } catch { MessageBox.Show("error: check again the data that you inserted and retry."); } } else { sshconn = false; string connection1 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + authTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";"; string connection2 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + charTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";"; string connection3 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + worldTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";"; MySqlConnection conn1 = new MySqlConnection(connection1); MySqlConnection conn2 = new MySqlConnection(connection2); MySqlConnection conn3 = new MySqlConnection(connection3); try { //this is needed only to check if inserted data is correct conn1.Open(); conn2.Open(); conn3.Open(); //closing test connections conn1.Close(); conn2.Close(); conn3.Close(); MessageBox.Show("logged in!"); //passing method from form1 to LuiceEditor Form LuiceEditor editor = new LuiceEditor(this); editor.Show(); } catch { MessageBox.Show("error: check again the data that you inserted and retry."); } } } public bool GetSsh() { return sshconn; } } }
gegge6265/Luice
Luice/Form1.cs
C#
gpl-3.0
3,744
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); create_tray_icon(); state = STATE_STOP; time = 0; connect(&timer, SIGNAL(timeout()), this, SLOT(timer_timeout())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_btnStartStop_clicked() { switch (state) { case STATE_STOP: state = STATE_WORK; ui->btnStartStop->setText("Stop"); time = ui->spnWork->value() + 1; timer.start(1000); ui->lcdNumber->setProperty("bg", true); break; case STATE_WORK: case STATE_RELAX: state = STATE_STOP; ui->btnStartStop->setText("Start"); timer.stop(); ui->lcdNumber->setProperty("bg", false); ui->lcdNumber->setStyleSheet(""); ui->lcdNumber->display(0); break; } } void MainWindow::timer_timeout() { time--; ui->lcdNumber->display(time); if(state == STATE_WORK) ui->lcdNumber->setStyleSheet("*[bg=\"true\"] { color: black; background-color: green }"); if(state == STATE_RELAX) ui->lcdNumber->setStyleSheet("*[bg=\"true\"] { color: black; background-color: red }"); if(time == 0 && state == STATE_WORK) { state = STATE_RELAX; qApp->beep(); time = ui->spnRelax->value() + 1; } if(time == 0 && state == STATE_RELAX) { state = STATE_WORK; qApp->beep(); time = ui->spnWork->value() + 1; } } void MainWindow::create_tray_icon() { m_tray_icon = new QSystemTrayIcon(QIcon(":icon/img/icon.png"), this); connect(m_tray_icon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onTrayClick(QSystemTrayIcon::ActivationReason))); QAction *show_action = new QAction("Show", m_tray_icon); connect(show_action, SIGNAL(triggered()), this, SLOT(show())); QAction *hide_action = new QAction("Hide", m_tray_icon); connect(hide_action, SIGNAL(triggered()), this, SLOT(hide())); QAction *quit_action = new QAction("Exit", m_tray_icon); connect(quit_action, SIGNAL(triggered()), qApp, SLOT(quit())); QMenu *tray_icon_menu = new QMenu; tray_icon_menu->addAction(show_action); tray_icon_menu->addAction(hide_action); tray_icon_menu->addSeparator(); tray_icon_menu->addAction(quit_action); tray_icon_menu->setDefaultAction(show_action); m_tray_icon->setContextMenu(tray_icon_menu); m_tray_icon->show(); } void MainWindow::onTrayClick(QSystemTrayIcon::ActivationReason ar) { if(ar == QSystemTrayIcon::DoubleClick || ar == QSystemTrayIcon::Trigger) { this->show(); this->raise(); this->activateWindow(); } }
fffaraz/CloseYourEyes
src/ui/mainwindow.cpp
C++
gpl-3.0
2,756
// Copyright (C) 2006,2007,2008,2009, George Hobbs, Russell Edwards /* * This file is part of TEMPO2. * * TEMPO2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * TEMPO2 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 TEMPO2. If not, see <http://www.gnu.org/licenses/>. */ /* * If you use TEMPO2 then please acknowledge it by citing * Hobbs, Edwards & Manchester (2006) MNRAS, Vol 369, Issue 2, * pp. 655-672 (bibtex: 2006MNRAS.369..655H) * or Edwards, Hobbs & Manchester (2006) MNRAS, VOl 372, Issue 4, * pp. 1549-1574 (bibtex: 2006MNRAS.372.1549E) when discussing the * timing model. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include "tempo2.h" #include "TKspectrum.h" #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_linalg.h> using namespace std; void help() /* Display help */ { } extern "C" int graphicalInterface(int argc,char *argv[],pulsar *psr,int *npsr) { char parFile[MAX_PSR][MAX_FILELEN]; char timFile[MAX_PSR][MAX_FILELEN]; char covarFuncFile[128]; int i, j; double globalParameter; const char *CVS_verNum = "$Revision: 1.1 $"; FILE *fout; strcpy(covarFuncFile,"NULL"); if (displayCVSversion == 1) CVSdisplayVersion((char *)"findCW.C",(char *)"plugin",CVS_verNum); *npsr = 0; printf("Graphical Interface: findCW\n"); printf("Author: X. Zhu, G. Hobbs\n"); printf("CVS Version: $Revision: 1.1 $\n"); printf(" --- type 'h' for help information\n"); /* Obtain all parameters from the command line */ for (i=2;i<argc;i++) { if (strcmp(argv[i],"-f")==0) { strcpy(parFile[*npsr],argv[++i]); strcpy(timFile[*npsr],argv[++i]); (*npsr)++; } else if (strcmp(argv[i],"-dcf")==0) strcpy(covarFuncFile,argv[++i]); } readParfile(psr,parFile,timFile,*npsr); /* Load the parameters */ readTimfile(psr,timFile,*npsr); /* Load the arrival times */ preProcess(psr,*npsr,argc,argv); for (i=0;i<2;i++) /* Do two iterations for pre- and post-fit residuals*/ // i=0; { logdbg("Calling formBatsAll"); formBatsAll(psr,*npsr); /* Form the barycentric arrival times */ logdbg("Calling formResiduals"); formResiduals(psr,*npsr,1); /* Form the residuals */ logdbg("Calling doFit"); if (i==0) doFitAll(psr,*npsr,covarFuncFile); /* Do the fitting */ else textOutput(psr,*npsr,globalParameter,0,0,0,(char *)""); /* Display the output */ } // Print A+ and Ax into a file fout = fopen("aplus_across.dat","w"); for (i=0;i<psr[0].quad_ifuncN_p;i++) { fprintf(fout,"%.2lf %g %g %g %g\n",psr[0].quad_ifuncT_p[i],psr[0].quad_ifuncV_p[i],psr[0].quad_ifuncE_p[i],psr[0].quad_ifuncV_c[i],psr[0].quad_ifuncE_c[i]); } fclose(fout); // return 0; // Calculate the Detection Statistics as a function of Fourier frequencies { double freq[1024]; double DS[1024]; double dt, Tspan, fmin, fmax; int nSpec; /* number of independent freq channels */ int nSpecOS4; /* number of freq channels with an OverSampling factor of 4 */ const int lp = psr[0].quad_ifuncN_p; /* length of A+ or Ax */ const int lpc = 2*psr[0].quad_ifuncN_p; /* length of the stacked data A+,x assuming A+&Ax have the same length*/ const int n_cst = 18; /* number of constraints set on A+&Ax */ const int mlen = lpc-n_cst; /* rank of the noise covariance matrix */ // Assuming that the ifuncs are regularly sampled // dt = psr[0].quad_ifuncT_p[1]-psr[0].quad_ifuncT_p[0]; Tspan = psr[0].quad_ifuncT_p[lp-1]-psr[0].quad_ifuncT_p[0]; fmin = 1.0/Tspan/86400.0; fmax = 1.0/dt/86400.0/2; nSpec = floor (fmax/fmin); nSpecOS4 = 4*nSpec; /* somehow gsl can't handle f=fmax=36.5*fin, so f only goes up to 36.25*fmin */ // check /* printf("%d\t%d\t%d\n", lp, lpc, mlen); printf("%g\t%g\t%d\n", fmin, fmax, nSpec); */ gsl_vector *time = gsl_vector_alloc (lp); gsl_vector *Apn = gsl_vector_alloc (lp); gsl_vector *Acn = gsl_vector_alloc (lp); for (i = 0; i < lp; i++) { gsl_vector_set (time, i, psr[0].quad_ifuncT_p[i]); gsl_vector_set (Apn, i, psr[0].quad_ifuncV_p[i]); gsl_vector_set (Acn, i, psr[0].quad_ifuncV_c[i]); } gsl_matrix *Sigma_n = gsl_matrix_alloc (lpc, lpc); /* noise convariance matrix */ gsl_matrix *Sigma_n1 = gsl_matrix_alloc (lpc, lpc); /* inverse noise convariance matrix */ for (i = 0; i < psr[0].globalNfit; i++) { for (j = 0; j < psr[0].globalNfit; j++) { if ((psr[0].fitParamI[i] == param_quad_ifunc_p || psr[0].fitParamI[i] == param_quad_ifunc_c) && (psr[0].fitParamI[j] == param_quad_ifunc_p || psr[0].fitParamI[j] == param_quad_ifunc_c)) { gsl_matrix_set (Sigma_n, i, j, psr[0].covar[i][j]); } } } // print the covariance matrix to screen /* for (j = 0; j < lpc; j++) printf ("Sigma_n(%d,%d) = %g\n", 0, j, gsl_matrix_get (Sigma_n, 0, j)); */ // eign-decomposition gsl_vector *eval = gsl_vector_alloc (lpc); gsl_matrix *evec = gsl_matrix_alloc (lpc, lpc); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (lpc); gsl_eigen_symmv (Sigma_n, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); gsl_matrix *D1 = gsl_matrix_alloc (mlen, mlen); gsl_matrix *A1 = gsl_matrix_alloc (lpc, mlen); gsl_matrix_set_zero (D1); /* print the eign-values, checked that they agree with results from Matlab for (j = 0; j < lpc; j++) printf ("%d\t%g\n", j, gsl_vector_get (eval, j)); */ for (i = 0; i < mlen; i++) { double eval_i = gsl_vector_get (eval, i+n_cst); gsl_matrix_set (D1, i, i, 1.0/eval_i); gsl_vector *evec_i = gsl_vector_alloc (lpc); gsl_matrix_get_col (evec_i, evec, i+n_cst); gsl_matrix_set_col (A1, i, evec_i); gsl_vector_free (evec_i); } gsl_vector_free (eval); gsl_matrix_free (evec); gsl_matrix *AD1 = gsl_matrix_alloc (lpc, mlen); gsl_matrix_set_zero (AD1); gsl_matrix_set_zero (Sigma_n1); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, A1, D1, 0.0, AD1); gsl_blas_dgemm (CblasNoTrans, CblasTrans, 1.0, AD1, A1, 0.0, Sigma_n1); /* Sigma_n1=A1*D1*A1' */ // print the inverse covariance matrix to screen /* checked and agree with Matlab results for (j = 0; j < lpc; j++) printf ("Sigma_n1(%d,%d) = %g\n", 1, j+1, gsl_matrix_get (Sigma_n1, 0, j)); */ gsl_matrix_free (Sigma_n); gsl_matrix_free (D1); gsl_matrix_free (A1); gsl_matrix_free (AD1); /* something (unknown) wrong with the following approach of getting submatrix gsl_matrix_view Sb1 = gsl_matrix_submatrix (Sigma_n1, 0, 0, lp, lp); gsl_matrix_view Sb2 = gsl_matrix_submatrix (Sigma_n1, 0, lp, lp, lp); gsl_matrix_view Sb3 = gsl_matrix_submatrix (Sigma_n1, lp, 0, lp, lp); gsl_matrix_view Sb4 = gsl_matrix_submatrix (Sigma_n1, lp, lp, lp, lp); gsl_matrix *S11 = &Sb1.matrix; gsl_matrix *S12 = &Sb2.matrix; gsl_matrix *S21 = &Sb3.matrix; gsl_matrix *S22 = &Sb4.matrix; */ gsl_matrix *S11 = gsl_matrix_alloc (lp, lp); gsl_matrix *S12 = gsl_matrix_alloc (lp, lp); gsl_matrix *S21 = gsl_matrix_alloc (lp, lp); gsl_matrix *S22 = gsl_matrix_alloc (lp, lp); for (i = 0; i < lp; i++) { for (j = 0; j < lp; j++) { gsl_matrix_set (S11, i, j, gsl_matrix_get (Sigma_n1, i, j)); gsl_matrix_set (S12, i, j, gsl_matrix_get (Sigma_n1, i, (lp+j))); gsl_matrix_set (S21, i, j, gsl_matrix_get (Sigma_n1, (lp+i), j)); gsl_matrix_set (S22, i, j, gsl_matrix_get (Sigma_n1, (lp+i), (lp+j))); } } gsl_matrix_free (Sigma_n1); /* print the submatrix for (j = 0; j < lp; j++) printf ("S11(%d,%d) = %g\n", 1, j+1, gsl_matrix_get (S11, 0, j)); */ // calculate the Detection Statistics for a set of frequencies for (i = 0; i < nSpecOS4; i++) { double fIndx = 0.5+0.25*i; double f = fmin*fIndx; double y11, y12, y21, y22, y31, y32, y41, y42; double r11, r12, r13, r14, r22, r23, r24, r33, r34, r44; double d1, d2, d3, d4, d5, d6, d7, d8; double y1, y2, y3, y4, r21, r31, r32, r41, r42, r43; gsl_vector *Sc = gsl_vector_alloc (lp); gsl_vector *Ss = gsl_vector_alloc (lp); for (j = 0; j < lp; j++) { gsl_vector_set (Sc, j, cos(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j])); gsl_vector_set (Ss, j, sin(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j])); } gsl_vector *tempy1 = gsl_vector_alloc (lp); gsl_vector *tempy2 = gsl_vector_alloc (lp); gsl_vector *tempy3 = gsl_vector_alloc (lp); gsl_vector *tempy4 = gsl_vector_alloc (lp); gsl_vector *tempy5 = gsl_vector_alloc (lp); gsl_vector *tempy6 = gsl_vector_alloc (lp); gsl_vector *tempy7 = gsl_vector_alloc (lp); gsl_vector *tempy8 = gsl_vector_alloc (lp); gsl_vector *tempr1 = gsl_vector_alloc (lp); gsl_vector *tempr2 = gsl_vector_alloc (lp); gsl_vector *tempr3 = gsl_vector_alloc (lp); gsl_vector *tempr4 = gsl_vector_alloc (lp); gsl_vector *tempr5 = gsl_vector_alloc (lp); gsl_vector *tempr6 = gsl_vector_alloc (lp); gsl_vector *tempr7 = gsl_vector_alloc (lp); gsl_vector *temp5 = gsl_vector_alloc (lp); gsl_vector *temp6 = gsl_vector_alloc (lp); gsl_vector *temp7 = gsl_vector_alloc (lp); gsl_vector *temp8 = gsl_vector_alloc (lp); gsl_blas_dgemv (CblasTrans, 1.0, S11, Apn, 0.0, tempy1); gsl_blas_dgemv (CblasTrans, 1.0, S21, Acn, 0.0, tempy2); gsl_blas_ddot (tempy1, Sc, &y11); gsl_blas_ddot (tempy2, Sc, &y12); y1 = y11 + y12; gsl_blas_ddot (tempy1, Ss, &y21); gsl_blas_ddot (tempy2, Ss, &y22); y2 = y21 + y22; gsl_blas_dgemv (CblasTrans, 1.0, S12, Apn, 0.0, tempy3); gsl_blas_dgemv (CblasTrans, 1.0, S22, Acn, 0.0, tempy4); gsl_blas_ddot (tempy3, Sc, &y31); gsl_blas_ddot (tempy4, Sc, &y32); y3 = y31 + y32; gsl_blas_ddot (tempy3, Ss, &y41); gsl_blas_ddot (tempy4, Ss, &y42); y4 = y41 + y42; gsl_blas_dgemv (CblasTrans, 1.0, S11, Sc, 0.0, tempr1); gsl_blas_dgemv (CblasTrans, 1.0, S12, Sc, 0.0, tempr2); gsl_blas_ddot (tempr1, Sc, &r11); gsl_blas_ddot (tempr1, Ss, &r12); gsl_blas_ddot (tempr2, Sc, &r13); gsl_blas_ddot (tempr2, Ss, &r14); gsl_blas_dgemv (CblasTrans, 1.0, S11, Ss, 0.0, tempr3); gsl_blas_dgemv (CblasTrans, 1.0, S21, Sc, 0.0, tempr4); gsl_blas_dgemv (CblasTrans, 1.0, S21, Ss, 0.0, tempr5); gsl_blas_ddot (tempr3, Ss, &r22); gsl_blas_ddot (tempr4, Ss, &r23); gsl_blas_ddot (tempr5, Ss, &r24); gsl_blas_dgemv (CblasTrans, 1.0, S22, Sc, 0.0, tempr6); gsl_blas_dgemv (CblasTrans, 1.0, S22, Ss, 0.0, tempr7); gsl_blas_ddot (tempr6, Sc, &r33); gsl_blas_ddot (tempr6, Ss, &r34); gsl_blas_ddot (tempr7, Ss, &r44); r21 = r12; r31 = r13; r32 = r23; r41 = r14; r42 = r24; r43 = r34; double a_data[] = { r11, r12, r13, r14, r21, r22, r23, r24, r31, r32, r33, r34, r41, r42, r43, r44 }; double b_data[] = { y1, y2, y3, y4 }; gsl_matrix_view m = gsl_matrix_view_array (a_data, 4, 4); gsl_vector_view b = gsl_vector_view_array (b_data, 4); gsl_vector *Cc = gsl_vector_alloc (4); int s; gsl_permutation * p = gsl_permutation_alloc (4); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, &b.vector, Cc); gsl_permutation_free (p); /* for (j = 0; j < 4; j++) printf ("Cc(%d) = %g\n", j+1, gsl_vector_get (Cc, j)); */ double Cc1 = gsl_vector_get (Cc, 0); double Cc2 = gsl_vector_get (Cc, 1); double Cc3 = gsl_vector_get (Cc, 2); double Cc4 = gsl_vector_get (Cc, 3); gsl_vector_free (Cc); gsl_vector *Ap = gsl_vector_alloc (lp); gsl_vector *Ac = gsl_vector_alloc (lp); for (j = 0; j < lp; j++) { gsl_vector_set (Ap, j, Cc1*cos(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j]) + Cc2*sin(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j])); gsl_vector_set (Ac, j, Cc3*cos(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j]) + Cc4*sin(2.0*86400.0*M_PI*f*psr[0].quad_ifuncT_p[j])); } gsl_blas_dgemv (CblasTrans, 1.0, S11, Ap, 0.0, tempy5); gsl_blas_dgemv (CblasTrans, 1.0, S21, Ac, 0.0, tempy6); gsl_blas_dgemv (CblasTrans, 1.0, S12, Ap, 0.0, tempy7); gsl_blas_dgemv (CblasTrans, 1.0, S22, Ac, 0.0, tempy8); gsl_blas_dgemv (CblasTrans, 1.0, S11, Apn, 0.0, temp5); gsl_blas_dgemv (CblasTrans, 1.0, S21, Acn, 0.0, temp6); gsl_blas_dgemv (CblasTrans, 1.0, S12, Apn, 0.0, temp7); gsl_blas_dgemv (CblasTrans, 1.0, S22, Acn, 0.0, temp8); gsl_blas_ddot (tempy5, Ap, &d1); gsl_blas_ddot (tempy6, Ap, &d2); gsl_blas_ddot (tempy7, Ac, &d3); gsl_blas_ddot (tempy8, Ac, &d4); gsl_blas_ddot (temp5, Ap, &d5); gsl_blas_ddot (temp6, Ap, &d6); gsl_blas_ddot (temp7, Ac, &d7); gsl_blas_ddot (temp8, Ac, &d8); freq[i] = f; DS[i] = 2.0*(d5+d6+d7+d8)-(d1+d2+d3+d4); gsl_vector_free (tempy1); gsl_vector_free (tempy2); gsl_vector_free (tempy3); gsl_vector_free (tempy4); gsl_vector_free (tempy5); gsl_vector_free (tempy6); gsl_vector_free (tempy7); gsl_vector_free (tempy8); gsl_vector_free (temp5); gsl_vector_free (temp6); gsl_vector_free (temp7); gsl_vector_free (temp8); gsl_vector_free (tempr1); gsl_vector_free (tempr2); gsl_vector_free (tempr3); gsl_vector_free (tempr4); gsl_vector_free (tempr5); gsl_vector_free (tempr6); gsl_vector_free (tempr7); gsl_vector_free (Sc); gsl_vector_free (Ss); gsl_vector_free (Ac); gsl_vector_free (Ap); } gsl_matrix_free (S11); gsl_matrix_free (S12); gsl_matrix_free (S21); gsl_matrix_free (S22); gsl_vector_free (time); gsl_vector_free (Apn); gsl_vector_free (Acn); fout = fopen("DectionSts.dat","w"); for (i=0;i<nSpecOS4;i++) fprintf(fout,"%d %g %g\n",i+1,freq[i],DS[i]); fclose(fout); } return 0; } // char * plugVersionCheck = TEMPO2_h_VER;
zhuww/tempo2
plugin/findCWs_plug.C
C++
gpl-3.0
15,178
package ontology.effects.unary; import core.VGDLSprite; import core.content.InteractionContent; import core.game.Game; import ontology.Types; import ontology.effects.Effect; import tools.Direction; import tools.Utils; import tools.Vector2d; /** * Created with IntelliJ IDEA. * User: Diego * Date: 03/12/13 * Time: 16:17 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class FlipDirection extends Effect { public FlipDirection(InteractionContent cnt) { is_stochastic = true; this.parseParameters(cnt); } @Override public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game) { sprite1.orientation = (Direction) Utils.choice(Types.DBASEDIRS, game.getRandomGenerator()); } }
tohahn/UE_ML
UE06/gvgai/src/ontology/effects/unary/FlipDirection.java
Java
gpl-3.0
786
/* * @file gui/dvonn/state.cpp * * This file is part of OpenXum games * * Copyright (c) 2011-2012 Eric Ramat <eramat@users.sourceforge.net> * * See the AUTHORS or Authors.txt file for copyright owners and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gui/utils/graphics.hpp> #include <gui/dvonn/gui.hpp> #include <gui/dvonn/state.hpp> using namespace openxum::common; namespace openxum { namespace dvonn { StateView::StateView(openxum::Gui* parent, openxum::common::Color) : openxum::StateView(parent) { } void StateView::draw() { context()->set_line_width(1.); // background context()->set_source_rgb(1., 1., 1.); context()->rectangle(0, 0, width(), height()); context()->fill(); context()->stroke(); } }} // namespace openxum dvonn
openxum-team/openxum-gtk
src/gui/dvonn/state.cpp
C++
gpl-3.0
1,414
/* fuzzylite (R), a fuzzy logic control library in C++. Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved. Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com> This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the FuzzyLite License included with the software. You should have received a copy of the FuzzyLite License along with fuzzylite. If not, see <http://www.fuzzylite.com/license/>. fuzzylite is a registered trademark of FuzzyLite Limited. */ #include "fl/hedge/HedgeFunction.h" namespace fl { HedgeFunction::HedgeFunction(const std::string& formula) : Hedge() { _function.variables["x"] = fl::nan; if (not formula.empty()) { _function.load(formula); } } std::string HedgeFunction::name() const { return "HedgeFunction"; } Complexity HedgeFunction::complexity() const { if (_function.root()) return _function.complexity().function(2 * std::log(scalar(_function.variables.size()))); return _function.complexity(); } scalar HedgeFunction::hedge(scalar x) const { _function.variables["x"] = x; return _function.membership(x); } Function& HedgeFunction::function() { return this->_function; } void HedgeFunction::setFormula(const std::string& formula) { _function.load(formula); } std::string HedgeFunction::getFormula() const { return _function.getFormula(); } HedgeFunction* HedgeFunction::clone() const { return new HedgeFunction(*this); } Hedge* HedgeFunction::constructor() { return new HedgeFunction; } }
fuzzylite/fuzzylite
fuzzylite/src/hedge/HedgeFunction.cpp
C++
gpl-3.0
1,724
// Code generated by entc, DO NOT EDIT. package ent import ( "context" "fmt" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gen0cide/laforge/ent/predicate" "github.com/gen0cide/laforge/ent/team" ) // TeamDelete is the builder for deleting a Team entity. type TeamDelete struct { config hooks []Hook mutation *TeamMutation } // Where appends a list predicates to the TeamDelete builder. func (td *TeamDelete) Where(ps ...predicate.Team) *TeamDelete { td.mutation.Where(ps...) return td } // Exec executes the deletion query and returns how many vertices were deleted. func (td *TeamDelete) Exec(ctx context.Context) (int, error) { var ( err error affected int ) if len(td.hooks) == 0 { affected, err = td.sqlExec(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*TeamMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } td.mutation = mutation affected, err = td.sqlExec(ctx) mutation.done = true return affected, err }) for i := len(td.hooks) - 1; i >= 0; i-- { if td.hooks[i] == nil { return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") } mut = td.hooks[i](mut) } if _, err := mut.Mutate(ctx, td.mutation); err != nil { return 0, err } } return affected, err } // ExecX is like Exec, but panics if an error occurs. func (td *TeamDelete) ExecX(ctx context.Context) int { n, err := td.Exec(ctx) if err != nil { panic(err) } return n } func (td *TeamDelete) sqlExec(ctx context.Context) (int, error) { _spec := &sqlgraph.DeleteSpec{ Node: &sqlgraph.NodeSpec{ Table: team.Table, ID: &sqlgraph.FieldSpec{ Type: field.TypeUUID, Column: team.FieldID, }, }, } if ps := td.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } return sqlgraph.DeleteNodes(ctx, td.driver, _spec) } // TeamDeleteOne is the builder for deleting a single Team entity. type TeamDeleteOne struct { td *TeamDelete } // Exec executes the deletion query. func (tdo *TeamDeleteOne) Exec(ctx context.Context) error { n, err := tdo.td.Exec(ctx) switch { case err != nil: return err case n == 0: return &NotFoundError{team.Label} default: return nil } } // ExecX is like Exec, but panics if an error occurs. func (tdo *TeamDeleteOne) ExecX(ctx context.Context) { tdo.td.ExecX(ctx) }
gen0cide/laforge
ent/team_delete.go
GO
gpl-3.0
2,551
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "CFCCellToCellStencil.H" #include "syncTools.H" #include "SortableList.H" #include "emptyPolyPatch.H" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Calculates per face the neighbour data (= cell or boundary face) void Foam::CFCCellToCellStencil::calcFaceBoundaryData ( labelList& neiGlobal ) const { const polyBoundaryMesh& patches = mesh().boundaryMesh(); const label nBnd = mesh().nFaces()-mesh().nInternalFaces(); const labelList& own = mesh().faceOwner(); neiGlobal.setSize(nBnd); forAll(patches, patchI) { const polyPatch& pp = patches[patchI]; label faceI = pp.start(); if (pp.coupled()) { // For coupled faces get the cell on the other side forAll(pp, i) { label bFaceI = faceI-mesh().nInternalFaces(); neiGlobal[bFaceI] = globalNumbering().toGlobal(own[faceI]); faceI++; } } else if (isA<emptyPolyPatch>(pp)) { forAll(pp, i) { label bFaceI = faceI-mesh().nInternalFaces(); neiGlobal[bFaceI] = -1; faceI++; } } else { // For noncoupled faces get the boundary face. forAll(pp, i) { label bFaceI = faceI-mesh().nInternalFaces(); neiGlobal[bFaceI] = globalNumbering().toGlobal(mesh().nCells()+bFaceI); faceI++; } } } syncTools::swapBoundaryFaceList(mesh(), neiGlobal, false); } // Calculates per cell the neighbour data (= cell or boundary in global // numbering). First element is always cell itself! void Foam::CFCCellToCellStencil::calcCellStencil(labelListList& globalCellCells) const { const label nBnd = mesh().nFaces()-mesh().nInternalFaces(); const labelList& own = mesh().faceOwner(); const labelList& nei = mesh().faceNeighbour(); // Calculate coupled neighbour (in global numbering) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ labelList neiGlobal(nBnd); calcFaceBoundaryData(neiGlobal); // Determine cellCells in global numbering // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ globalCellCells.setSize(mesh().nCells()); forAll(globalCellCells, cellI) { const cell& cFaces = mesh().cells()[cellI]; labelList& cCells = globalCellCells[cellI]; cCells.setSize(cFaces.size()+1); label nNbr = 0; // Myself cCells[nNbr++] = globalNumbering().toGlobal(cellI); // Collect neighbouring cells/faces forAll(cFaces, i) { label faceI = cFaces[i]; if (mesh().isInternalFace(faceI)) { label nbrCellI = own[faceI]; if (nbrCellI == cellI) { nbrCellI = nei[faceI]; } cCells[nNbr++] = globalNumbering().toGlobal(nbrCellI); } else { label nbrCellI = neiGlobal[faceI-mesh().nInternalFaces()]; if (nbrCellI != -1) { cCells[nNbr++] = nbrCellI; } } } cCells.setSize(nNbr); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::CFCCellToCellStencil::CFCCellToCellStencil(const polyMesh& mesh) : cellToCellStencil(mesh) { // Calculate per cell the (face) connected cells (in global numbering) calcCellStencil(*this); } // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/fvMesh/extendedStencil/cellToCell/fullStencils/CFCCellToCellStencil.C
C++
gpl-3.0
4,942
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2000 Simon Hausmann <hausmann@kde.org> * Copyright (C) 2003, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. * (C) 2006 Graham Dennis (graham.dennis@gmail.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "HTMLAnchorElement.h" #ifdef ARTEMIS #include "ScriptEventListener.h" #endif #include "Attribute.h" #include "DNS.h" #include "EventNames.h" #include "Frame.h" #include "FrameLoaderClient.h" #include "FrameLoaderTypes.h" #include "HTMLImageElement.h" #include "HTMLNames.h" #include "HTMLParserIdioms.h" #include "KeyboardEvent.h" #include "MouseEvent.h" #include "Page.h" #include "PingLoader.h" #include "RenderImage.h" #include "SecurityOrigin.h" #include "SecurityPolicy.h" #include "Settings.h" namespace WebCore { using namespace HTMLNames; HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tagName, Document* document) : HTMLElement(tagName, document) , m_hasRootEditableElementForSelectionOnMouseDown(false) , m_wasShiftKeyDownOnMouseDown(false) , m_linkRelations(0) , m_cachedVisitedLinkHash(0) { } PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(Document* document) { return adoptRef(new HTMLAnchorElement(aTag, document)); } PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(const QualifiedName& tagName, Document* document) { return adoptRef(new HTMLAnchorElement(tagName, document)); } HTMLAnchorElement::~HTMLAnchorElement() { clearRootEditableElementForSelectionOnMouseDown(); } // This function does not allow leading spaces before the port number. static unsigned parsePortFromStringPosition(const String& value, unsigned portStart, unsigned& portEnd) { portEnd = portStart; while (isASCIIDigit(value[portEnd])) ++portEnd; return value.substring(portStart, portEnd - portStart).toUInt(); } bool HTMLAnchorElement::supportsFocus() const { if (rendererIsEditable()) return HTMLElement::supportsFocus(); // If not a link we should still be able to focus the element if it has tabIndex. return isLink() || HTMLElement::supportsFocus(); } bool HTMLAnchorElement::isMouseFocusable() const { // Anchor elements should be mouse focusable, https://bugs.webkit.org/show_bug.cgi?id=26856 #if !PLATFORM(GTK) && !PLATFORM(QT) && !PLATFORM(EFL) if (isLink()) // Only allow links with tabIndex or contentEditable to be mouse focusable. return HTMLElement::supportsFocus(); #endif // Allow tab index etc to control focus. return HTMLElement::isMouseFocusable(); } bool HTMLAnchorElement::isKeyboardFocusable(KeyboardEvent* event) const { if (!isLink()) return HTMLElement::isKeyboardFocusable(event); if (!isFocusable()) return false; if (!document()->frame()) return false; if (!document()->frame()->eventHandler()->tabsToLinks(event)) return false; return hasNonEmptyBoundingBox(); } static void appendServerMapMousePosition(String& url, Event* event) { if (!event->isMouseEvent()) return; ASSERT(event->target()); Node* target = event->target()->toNode(); ASSERT(target); if (!target->hasTagName(imgTag)) return; HTMLImageElement* imageElement = static_cast<HTMLImageElement*>(event->target()->toNode()); if (!imageElement || !imageElement->isServerMap()) return; RenderImage* renderer = toRenderImage(imageElement->renderer()); if (!renderer) return; // FIXME: This should probably pass true for useTransforms. FloatPoint absolutePosition = renderer->absoluteToLocal(FloatPoint(static_cast<MouseEvent*>(event)->pageX(), static_cast<MouseEvent*>(event)->pageY())); int x = absolutePosition.x(); int y = absolutePosition.y(); url += "?"; url += String::number(x); url += ","; url += String::number(y); } void HTMLAnchorElement::defaultEventHandler(Event* event) { if (isLink()) { if (focused() && isEnterKeyKeydownEvent(event) && treatLinkAsLiveForEventType(NonMouseEvent)) { event->setDefaultHandled(); dispatchSimulatedClick(event); return; } if (isLinkClick(event) && treatLinkAsLiveForEventType(eventType(event))) { handleClick(event); return; } if (rendererIsEditable()) { // This keeps track of the editable block that the selection was in (if it was in one) just before the link was clicked // for the LiveWhenNotFocused editable link behavior if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() != RightButton && document()->frame() && document()->frame()->selection()) { setRootEditableElementForSelectionOnMouseDown(document()->frame()->selection()->rootEditableElement()); m_wasShiftKeyDownOnMouseDown = static_cast<MouseEvent*>(event)->shiftKey(); } else if (event->type() == eventNames().mouseoverEvent) { // These are cleared on mouseover and not mouseout because their values are needed for drag events, // but drag events happen after mouse out events. clearRootEditableElementForSelectionOnMouseDown(); m_wasShiftKeyDownOnMouseDown = false; } } } HTMLElement::defaultEventHandler(event); } void HTMLAnchorElement::setActive(bool down, bool pause) { if (rendererIsEditable()) { EditableLinkBehavior editableLinkBehavior = EditableLinkDefaultBehavior; if (Settings* settings = document()->settings()) editableLinkBehavior = settings->editableLinkBehavior(); switch (editableLinkBehavior) { default: case EditableLinkDefaultBehavior: case EditableLinkAlwaysLive: break; case EditableLinkNeverLive: return; // Don't set the link to be active if the current selection is in the same editable block as // this link case EditableLinkLiveWhenNotFocused: if (down && document()->frame() && document()->frame()->selection()->rootEditableElement() == rootEditableElement()) return; break; case EditableLinkOnlyLiveWithShiftKey: return; } } ContainerNode::setActive(down, pause); } void HTMLAnchorElement::parseAttribute(Attribute* attr) { if (attr->name() == hrefAttr) { bool wasLink = isLink(); setIsLink(!attr->isNull()); if (wasLink != isLink()) setNeedsStyleRecalc(); if (isLink()) { String parsedURL = stripLeadingAndTrailingHTMLSpaces(attr->value()); if (document()->isDNSPrefetchEnabled()) { if (protocolIs(parsedURL, "http") || protocolIs(parsedURL, "https") || parsedURL.startsWith("//")) prefetchDNS(document()->completeURL(parsedURL).host()); } if (document()->page() && !document()->page()->javaScriptURLsAreAllowed() && protocolIsJavaScript(parsedURL)) { clearIsLink(); // FIXME: This is horribly factored. if (Attribute* hrefAttribute = getAttributeItem(hrefAttr)) hrefAttribute->setValue(nullAtom); } #ifdef ARTEMIS else if(protocolIsJavaScript(parsedURL) && !hasEventListeners(eventNames().clickEvent)) { // Don't set the onclick event handler if it already has one. setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, attr)); } #endif } invalidateCachedVisitedLinkHash(); } else if (attr->name() == nameAttr || attr->name() == titleAttr) { // Do nothing. } else if (attr->name() == relAttr) setRel(attr->value()); else HTMLElement::parseAttribute(attr); } void HTMLAnchorElement::accessKeyAction(bool sendMouseEvents) { // send the mouse button events if the caller specified sendMouseEvents dispatchSimulatedClick(0, sendMouseEvents); } bool HTMLAnchorElement::isURLAttribute(Attribute *attr) const { return attr->name() == hrefAttr || HTMLElement::isURLAttribute(attr); } bool HTMLAnchorElement::canStartSelection() const { // FIXME: We probably want this same behavior in SVGAElement too if (!isLink()) return HTMLElement::canStartSelection(); return rendererIsEditable(); } bool HTMLAnchorElement::draggable() const { // Should be draggable if we have an href attribute. const AtomicString& value = getAttribute(draggableAttr); if (equalIgnoringCase(value, "true")) return true; if (equalIgnoringCase(value, "false")) return false; return hasAttribute(hrefAttr); } KURL HTMLAnchorElement::href() const { return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(hrefAttr))); } void HTMLAnchorElement::setHref(const AtomicString& value) { setAttribute(hrefAttr, value); } bool HTMLAnchorElement::hasRel(uint32_t relation) const { return m_linkRelations & relation; } void HTMLAnchorElement::setRel(const String& value) { m_linkRelations = 0; SpaceSplitString newLinkRelations(value, true); // FIXME: Add link relations as they are implemented if (newLinkRelations.contains("noreferrer")) m_linkRelations |= RelationNoReferrer; } const AtomicString& HTMLAnchorElement::name() const { return getNameAttribute(); } short HTMLAnchorElement::tabIndex() const { // Skip the supportsFocus check in HTMLElement. return Element::tabIndex(); } String HTMLAnchorElement::target() const { return getAttribute(targetAttr); } String HTMLAnchorElement::hash() const { String fragmentIdentifier = href().fragmentIdentifier(); return fragmentIdentifier.isEmpty() ? emptyString() : "#" + fragmentIdentifier; } void HTMLAnchorElement::setHash(const String& value) { KURL url = href(); if (value[0] == '#') url.setFragmentIdentifier(value.substring(1)); else url.setFragmentIdentifier(value); setHref(url.string()); } String HTMLAnchorElement::host() const { const KURL& url = href(); if (url.hostEnd() == url.pathStart()) return url.host(); if (isDefaultPortForProtocol(url.port(), url.protocol())) return url.host(); return url.host() + ":" + String::number(url.port()); } void HTMLAnchorElement::setHost(const String& value) { if (value.isEmpty()) return; KURL url = href(); if (!url.canSetHostOrPort()) return; size_t separator = value.find(':'); if (!separator) return; if (separator == notFound) url.setHostAndPort(value); else { unsigned portEnd; unsigned port = parsePortFromStringPosition(value, separator + 1, portEnd); if (!port) { // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes // specifically goes against RFC 3986 (p3.2) and // requires setting the port to "0" if it is set to empty string. url.setHostAndPort(value.substring(0, separator + 1) + "0"); } else { if (isDefaultPortForProtocol(port, url.protocol())) url.setHostAndPort(value.substring(0, separator)); else url.setHostAndPort(value.substring(0, portEnd)); } } setHref(url.string()); } String HTMLAnchorElement::hostname() const { return href().host(); } void HTMLAnchorElement::setHostname(const String& value) { // Before setting new value: // Remove all leading U+002F SOLIDUS ("/") characters. unsigned i = 0; unsigned hostLength = value.length(); while (value[i] == '/') i++; if (i == hostLength) return; KURL url = href(); if (!url.canSetHostOrPort()) return; url.setHost(value.substring(i)); setHref(url.string()); } String HTMLAnchorElement::pathname() const { return href().path(); } void HTMLAnchorElement::setPathname(const String& value) { KURL url = href(); if (!url.canSetPathname()) return; if (value[0] == '/') url.setPath(value); else url.setPath("/" + value); setHref(url.string()); } String HTMLAnchorElement::port() const { if (href().hasPort()) return String::number(href().port()); return emptyString(); } void HTMLAnchorElement::setPort(const String& value) { KURL url = href(); if (!url.canSetHostOrPort()) return; // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes // specifically goes against RFC 3986 (p3.2) and // requires setting the port to "0" if it is set to empty string. unsigned port = value.toUInt(); if (isDefaultPortForProtocol(port, url.protocol())) url.removePort(); else url.setPort(port); setHref(url.string()); } String HTMLAnchorElement::protocol() const { return href().protocol() + ":"; } void HTMLAnchorElement::setProtocol(const String& value) { KURL url = href(); url.setProtocol(value); setHref(url.string()); } String HTMLAnchorElement::search() const { String query = href().query(); return query.isEmpty() ? emptyString() : "?" + query; } String HTMLAnchorElement::origin() const { RefPtr<SecurityOrigin> origin = SecurityOrigin::create(href()); return origin->toString(); } void HTMLAnchorElement::setSearch(const String& value) { KURL url = href(); String newSearch = (value[0] == '?') ? value.substring(1) : value; // Make sure that '#' in the query does not leak to the hash. url.setQuery(newSearch.replace('#', "%23")); setHref(url.string()); } String HTMLAnchorElement::text() { return innerText(); } String HTMLAnchorElement::toString() const { return href().string(); } bool HTMLAnchorElement::isLiveLink() const { return isLink() && treatLinkAsLiveForEventType(m_wasShiftKeyDownOnMouseDown ? MouseEventWithShiftKey : MouseEventWithoutShiftKey); } void HTMLAnchorElement::sendPings(const KURL& destinationURL) { if (!hasAttribute(pingAttr) || !document()->settings()->hyperlinkAuditingEnabled()) return; SpaceSplitString pingURLs(getAttribute(pingAttr), false); for (unsigned i = 0; i < pingURLs.size(); i++) PingLoader::sendPing(document()->frame(), document()->completeURL(pingURLs[i]), destinationURL); } void HTMLAnchorElement::handleClick(Event* event) { event->setDefaultHandled(); Frame* frame = document()->frame(); if (!frame) return; String url = stripLeadingAndTrailingHTMLSpaces(fastGetAttribute(hrefAttr)); appendServerMapMousePosition(url, event); KURL kurl = document()->completeURL(url); #if ENABLE(DOWNLOAD_ATTRIBUTE) if (hasAttribute(downloadAttr)) { ResourceRequest request(kurl); if (!hasRel(RelationNoReferrer)) { String referrer = SecurityPolicy::generateReferrerHeader(document()->referrerPolicy(), kurl, frame->loader()->outgoingReferrer()); if (!referrer.isEmpty()) request.setHTTPReferrer(referrer); frame->loader()->addExtraFieldsToMainResourceRequest(request); } frame->loader()->client()->startDownload(request, fastGetAttribute(downloadAttr)); } else #endif frame->loader()->urlSelected(kurl, target(), event, false, false, hasRel(RelationNoReferrer) ? NeverSendReferrer : MaybeSendReferrer); sendPings(kurl); } HTMLAnchorElement::EventType HTMLAnchorElement::eventType(Event* event) { if (!event->isMouseEvent()) return NonMouseEvent; return static_cast<MouseEvent*>(event)->shiftKey() ? MouseEventWithShiftKey : MouseEventWithoutShiftKey; } bool HTMLAnchorElement::treatLinkAsLiveForEventType(EventType eventType) const { if (!rendererIsEditable()) return true; Settings* settings = document()->settings(); if (!settings) return true; switch (settings->editableLinkBehavior()) { case EditableLinkDefaultBehavior: case EditableLinkAlwaysLive: return true; case EditableLinkNeverLive: return false; // If the selection prior to clicking on this link resided in the same editable block as this link, // and the shift key isn't pressed, we don't want to follow the link. case EditableLinkLiveWhenNotFocused: return eventType == MouseEventWithShiftKey || (eventType == MouseEventWithoutShiftKey && rootEditableElementForSelectionOnMouseDown() != rootEditableElement()); case EditableLinkOnlyLiveWithShiftKey: return eventType == MouseEventWithShiftKey; } ASSERT_NOT_REACHED(); return false; } bool isEnterKeyKeydownEvent(Event* event) { return event->type() == eventNames().keydownEvent && event->isKeyboardEvent() && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "Enter"; } bool isMiddleMouseButtonEvent(Event* event) { return event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == MiddleButton; } bool isLinkClick(Event* event) { return event->type() == eventNames().clickEvent && (!event->isMouseEvent() || static_cast<MouseEvent*>(event)->button() != RightButton); } void handleLinkClick(Event* event, Document* document, const String& url, const String& target, bool hideReferrer) { event->setDefaultHandled(); Frame* frame = document->frame(); if (!frame) return; frame->loader()->urlSelected(document->completeURL(url), target, event, false, false, hideReferrer ? NeverSendReferrer : MaybeSendReferrer); } #if ENABLE(MICRODATA) String HTMLAnchorElement::itemValueText() const { return getURLAttribute(hrefAttr); } void HTMLAnchorElement::setItemValueText(const String& value, ExceptionCode&) { setAttribute(hrefAttr, value); } #endif typedef HashMap<const HTMLAnchorElement*, RefPtr<Element> > RootEditableElementMap; static RootEditableElementMap& rootEditableElementMap() { DEFINE_STATIC_LOCAL(RootEditableElementMap, map, ()); return map; } Element* HTMLAnchorElement::rootEditableElementForSelectionOnMouseDown() const { if (!m_hasRootEditableElementForSelectionOnMouseDown) return 0; return rootEditableElementMap().get(this).get(); } void HTMLAnchorElement::clearRootEditableElementForSelectionOnMouseDown() { if (!m_hasRootEditableElementForSelectionOnMouseDown) return; rootEditableElementMap().remove(this); m_hasRootEditableElementForSelectionOnMouseDown = false; } void HTMLAnchorElement::setRootEditableElementForSelectionOnMouseDown(Element* element) { if (!element) { clearRootEditableElementForSelectionOnMouseDown(); return; } rootEditableElementMap().set(this, element); m_hasRootEditableElementForSelectionOnMouseDown = true; } }
cs-au-dk/Artemis
WebKit/Source/WebCore/html/HTMLAnchorElement.cpp
C++
gpl-3.0
19,891
using UnityEngine; /// <summary> /// Buff represents an "upgrade" to a unit. /// </summary> public interface IBuff { /// <summary> /// Determines how long the buff should last (expressed in turns). If set to negative number, buff will be permanent. /// </summary> /// 负数表示。。。手动删除。 int Duration { get; set; } //if(duration == 0) //{ // Duration = duration; //} //else //{ // Duration = RoundManager.GetInstance().Players.Count* duration - 1; //} /// <summary> /// Describes how the unit should be upgraded. /// </summary> void Apply(Transform character); /// <summary> /// Returns units stats to normal. /// </summary> void Undo(Transform character); /// <summary> /// Returns deep copy of the object. /// </summary> IBuff Clone(); }
Phynic/SLGanim
Assets/Scripts/Core/Buff/IBuff.cs
C#
gpl-3.0
870
<?php /** * Gestion automatisée des innactifs * * @author Francois Mazerolle <admin@maz-concept.com> * @copyright Copyright (c) 2009, Francois Mazerolle * @version 1.0 * @package CyberCity_2034 */ class Innactif { public static function go(&$account) { $dbMgr = DbManager::getInstance(); //Instancier le gestionnaire $db = $dbMgr->getConn('game'); //Demander la connexion existante $nextnow = mktime (date("H")-INNACTIVITE_TELEPORT_DELAY, date("i"), date("s"), date("m"), date("d"), date("Y")); $delExpir = mktime (date("H"), date("i"), date("s"), date("m"), date("d")-INNACTIVITE_DELETE_DELAY, date("Y")); try { //Trouver les innactifs $query = 'SELECT p.id' . ' FROM ' . DB_PREFIX . 'perso as p, ' . DB_PREFIX . 'account as a' . ' WHERE a.last_conn<:expiration' . ' AND p.userId = a.id' . ' AND p.lieu!=:lieu' . ' AND p.lieu!=:lieuVac' . ' LIMIT 5;'; $prep = $db->prepare($query); $prep->bindValue('expiration', $nextnow, PDO::PARAM_INT); $prep->bindValue('lieu', INNACTIVITE_TELEPORT_LOCATION, PDO::PARAM_STR); $prep->bindValue('lieuVac', INNACTIVITE_VOLUNTARY_LOCATION, PDO::PARAM_STR); $prep->executePlus($db, __FILE__, __LINE__); $arrPerso = $prep->fetchAll(); $prep->closeCursor(); $prep = NULL; if(count($arrPerso)==0) return; //Ne pas essayer de supprimer des perso, on le fera au prochain innactif $query = 'UPDATE ' . DB_PREFIX . 'perso' . ' SET lieu=:lieu' . ' WHERE id=:persoId;'; $prep = $db->prepare($query); foreach($arrPerso as &$id) { $id= (int)$id[0]; //Téléporter les innactifs $prep->bindValue('lieu', INNACTIVITE_TELEPORT_LOCATION, PDO::PARAM_STR); $prep->bindValue('persoId', $id, PDO::PARAM_INT); $prep->executePlus($db, __FILE__, __LINE__); Member_He::add('System', $id, 'innact', 'Votre personnage a été téléporté pour inactivité.'); } $prep->closeCursor(); $prep = NULL; } catch(Exception $e) { fctBugReport('Erreur', $e->getMessage(), __FILE__, __LINE__); } try { //Trouver les trop innactifs (les supprimer) $query = 'SELECT p.id, p.nom, a.email' . ' FROM ' . DB_PREFIX . 'perso as p, ' . DB_PREFIX . 'account as a' . ' WHERE a.last_conn<:expiration' . ' AND p.userId = a.id' . ' AND p.lieu != :lieuVac' . ' LIMIT 1;'; $prep = $db->prepare($query); $prep->bindValue('expiration', $delExpir, PDO::PARAM_INT); $prep->bindValue('lieuVac', INNACTIVITE_VOLUNTARY_LOCATION, PDO::PARAM_STR); $prep->executePlus($db, __FILE__, __LINE__); $arrPerso = $prep->fetchAll(); $prep->closeCursor(); $prep = NULL; if (count($arrPerso)==0) return; //Ne pas essayer de supprimer des perso, on le fera au prochain innactif foreach($arrPerso as &$arr) { //Apeller la fonction qui gère la suppression de perso. Mj_Perso_Del::delete($arr['id'], 'system'); $tpl = new Template($account); //Envoyer un email de bye bye $tpl->set('PERSO_NOM', stripslashes($arr['nom'])); $MSG = $tpl->fetch($account->getSkinRemotePhysicalPath() . 'html/Visitor/innactivite_email.htm',__FILE__,__LINE__); $ret= @mail( $arr['email'], "Cybercity 2034 - Suppression", $MSG, "From: robot@cybercity2034.com\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n" ); } } catch(Exception $e) { fctBugReport('Erreur', $e->getMessage(), __FILE__, __LINE__); } } }
FMaz008/ccv4
classes/Innactif.php
PHP
gpl-3.0
3,578
// ****************************************************************************** // // Filename: progressbar.cpp // Project: Vox // Author: Steven Ball // // Purpose: // A progress bar component to show visual feedback of progress. // // Revision History: // Initial Revision - 13/07/08 // // Copyright (c) 2005-2006, Steven Ball // // ****************************************************************************** #include "progressbar.h" #include "directdrawrectangle.h" #include "multitextureicon.h" #include "icon.h" ProgressBar::ProgressBar(Renderer* pRenderer, unsigned int GUIFont, float min, float max) : Container(pRenderer), m_minValue(min), m_maxValue(max), m_eProgressDirection(EProgressDirection_Horizontal) { m_currentValue = m_minValue; m_pProgressBackground = new DirectDrawRectangle(pRenderer); m_pProgressFiller = new DirectDrawRectangle(pRenderer); DirectDrawRectangle *lpDirectDrawRect = (DirectDrawRectangle *)m_pProgressBackground; lpDirectDrawRect->SetBackgroundColourTopLeft(Colour(0.75f, 0.75f, 0.75f, 1.0f)); lpDirectDrawRect->SetBackgroundColourTopRight(Colour(0.75f, 0.75f, 0.75f, 1.0f)); lpDirectDrawRect->SetBackgroundColourBottomLeft(Colour(0.75f, 0.75f, 0.75f, 1.0f)); lpDirectDrawRect->SetBackgroundColourBottomRight(Colour(0.75f, 0.75f, 0.75f, 1.0f)); lpDirectDrawRect->SetOutlineColourTop(Colour(0.25f, 0.25f, 0.25f, 1.0f)); lpDirectDrawRect->SetOutlineColourBottom(Colour(0.25f, 0.25f, 0.25f, 1.0f)); lpDirectDrawRect->SetOutlineColourLeft(Colour(0.25f, 0.25f, 0.25f, 1.0f)); lpDirectDrawRect->SetOutlineColourRight(Colour(0.25f, 0.25f, 0.25f, 1.0f)); lpDirectDrawRect = (DirectDrawRectangle *)m_pProgressFiller; lpDirectDrawRect->SetBackgroundColourTopLeft(Colour(0.52f, 0.53f, 0.91f, 1.0f)); lpDirectDrawRect->SetBackgroundColourTopRight(Colour(0.52f, 0.53f, 0.91f, 1.0f)); lpDirectDrawRect->SetBackgroundColourBottomLeft(Colour(0.52f, 0.53f, 0.91f, 1.0f)); lpDirectDrawRect->SetBackgroundColourBottomRight(Colour(0.52f, 0.53f, 0.91f, 1.0f)); lpDirectDrawRect->SetOutlineColourTop(Colour(1.0f, 1.0f, 1.0f, 1.0f)); lpDirectDrawRect->SetOutlineColourBottom(Colour(0.0f, 0.0f, 0.0f, 1.0f)); lpDirectDrawRect->SetOutlineColourLeft(Colour(1.0f, 1.0f, 1.0f, 1.0f)); lpDirectDrawRect->SetOutlineColourRight(Colour(0.0f, 0.0f, 0.0f, 1.0f)); Add(m_pProgressFiller); Add(m_pProgressBackground); m_pProgressBackground->SetDepth(2.0f); m_pProgressFiller->SetDepth(3.0f); } ProgressBar::~ProgressBar() { delete m_pProgressBackground; delete m_pProgressFiller; } float ProgressBar::GetMinValue() { return m_minValue; } float ProgressBar::GetMaxValue() { return m_maxValue; } float ProgressBar::GetCurrentValue() { return m_currentValue; } void ProgressBar::SetMinValue(float minValue) { m_minValue = minValue; } void ProgressBar::SetMaxValue(float maxValue) { m_maxValue = maxValue; } void ProgressBar::SetCurrentValue(float currentValue) { m_currentValue = currentValue; // Bounds checking if(m_currentValue < m_minValue) { m_currentValue = m_minValue; OnMinValueReached(); } else if(m_currentValue > m_maxValue) { m_currentValue = m_maxValue; OnMaxValueReached(); } } EProgressDirection ProgressBar::GetProgressDirection() { return m_eProgressDirection; } void ProgressBar::SetProgressDirection(EProgressDirection lDirection) { m_eProgressDirection = lDirection; } void ProgressBar::SetProgressFiller(RenderRectangle *icon) { MultiTextureIcon* lpMulti = dynamic_cast<MultiTextureIcon*>(icon); Icon* lpIcon = dynamic_cast<Icon*>(icon); if(m_pProgressFiller) { // If we already own an icon, remove it from out component list and also delete it, since we will be replacing it Remove(m_pProgressFiller); delete m_pProgressFiller; m_pProgressFiller = NULL; } // Check what type of render rectangle we have been given, and then assign our new data if(lpMulti) { MultiTextureIcon* lpNewMulti = new MultiTextureIcon((*lpMulti)); m_pProgressFiller = lpNewMulti; } else if(lpIcon) { Icon* lpNewIcon = new Icon((*lpIcon)); m_pProgressFiller = lpNewIcon; } // Re-add this icon to the component list Add(m_pProgressFiller); // Properly set the depth again, since this will have changed after we added the component again m_pProgressFiller->SetDepth(3.0f); } void ProgressBar::SetProgressBackground(RenderRectangle *icon) { MultiTextureIcon* lpMulti = dynamic_cast<MultiTextureIcon*>(icon); Icon* lpIcon = dynamic_cast<Icon*>(icon); if(m_pProgressBackground) { // If we already own an icon, remove it from out component list and also delete it, since we will be replacing it Remove(m_pProgressBackground); delete m_pProgressBackground; m_pProgressBackground = NULL; } // Check what type of render rectangle we have been given, and then assign our new data if(lpMulti) { MultiTextureIcon* lpNewMulti = new MultiTextureIcon((*lpMulti)); m_pProgressBackground = lpNewMulti; } else if(lpIcon) { Icon* lpNewIcon = new Icon((*lpIcon)); m_pProgressBackground = lpNewIcon; } // Re-add this icon to the component list Add(m_pProgressBackground); // Properly set the depth again, since this will have changed after we added the component again m_pProgressBackground->SetDepth(2.0f); } EComponentType ProgressBar::GetComponentType() const { return EComponentType_ProgressBar; } void ProgressBar::OnMinValueReached() { } void ProgressBar::OnMaxValueReached() { // TEMP! m_currentValue = m_minValue; } void ProgressBar::DrawSelf() { int l_containerWidth = m_dimensions.m_width; int l_containerHeight = m_dimensions.m_height; int l_depth = static_cast<int>(GetDepth()); int l_backgroundX1; int l_backgroundX2; int l_backgroundY1; int l_backgroundY2; int l_progressionX1; int l_progressionX2; int l_progressionY1; int l_progressionY2; int l_outlineX1; int l_outlineX2; int l_outlineY1; int l_outlineY2; int lProgression; if(m_eProgressDirection == EProgressDirection_Horizontal) { lProgression = (int)(m_dimensions.m_width * ((m_currentValue - m_minValue) / (m_maxValue - m_minValue))); l_backgroundX1 = 0; l_backgroundX2 = l_containerWidth; l_backgroundY1 = 0; l_backgroundY2 = l_containerHeight; l_progressionX1 = 0; l_progressionX2 = lProgression; l_progressionY1 = 0; l_progressionY2 = l_containerHeight; l_outlineX1 = 0; l_outlineX2 = l_containerWidth + 1; l_outlineY1 = 0; l_outlineY2 = l_containerHeight + 1; } else //m_eProgressDirection == EProgressDirection_Vertical { lProgression = (int)(m_dimensions.m_height * ((m_currentValue - m_minValue) / (m_maxValue - m_minValue))); l_backgroundX1 = 0; l_backgroundX2 = l_containerWidth; l_backgroundY1 = 0; l_backgroundY2 = l_containerHeight; l_progressionX1 = 0; l_progressionX2 = l_containerWidth; l_progressionY1 = 0; l_progressionY2 = lProgression; l_outlineX1 = 0; l_outlineX2 = l_containerWidth + 1; l_outlineY1 = 0; l_outlineY2 = l_containerHeight + 1; } /* // Draw the progression m_pRenderer->PushMatrix(); m_pRenderer->SetRenderMode(RM_SOLID); m_pRenderer->EnableImmediateMode(IM_QUADS); m_pRenderer->ImmediateColourAlpha(1.0f, 0.0f, 0.0f, 1.0f); m_pRenderer->ImmediateVertex(l_progressionX1, l_progressionY1, l_depth); m_pRenderer->ImmediateVertex(l_progressionX2, l_progressionY1, l_depth); m_pRenderer->ImmediateVertex(l_progressionX2, l_progressionY2, l_depth); m_pRenderer->ImmediateVertex(l_progressionX1, l_progressionY2, l_depth); m_pRenderer->DisableImmediateMode(); m_pRenderer->PopMatrix(); // Draw the background m_pRenderer->PushMatrix(); m_pRenderer->SetRenderMode(RM_SOLID); m_pRenderer->EnableImmediateMode(IM_QUADS); m_pRenderer->ImmediateColourAlpha(1.0f, 1.0f, 1.0f, 1.0f); m_pRenderer->ImmediateVertex(l_backgroundX1, l_backgroundY1, l_depth); m_pRenderer->ImmediateVertex(l_backgroundX2, l_backgroundY1, l_depth); m_pRenderer->ImmediateVertex(l_backgroundX2, l_backgroundY2, l_depth); m_pRenderer->ImmediateVertex(l_backgroundX1, l_backgroundY2, l_depth); m_pRenderer->DisableImmediateMode(); m_pRenderer->PopMatrix(); // Draw the outline m_pRenderer->PushMatrix(); m_pRenderer->SetLineWidth(1.0f); m_pRenderer->SetRenderMode(RM_SOLID); m_pRenderer->EnableImmediateMode(IM_LINE_LOOP); m_pRenderer->ImmediateColourAlpha(0.0f, 0.0f, 0.0f, 1.0f); m_pRenderer->ImmediateVertex(l_outlineX1, l_outlineY1, l_depth); m_pRenderer->ImmediateVertex(l_outlineX2, l_outlineY1, l_depth); m_pRenderer->ImmediateVertex(l_outlineX2, l_outlineY2, l_depth); m_pRenderer->ImmediateVertex(l_outlineX1, l_outlineY2, l_depth); m_pRenderer->DisableImmediateMode(); m_pRenderer->PopMatrix(); */ m_pProgressBackground->SetDimensions(l_backgroundX1, l_backgroundY1, l_backgroundX2, l_backgroundY2); m_pProgressFiller->SetDimensions(l_progressionX1, l_progressionY1, l_progressionX2, l_progressionY2); m_pProgressBackground->SetVisible(true); m_pProgressFiller->SetVisible(true); }
AlwaysGeeky/Vox
source/gui/progressbar.cpp
C++
gpl-3.0
8,973
/** * */ package topology.graphParsers.common; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * @author Omer Zohar * This class returns names of files with given extention for a given directory */ public class FileLister { private String m_sfilepath=null; private FilenameFilter m_filter= null; /** * */ public FileLister(String path, FilenameFilter filter) { m_sfilepath=path; m_filter=filter; } public String[] getfilesfromdir(){ File dir = null; try { dir = new File (m_sfilepath).getCanonicalFile(); } catch (IOException e) { System.out.println("Error getting canonical file"); e.printStackTrace(); } String[] s=new String[0]; if (dir.isDirectory()){ s=dir.list(m_filter); for (int i=0;i<s.length;i++) s[i]=m_sfilepath+s[i]; } else { System.out.println(m_sfilepath + "is not a directory."); } return s; } /** * @param args */ public static void main(String[] args) { FilenameFilter extFilter = new FilenameExtentionFilter("fvl"); FileLister f=new FileLister("D:\\Java\\Projects\\betweness\\res\\plankton\\www.ircache.net\\Plankton\\Data\\199810",extFilter); String[] s=f.getfilesfromdir(); for (int i=0;i<s.length;i++) System.out.println(s[i]); } }
puzis/kpp
src/topology/graphParsers/common/FileLister.java
Java
gpl-3.0
1,357
# Copyright FuseSoC contributors # Licensed under the 2-Clause BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-2-Clause def test_generators(): import os import tempfile from fusesoc.config import Config from fusesoc.coremanager import CoreManager from fusesoc.edalizer import Edalizer from fusesoc.librarymanager import Library from fusesoc.vlnv import Vlnv tests_dir = os.path.dirname(__file__) cores_dir = os.path.join(tests_dir, "capi2_cores", "misc", "generate") lib = Library("edalizer", cores_dir) cm = CoreManager(Config()) cm.add_library(lib) core = cm.get_core(Vlnv("::generate")) build_root = tempfile.mkdtemp(prefix="export_") cache_root = tempfile.mkdtemp(prefix="export_cache_") export_root = os.path.join(build_root, "exported_files") edalizer = Edalizer( toplevel=core.name, flags={"tool": "icarus"}, core_manager=cm, cache_root=cache_root, work_root=os.path.join(build_root, "work"), export_root=export_root, system_name=None, ) edalizer.run() gendir = os.path.join( cache_root, "generated", "generate-testgenerate_without_params_0" ) assert os.path.isfile(os.path.join(gendir, "generated.core")) assert os.path.isfile(os.path.join(gendir, "testgenerate_without_params_input.yml")) gendir = os.path.join( cache_root, "generated", "generate-testgenerate_with_params_0" ) assert os.path.isfile(os.path.join(gendir, "generated.core")) assert os.path.isfile(os.path.join(gendir, "testgenerate_with_params_input.yml"))
lowRISC/fusesoc
tests/test_edalizer.py
Python
gpl-3.0
1,641
/* * This file is part of Gradoop. * * Gradoop is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gradoop 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 Gradoop. If not, see <http://www.gnu.org/licenses/>. */ package org.gradoop.common.model.api.entities; import org.gradoop.common.model.impl.id.GradoopId; /** * Describes data assigned to an edge in the EPGM. */ public interface EPGMEdge extends EPGMGraphElement { /** * Returns the source vertex identifier. * * @return source vertex id */ GradoopId getSourceId(); /** * Sets the source vertex identifier. * * @param sourceId source vertex id */ void setSourceId(GradoopId sourceId); /** * Returns the target vertex identifier. * * @return target vertex id */ GradoopId getTargetId(); /** * Sets the target vertex identifier. * * @param targetId target vertex id. */ void setTargetId(GradoopId targetId); }
Venom590/gradoop
gradoop-common/src/main/java/org/gradoop/common/model/api/entities/EPGMEdge.java
Java
gpl-3.0
1,396
#! /usr/bin/env python3 from bollinger import bands, plot, strategies import argparse parser = argparse.ArgumentParser(description="plots bollinger bands or suggests investments", epilog="example: bolly.py plot AMZN FB") parser.add_argument("action", metavar="ACTION", choices=["plot", "suggest"], help="either plot or suggest") parser.add_argument("symbols", metavar="SYMBOL", nargs="+", help="stock symbols") parser.add_argument("-s", "--strategy", choices=["uponce", "downonce", "moreup", "moredown"], default="moredown", help="selects invesment strategy") args = parser.parse_args() if args.action == "plot": for symbol in args.symbols: print("plot [ %s ]: " %(symbol), end="") b = bands.Bands(symbol) b.fetch() try: p = plot.Plot(b) p.save() print("OK") except Exception as ex: print("FAIL: (%s)"%(ex)) if args.action == "suggest": for symbol in args.symbols: print("suggest [ %s ]: " %(symbol), end="") b = bands.Bands(symbol) b.fetch() try: if args.strategy == "uponce": s = strategies.UpOnce(b) elif args.strategy == "downonce": s = strategies.DownOnce(b) elif args.strategy == "moreup": s = strategies.MoreUp(b) elif args.strategy == "moredown": s = strategies.MoreDown(b) print("YES" if s.invest() else "NO") except Exception as ex: print("FAIL: (%s)"%(ex))
juantascon/bollinger-bands
python/bolly.py
Python
gpl-3.0
1,507
import Struct from "ref-struct-napi"; const Registers = Struct({ "r15": "int64", "r14": "int64", "r13": "int64", "r12": "int64", "rbp": "int64", "rbx": "int64", "r11": "int64", "r10": "int64", "r9": "int64", "r8": "int64", "rax": "int64", "rcx": "int64", "rdx": "int64", "rsi": "int64", "rdi": "int64", "orig_rax": "int64", "rip": "int64", "cs": "int64", "eflags": "int64", "rsp": "int64", "ss": "int64", "fs_base": "int64", "gs_base": "int64", "ds": "int64", "es": "int64", "fs": "int64", "gs": "int64", }); export default { Registers };
k13-engineering/unix-ptrace
lib/arch/x86_64.js
JavaScript
gpl-3.0
597
/**************************************************************************** ePMC - an extensible probabilistic model checker Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package epmc.command; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import epmc.util.Util; import epmc.jani.interaction.commandline.CommandLineCategory; import epmc.jani.interaction.commandline.CommandLineCommand; import epmc.jani.interaction.commandline.CommandLineOption; import epmc.jani.interaction.commandline.CommandLineOptions; /** * Class to print usage information about options set. * The usage information consists of a description of the parameters of the * options and commands of the options set, and how to use them. * * @author Ernst Moritz Hahn */ public final class UsagePrinterJANI { /** String containing "[program-options]". */ private final static String PROGRAM_OPTIONS_STRING = "[program-options]"; /** String containing "command". */ private final static String COMMAND_STRING = "command"; /** String containing dot. */ private final static String DOT = "."; /** String containing new line*/ private final static String NEWLINE = "\n"; /** Key in the resource file to read "Usage". */ private final static String COLON = ":"; /** String containing \0 */ private final static String NULL_STRING = "\0"; /** Empty string. */ private final static String EMPTY = ""; /** String containing single space character. */ private final static String SPACE = " "; /** String containing a single pipe character. */ private final static String PIPE = "|"; /** String containing smaller than character. */ private final static String SMALLER_THAN = "<"; /** String containing larger than character. */ private final static String LARGER_THAN = ">"; /** Prefix used for the options. */ private final static String OPTION_PREFIX = "--"; /** Maximal line length of the program options description */ private final static int MAX_LINE_LENGTH = 72; /** * First part of regular expression to split line into parts of given * length. To complete the sequence, this string shall be followed by a * number and then {@link #ALIGN_CHARS_REGEXP_SECOND}. * */ private static final String ALIGN_CHARS_REGEXP_FIRST = "(?<=\\G.{"; /** * Second part of regular expression to split line into parts of given * length, see {@link #ALIGN_CHARS_REGEXP_FIRST}. */ private static final String ALIGN_CHARS_REGEXP_SECOND = "})"; /** * Get usage information of the given options set. * The options parameter may not be {@code null}. * * @param options options to get usage information of * @return usage information of the given options set */ public static String getUsage(CommandLineOptions options) { assert options != null; StringBuilder builder = new StringBuilder(); appendCommands(builder, options); appendOptions(builder, options); return builder.toString(); } /** * Append information about the options commands to given string builder. * None of the parameters may be {@code null}. * * @param builder string builder to append information to * @param options options the command information shall be appended */ private static void appendCommands(StringBuilder builder, CommandLineOptions options) { assert builder != null; assert options != null; Locale locale = Locale.getDefault(); MessageFormat formatter = new MessageFormat(EMPTY); formatter.setLocale(locale); builder.append(options.getToolName() + COLON + SPACE); builder.append(options.getToolDescription() + NEWLINE + NEWLINE); String revision = Util.getManifestEntry(Util.SCM_REVISION); if (revision != null) { revision = revision.trim(); } if (revision != null && !revision.equals(EMPTY)) { formatter.applyPattern(options.getRunningToolRevisionPatter()); builder.append(formatter.format(new Object[]{options.getToolName(), revision}) + NEWLINE); } builder.append(options.getUsagePattern()); String usageString = COLON + SPACE + SMALLER_THAN + options.getToolCmdPattern() + LARGER_THAN + SPACE + SMALLER_THAN + COMMAND_STRING + LARGER_THAN + SPACE + PROGRAM_OPTIONS_STRING + NEWLINE + NEWLINE; builder.append(usageString); builder.append(options.getAvailableCommandsPattern() + COLON + NEWLINE); List<String> cmdStrings = new ArrayList<>(); int maxCmdStringSize = 0; for (String commandString : options.getCommands().keySet()) { String cmdStr = SPACE + SPACE + commandString + SPACE; maxCmdStringSize = Math.max(maxCmdStringSize, cmdStr.length()); cmdStrings.add(cmdStr); } maxCmdStringSize += 2; Iterator<CommandLineCommand> cmdIter = options.getCommands().values().iterator(); for (String formattedCommandStr : cmdStrings) { CommandLineCommand command = cmdIter.next(); String dots = dots(maxCmdStringSize - formattedCommandStr.length()); formattedCommandStr += dots + SPACE; formattedCommandStr += command.getShortDescription(); formattedCommandStr += NEWLINE; builder.append(formattedCommandStr); } builder.append(NEWLINE); } /** * Append information about the options of the given options set to builder. * None of the parameters may be {@code null}. * * @param builder string builder to append information to * @param options options the command information shall be appended */ private static void appendOptions(StringBuilder builder, CommandLineOptions options) { assert builder != null; assert options != null; Map<CommandLineCategory,Set<CommandLineOption>> optionsByCategory = buildOptionsByCategory(options); Map<CommandLineCategory,Set<CommandLineCategory>> hierarchy = buildHierarchy(options); builder.append(options.getAvailableProgramOptionsPattern() + COLON + NEWLINE); Collection<CommandLineOption> nonCategorisedOptions = optionsByCategory.get(null); for (CommandLineOption option : nonCategorisedOptions) { appendOption(builder, option, options, 0); } for (CommandLineCategory category : optionsByCategory.keySet()) { if (category == null || category.getParent() != null) { continue; } appendCategorisedOptions(builder, category, hierarchy, optionsByCategory, options, 0); } } private static void appendCategorisedOptions(StringBuilder builder, CommandLineCategory category, Map<CommandLineCategory, Set<CommandLineCategory>> hierarchy, Map<CommandLineCategory, Set<CommandLineOption>> optionsByCategory, CommandLineOptions options, int level) { assert hierarchy != null; Set<CommandLineOption> categorisedOptions = optionsByCategory.get(category); builder.append(spacify(category.getShortDescription() + COLON, 2 + 2 * level)); for (CommandLineOption option : categorisedOptions) { appendOption(builder, option, options, level + 1); } for (CommandLineCategory child : hierarchy.get(category)) { appendCategorisedOptions(builder, child, hierarchy, optionsByCategory, options, level + 1); } } private static void appendOption(StringBuilder builder, CommandLineOption option, CommandLineOptions options, int level) { assert builder != null; assert option != null; String topLine = buildOptionTopLine(option); builder.append(spacify(topLine, 2 + level * 2)); String description = alignWords(option.getShortDescription(), MAX_LINE_LENGTH - (6 + level * 2)); description = spacify(description, 6 + level * 2); builder.append(description); String typeLines = buildOptionTypeLines(options, option); typeLines = alignPiped(typeLines, MAX_LINE_LENGTH - (6 + level * 2)); typeLines = spacify(typeLines, 6 + level * 2); builder.append(typeLines); String defaultLines = buildOptionDefaultLines(options, option); if (defaultLines != null) { defaultLines = alignCharacters(defaultLines, MAX_LINE_LENGTH - (6 + level * 2)); defaultLines = spacify(defaultLines, 6 + level * 2); builder.append(defaultLines); } } private static Map<CommandLineCategory,Set<CommandLineCategory>> buildHierarchy(CommandLineOptions options) { assert options != null; Map<CommandLineCategory,Set<CommandLineCategory>> result = new LinkedHashMap<>(); for (CommandLineCategory category : options.getAllCategories().values()) { result.put(category, new LinkedHashSet<>()); } for (CommandLineCategory category : options.getAllCategories().values()) { CommandLineCategory parent = category.getParent(); if (parent == null) { continue; } result.get(parent).add(category); } return result; } private static Map<CommandLineCategory, Set<CommandLineOption>> buildOptionsByCategory( CommandLineOptions options) { assert options != null; Map<CommandLineCategory, Set<CommandLineOption>> result = new LinkedHashMap<>(); for (CommandLineOption option : options.getAllOptions().values()) { CommandLineCategory category = option.getCategory(); Set<CommandLineOption> catSet = result.get(category); if (catSet == null) { catSet = new LinkedHashSet<>(); result.put(category, catSet); } catSet.add(option); } return result; } /** * Create a string describing the type of a given option. * The internationalization information will read from resource bundle with * the given base name. The returned string is of the format * &quot;&lt;word-type-in-language&gt;: &lt;type-info&gt;&lt;newline&gt;. * None of the parameters may be {@code null}. * * @param resourceBundle base name of resource bundle * @param option option to get type info description of * @return string describing the type of a given option */ private static String buildOptionTypeLines(CommandLineOptions options, CommandLineOption option) { assert options != null; assert option != null; String typeInfo = options.getTypePattern() + COLON + SPACE + option.getTypeInfo() + NEWLINE; return typeInfo; } /** * Build string describing default value of given option. * The internationalization information will read from resource bundle with * the given base name. The returned string is of the format * &quot;&lt;word-default-in-language&gt;: &lt;default&gt;&lt;newline&gt;. * If the option does not have a default value, the method will return * {@code null}. * None of the parameters may be {@code null}. * * @param resourceBundle base name of resource bundle * @param option option to get default value description of * @return describing the default value of a given option or {@code null} */ private static String buildOptionDefaultLines(CommandLineOptions options, CommandLineOption option) { assert options != null; assert option != null; String defaultValue = option.getDefault(); String result = null; if (defaultValue != null && !defaultValue.equals(EMPTY)) { result = options.getDefaultPattern() + COLON + SPACE + defaultValue + SPACE + NEWLINE; } return result; } private static String buildOptionTopLine(CommandLineOption option) { String poStr = OPTION_PREFIX + option.getIdentifier() + SPACE; return poStr; } /** * Obtain a sequence of a give number of dots ("."). * The number of dots must be nonnegative. * * @param numDots length of sequence * @return sequence of a give number of dots (".") */ private static String dots(int numDots) { assert numDots >= 0; return new String(new char[numDots]).replace(NULL_STRING, DOT); } /** * Obtain a sequence of a give number of spaces (" "). * The number of spaces must be nonnegative. * * @param numSpaces length of sequence * @return sequence of a give number of spaces (" ") */ private static String spaces(int numSpaces) { assert numSpaces >= 0; return new String(new char[numSpaces]).replace(NULL_STRING, SPACE); } /** * Align lines by prefixing them by the given number of spaces. * The input string parameter may not be {@code null}, and the number of * spaces must be nonnegative. * * @param lines lines to align * @param numSpaces number of spaces to prefix lines with * @return aligned string */ private static String spacify(String lines, int numSpaces) { assert lines != null; assert numSpaces >= 0; String[] linesArray = lines.split(NEWLINE); StringBuilder result = new StringBuilder(); for (int lineNr = 0; lineNr < linesArray.length; lineNr++) { result.append(spaces(numSpaces) + linesArray[lineNr] + NEWLINE); } return result.toString(); } /** * Split string by words into lines not exceeding length limit. * The line length may be exceeded if there is a single word larger than * the given line length. The method only splits along word limits; it is * not able to perform hyphenation etc. * The string to split must not be {@code null}, and the maximal line length * must be positive. * * @param string string to split * @param maxLineLength maximal line length * @return split string */ private static String alignWords(String string, int maxLineLength) { return alignSplit(string, maxLineLength, SPACE); } private static String alignPiped(String string, int maxLineLength) { return alignSplit(string, maxLineLength, PIPE); } private static String alignSplit(String string, int maxLineLength, String split) { assert string != null; assert maxLineLength >= 1; String[] words = string.split(Pattern.quote(split)); StringBuilder result = new StringBuilder(); int lineLength = 0; for (String word : words) { lineLength += word.length() + 1; if (lineLength > maxLineLength) { result.append(NEWLINE); lineLength = word.length() + 1; } result.append(word + split); } result.delete(result.length() - 1, result.length()); return result.toString(); } /** * Split string into lines of given length along characters. * The string to split may not be {@code null}, and the maximal line length * must be positive. * * @param string string to split * @param maxLineLength maximal line length * @return split string */ private static String alignCharacters(String string, int maxLineLength) { assert string != null; assert maxLineLength >= 1; String[] lines = string.split(ALIGN_CHARS_REGEXP_FIRST + maxLineLength + ALIGN_CHARS_REGEXP_SECOND); StringBuilder result = new StringBuilder(); for (String line : lines) { result.append(line + NEWLINE); } return result.toString(); } /** * Private constructor to prevent instantiation. */ private UsagePrinterJANI() { } }
liyi-david/ePMC
plugins/command-help/src/main/java/epmc/command/UsagePrinterJANI.java
Java
gpl-3.0
17,019
package com.earth2me.essentials; import com.earth2me.essentials.commands.WarpNotFoundException; import com.earth2me.essentials.utils.StringUtil; import net.ess3.api.InvalidNameException; import net.ess3.api.InvalidWorldException; import org.bukkit.Location; import org.bukkit.Server; import java.io.File; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class Warps implements IConf, net.ess3.api.IWarps { private static final Logger logger = Logger.getLogger("Essentials"); private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>(); private final File warpsFolder; private final Server server; public Warps(Server server, File dataFolder) { this.server = server; warpsFolder = new File(dataFolder, "warps"); if (!warpsFolder.exists()) { warpsFolder.mkdirs(); } reloadConfig(); } @Override public boolean isEmpty() { return warpPoints.isEmpty(); } @Override public Collection<String> getList() { final List<String> keys = new ArrayList<String>(); for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { keys.add(stringIgnoreCase.getString()); } Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); return keys; } @Override public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } return conf.getLocation(null, server); } @Override public void setWarp(String name, Location loc) throws Exception { setWarp(null, name, loc); } @Override public void setWarp(IUser user, String name, Location loc) throws Exception { String filename = StringUtil.sanitizeFileName(name); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { File confFile = new File(warpsFolder, filename + ".yml"); if (confFile.exists()) { throw new Exception(tl("similarWarpExist")); } conf = new EssentialsConf(confFile); warpPoints.put(new StringIgnoreCase(name), conf); } conf.setProperty(null, loc); conf.setProperty("name", name); if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString()); try { conf.saveWithError(); } catch (IOException ex) { throw new IOException(tl("invalidWarpName")); } } @Override public UUID getLastOwner(String warp) throws WarpNotFoundException { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } UUID uuid = null; try { uuid = UUID.fromString(conf.getString("lastowner")); } catch (Exception ex) {} return uuid; } @Override public void removeWarp(String name) throws Exception { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { throw new Exception(tl("warpNotExist")); } if (!conf.getFile().delete()) { throw new Exception(tl("warpDeleteError")); } warpPoints.remove(new StringIgnoreCase(name)); } @Override public final void reloadConfig() { warpPoints.clear(); File[] listOfFiles = warpsFolder.listFiles(); if (listOfFiles.length >= 1) { for (int i = 0; i < listOfFiles.length; i++) { String filename = listOfFiles[i].getName(); if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { try { EssentialsConf conf = new EssentialsConf(listOfFiles[i]); conf.load(); String name = conf.getString("name"); if (name != null) { warpPoints.put(new StringIgnoreCase(name), conf); } } catch (Exception ex) { logger.log(Level.WARNING, tl("loadWarpError", filename), ex); } } } } } //This is here for future 3.x api support. Not implemented here becasue storage is handled differently @Override public File getWarpFile(String name) throws InvalidNameException { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getCount() { return getList().size(); } private static class StringIgnoreCase { private final String string; public StringIgnoreCase(String string) { this.string = string; } @Override public int hashCode() { return getString().toLowerCase(Locale.ENGLISH).hashCode(); } @Override public boolean equals(Object o) { if (o instanceof StringIgnoreCase) { return getString().equalsIgnoreCase(((StringIgnoreCase) o).getString()); } return false; } public String getString() { return string; } } }
dordsor21/dordsentials
Essentials/src/com/earth2me/essentials/Warps.java
Java
gpl-3.0
5,560
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper 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 LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $LastChangedBy$ * * $Date$ * * * \*===========================================================================*/ #include "MaterialPicker.hh" #include <OpenFlipper/BasePlugin/PluginFunctions.hh> #include <OpenFlipper/common/GlobalOptions.hh> #include <ACG/QtWidgets/QtMaterialDialog.hh> #include <sstream> //------------------------------------------------------------------------------ MaterialPicker::MaterialPicker() : pickModeName_("MaterialPicker"), propName_(name()+QString("/Materials")), pickMaterialButton_(0), fillMaterialButton_(0), materialListWidget_(0), materialStrings_(), shortKeyRow_(), materialNode_(), pickMaterial_(false), fillMaterial_(false) { } //------------------------------------------------------------------------------ MaterialPicker::~MaterialPicker() { } //------------------------------------------------------------------------------ void MaterialPicker::initializePlugin() { QWidget* toolBox = new QWidget(); pickMaterialButton_ = new QPushButton("&pick Material", toolBox); fillMaterialButton_ = new QPushButton("&fill Material", toolBox); QPushButton* clearListButton = new QPushButton("Clear List", toolBox); QPushButton* removeItemButton = new QPushButton("Remove", toolBox); pickMaterialButton_->setCheckable(true); fillMaterialButton_->setCheckable(true); QLabel* materials = new QLabel("Materials:"); materialListWidget_ = new QListWidget(toolBox); //load saved materials materialStrings_ = OpenFlipperSettings().value(propName_, QStringList()).toStringList(); for (int i = 0; i < materialStrings_.size(); ++i) { QStringList savedString = materialStrings_[i].split(";"); std::stringstream stream; MaterialInfo materialInfo; stream << savedString[1].toStdString(); stream >> materialInfo.color_material; stream.str(""); stream.clear(); stream << savedString[2].toStdString(); stream >> materialInfo.base_color; stream.str(""); stream.clear(); stream << savedString[3].toStdString(); stream >> materialInfo.ambient_color; stream.str(""); stream.clear(); stream << savedString[4].toStdString(); stream >> materialInfo.diffuse_color; stream.str(""); stream.clear(); stream << savedString[5].toStdString(); stream >> materialInfo.specular_color; stream.str(""); stream.clear(); stream << savedString[6].toStdString(); stream >> materialInfo.shininess; stream.str(""); stream.clear(); stream << savedString[7].toStdString(); stream >> materialInfo.reflectance; stream.str(""); stream.clear(); stream << savedString[8].toStdString(); stream >> materialInfo.key; if (materialInfo.key != Qt::Key_unknown) shortKeyRow_[materialInfo.key] = materialListWidget_->count(); materialListWidget_->addItem( itemName(savedString[0],materialInfo.key) ); materialList_.push_back(materialInfo); } //if material was saved, set first as current if (materialStrings_.size()) materialListWidget_->setCurrentItem(materialListWidget_->item(0)); else fillMaterialButton_->setEnabled(false); QGridLayout* removeGrid = new QGridLayout(); removeGrid->addWidget(removeItemButton,0,0); removeGrid->addWidget(clearListButton,0,1); QGridLayout* pickGrid = new QGridLayout(); pickGrid->addWidget(pickMaterialButton_, 0, 0); pickGrid->addWidget(fillMaterialButton_, 0, 1); QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, toolBox); layout->addWidget(materials); layout->addWidget(materialListWidget_); layout->addLayout(removeGrid); layout->addLayout(pickGrid); connect(pickMaterialButton_, SIGNAL(clicked()), this, SLOT(slotPickMaterialMode())); connect(fillMaterialButton_, SIGNAL(clicked()), this, SLOT(slotFillMaterialMode())); connect(clearListButton, SIGNAL(clicked()), this, SLOT(clearList())); connect(materialListWidget_, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(editMode(QListWidgetItem*))); connect(materialListWidget_->itemDelegate(), SIGNAL(closeEditor(QWidget*, QAbstractItemDelegate::EndEditHint)),this,SLOT(saveNewName(QWidget*, QAbstractItemDelegate::EndEditHint))); connect(removeItemButton, SIGNAL(clicked()), this, SLOT(slotRemoveCurrentItem())); connect(materialListWidget_,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(createContextMenu(const QPoint&))); materialListWidget_->setContextMenuPolicy(Qt::CustomContextMenu); QIcon* toolIcon = new QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"material_picker.png"); emit addToolbox( tr("Material Picker"), toolBox, toolIcon); } //------------------------------------------------------------------------------ void MaterialPicker::removeItem(QListWidgetItem* _item) { unsigned index = materialListWidget_->row(_item); materialListWidget_->takeItem(index); materialList_.erase(materialList_.begin()+index); materialStrings_.erase(materialStrings_.begin()+index); if (materialStrings_.isEmpty()) OpenFlipperSettings().remove(propName_); else OpenFlipperSettings().setValue(propName_, materialStrings_); fillMaterialButton_->setEnabled(materialListWidget_->count()); //update hotkey table std::map<int,size_t>::iterator eraseIter = shortKeyRow_.end(); for (std::map<int,size_t>::iterator iter = shortKeyRow_.begin(); iter != shortKeyRow_.end(); ++iter) { if (iter->second > index) --(iter->second); else if (iter->second == index) eraseIter = iter; } if (eraseIter != shortKeyRow_.end()) shortKeyRow_.erase(eraseIter); } //------------------------------------------------------------------------------ void MaterialPicker::clearList() { materialListWidget_->clear(); materialList_.clear(); materialStrings_.clear(); fillMaterialButton_->setEnabled(false); //setting value empty instead of removing will cause an error at start up OpenFlipperSettings().remove(propName_); } //------------------------------------------------------------------------------ void MaterialPicker::slotRemoveCurrentItem() { if (!materialListWidget_->count()) return; QMessageBox msgBox; QListWidgetItem* item = materialListWidget_->currentItem(); msgBox.setText(tr("Remove ")+plainName(item->text(),materialListWidget_->currentRow())+tr("?")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Ok); int ret = msgBox.exec(); if (ret == QMessageBox::Ok) removeItem(materialListWidget_->currentItem()); } //------------------------------------------------------------------------------ void MaterialPicker::slotPickMaterialMode() { pickMaterialButton_->setChecked(true); fillMaterialButton_->setChecked(false); pickMaterial_ = true; fillMaterial_ = false; PluginFunctions::actionMode( Viewer::PickingMode ); PluginFunctions::pickMode(pickModeName_); } //------------------------------------------------------------------------------ void MaterialPicker::slotFillMaterialMode() { fillMaterialButton_->setChecked(true); pickMaterialButton_->setChecked(false); fillMaterial_ = true; pickMaterial_ = false; PluginFunctions::actionMode( Viewer::PickingMode ); PluginFunctions::pickMode(pickModeName_); } //------------------------------------------------------------------------------ void MaterialPicker::pluginsInitialized() { emit addPickMode(pickModeName_); for (unsigned i = 0; i < supportedKeys_; ++i) emit registerKey (Qt::Key_1+i, Qt::ControlModifier, QString(tr("Material %1")).arg(i+1), false); } //------------------------------------------------------------------------------ void MaterialPicker::slotMouseEvent(QMouseEvent* _event) { if ( PluginFunctions::pickMode() != pickModeName_) return; if (_event->type() == QEvent::MouseButtonPress) { unsigned int node_idx, target_idx; OpenMesh::Vec3d hitPoint; // Get picked object's identifier by picking in scenegraph if ( PluginFunctions::scenegraphPick(ACG::SceneGraph::PICK_ANYTHING ,_event->pos(), node_idx, target_idx, &hitPoint) ){ BaseObjectData* object; if ( PluginFunctions::getPickedObject(node_idx, object) ) { // pick material if ( pickMaterial_ && !fillMaterial_ ) { MaterialNode* material = object->materialNode(); if (material) { // store the material information MaterialInfo materialInfo; materialInfo.color_material = material->colorMaterial(); materialInfo.base_color = material->base_color(); materialInfo.ambient_color = material->ambient_color(); materialInfo.diffuse_color = material->diffuse_color(); materialInfo.specular_color = material->specular_color(); materialInfo.shininess = material->shininess(); materialInfo.reflectance = material->reflectance(); materialInfo.key = Qt::Key_unknown; if (shortKeyRow_.size() < supportedKeys_) { materialInfo.key = Qt::Key_1+(int)shortKeyRow_.size(); shortKeyRow_[materialInfo.key] = materialListWidget_->count(); } // update list widget and material list QString name = QString("material id: %1").arg(material->id()); materialListWidget_->addItem( itemName(name,materialInfo.key) ); materialListWidget_->setCurrentItem( materialListWidget_->item(materialListWidget_->count() - 1) ); materialList_.push_back(materialInfo); //save material QString matStr = materialString(materialInfo,name); materialStrings_.push_back(matStr); OpenFlipperSettings().setValue(propName_, materialStrings_); fillMaterialButton_->setEnabled(true); OpenFlipperSettings().setValue(propName_, materialStrings_); } // apply material from current item in list widget to picked object } else if ( fillMaterial_ && !pickMaterial_ ){ MaterialNode* material = object->materialNode(); if (material) { if (materialListWidget_->count() > 0) { int row = materialListWidget_->currentRow(); material->colorMaterial(materialList_[row].color_material); material->set_base_color(materialList_[row].base_color); material->set_ambient_color(materialList_[row].ambient_color); material->set_diffuse_color(materialList_[row].diffuse_color); material->set_specular_color(materialList_[row].specular_color); material->set_shininess(materialList_[row].shininess); material->set_reflectance(materialList_[row].reflectance); } } } } } } } //------------------------------------------------------------------------------ void MaterialPicker::editModeCurrent() { editMode(materialListWidget_->currentItem()); } //------------------------------------------------------------------------------ void MaterialPicker::editMode(QListWidgetItem* _item) { _item->setFlags(_item->flags() | Qt::ItemIsEditable); materialListWidget_->editItem(_item); _item->setText( plainName(_item->text(),materialListWidget_->row(_item))); } //------------------------------------------------------------------------------ void MaterialPicker::saveNewName ( QWidget * _editor, QAbstractItemDelegate::EndEditHint _hint ) { saveNewName(materialListWidget_->currentItem()); } //------------------------------------------------------------------------------ QString MaterialPicker::plainName(const QString &string, int index) { if (materialList_[index].key == Qt::Key_unknown) return string; QString str(string); return str.remove(0,4); } //------------------------------------------------------------------------------ void MaterialPicker::saveNewName (QListWidgetItem* _item) { unsigned index = materialListWidget_->row(_item); QString str = materialStrings_[index]; QStringList strList = str.split(";"); //pass name strList[0] = _item->text(); //highlight hotkey support if (materialList_[index].key != Qt::Key_unknown) _item->setText( itemName(strList[0], materialList_[index].key) ); //create new String to save str = ""; for (int i = 0; i < strList.size()-1; ++i) str += strList[i] + ";"; str += strList[strList.size()-1]; materialStrings_[index] = str; OpenFlipperSettings().setValue(propName_, materialStrings_); } //------------------------------------------------------------------------------ QString MaterialPicker::itemName(const QString &_name, int _key) { if (_key == Qt::Key_unknown) return _name; return QString(tr("(%1) ")).arg(QString::number(_key-Qt::Key_1+1)) +_name; } //------------------------------------------------------------------------------ void MaterialPicker::slotPickModeChanged(const std::string& _mode) { pickMaterialButton_->setChecked( _mode == pickModeName_ && pickMaterial_ ); fillMaterialButton_->setChecked( _mode == pickModeName_ && fillMaterial_ ); } //------------------------------------------------------------------------------ void MaterialPicker::slotKeyEvent(QKeyEvent* _event) { for (unsigned i = 0; i < supportedKeys_; ++i) { int key = Qt::Key_1+i; if (_event->key() == key && _event->modifiers() == Qt::ControlModifier) { if (shortKeyRow_.find(key) == shortKeyRow_.end()) return; slotFillMaterialMode(); materialListWidget_->setCurrentRow((int)shortKeyRow_[key]); } } } //------------------------------------------------------------------------------ void MaterialPicker::changeHotKey(const int _key) { std::map<int,size_t>::iterator iter = shortKeyRow_.find(_key); if (iter != shortKeyRow_.end()) { //remove old key int oldIndex = (int)iter->second; QListWidgetItem* oldItem = materialListWidget_->item(oldIndex); //remove name oldItem->setText( plainName(oldItem->text(),oldIndex) ); materialList_[oldIndex].key = Qt::Key_unknown; //unregister key after rename, otherwise the renaming will fail materialStrings_[oldIndex] = materialString(materialList_[oldIndex],oldItem->text()); saveNewName(oldItem); } //set the new item (save and hint) int newIndex = materialListWidget_->currentRow(); QListWidgetItem* newItem = materialListWidget_->item(newIndex); materialList_[newIndex].key = _key; materialStrings_[newIndex] = materialString(materialList_[newIndex],newItem->text()); saveNewName(newItem); shortKeyRow_[_key] = newIndex; } //------------------------------------------------------------------------------ QString MaterialPicker::materialString(const MaterialInfo& _mat, const QString &_name) { std::stringstream stream; stream << _name.toStdString(); stream << ";" << _mat.color_material; stream << ";" << _mat.base_color; stream << ";" << _mat.ambient_color; stream << ";" << _mat.diffuse_color; stream << ";" << _mat.specular_color; stream << ";" << _mat.shininess; stream << ";" << _mat.reflectance; stream << ";" << _mat.key; return QString(stream.str().c_str()); } //------------------------------------------------------------------------------ void MaterialPicker::slotMaterialProperties() { if (materialNode_) return; //QListWidgetItem* item = materialListWidget_->currentItem(); materialListWidget_->setDisabled(true); materialNode_.reset(new MaterialNode()); int row = materialListWidget_->currentRow(); materialNode_->colorMaterial(materialList_[row].color_material); materialNode_->set_base_color(materialList_[row].base_color); materialNode_->set_ambient_color(materialList_[row].ambient_color); materialNode_->set_diffuse_color(materialList_[row].diffuse_color); materialNode_->set_specular_color(materialList_[row].specular_color); materialNode_->set_shininess(materialList_[row].shininess); materialNode_->set_reflectance(materialList_[row].reflectance); ACG::QtWidgets::QtMaterialDialog* dialog = new ACG::QtWidgets::QtMaterialDialog( 0, materialNode_.get() ); dialog->setWindowFlags(dialog->windowFlags() | Qt::WindowStaysOnTopHint); connect(dialog,SIGNAL(finished(int)),this,SLOT(slotEnableListWidget(int))); connect(dialog,SIGNAL(accepted()),this,SLOT(slotMaterialChanged())); dialog->setWindowIcon( QIcon(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"datacontrol-material.png")); dialog->show(); } //------------------------------------------------------------------------------ void MaterialPicker::slotMaterialChanged() { if (materialNode_) { int index = materialListWidget_->currentRow(); // store the material information MaterialInfo materialInfo; materialInfo.color_material = materialNode_->colorMaterial(); materialInfo.base_color = materialNode_->base_color(); materialInfo.ambient_color = materialNode_->ambient_color(); materialInfo.diffuse_color = materialNode_->diffuse_color(); materialInfo.specular_color = materialNode_->specular_color(); materialInfo.shininess = materialNode_->shininess(); materialInfo.reflectance = materialNode_->reflectance(); materialInfo.key = materialList_[index].key; QString name = plainName(materialListWidget_->currentItem()->text(),materialListWidget_->currentRow()); materialStrings_[index] = materialString(materialInfo,name); materialList_[index] = materialInfo; OpenFlipperSettings().setValue(propName_, materialStrings_); } OpenFlipperSettings().setValue(propName_, materialStrings_); } //------------------------------------------------------------------------------ void MaterialPicker::slotEnableListWidget(int _save){ materialListWidget_->setEnabled(true); if (_save == QDialog::Accepted) slotMaterialChanged(); materialNode_.reset(); } //------------------------------------------------------------------------------ void MaterialPicker::createContextMenu(const QPoint& _point) { QMenu *menu = new QMenu(materialListWidget_); QAction* action = menu->addAction(tr("Material Properties")); QIcon icon; icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"datacontrol-material.png"); action->setIcon(icon); action->setEnabled(true); connect(action,SIGNAL(triggered(bool)),this,SLOT(slotMaterialProperties())); action = menu->addAction(tr("Rename")); connect(action,SIGNAL(triggered(bool)),this,SLOT(editModeCurrent())); action = menu->addAction(tr("Remove")); connect(action, SIGNAL(triggered(bool)),this,SLOT(slotRemoveCurrentItem())); menu->addSeparator(); //add hotkey selectors QSignalMapper* signalMapper = new QSignalMapper(menu); for (unsigned i = 0; i < supportedKeys_; ++i) { QAction* action = menu->addAction(tr("Key %1").arg(i+1)); connect(action,SIGNAL(triggered(bool)),signalMapper,SLOT(map())); signalMapper->setMapping(action,Qt::Key_1+i); std::map<int,size_t>::iterator iter = shortKeyRow_.find(Qt::Key_1+i); //Disable already selected hotkey number if (iter != shortKeyRow_.end() && iter->second == static_cast<size_t>(materialListWidget_->currentRow())) action->setDisabled(true); } connect(signalMapper, SIGNAL(mapped(const int &)),this, SLOT(changeHotKey(const int &))); menu->exec(materialListWidget_->mapToGlobal(_point),0); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2( materialPicker , MaterialPicker ); #endif
heartvalve/OpenFlipper
Plugin-MaterialPicker/MaterialPicker.cc
C++
gpl-3.0
22,607
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Atto text editor integration version file. * * @package atto_orderedlist * @copyright 2013 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Initialise this plugin * @param string $elementid */ function atto_orderedlist_init_editor($elementid) { global $PAGE, $OUTPUT; $icon = array('e/numbered_list', 'editor_atto'); $PAGE->requires->yui_module('moodle-atto_orderedlist-button', 'M.atto_orderedlist.init', array(array('elementid'=>$elementid, 'icon'=>$icon, 'group'=>'list'))); } /** * Return the order this plugin should be displayed in the toolbar * @return array groupname followed by the absolute position within the toolbar */ function atto_orderedlist_sort_order() { return 6; }
damyon/moodle-editor_atto
plugins/orderedlist/lib.php
PHP
gpl-3.0
1,585
/* DataFile.cpp Copyright (c) 2014 by Michael Zahniser Endless Sky is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Endless Sky 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. */ #include "DataFile.h" #include <fstream> using namespace std; DataFile::DataFile(const string &path) { Load(path); } DataFile::DataFile(istream &in) { Load(in); } void DataFile::Load(const string &path) { // Check if the file exists before doing anything with it. ifstream in(path); if(!in.is_open()) return; // Find out how big the file is. in.seekg(0, ios_base::end); size_t size = in.tellg(); in.seekg(0, ios_base::beg); // Allocate one extra character for the sentinel '\n' character. vector<char> data(size + 1); in.read(&*data.begin(), size); // As a sentinel, make sure the file always ends in a newline. data.back() = '\n'; Load(&*data.begin(), &*data.end()); } void DataFile::Load(istream &in) { vector<char> data; static const size_t BLOCK = 4096; while(in) { size_t currentSize = data.size(); data.resize(currentSize + BLOCK); in.read(&*data.begin() + currentSize, BLOCK); data.resize(currentSize + in.gcount()); } // As a sentinel, make sure the file always ends in a newline. if(data.back() != '\n') data.push_back('\n'); Load(&*data.begin(), &*data.end()); } list<DataNode>::const_iterator DataFile::begin() const { return root.begin(); } list<DataNode>::const_iterator DataFile::end() const { return root.end(); } void DataFile::Load(const char *it, const char *end) { vector<DataNode *> stack(1, &root); vector<int> whiteStack(1, -1); for( ; it != end; ++it) { // Find the first non-white character in this line. int white = 0; for( ; *it <= ' ' && *it != '\n'; ++it) ++white; // If the line is a comment, skip to the end of the line. if(*it == '#') { while(*it != '\n') ++it; } // Skip empty lines (including comment lines). if(*it == '\n') continue; // Determine where in the node tree we are inserting this node, based on // whether it has more indentation that the previous node, less, or the same. while(whiteStack.back() >= white) { whiteStack.pop_back(); stack.pop_back(); } // Add this node as a child of the proper node. list<DataNode> &children = stack.back()->children; children.push_back(DataNode()); DataNode &node = children.back(); // Remember where in the tree we are. stack.push_back(&node); whiteStack.push_back(white); // Tokenize the line. Skip comments and empty lines. while(*it != '\n') { char endQuote = *it; bool isQuoted = (endQuote == '"' || endQuote == '`'); it += isQuoted; const char *start = it; // Find the end of this token. while(*it != '\n' && (isQuoted ? (*it != endQuote) : (*it > ' '))) ++it; node.tokens.emplace_back(start, it); if(*it != '\n') { it += isQuoted; while(*it != '\n' && *it <= ' ' && *it != '#') ++it; // If a comment is encountered outside of a token, skip the rest // of this line of the file. if(*it == '#') { while(*it != '\n') ++it; } } } } }
seanfahey/endless-sky
source/DataFile.cpp
C++
gpl-3.0
3,506
var searchData= [ ['img',['IMG',['../define_8h.html#a116f6464c8184676310301dc13ed1dd5',1,'define.h']]], ['items',['ITEMS',['../define_8h.html#a8e3d0b04841186d4f38b7880a9e4b5c6',1,'define.h']]] ];
philipgraf/Dr_mad_daemon
doc/html/search/defines_69.js
JavaScript
gpl-3.0
200
/** * This package contains the services of the server and the locator. * * @author Nicolas SYMPHORIEN (nicolas.symphorien@gmail.com) * */ package com.seikomi.janus.services;
Seikomi/Janus-Server
src/main/java/com/seikomi/janus/services/package-info.java
Java
gpl-3.0
187
/* * Copyright 2009-2015 Tilmann Zaeschke. All rights reserved. * * This file is part of ZooDB. * * ZooDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZooDB 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 ZooDB. If not, see <http://www.gnu.org/licenses/>. * * See the README and COPYING files for further information. */ package org.zoodb.internal.server.index; import org.zoodb.internal.server.DiskIO.PAGE_TYPE; import org.zoodb.internal.server.StorageChannel; public class IndexFactory { /** * @param type * @param storage * @return a new index */ public static LongLongIndex createIndex(PAGE_TYPE type, StorageChannel storage) { return new PagedLongLong(type, storage); } /** * @param type * @param storage * @param pageId page id of the root page * @return an index reconstructed from disk */ public static LongLongIndex loadIndex(PAGE_TYPE type, StorageChannel storage, int pageId) { return new PagedLongLong(type, storage, pageId); } /** * @param type * @param storage * @return a new index */ public static LongLongIndex.LongLongUIndex createUniqueIndex(PAGE_TYPE type, StorageChannel storage) { return new PagedUniqueLongLong(type, storage); } /** * @param type * @param storage * @param pageId page id of the root page * @return an index reconstructed from disk */ public static LongLongIndex.LongLongUIndex loadUniqueIndex(PAGE_TYPE type, StorageChannel storage, int pageId) { return new PagedUniqueLongLong(type, storage, pageId); } /** * EXPERIMENTAL! Index that has bit width of key and value as parameters. * @param type * @param storage * @return a new index */ public static LongLongIndex.LongLongUIndex createUniqueIndex(PAGE_TYPE type, StorageChannel storage, int keySize, int valSize) { return new PagedUniqueLongLong(type, storage, keySize, valSize); } /** * EXPERIMENTAL! Index that has bit width of key and value as parameters. * @param type * @param storage * @param pageId page id of the root page * @return an index reconstructed from disk */ public static LongLongIndex.LongLongUIndex loadUniqueIndex(PAGE_TYPE type, StorageChannel storage, int pageId, int keySize, int valSize) { return new PagedUniqueLongLong(type, storage, pageId, keySize, valSize); } }
NickCharsley/zoodb
src/org/zoodb/internal/server/index/IndexFactory.java
Java
gpl-3.0
2,783
<?php /** * The file responsible for defining the custom helper functions. * * @link https://www.wpdispensary.com/ * @since 1.9 * * @package WPD_Coupons * @subpackage WPD_Coupons/inc */ /** * Coupon types * * @since 1.9 */ function get_wpd_coupons_types() { return (array) apply_filters( 'wpd_coupons_types', array( 'percentage' => __( 'Percentage', 'wpd-coupons' ), 'flat_rate' => __( 'Flat Rate', 'wpd-coupons' ), ) ); } /** * Get a coupon type's name. * * @param string $type Coupon type. * @return string */ function get_wpd_coupons_type( $type = '' ) { $types = get_wpd_coupons_types(); return isset( $types[ $type ] ) ? $types[ $type ] : ''; } /** * Get a coupon code by ID. * * @param string $coupon_id Coupon ID. * @return string */ function get_wpd_coupon_code( $coupon_id = '' ) { // Require ID. if ( '' == $coupon_id ) { return false; } // Get coupon code. $coupon_code = get_post_meta( $coupon_id, 'wpd_coupon_code', TRUE ); return $coupon_code; }
deviodigital/dispensary-coupons
inc/dispensary-coupons-helper-functions.php
PHP
gpl-3.0
1,051
package com.Deoda.MCMBTools.proxy; public interface IProxy { }
deodaj/MCMBTools
src/main/java/com/Deoda/MCMBTools/proxy/IProxy.java
Java
gpl-3.0
65
# -*- coding: utf-8 -*- import sys import csv from itertools import izip # https://pypi.python.org/pypi/unicodecsv # http://semver.org/ VERSION = (0, 9, 4) __version__ = ".".join(map(str, VERSION)) pass_throughs = [ 'register_dialect', 'unregister_dialect', 'get_dialect', 'list_dialects', 'field_size_limit', 'Dialect', 'excel', 'excel_tab', 'Sniffer', 'QUOTE_ALL', 'QUOTE_MINIMAL', 'QUOTE_NONNUMERIC', 'QUOTE_NONE', 'Error' ] __all__ = [ 'reader', 'writer', 'DictReader', 'DictWriter', ] + pass_throughs for prop in pass_throughs: globals()[prop] = getattr(csv, prop) def _stringify(s, encoding, errors): if s is None: return '' if isinstance(s, unicode): return s.encode(encoding, errors) elif isinstance(s, (int, float)): pass # let csv.QUOTE_NONNUMERIC do its thing. elif not isinstance(s, str): s = str(s) return s def _stringify_list(l, encoding, errors='strict'): try: return [_stringify(s, encoding, errors) for s in iter(l)] except TypeError, e: raise csv.Error(str(e)) def _unicodify(s, encoding): if s is None: return None if isinstance(s, (unicode, int, float)): return s elif isinstance(s, str): return s.decode(encoding) return s class UnicodeWriter(object): """ >>> import unicodecsv >>> from cStringIO import StringIO >>> f = StringIO() >>> w = unicodecsv.writer(f, encoding='utf-8') >>> w.writerow((u'é', u'ñ')) >>> f.seek(0) >>> r = unicodecsv.reader(f, encoding='utf-8') >>> row = r.next() >>> row[0] == u'é' True >>> row[1] == u'ñ' True """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', errors='strict', *args, **kwds): self.encoding = encoding self.writer = csv.writer(f, dialect, *args, **kwds) self.encoding_errors = errors def writerow(self, row): self.writer.writerow( _stringify_list(row, self.encoding, self.encoding_errors)) def writerows(self, rows): for row in rows: self.writerow(row) @property def dialect(self): return self.writer.dialect writer = UnicodeWriter class UnicodeReader(object): def __init__(self, f, dialect=None, encoding='utf-8', errors='strict', **kwds): format_params = ['delimiter', 'doublequote', 'escapechar', 'lineterminator', 'quotechar', 'quoting', 'skipinitialspace'] if dialect is None: if not any([kwd_name in format_params for kwd_name in kwds.keys()]): dialect = csv.excel self.reader = csv.reader(f, dialect, **kwds) self.encoding = encoding self.encoding_errors = errors def next(self): row = self.reader.next() encoding = self.encoding encoding_errors = self.encoding_errors float_ = float unicode_ = unicode try: val = [(value if isinstance(value, float_) else unicode_(value, encoding, encoding_errors)) for value in row] except UnicodeDecodeError as e: # attempt a different encoding... encoding = 'ISO-8859-1' val = [(value if isinstance(value, float_) else unicode_(value, encoding, encoding_errors)) for value in row] return val def __iter__(self): return self @property def dialect(self): return self.reader.dialect @property def line_num(self): return self.reader.line_num reader = UnicodeReader class DictWriter(csv.DictWriter): """ >>> from cStringIO import StringIO >>> f = StringIO() >>> w = DictWriter(f, ['a', u'ñ', 'b'], restval=u'î') >>> w.writerow({'a':'1', u'ñ':'2'}) >>> w.writerow({'a':'1', u'ñ':'2', 'b':u'ø'}) >>> w.writerow({'a':u'é', u'ñ':'2'}) >>> f.seek(0) >>> r = DictReader(f, fieldnames=['a', u'ñ'], restkey='r') >>> r.next() == {'a': u'1', u'ñ':'2', 'r': [u'î']} True >>> r.next() == {'a': u'1', u'ñ':'2', 'r': [u'\xc3\xb8']} True >>> r.next() == {'a': u'\xc3\xa9', u'ñ':'2', 'r': [u'\xc3\xae']} True """ def __init__(self, csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', encoding='utf-8', errors='strict', *args, **kwds): self.encoding = encoding csv.DictWriter.__init__( self, csvfile, fieldnames, restval, extrasaction, dialect, *args, **kwds) self.writer = UnicodeWriter( csvfile, dialect, encoding=encoding, errors=errors, *args, **kwds) self.encoding_errors = errors def writeheader(self): fieldnames = _stringify_list( self.fieldnames, self.encoding, self.encoding_errors) header = dict(zip(self.fieldnames, self.fieldnames)) self.writerow(header) class DictReader(csv.DictReader): """ >>> from cStringIO import StringIO >>> f = StringIO() >>> w = DictWriter(f, fieldnames=['name', 'place']) >>> w.writerow({'name': 'Cary Grant', 'place': 'hollywood'}) >>> w.writerow({'name': 'Nathan Brillstone', 'place': u'øLand'}) >>> w.writerow({'name': u'Willam ø. Unicoder', 'place': u'éSpandland'}) >>> f.seek(0) >>> r = DictReader(f, fieldnames=['name', 'place']) >>> print r.next() == {'name': 'Cary Grant', 'place': 'hollywood'} True >>> print r.next() == {'name': 'Nathan Brillstone', 'place': u'øLand'} True >>> print r.next() == {'name': u'Willam ø. Unicoder', 'place': u'éSpandland'} True """ def __init__(self, csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', encoding='utf-8', errors='strict', *args, **kwds): if fieldnames is not None: fieldnames = _stringify_list(fieldnames, encoding) csv.DictReader.__init__( self, csvfile, fieldnames, restkey, restval, dialect, *args, **kwds) self.reader = UnicodeReader(csvfile, dialect, encoding=encoding, errors=errors, *args, **kwds) if fieldnames is None and not hasattr(csv.DictReader, 'fieldnames'): # Python 2.5 fieldnames workaround. # (http://bugs.python.org/issue3436) reader = UnicodeReader( csvfile, dialect, encoding=encoding, *args, **kwds) self.fieldnames = _stringify_list(reader.next(), reader.encoding) self.unicode_fieldnames = [_unicodify(f, encoding) for f in self.fieldnames] self.unicode_restkey = _unicodify(restkey, encoding) def next(self): row = csv.DictReader.next(self) result = dict((uni_key, row[str_key]) for (str_key, uni_key) in izip(self.fieldnames, self.unicode_fieldnames)) rest = row.get(self.restkey) if rest: result[self.unicode_restkey] = rest return result
archives-new-zealand/archwayimportgenerator
libs/unicodecsv.py
Python
gpl-3.0
7,077
#include "faktionbankkauftwertpapiere.h" FAktionBankKauftWertpapiere::FAktionBankKauftWertpapiere(){ } FAktionBankKauftWertpapiere::FAktionBankKauftWertpapiere(FGeld BETRAG, int BANKNR, int BANKKUNDENNR){ Betrag = BETRAG; BankNr = BANKNR; BankKundenNr = BANKKUNDENNR; } void FAktionBankKauftWertpapiere::Execute_on(FAlleDaten *AlleDaten){ // Operation auf Geschäftsbanken ausführen. AlleDaten->Banken[BankNr].Wertpapiere += Betrag; AlleDaten->Banken[BankNr].GiroKonten[BankKundenNr] += Betrag; // Fehlermeldungen Fehlerbeschreibung = AlleDaten->Checken_ob_alle_Bilanzen_valide_sind_sonst_Fehlermeldung(); // Beschreibung BeschreibungDerOperation = ") Die Bank hat Wertpapiere gekauft."; }
FrankStimmel/Bankbilanz
Operatoren/faktionbankkauftwertpapiere.cpp
C++
gpl-3.0
781
/******************************************************************************* * Copyright (c) 2016 Raul Vidal Ortiz. * * This file is part of Assembler. * * Assembler is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Assembler 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 Assembler. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package assembler; public final class Opcodes { public static final String nop = "00000000"; public static final String halt = "11111111"; public static final String addd = "00000001"; public static final String subd = "00000010"; public static final String movd = "00001001"; public static final String movi = "00011001"; public static final String movhi = "00101001"; public static final String ld = "01000000"; public static final String sd = "01000001"; public static final String jmp = "10000100"; public static final String beq = "10000000"; public static final Integer bitsinst = 32; public static final Integer bytesinst = bitsinst/8; public static final Integer bitsopcode = 8; public static final Integer bitsreg = 5; public static final Integer numregs = (int) Math.pow(2, Opcodes.bitsreg); public static final Integer bitsaddress = 32; public static final Integer bitsoffset = 14; public static final Integer bitsimmmov = 19; public static final Integer bitsjmpaddr = 24; public static final Integer limitposaddr = (int) Math.pow(2,Opcodes.bitsaddress-1)-1; public static final Integer limitnegaddr = 0; public static final Integer limitposoffset = (int) Math.pow(2, Opcodes.bitsoffset-1)-1; public static final Integer limitnegoffset = (int) -(Math.pow(2, Opcodes.bitsoffset-1)); public static final Integer limitposimmov = (int) Math.pow(2, Opcodes.bitsimmmov-1)-1; public static final Integer limitnegimmov = (int) -(Math.pow(2, Opcodes.bitsimmmov-1)); public static final Integer limitposjmpaddr = (int) Math.pow(2, Opcodes.bitsjmpaddr-1)-1; public static final Integer limitnegjmpaddr = (int) -(Math.pow(2, Opcodes.bitsjmpaddr-1)); private Opcodes() {} public static String OpStringToOpcode(String op) { switch (op) { case "nop": return Opcodes.nop; case "halt": return Opcodes.halt; case "addd": return Opcodes.addd; case "subd": return Opcodes.subd; case "movd": return Opcodes.movd; case "movi": return Opcodes.movi; case "movhi": return Opcodes.movhi; case "ld": return Opcodes.ld; case "sd": return Opcodes.sd; case "jmp": return Opcodes.jmp; case "beq": return Opcodes.beq; } return null; } public static String addZeroes(String binary, Integer size) { if (binary.length() < size) { Integer distance = size-binary.length(); for (int i = 0; i < distance; i++) { binary = "0".concat(binary); } } return binary; } public static String trimOnes(String binary, Integer size) { Integer distance = binary.length() - size; return binary.substring(distance); } }
Raulvo/vhdl
assembler/src/assembler/Opcodes.java
Java
gpl-3.0
3,587
<div class="container"> <?php if(isset($handleMsg)){ echo '<div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Success! </strong>'.$handleMsg.' </div>'; } if(isset($reports)){ $nReports = 0; while ($row = $reports->fetch_assoc()) { ++$nReports; echo '<a href="index.php?page=official&tab=reports&reportid='.$row['id'].'"class="list-group-item '.($row['urgent']==1?'report-urgent':'report-normal').'"> <div class="row"> <div class="col-md-9"> <p class="list-group-item-title">'.$row['location'].'</p> <p class="list-group-item-text">'.$row['description'].'</p> </div> <div class="col-md-3"> <p class="list-group-item-text">'.date('M j, Y - g:i A', strtotime($row['time'])).'</p> </div> </div> </a>'; } if($nReports == 0){ echo '<label> no recent reports found </label>'; } }else echo '<label> failed to fetch reports, please try again later</label>'; ?> </div>
FrozenHelium/rescue
views/official_reports_view.php
PHP
gpl-3.0
1,501
/** * Iniciar panel de navegación (menú) */ function initSideBar(nav) { //-------------- Declaraciones ------------// let addMenuItem = function(menu, icon, label, click){ let li = $('<li><a href="javascript:void(0)"><i class="fa '+icon+' fa-fw"></i> '+label+'</a></li>'); if(click) li.on('click', click); menu.append(li); } let addSubMenu = function(id, menu, icon, label, filler){ let li = $('<li><a href="javascript:void(0)"><i class="fa '+icon+' fa-fw"></i> '+label+'<span class="fa arrow"></span></a></li>'); let ul = $('<ul class="nav nav-second-level"></ul>'); filler(ul); li.append(ul); menu.append(li); } let addSubMenuItem = function(menu, label, click){ let li = $('<li><a href="javascript:void(0)">'+label+'</a></li>'); if(click) li.on('click', click); menu.append(li); } let sidebar = $(` <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> </ul> </div> </div>`); let menu = sidebar.find('#side-menu'); //-------------- Ejecución -------------// // Agregar item "Inicio" addMenuItem(menu, 'fa-home', 'Inicio', function() { initHomePanel(); }); // Agregar item "Perfil" addMenuItem(menu, 'fa-user', 'Perfil', function() { initProfilePanel(); }); // Agregar item "Marcas" addMenuItem(menu, 'fa-bookmark', 'Marcas', function() { api.getAllBrands(function(data) { initContentPanel('Marcas', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"} ], 'brands', data.brands ); }); }); }); // Agregar item "Categorías" addMenuItem(menu, 'fa-tags', 'Categorías', function() { api.getAllCategories(function(data) { initContentPanel('Categorías', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Descripción", data: "description"} ], 'categories', data.categories ); }); }); }); // Agregar item "Clientes" addMenuItem(menu, 'fa-users', 'Clientes', function() { api.getAllClients(function(data) { initContentPanel('Clientes', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "CUIT", data: "cuit"}, {title: "Correo electrónico", data: "email"}, {title: "Teléfono", data:"phone"}, {title: "Dirección", data: "location"}, ], 'clients', data.clients ); }); }); }); // Agregar item "Productos" addMenuItem(menu, 'fa-th-list', 'Productos', function() { api.getAllProducts(function(data) { initContentPanel('Products', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "Marca", data: "brand"}, {title: "Proveedor", data: "provider"}, {title: "Precio minorista", data:"retail_price"}, {title: "Precio mayorista", data: "wholesale_price"}, ], 'products', data.products ); let btnSubmit = $('<button type="button" id="submit-products" class="btn btn-success">Success</button>'); container.append(btnSubmit); }); }); }); // Agregar item "Proveedores" addMenuItem(menu, 'fa-truck', 'Proveedores', function() { api.getAllProviders(function(data) { initContentPanel('Providers', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "Correo electrónico", data: "email"}, {title: "Teléfono", data:"phone"}, {title: "Compañía", data: "company"}, ], 'providers', data.providers ); }); }); }); // Agregar item "Ventas" addMenuItem(menu, 'fa-shopping-cart', 'Ventas', function() { api.getAllSales(function(data) { initContentPanel('Ventas', function(container) { createTable( container, columnas = [ {title: "#", data: "id"}, {title: "Usuario", data: "user"}, {title: "Cliente", data: "client"}, {title: "Total", data: "total"}, {title: "Fecha", data:"timestamp"}, ], 'sales', data.sales ); }); }); }); // Agregar item "Entregas" addSubMenu("deliveries", menu, 'fa-car', 'Entregas', function(submenu) { addSubMenuItem(submenu, "Hoy", function() { initDeliveriesPanel('today'); }); addSubMenuItem(submenu, "Atrasadas", function() { initDeliveriesPanel('delayed'); }); addSubMenuItem(submenu, "Pendientes", function() { initDeliveriesPanel('pending'); }); }); // Agregar item "Deudores" addMenuItem(menu, 'fa-warning', 'Deudores', function() { initDebtorsPanel(); }); nav.append(sidebar); }
germix/canawa
front2/admin/sidebar.js
JavaScript
gpl-3.0
4,973
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class boundaryMeasurements Description \*----------------------------------------------------------------------------*/ #include "boundaryMeasurements.H" #include "processorPolyPatch.H" #include "cyclicPolyPatch.H" #include "wallPolyPatch.H" #include "dsmcCloud.H" namespace Foam { // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // void boundaryMeasurements::writenStuckParticles() { tmp<volScalarField> tnStuckParticles ( new volScalarField ( IOobject ( "nStuckParticles", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("nStuckParticles", dimless, 0.0) ) ); volScalarField& nStuckParticles = tnStuckParticles.ref(); nStuckParticles.boundaryFieldRef() = nParticlesOnStickingBoundaries_; nStuckParticles.write(); } void boundaryMeasurements::writenAbsorbedParticles() { tmp<volScalarField> tnAbsorbedParticles ( new volScalarField ( IOobject ( "nAbsorbedParticles", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("nAbsorbedParticles", dimless, 0.0) ) ); volScalarField& nAbsorbedParticles = tnAbsorbedParticles.ref(); nAbsorbedParticles.boundaryFieldRef() = nAbsorbedParticles_; nAbsorbedParticles.write(); } void boundaryMeasurements::writePatchFields() { //- Temperature field tmp<volScalarField> tboundaryT ( new volScalarField ( IOobject ( "boundaryT", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedScalar("boundaryT", dimTemperature, 0.0) ) ); volScalarField& boundaryT = tboundaryT.ref(); boundaryT.boundaryFieldRef() = boundaryT_; boundaryT.write(); //- Velocity field tmp<volVectorField> tboundaryU ( new volVectorField ( IOobject ( "boundaryU", mesh_.time().timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), mesh_, dimensionedVector("boundaryU", dimVelocity, vector::zero) ) ); volVectorField& boundaryU = tboundaryU.ref(); boundaryU.boundaryFieldRef() = boundaryU_; boundaryU.write(); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from mesh and cloud boundaryMeasurements::boundaryMeasurements ( const polyMesh& mesh, dsmcCloud& cloud ) : mesh_(refCast<const fvMesh>(mesh)), cloud_(cloud), nParticlesOnStickingBoundaries_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), nAbsorbedParticles_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryT_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryU_ ( mesh_.boundary(), mesh_.C(), calculatedFvPatchVectorField::typeName ) { nParticlesOnStickingBoundaries_ = 0.0; nAbsorbedParticles_ = 0.0; } //- Construct from mesh, cloud and boolean (dsmcFoam) boundaryMeasurements::boundaryMeasurements ( const polyMesh& mesh, dsmcCloud& cloud, const bool& dummy ) : mesh_(refCast<const fvMesh>(mesh)), cloud_(cloud), typeIds_(cloud_.typeIdList().size(), -1), speciesRhoNIntBF_(), speciesRhoNElecBF_(), speciesRhoNBF_(), speciesRhoMBF_(), speciesLinearKEBF_(), speciesMccBF_(), speciesMomentumBF_(), speciesUMeanBF_(), speciesErotBF_(), speciesZetaRotBF_(), speciesEvibBF_(), speciesEelecBF_(), speciesqBF_(), speciesfDBF_(), speciesEvibModBF_(), nParticlesOnStickingBoundaries_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), nAbsorbedParticles_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryT_ ( mesh_.boundary(), mesh_.V(), calculatedFvPatchScalarField::typeName ), boundaryU_ ( mesh_.boundary(), mesh_.C(), calculatedFvPatchVectorField::typeName ) { nParticlesOnStickingBoundaries_ = 0.0; nAbsorbedParticles_ = 0.0; } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // boundaryMeasurements::~boundaryMeasurements() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // void boundaryMeasurements::updatenStuckParticlesOnPatch ( const label patchi, const scalarList& pnStuckParticles ) { forAll(pnStuckParticles, facei) { nParticlesOnStickingBoundaries_[patchi][facei] = pnStuckParticles[facei]; } } void boundaryMeasurements::updatenAbsorbedParticlesOnPatch ( const label patchi, const label facei, const scalar nAbsorbedParticles ) { nAbsorbedParticles_[patchi][facei] += nAbsorbedParticles; } void boundaryMeasurements::setBoundaryT ( const label patchi, const scalarList& pboundaryT ) { forAll(pboundaryT, facei) { boundaryT_[patchi][facei] = pboundaryT[facei]; } } void boundaryMeasurements::setBoundaryU ( const label patchi, const vectorList& pboundaryU ) { forAll(pboundaryU, facei) { boundaryU_[patchi][facei] = pboundaryU[facei]; } } void boundaryMeasurements::setBoundarynStuckParticles ( const label patchi, const scalarList& pnStuckParticles ) { forAll(pnStuckParticles, facei) { nParticlesOnStickingBoundaries_[patchi][facei] = pnStuckParticles[facei]; } } void boundaryMeasurements::setBoundarynAbsorbedParticles ( const label patchi, const scalarList& pnAbsorbedParticles ) { forAll(pnAbsorbedParticles, facei) { nAbsorbedParticles_[patchi][facei] = pnAbsorbedParticles[facei]; } } void boundaryMeasurements::outputResults() { if (mesh_.time().outputTime()) { if (cloud_.boundaries().isAStickingPatch()) { writenStuckParticles(); } if (cloud_.boundaries().isAAbsorbingPatch()) { writenAbsorbedParticles(); } if (cloud_.boundaries().isAFieldPatch()) { writePatchFields(); } } } void boundaryMeasurements::setInitialConfig() { forAll(typeIds_, i) { typeIds_[i] = i; } reset(); } void boundaryMeasurements::clean() { //- clean geometric fields forAll(typeIds_, i) { forAll(speciesRhoNBF_[i], j) { speciesRhoNIntBF_[i][j] = 0.0; speciesRhoNElecBF_[i][j] = 0.0; speciesRhoNBF_[i][j] = 0.0; speciesRhoMBF_[i][j] = 0.0; speciesLinearKEBF_[i][j] = 0.0; speciesMccBF_[i][j] = 0.0; speciesMomentumBF_[i][j] = vector::zero; speciesUMeanBF_[i][j] = vector::zero; speciesErotBF_[i][j] = 0.0; speciesZetaRotBF_[i][j] = 0.0; speciesEvibBF_[i][j] = 0.0; speciesEelecBF_[i][j] = 0.0; speciesqBF_[i][j] = 0.0; speciesfDBF_[i][j] = vector::zero; } forAll(speciesEvibModBF_[i], mod) { forAll(speciesEvibModBF_[i][mod], j) { speciesEvibModBF_[i][mod][j] = 0.0; } } } forAll(nParticlesOnStickingBoundaries_, j) { nParticlesOnStickingBoundaries_[j] = 0.0; } } void boundaryMeasurements::reset() { //- reset sizes of the fields after mesh is changed const label nSpecies = typeIds_.size(); const label nPatches = mesh_.boundaryMesh().size(); speciesRhoNIntBF_.setSize(nSpecies); speciesRhoNElecBF_.setSize(nSpecies); speciesRhoNBF_.setSize(nSpecies); speciesRhoMBF_.setSize(nSpecies); speciesLinearKEBF_.setSize(nSpecies); speciesMccBF_.setSize(nSpecies); speciesMomentumBF_.setSize(nSpecies); speciesUMeanBF_.setSize(nSpecies); speciesErotBF_.setSize(nSpecies); speciesZetaRotBF_.setSize(nSpecies); speciesEvibBF_.setSize(nSpecies); speciesEelecBF_.setSize(nSpecies); speciesqBF_.setSize(nSpecies); speciesfDBF_.setSize(nSpecies); speciesEvibModBF_.setSize(nSpecies); forAll(typeIds_, i) { const label spId = typeIds_[i]; const label nVibMod = cloud_.constProps(spId).nVibrationalModes(); speciesRhoNIntBF_[i].setSize(nPatches); speciesRhoNElecBF_[i].setSize(nPatches); speciesRhoNBF_[i].setSize(nPatches); speciesRhoMBF_[i].setSize(nPatches); speciesLinearKEBF_[i].setSize(nPatches); speciesMccBF_[i].setSize(nPatches); speciesMomentumBF_[i].setSize(nPatches); speciesUMeanBF_[i].setSize(nPatches); speciesErotBF_[i].setSize(nPatches); speciesZetaRotBF_[i].setSize(nPatches); speciesEvibBF_[i].setSize(nPatches); speciesEelecBF_[i].setSize(nPatches); speciesqBF_[i].setSize(nPatches); speciesfDBF_[i].setSize(nPatches); speciesEvibModBF_[i].setSize(nVibMod); forAll(speciesEvibModBF_[i], mod) { speciesEvibModBF_[i][mod].setSize(nPatches); } forAll(speciesRhoNBF_[i], j) { const label nFaces = mesh_.boundaryMesh()[j].size(); speciesRhoNIntBF_[i][j].setSize(nFaces, 0.0); speciesRhoNElecBF_[i][j].setSize(nFaces, 0.0); speciesRhoNBF_[i][j].setSize(nFaces, 0.0); speciesRhoMBF_[i][j].setSize(nFaces, 0.0); speciesLinearKEBF_[i][j].setSize(nFaces, 0.0); speciesMccBF_[i][j].setSize(nFaces, 0.0); speciesMomentumBF_[i][j].setSize(nFaces, vector::zero); speciesUMeanBF_[i][j].setSize(nFaces, vector::zero); speciesErotBF_[i][j].setSize(nFaces, 0.0); speciesZetaRotBF_[i][j].setSize(nFaces, 0.0); speciesEvibBF_[i][j].setSize(nFaces, 0.0); speciesEelecBF_[i][j].setSize(nFaces, 0.0); speciesqBF_[i][j].setSize(nFaces, 0.0); speciesfDBF_[i][j].setSize(nFaces, vector::zero); } forAll(speciesEvibModBF_[i], mod) { forAll(speciesEvibModBF_[i][mod], j) { const label nFaces = mesh_.boundaryMesh()[j].size(); speciesEvibModBF_[i][mod][j].setSize(nFaces, 0.0); } } } nParticlesOnStickingBoundaries_.setSize(nPatches); nAbsorbedParticles_.setSize(nPatches); boundaryT_.setSize(nPatches); boundaryU_.setSize(nPatches); forAll(mesh_.boundaryMesh(), j) { const label nFaces = mesh_.boundaryMesh()[j].size(); nParticlesOnStickingBoundaries_[j].setSize(nFaces, 0.0); nAbsorbedParticles_[j].setSize(nFaces, 0.0); boundaryT_[j].setSize(nFaces, 0.0); boundaryU_[j].setSize(nFaces, vector::zero); } } void boundaryMeasurements::updateFields(dsmcParcel& p) {} } // End namespace Foam // ************************************************************************* //
vincentcasseau/hyStrath
src/lagrangian/dsmc/boundaryMeasurements/boundaryMeasurements.C
C++
gpl-3.0
12,830
//------------------------------------------------------------------------------ // Copyright (C) 2016 Josi Coder // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // You should have received a copy of the GNU General Public License along with // this program. If not, see <http://www.gnu.org/licenses/>. //-------------------------------------------------------------------------------- using System; using CtLab.Messages.Interfaces; using CtLab.SpiDirect.Interfaces; namespace CtLab.Device.Base { /// <summary> /// Provides access to a c't Lab device via the ct Lab protocol. /// </summary> public class SpiDirectDeviceConnection : DeviceConnectionBase { /// <summary> /// Initializes an instance of this class. /// </summary> /// <param name="setCommandClassDictionary">The dictonary used for the set command classes.</param> /// <param name="queryCommandClassDictionary">The dictonary used for the query command classes.</param> /// <param name="receivedMessagesCache">The message cache used to receive the messages.</param> public SpiDirectDeviceConnection(ISetCommandClassDictionary setCommandClassDictionary, IQueryCommandClassDictionary queryCommandClassDictionary, IMessageCache receivedMessagesCache) : base(setCommandClassDictionary, queryCommandClassDictionary, receivedMessagesCache) {} /// <summary> /// Gets the predicate used to determine which message channels are affected when detaching /// the c't Lab device from the command dictionaries and messages caches. /// </summary> protected override Func<IMessageChannel, bool> DetachPredicate { get { Func<IMessageChannel, bool> sameMainchannelPredicate = channel => { return true; }; return sameMainchannelPredicate; } } /// <summary> /// Creates a message channel for the specified FPGA register. /// </summary> /// <param name="registerNumber"> /// The number of the FPGA register to create the message channel vor. /// </param> /// <returns>The created message channel.</returns> protected override IMessageChannel CreateMessageChannel (ushort registerNumber) { return new MessageChannel((byte)registerNumber); } } }
JosiCoder/CtLab
Library/Device.Base/SpiDirectDeviceConnection.cs
C#
gpl-3.0
2,920
/********************************************************** * Version $Id: GSPoints_Distances.cpp 1921 2014-01-09 10:24:11Z oconrad $ *********************************************************/ /////////////////////////////////////////////////////////// // // // SAGA // // // // System for Automated Geoscientific Analyses // // // // Module Library: // // statistics_points // // // //-------------------------------------------------------// // // // GSPoints_Distances.cpp // // // // Copyright (C) 2010 by // // Olaf Conrad // // // //-------------------------------------------------------// // // // This file is part of 'SAGA - System for Automated // // Geoscientific Analyses'. SAGA is free software; you // // can redistribute it and/or modify it under the terms // // of the GNU General Public License as published by the // // Free Software Foundation; version 2 of the License. // // // // SAGA is distributed in the hope that it will be // // useful, but WITHOUT ANY WARRANTY; without even the // // implied warranty of MERCHANTABILITY or FITNESS FOR A // // PARTICULAR PURPOSE. See the GNU General Public // // License for more details. // // // // You should have received a copy of the GNU General // // Public License along with this program; if not, // // write to the Free Software Foundation, Inc., // // 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, // // USA. // // // //-------------------------------------------------------// // // // e-mail: oconrad@saga-gis.org // // // // contact: Olaf Conrad // // Institute of Geography // // University of Hamburg // // Germany // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #include "GSPoints_Distances.h" /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- CGSPoints_Distances::CGSPoints_Distances(void) { CSG_Parameter *pNode; //----------------------------------------------------- Set_Name (_TL("Minimum Distance Analysis")); Set_Author (SG_T("O.Conrad (c) 2010")); Set_Description( _TL("") ); //----------------------------------------------------- pNode = Parameters.Add_Shapes( NULL , "POINTS" , _TL("Points"), _TL(""), PARAMETER_INPUT, SHAPE_TYPE_Point ); Parameters.Add_Table( NULL , "TABLE" , _TL("Minimum Distance Analysis"), _TL(""), PARAMETER_OUTPUT ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #define SET_VALUE(s, v) { pRecord = pTable->Add_Record(); pRecord->Set_Value(0, s); pRecord->Set_Value(1, v); } //--------------------------------------------------------- bool CGSPoints_Distances::On_Execute(void) { //----------------------------------------------------- CSG_Shapes *pPoints = Parameters("POINTS") ->asShapes(); CSG_Table *pTable = Parameters("TABLE") ->asTable(); //----------------------------------------------------- CSG_PRQuadTree QT(pPoints, 0); CSG_Simple_Statistics s; double x, y, z; for(int iPoint=0; iPoint<pPoints->Get_Count() && Set_Progress(iPoint, pPoints->Get_Count()); iPoint++) { TSG_Point p = pPoints->Get_Shape(iPoint)->Get_Point(0); if( QT.Select_Nearest_Points(p.x, p.y, 2) && QT.Get_Selected_Point(1, x, y, z) && (x != p.x || y != p.y) ) { s.Add_Value(SG_Get_Distance(x, y, p.x, p.y)); } } //----------------------------------------------------- if( s.Get_Count() > 0 ) { CSG_Table_Record *pRecord; pTable->Destroy(); pTable->Set_Name(CSG_String::Format(SG_T("%s [%s]"), _TL("Minimum Distance Analysis"), pPoints->Get_Name())); pTable->Add_Field(SG_T("NAME") , SG_DATATYPE_String); pTable->Add_Field(SG_T("VALUE") , SG_DATATYPE_Double); SET_VALUE(_TL("Mean Average") , s.Get_Mean()); SET_VALUE(_TL("Minimum") , s.Get_Minimum()); SET_VALUE(_TL("Maximum") , s.Get_Maximum()); SET_VALUE(_TL("Standard Deviation") , s.Get_StdDev()); SET_VALUE(_TL("Duplicates") , pPoints->Get_Count() - s.Get_Count()); DataObject_Update(pTable, SG_UI_DATAOBJECT_SHOW); return( true ); } Message_Dlg(_TL("not enough observations")); return( false ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //---------------------------------------------------------
UoA-eResearch/saga-gis
saga-gis/src/modules/statistics/statistics_points/GSPoints_Distances.cpp
C++
gpl-3.0
6,210
$(document).ready(function () { // Open contact modal $('.contact').click(function(){ $('#contactModal').modal('toggle', { keyboard: false }).on('shown.bs.modal', function(){ var form = $('#ContactForm'); var submitButton = $('.submitContactForm'); submitButton.click(function(){ var email = $('#id_email'); var message = $('#id_message'); if(validateEmail(email.val()) && message.val() != ""){ //Valid information $.post( "/frontpage/contact/", form.serialize(), function(data){ if (data == 'True'){ $('#contactFormContainer').hide(); $('.submitContactForm').hide(); $('.contactformWarning').hide(); $('.contactformSuccess').show(); } else { $('.contactformWarning').show(); } }).fail(function() { $('.contactformWarning').show(); }); } else { //Not valid information $('.contactformWarning').show(); } }); }); }); // Validate email. function validateEmail($email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if( !emailReg.test( $email ) ) { return false; } else { return true; } } // Mobile messages var mobileUser = jQuery.browser.mobile; if (mobileUser){ $('.mobile-show').show(); $('.mobile-hide').hide(); } else { $('.mobile-show').hide(); $('.mobile-hide').show(); } });
Tacnet/Tacnet
tacnet/apps/base/static/js/base.js
JavaScript
gpl-3.0
1,991
/* * Copyright (c) Mirth Corporation. All rights reserved. * * http://www.mirthcorp.com * * The software in this package is published under the terms of the MPL license a copy of which has * been included with this distribution in the LICENSE.txt file. */ package com.mirth.connect.plugins; import com.mirth.connect.client.ui.editors.transformer.TransformerPane; public abstract class TransformerStepPlugin extends MirthEditorPanePlugin { public TransformerStepPlugin(String name) { super(name); } public abstract void initialize(TransformerPane pane); }
encapturemd/MirthConnect
client/src/com/mirth/connect/plugins/TransformerStepPlugin.java
Java
mpl-2.0
610
using System.Collections.Generic; using UniaraVirtual.Code.Model; namespace UniaraVirtual.Code { public class FaltaResponse { public string MessageResult { get; set; } public string RequestDate { get; set; } public int StatusCodeResult { get; set; } public List<Falta> DataResult { get; set; } } }
weberamaral/app-uniara-virtual
windowsphone/UniaraVirtual/Code/FaltaResponse.cs
C#
mpl-2.0
346
/** * Copyright (C), 2012 Adaptinet.org (Todd Fearn, Anthony Graffeo) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * */ package org.adaptinet.mimehandlers; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLDecoder; import java.security.MessageDigest; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; import org.adaptinet.http.HTTP; import org.adaptinet.http.Request; import org.adaptinet.http.Response; import org.adaptinet.socket.PropData; import org.adaptinet.transceiver.ITransceiver; public class MimeHTML_HTTP implements MimeBase { private String url = null; private String urlBase = null; private String webBase = null; private String mimeType = null; private String pathName = null; private ITransceiver transceiver = null; private int status = 200; private boolean bAdminPort = false; static private String PLUGIN_ENTRY = "plugins/plugin?entry="; static private String PEER_ENTRY = "peers/peer?entry="; static private int PLUGIN_ENTRYLEN = 0; static private int PEER_ENTRYLEN = 0; static final String footer = "<br><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" " + "width=\"100%\" ><tr><td width=\"127\" class=\"footerorange\">" + "<IMG height=\"1\" src=\"/images/space.gif\" width=\"127\"></td><td width=\"400\" " + "class=\"footerorange\"><IMG height=\"1\" src=\"/images/space.gif\" width=\"400\"></td>" + "<td width=\"100%\" class=\"footerorange\"><IMG height=\"1\" src=\"/images/space.gif\" " + "width=\"1\"></td></tr><tr><td width=\"127\" class=\"footerorange\">" + "<IMG height=27 src=\"/images/space.gif\" width=127></td><td align=\"left\" " + "class=\"footerorange\" nowrap>25 B Vreeland Rd. Suite 103, Florham Park, NJ" + " 07932 &nbsp;&nbsp;&nbsp; 973-451-9600 &nbsp; fx 973-439-1745</td>" + "<td width=\"100%\" class=\"footerorange\"><IMG height=27 " + "src=\"/images/space.gif\" width=1></td></tr><tr><td width=\"127\">" + "<IMG height=1 src=\"/images/space.gif\" width=127></td><td align=\"left\" " + "class=\"footer\" nowrap>all materials © Adaptinet Inc. All rights reserved.</td>" + "<td align=\"right\" width=\"100%\" class=\"footer\" nowrap>" + "<A class=\"footerlink\" href=\"#\">contact Adaptinet</A> &nbsp;|&nbsp;" + " <A class=\"footerlink\" href=\"#\">support</A> &nbsp;</td></tr></table><br><br><br><br>"; static { PLUGIN_ENTRYLEN = PLUGIN_ENTRY.length(); PEER_ENTRYLEN = PEER_ENTRY.length(); } public MimeHTML_HTTP() { } public void init(String u, ITransceiver s) { transceiver = s; urlBase = s.getHTTPRoot(); webBase = s.getWebRoot(); if (urlBase == null || urlBase.equals(".")) { urlBase = System.getProperty("user.dir", ""); } if (!urlBase.endsWith(File.separator)) urlBase += File.separator; if (webBase == null || webBase.equals(".")) { webBase = System.getProperty("user.dir", ""); } if (!webBase.endsWith(File.separator)) webBase += File.separator; url = u; parseUrl(); } private void parseUrl() { try { pathName = URLDecoder.decode(url, "UTF-8"); } catch (Exception e) { pathName = url; } if (pathName.endsWith("/")) pathName += "index.html"; if (pathName.startsWith("/")) pathName = pathName.substring(1); int dot = pathName.indexOf("."); if (dot > 0) { String ext = pathName.substring(dot + 1); setMimeForExt(ext); } else mimeType = HTTP.contentTypeHTML; } public String getContentType() { return mimeType; } private void setMimeForExt(String ext) { if (ext.equalsIgnoreCase("jpg")) mimeType = HTTP.contentTypeJPEG; else if (ext.equalsIgnoreCase("htm") || ext.equalsIgnoreCase("html")) mimeType = HTTP.contentTypeHTML; else if (ext.equalsIgnoreCase("gif")) mimeType = HTTP.contentTypeGIF; else if (ext.equalsIgnoreCase("xsl")) mimeType = HTTP.contentTypeXML; else mimeType = HTTP.contentTypeHTML; } public ByteArrayOutputStream process(ITransceiver transceiver, Request request) { // note: this process has gotten pretty big, really fast // need to revisit the exception handling here, there is a better way File file = null; String monitor = null; long length = 0; try { bAdminPort = (request.getPort() == transceiver.getAdminPort()); status = isAuthorized(request.getUsername(), request.getPassword()); if (!bAdminPort) { // non-admin port are regular html requests... String base = webBase; if (bAdminPort) base = urlBase; file = new File(base + pathName); if (file.isFile() == false || !file.canRead()) throw new FileNotFoundException(); else length = file.length(); } else { if (pathName.equalsIgnoreCase("configuration.html")) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); monitor = getConfiguration(transceiver); System.out.println(monitor); if (monitor != null) length = monitor.length(); else status = HTTP.NOT_FOUND; } else if (pathName.equalsIgnoreCase("monitor.html")) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); try { monitor = getMonitor(); length = monitor.length(); } catch (Exception e) { monitor = e.getMessage(); status = HTTP.INTERNAL_SERVER_ERROR; } catch (Throwable t) { monitor = t.getMessage(); status = HTTP.INTERNAL_SERVER_ERROR; } } else if (pathName.equalsIgnoreCase("plugins.html")) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); monitor = getPlugins(transceiver); if (monitor != null) length = monitor.length(); else status = HTTP.INTERNAL_SERVER_ERROR; } else if (pathName.equalsIgnoreCase("peers.html")) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); monitor = getPeers(transceiver); if (monitor != null) length = monitor.length(); else status = HTTP.INTERNAL_SERVER_ERROR; } else if (pathName.startsWith(PLUGIN_ENTRY)) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); if (pathName.length() > PLUGIN_ENTRYLEN) monitor = getPluginEntry(transceiver, pathName .substring(PLUGIN_ENTRYLEN)); else monitor = getPluginEntry(transceiver, ""); if (monitor != null) length = monitor.length(); else status = HTTP.NOT_FOUND; } else if (pathName.startsWith(PEER_ENTRY)) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); if (pathName.length() > PEER_ENTRYLEN) monitor = getPeerEntry(transceiver, pathName .substring(PEER_ENTRYLEN)); else monitor = getPeerEntry(transceiver, ""); if (monitor != null) length = monitor.length(); else status = HTTP.NOT_FOUND; } else if (pathName.startsWith("setadmin?")) { if (status == HTTP.UNAUTHORIZED || bAdminPort == false) throw new IllegalAccessException(); monitor = setAdmin(pathName.substring(9), request); length = monitor.length(); } else // files { String base = webBase; if (bAdminPort) base = urlBase; file = new File(base + pathName); if (file.isFile() == false || !file.canRead()) throw new FileNotFoundException(); else length = file.length(); } } } catch (IOException e) { status = HTTP.NOT_FOUND; } catch (IllegalAccessException iae) { status = HTTP.UNAUTHORIZED; } catch (Exception e) { status = HTTP.INTERNAL_SERVER_ERROR; } try { Response resp = new Response(request.getOutStream(), transceiver .getHost(), mimeType); resp.setResponse(new ByteArrayOutputStream()); resp.setStatus(status); resp.writeHeader(length); if (status != HTTP.OK) return null; BufferedOutputStream out = new BufferedOutputStream(request .getOutStream()); if (file != null) { BufferedInputStream in = new BufferedInputStream( new FileInputStream(file)); byte[] bytes = new byte[255]; while (true) { int read = in.read(bytes); if (read < 0) break; out.write(bytes, 0, read); } in.close(); } else if (monitor != null) { out.write(monitor.getBytes()); } out.flush(); } catch (Exception e) { } return null; } public static String getPlugins(ITransceiver transceiver) { try { return PluginXML.getEntries(transceiver); } catch (Exception e) { return null; } } public static String getPeers(ITransceiver transceiver) { try { return PeerXML.getEntries(transceiver); } catch (Exception e) { return null; } } public static String getConfiguration(ITransceiver transceiver) { try { return TransceiverConfiguration.getConfiguration(transceiver); } catch (Exception e) { return null; } } public static String getPluginEntry(ITransceiver transceiver, String entry) { try { return PluginXML.getEntry(transceiver, entry); } catch (Exception e) { return null; } } public static String getPeerEntry(ITransceiver transceiver, String peer) { try { return PeerXML.getEntry(transceiver, peer); } catch (Exception e) { return null; } } public static String getLicenseKey(ITransceiver transceiver) { try { // return // simpleTransform.transform(licensingXML.getLicense(transceiver), // transceiver.getHTTPRoot() + "/licensing.xsl"); return null; } catch (Exception e) { return null; } } private String setAdmin(String params, Request request) { try { StringTokenizer tokenizer = new StringTokenizer(params, "&"); int size = tokenizer.countTokens() * 2; String token = null; Properties properties = new Properties(); for (int i = 0; i < size; i += 2) { if (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); int loc = token.indexOf('='); properties.setProperty(token.substring(0, loc), token .substring(loc + 1, token.length())); } } String userid = properties.getProperty("userid"); String current = properties.getProperty("current"); String password = properties.getProperty("password"); String confirm = properties.getProperty("password2"); // check current password here if (isAuthorized(request.getUsername(), current) == HTTP.UNAUTHORIZED) return "<H2>The current password is incorrect for user: " + request.getUsername() + "</H2>"; if (!password.equals(confirm)) return "<H2>The password does not match the confirm password</H2>"; if (password.equals("")) return "<H2>The password cannot be empty.</H2>"; MessageDigest md = MessageDigest.getInstance("MD5"); String digest = new String(md.digest(password.getBytes())); String userpass = userid + ":" + digest; String authfile = urlBase + ".xbpasswd"; FileOutputStream fs = new FileOutputStream(authfile); fs.write(userpass.getBytes()); fs.close(); return "<H2>Change password success for " + userid + "</H2>"; } catch (Exception e) { } return "<H2>Change password failure.</H2>"; } public int getStatus() { return status; } private int isAuthorized(String username, String password) { try { if (!bAdminPort) return HTTP.OK; String authfile = urlBase + ".xbpasswd"; File file = new File(authfile); if (!file.isFile()) return HTTP.OK; BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String userpass = br.readLine(); br.close(); StringTokenizer st = new StringTokenizer(userpass, ":"); String user = st.hasMoreTokens() ? st.nextToken() : ""; String pass = st.hasMoreTokens() ? st.nextToken() : ""; MessageDigest md = MessageDigest.getInstance("MD5"); String digest = new String(md.digest(password != null ? password .getBytes() : "".getBytes())); if (user.equals(username) && pass.equals(digest)) return HTTP.OK; } catch (IOException ioe) { } catch (NullPointerException npe) { } catch (Exception e) { e.printStackTrace(); } return HTTP.UNAUTHORIZED; } String getMonitor() { StringBuffer buffer = new StringBuffer(); try { Vector<PropData> vec = transceiver.requestList(); buffer.append("<html><head><title>Status</title>"); buffer.append("<link rel=\"Stylesheet\" href=\"/style.css\">"); buffer.append("<script language=\"JavaScript\" src=\"/css.js\"></script></head>"); buffer.append("<body BGCOLOR=\"#FFFFFF\">"); buffer.append("<TABLE cellPadding=0 cellSpacing=0 border=0 WIDTH=\"500\"<tr><TD><IMG alt=\"\" src=\"images/empty.gif\" width=30 border=0></TD><td>"); buffer.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"); buffer.append("<tr valign=\"top\" class=\"header\">"); buffer.append("<td>Plugin Name</td>"); buffer.append("<td>System ID</td>"); buffer.append("<td>Status</td>"); buffer.append("<td>Control</td></tr>"); Enumeration<PropData> e = vec.elements(); while (e.hasMoreElements()) { PropData data = e.nextElement(); buffer.append("<tr class=\"text\">"); buffer.append("<td><strong>"); buffer.append(data.getName()); buffer.append("</strong></td>"); buffer.append("<td>"); buffer.append(data.getId()); buffer.append("</td>"); buffer.append("<td>"); buffer.append(data.getState()); buffer.append("</td>"); buffer.append("<td>"); buffer.append("<FORM Method=\"POST\" Action=\"\">"); buffer .append("<INPUT type=\"hidden\" name=\"command\" value=\"killrequest\"></INPUT>"); buffer .append("<INPUT TYPE=\"Submit\" value=\" Kill \"></INPUT>"); buffer .append("<INPUT type=\"checkbox\" name=\"Force\" value=\"true\">Force</INPUT>"); buffer.append("<INPUT type=\"hidden\" "); buffer.append("name=\"SYSTEMID\" "); buffer.append("value=\">"); buffer.append(data.getId()); buffer.append("\"></INPUT>"); buffer.append("<INPUT type=\"hidden\" "); buffer.append("name=\"Name\" "); buffer.append("value=\">"); buffer.append(data.getName()); buffer.append("\"></INPUT>"); buffer.append("</td>"); } buffer.append("</FORM>"); buffer.append("</table></td></tr></table>"); buffer.append(footer); buffer.append("</body>"); buffer.append("</html>"); } catch (Exception e) { return null; } return buffer.toString(); } }
tfearn/AdaptinetSDK
src/org/adaptinet/mimehandlers/MimeHTML_HTTP.java
Java
mpl-2.0
15,471
package msd import ( "encoding/base64" "github.com/bluefw/blued/discoverd/api" "github.com/gin-gonic/gin" "log" "net/http" ) type ServiceResource struct { repo *DiscoverdRepo logger *log.Logger } func NewServiceResource(dr *DiscoverdRepo, l *log.Logger) *ServiceResource { return &ServiceResource{ repo: dr, logger: l, } } func (sr *ServiceResource) RegMicroApp(c *gin.Context) { var as api.MicroApp if err := c.Bind(&as); err != nil { c.JSON(http.StatusBadRequest, api.NewError("problem decoding body")) return } sr.repo.Register(&as) c.JSON(http.StatusCreated, nil) } func (sr *ServiceResource) GetRouterTable(c *gin.Context) { addr, err := base64.StdEncoding.DecodeString(c.Params.ByName("addr")) if err != nil { c.JSON(http.StatusBadRequest, api.NewError("error decoding addr")) return } rt := sr.repo.GetRouterTable(string(addr)) c.JSON(http.StatusOK, rt) } func (sr *ServiceResource) Refresh(c *gin.Context) { addr, err := base64.StdEncoding.DecodeString(c.Params.ByName("addr")) if err != nil { c.JSON(http.StatusBadRequest, api.NewError("error decoding addr")) return } appStatus := sr.repo.Refresh(string(addr)) c.JSON(http.StatusAccepted, appStatus) }
bluefw/blued
discoverd/msd/msd_rs.go
GO
mpl-2.0
1,213
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. package databasemanagement import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) // ResetDatabaseParametersRequest wrapper for the ResetDatabaseParameters operation // // See also // // Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/databasemanagement/ResetDatabaseParameters.go.html to see an example of how to use ResetDatabaseParametersRequest. type ResetDatabaseParametersRequest struct { // The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. ManagedDatabaseId *string `mandatory:"true" contributesTo:"path" name:"managedDatabaseId"` // The details required to reset database parameters. ResetDatabaseParametersDetails `contributesTo:"body"` // The client request ID for tracing. OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` // A token that uniquely identifies a request so it can be retried in case of a timeout or // server error without risk of executing that same action again. Retry tokens expire after 24 // hours, but can be invalidated before then due to conflicting operations. For example, if a resource // has been deleted and purged from the system, then a retry of the original creation request // might be rejected. OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` // Metadata about the request. This information will not be transmitted to the service, but // represents information that the SDK will consume to drive retry behavior. RequestMetadata common.RequestMetadata } func (request ResetDatabaseParametersRequest) String() string { return common.PointerString(request) } // HTTPRequest implements the OCIRequest interface func (request ResetDatabaseParametersRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } // BinaryRequestBody implements the OCIRequest interface func (request ResetDatabaseParametersRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } // RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy. func (request ResetDatabaseParametersRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } // ResetDatabaseParametersResponse wrapper for the ResetDatabaseParameters operation type ResetDatabaseParametersResponse struct { // The underlying http response RawResponse *http.Response // The UpdateDatabaseParametersResult instance UpdateDatabaseParametersResult `presentIn:"body"` // Unique Oracle-assigned identifier for the request. If you need to contact // Oracle about a particular request, please provide the request ID. OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response ResetDatabaseParametersResponse) String() string { return common.PointerString(response) } // HTTPResponse implements the OCIResponse interface func (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response { return response.RawResponse }
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/databasemanagement/reset_database_parameters_request_response.go
GO
mpl-2.0
3,604
/** * @fileOverview scripts about the frontpage. */ var calendarth = require('calendarth'); var util = require('./util'); var Front = module.exports = function() { this.$agendaContainer = null; this.$agendaItem = null; this.$error = null; }; /** @const {number} Maximum events to display, use an even number */ Front.MAX_EVENTS_SHOW = 10; /** * Initialize the frontpage view. * */ Front.prototype.init = function() { this.$agendaContainer = $('#agenda-items'); this.$agendaItem = $('#agenda-tpl'); this.$error = $('#agenda-error'); this.calendarth = calendarth({ apiKey: window.serv.calendarApiKey, calendarId: window.serv.callendarId, maxResults: 12 }); this.calendarth.fetch(this._handleCalResult.bind(this)); this._fixPanels(); }; /** * A temp fix for panels height. * * @private */ Front.prototype._fixPanels = function() { var max = 0; $('.panel-info').each(function() { var currentHeight = $(this).height(); if (currentHeight > max) { max = currentHeight; } }); $('.panel-info').height(max); }; /** * Handle incoming calendarth data. * * @param {?string|Error} err Possible error message. * @param {Object=} data The calendar data object. * @private */ Front.prototype._handleCalResult = function(err, data) { this.$agendaContainer.empty(); if (err) { this.$agendaContainer.append(this.$error.clone().removeClass('hide')); return; } var meetups = []; var displayed = 0; var elements = '<div class="row">'; data.items.forEach(function(item) { if (displayed >= Front.MAX_EVENTS_SHOW) { return; } if (meetups.indexOf(item.summary) > -1) { return; } else { meetups.push(item.summary); } if (displayed && displayed % 2 === 0) { // rows elements += '</div><div class="row">'; } elements += this._assignValues(this.$agendaItem.clone(), item); displayed++; }, this); elements += '</div>'; this.$agendaContainer.append(elements); }; /** * Assign the Calendar item values to the Calendar item element. * * @param {jQuery} $item A jquery item we will manipulate. * @param {Object} item [description] * @return {string} The html representation. * @private */ Front.prototype._assignValues = function($item, item) { $item.removeClass('hide'); $item.find('.panel-title').text(item.summary); var data = this._parseDesc(item.description); $item.find('.agenda-tpl-when span').text(util.formatDate(item.start, item.end)); var location = ''; if (data.mapUrl) { location = '<a href="' + data.mapUrl + '" target="_blank">'; location += item.location; location += '</a>'; } else { location = item.location; } $item.find('.agenda-tpl-address span').html(location); if (data.venue) { $item.find('.agenda-tpl-venue span').text(data.venue); } else { $item.find('.agenda-tpl-venue').addClass('hide'); } if (data.infoUrl) { var infoUrl = ''; if (data.infoUrl.length > 25) { infoUrl = data.infoUrl.substr(0, 25) + '...'; } else { infoUrl = data.infoUrl; } $item.find('.agenda-tpl-info a').attr('href', data.infoUrl).text(infoUrl); } else { $item.find('.agenda-tpl-info').addClass('hide'); } if (data.about) { $item.find('.agenda-tpl-about span').html(data.about); } else { $item.find('.agenda-tpl-about').addClass('hide'); } if (data.language) { $item.find('.agenda-tpl-language span').html(data.language); } else { $item.find('.agenda-tpl-language').addClass('hide'); } var eventUrl = this.calendarth.getEventUrl(item); $item.find('.addcal').attr('href', eventUrl); $item.find('.viewcal').attr('href', item.htmlLink); return $item.html(); }; /** * Parse the description and generated info. * * @param {string} descr The description * @return {Object} An object containing the following properties: * venue {?string} The venue where the event happens or null. * info {?string} The informational url or null. * map {?string} The map url or null. * language {?string} The event language. * @private */ Front.prototype._parseDesc = function(descr) { var out = { venue: null, infoUrl: null, mapUrl: null, about: null, language: null, rest: '' }; if (!descr) { return out; } var lines = descr.split('\n'); lines.forEach(function(line) { if (!line.length) { return; } var splitPos = line.indexOf(':'); if (splitPos === -1) { return; } var key = line.substr(0, splitPos).toLowerCase().trim(); var value = line.substr(splitPos + 1).trim(); switch(key) { case 'venue': out.venue = value; break; case 'info': out.infoUrl = value; break; case 'map': out.mapUrl = value; break; case 'about': out.about = value; break; case 'language': out.language = value; break; default: out.rest += line + '<br />'; break; } }, this); return out; };
WeAreTech/wearetech.io
front/js-city/frontpage.js
JavaScript
mpl-2.0
5,035
package gocdn import ( "io/ioutil" "os" "path" "log" ) func cacheFile(fileName string, data []byte) (err error){ fileName = path.Clean(fileName) dir := path.Dir(fileName) if err = os.MkdirAll(dir, os.FileMode(0775)); err != nil { log.Printf("Could not create directory: %s", dir) return } if err = ioutil.WriteFile(fileName, data, 0644); err != nil { log.Printf("Could not write file: %s", dir) return } return }
bradberger/gocdn
cache.go
GO
mpl-2.0
466
package org.osmdroid.bonuspack.utils; import java.util.LinkedHashMap; import android.graphics.Bitmap; import android.util.Log; /** * Simple memory cache for handling images loaded from the web. * The url is the key. * @author M.Kergall */ public class WebImageCache { LinkedHashMap<String, Bitmap> mCacheMap; int mCapacity; public WebImageCache(int maxItems) { mCapacity = maxItems; mCacheMap = new LinkedHashMap<String, Bitmap>(maxItems+1, 1.1f, true){ private static final long serialVersionUID = -4831331496601290979L; protected boolean removeEldestEntry(Entry<String, Bitmap> eldest) { return size() > mCapacity; } }; } private void putInCache(String url, Bitmap image){ synchronized(mCacheMap){ mCacheMap.put(url, image); } //Log.d(BonusPackHelper.LOG_TAG, "WebImageCache:updateCache size="+mCacheMap.size()); } /** * get the image, either from the cache, or from the web if not in the cache. * Can be called by multiple threads. * If 2 threads ask for the same url simultaneously, this could put the image twice in the cache. * => TODO, have a "queue" of current requests. * @param url of the image * @return the image, or null if any failure. */ public Bitmap get(String url){ Bitmap image; synchronized(mCacheMap) { image = mCacheMap.get(url); } if (image == null){ Log.d(BonusPackHelper.LOG_TAG, "WebImageCache:load :"+url); image = BonusPackHelper.loadBitmap(url); if (image != null){ putInCache(url, image); } } return image; } }
dimy93/sports-cubed-android
OSMBonusPack/src/org/osmdroid/bonuspack/utils/WebImageCache.java
Java
mpl-2.0
1,601
/* * Copyright (c) 2014 Universal Technical Resource Services, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ATMLCommonLibrary.controls.limit { partial class SingleLimitSimpleControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.simpleLimitControl = new ATMLCommonLibrary.controls.limit.SimpleLimitControl(); this.lblLimitString = new System.Windows.Forms.Label(); this.SuspendLayout(); // // simpleLimitControl // this.simpleLimitControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.simpleLimitControl.LimitName = "Limit"; this.simpleLimitControl.Location = new System.Drawing.Point(0, 3); this.simpleLimitControl.Name = "simpleLimitControl"; this.simpleLimitControl.SchemaTypeName = null; this.simpleLimitControl.ShowTitle = true; this.simpleLimitControl.Size = new System.Drawing.Size(452, 43); this.simpleLimitControl.TabIndex = 0; this.simpleLimitControl.TargetNamespace = null; // // lblLimitString // this.lblLimitString.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblLimitString.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblLimitString.Location = new System.Drawing.Point(15, 53); this.lblLimitString.Name = "lblLimitString"; this.lblLimitString.Size = new System.Drawing.Size(424, 105); this.lblLimitString.TabIndex = 1; // // SingleLimitSimpleControl // this.Controls.Add(this.lblLimitString); this.Controls.Add(this.simpleLimitControl); this.MinimumSize = new System.Drawing.Size(455, 175); this.Name = "SingleLimitSimpleControl"; this.Size = new System.Drawing.Size(455, 175); this.ResumeLayout(false); } #endregion private SimpleLimitControl simpleLimitControl; private System.Windows.Forms.Label lblLimitString; } }
UtrsSoftware/ATMLWorkBench
ATMLLibraries/ATMLCommonLibrary/controls/limit/SingleLimitSimpleControl.Designer.cs
C#
mpl-2.0
3,620
# frozen_string_literal: true class Invoice < ActiveRecord::Base class ReadOnlyError < StandardError; end belongs_to :publisher belongs_to :uploaded_by, class_name: "Publisher" belongs_to :paid_by, class_name: "Publisher" belongs_to :finalized_by, class_name: "Publisher" has_many :invoice_files, -> { order(created_at: :desc) } URL_DATE_FORMAT = "%Y-%m" IN_PROGRESS = "in progress" PENDING = "pending" PAID = "paid" STATUS_FIELDS = [PENDING, PAID, IN_PROGRESS].freeze validates :publisher_id, :date, presence: true validates :status, inclusion: { in: STATUS_FIELDS } validates :date, uniqueness: { scope: :publisher_id } # Ensure these two values are numbers even though field is a string validates :amount, numericality: true, allow_nil: true validates :finalized_amount, numericality: true, allow_blank: true def human_date if date.day == 1 date.strftime("%B %Y") else date.strftime("%B %d, %Y") end end def in_progress? status == IN_PROGRESS end def pending? status == PENDING end def paid? status == PAID end def finalized_amount_to_probi if finalized_amount (finalized_amount.tr(",", "").to_d * BigDecimal("1.0e18")).to_i else 0 end end def as_json(_options = {}) { id: id, amount: amount, status: status.titleize, date: human_date, url: Rails.application.routes.url_helpers.partners_payments_invoice_path(date.in_time_zone("UTC").strftime(URL_DATE_FORMAT)), files: invoice_files.where(archived: false).as_json.compact, paid: paid?, paymentDate: payment_date, finalizedAmount: finalized_amount, createdAt: created_at.strftime("%b %d, %Y"), } end end
brave/publishers
app/models/invoice.rb
Ruby
mpl-2.0
1,758
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.commons.io.mmap; import java.io.IOException; import java.nio.file.Path; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public interface MemoryMappedFileFactory { MemoryMappedFile create(Path path) throws IOException; }
itesla/ipst-core
commons/src/main/java/eu/itesla_project/commons/io/mmap/MemoryMappedFileFactory.java
Java
mpl-2.0
600
package net.minecraft.entity.ai; import net.minecraft.entity.EntityCreature; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.village.Village; import net.minecraft.village.VillageDoorInfo; public class EntityAIMoveIndoors extends EntityAIBase { private final EntityCreature entityObj; private VillageDoorInfo doorInfo; private int insidePosX = -1; private int insidePosZ = -1; public EntityAIMoveIndoors(EntityCreature entityObjIn) { this.entityObj = entityObjIn; this.setMutexBits(1); } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { BlockPos blockpos = new BlockPos(this.entityObj); if ((!this.entityObj.world.isDaytime() || this.entityObj.world.isRaining() && !this.entityObj.world.getBiome(blockpos).canRain()) && this.entityObj.world.provider.hasSkyLight()) { if (this.entityObj.getRNG().nextInt(50) != 0) { return false; } else if (this.insidePosX != -1 && this.entityObj.getDistanceSq((double)this.insidePosX, this.entityObj.posY, (double)this.insidePosZ) < 4.0D) { return false; } else { Village village = this.entityObj.world.getVillageCollection().getNearestVillage(blockpos, 14); if (village == null) { return false; } else { this.doorInfo = village.getDoorInfo(blockpos); return this.doorInfo != null; } } } else { return false; } } /** * Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return !this.entityObj.getNavigator().noPath(); } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.insidePosX = -1; BlockPos blockpos = this.doorInfo.getInsideBlockPos(); int i = blockpos.getX(); int j = blockpos.getY(); int k = blockpos.getZ(); if (this.entityObj.getDistanceSq(blockpos) > 256.0D) { Vec3d vec3d = RandomPositionGenerator.findRandomTargetBlockTowards(this.entityObj, 14, 3, new Vec3d((double)i + 0.5D, (double)j, (double)k + 0.5D)); if (vec3d != null) { this.entityObj.getNavigator().tryMoveToXYZ(vec3d.xCoord, vec3d.yCoord, vec3d.zCoord, 1.0D); } } else { this.entityObj.getNavigator().tryMoveToXYZ((double)i + 0.5D, (double)j, (double)k + 0.5D, 1.0D); } } /** * Resets the task */ public void resetTask() { this.insidePosX = this.doorInfo.getInsideBlockPos().getX(); this.insidePosZ = this.doorInfo.getInsideBlockPos().getZ(); this.doorInfo = null; } }
lucemans/ShapeClient-SRC
net/minecraft/entity/ai/EntityAIMoveIndoors.java
Java
mpl-2.0
3,231
import { gql } from 'apollo-server-core'; export const memoryUsageSchema = gql` "Quantity of memory used for some computation." type MemoryUsage { "Quantity of memory expressed in bytes." bytes: Float! } "Field containing a memory usage, i.e., the quantity of memory used for some computation." type MemoryUsageField implements HasValence { "The memory usage, if known." memoryUsage: MemoryUsage "Maximum value over which the precise quantity of memory used is not relevant anymore." memoryUsageMaxRelevant: MemoryUsage! "Main upper limit on this memory usage to show users, if any." memoryUsagePrimaryWatermark: MemoryUsage valence: Valence } "Column containing memory usages." type MemoryUsageColumn implements TitledColumn { title: Text! } `;
algorithm-ninja/task-wizard
server/src/core/feedback/memory-usage.ts
TypeScript
mpl-2.0
866
/* Copyright (c) 2015, Digi International Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /***************************************************** puts.c This program writes a null terminated string over serial port B. It must be run with a serial utility such as Hyperterminal. Connect RS232 cable from PC to Rabbit: Connect PC's RS232 GND to Rabbit GND Connect PC's RS232 TD to Rabbit RXB Connect PC's RS232 RD to Rabbit TXB Configure the serial utility for port connected to RS232, 19200 8N1. Run Hyperterminal. Run this program. ******************************************************/ #class auto /***************************************************** The input and output buffers sizes are defined here. If these are not defined to be (2^n)-1, where n = 1...15, or they are not defined at all, they will default to 31 and a compiler warning will be displayed. ******************************************************/ #define BINBUFSIZE 15 #define BOUTBUFSIZE 15 void main() { static const char s[] = "Hello Z-World\r\n"; serBopen(19200); serBputs(s); // first, wait until the serial buffer is empty while (serBwrFree() != BOUTBUFSIZE) ; // then, wait until the Tx data register and the Tx shift register // are both empty while (BitRdPortI(SBSR, 3) || BitRdPortI(SBSR, 2)); // now we can close the serial port without cutting off Tx data serBclose(); }
digidotcom/DCRabbit_9
Samples/RCM2200/PUTS.C
C++
mpl-2.0
2,216
package aws import ( "fmt" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/terraform" ) func TestAccAWSEbsSnapshotCopy_basic(t *testing.T) { var snapshot ec2.Snapshot resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfig, Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`snapshot/snap-.+`)), ), }, }, }) } func TestAccAWSEbsSnapshotCopy_tags(t *testing.T) { var snapshot ec2.Snapshot resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfigTags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { Config: testAccAwsEbsSnapshotCopyConfigTags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { Config: testAccAwsEbsSnapshotCopyConfigTags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, }) } func TestAccAWSEbsSnapshotCopy_withDescription(t *testing.T) { var snapshot ec2.Snapshot resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfigWithDescription, Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttr(resourceName, "description", "Copy Snapshot Acceptance Test"), ), }, }, }) } func TestAccAWSEbsSnapshotCopy_withRegions(t *testing.T) { var providers []*schema.Provider var snapshot ec2.Snapshot resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) testAccMultipleRegionsPreCheck(t) testAccAlternateRegionPreCheck(t) }, ProviderFactories: testAccProviderFactories(&providers), CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfigWithRegions, Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), ), }, }, }) } func TestAccAWSEbsSnapshotCopy_withKms(t *testing.T) { var snapshot ec2.Snapshot kmsKeyResourceName := "aws_kms_key.test" resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfigWithKms, Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), ), }, }, }) } func TestAccAWSEbsSnapshotCopy_disappears(t *testing.T) { var snapshot ec2.Snapshot resourceName := "aws_ebs_snapshot_copy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckEbsSnapshotCopyDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEbsSnapshotCopyConfig, Check: resource.ComposeTestCheckFunc( testAccCheckEbsSnapshotCopyExists(resourceName, &snapshot), testAccCheckResourceDisappears(testAccProvider, resourceAwsEbsSnapshotCopy(), resourceName), ), ExpectNonEmptyPlan: true, }, }, }) } func testAccCheckEbsSnapshotCopyDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_ebs_snapshot_copy" { continue } resp, err := conn.DescribeSnapshots(&ec2.DescribeSnapshotsInput{ SnapshotIds: []*string{aws.String(rs.Primary.ID)}, }) if isAWSErr(err, "InvalidSnapshot.NotFound", "") { continue } if err == nil { for _, snapshot := range resp.Snapshots { if aws.StringValue(snapshot.SnapshotId) == rs.Primary.ID { return fmt.Errorf("EBS Snapshot still exists") } } } return err } return nil } func testAccCheckEbsSnapshotCopyExists(n string, v *ec2.Snapshot) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.Meta().(*AWSClient).ec2conn input := &ec2.DescribeSnapshotsInput{ SnapshotIds: []*string{aws.String(rs.Primary.ID)}, } output, err := conn.DescribeSnapshots(input) if err != nil { return err } if output == nil || len(output.Snapshots) == 0 { return fmt.Errorf("Error finding EC2 Snapshot %s", rs.Primary.ID) } *v = *output.Snapshots[0] return nil } } const testAccAwsEbsSnapshotCopyConfig = ` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "current" {} resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = 1 } resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "testAccAwsEbsSnapshotCopyConfig" } } resource "aws_ebs_snapshot_copy" "test" { source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.current.name}" } ` func testAccAwsEbsSnapshotCopyConfigTags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "current" {} resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = 1 } resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "testAccAwsEbsSnapshotCopyConfig" } } resource "aws_ebs_snapshot_copy" "test" { source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.current.name}" tags = { Name = "testAccAwsEbsSnapshotCopyConfig" "%s" = "%s" } } `, tagKey1, tagValue1) } func testAccAwsEbsSnapshotCopyConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "current" {} resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = 1 } resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "testAccAwsEbsSnapshotCopyConfig" } } resource "aws_ebs_snapshot_copy" "test" { source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.current.name}" tags = { Name = "testAccAwsEbsSnapshotCopyConfig" "%s" = "%s" "%s" = "%s" } } `, tagKey1, tagValue1, tagKey2, tagValue2) } const testAccAwsEbsSnapshotCopyConfigWithDescription = ` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "current" {} resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = 1 tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithDescription" } } resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" description = "EBS Snapshot Acceptance Test" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithDescription" } } resource "aws_ebs_snapshot_copy" "test" { description = "Copy Snapshot Acceptance Test" source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.current.name}" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithDescription" } } ` var testAccAwsEbsSnapshotCopyConfigWithRegions = testAccAlternateRegionProviderConfig() + ` data "aws_availability_zones" "alternate_available" { provider = "aws.alternate" state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "alternate" { provider = "aws.alternate" } resource "aws_ebs_volume" "test" { provider = "aws.alternate" availability_zone = "${data.aws_availability_zones.alternate_available.names[0]}" size = 1 tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithRegions" } } resource "aws_ebs_snapshot" "test" { provider = "aws.alternate" volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithRegions" } } resource "aws_ebs_snapshot_copy" "test" { source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.alternate.name}" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithRegions" } } ` const testAccAwsEbsSnapshotCopyConfigWithKms = ` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } data "aws_region" "current" {} resource "aws_kms_key" "test" { description = "testAccAwsEbsSnapshotCopyConfigWithKms" deletion_window_in_days = 7 } resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = 1 tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithKms" } } resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithKms" } } resource "aws_ebs_snapshot_copy" "test" { source_snapshot_id = "${aws_ebs_snapshot.test.id}" source_region = "${data.aws_region.current.name}" encrypted = true kms_key_id = "${aws_kms_key.test.arn}" tags = { Name = "testAccAwsEbsSnapshotCopyConfigWithKms" } } `
kjmkznr/terraform-provider-aws
aws/resource_aws_ebs_snapshot_copy_test.go
GO
mpl-2.0
11,780
/* * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.business.fixtures.identity; import javax.inject.Named; import org.seedstack.business.domain.Entity; import org.seedstack.business.util.SequenceGenerator; @Named("guice") public class GuiceIdentityGenerator implements SequenceGenerator { @Override public <E extends Entity<Long>> Long generate(Class<E> entityClass) { return (long) Math.random(); } }
seedstack/business
core/src/test/java/org/seedstack/business/fixtures/identity/GuiceIdentityGenerator.java
Java
mpl-2.0
678
package aws import ( "fmt" "log" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/licensemanager" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func init() { resource.AddTestSweepers("aws_licensemanager_license_configuration", &resource.Sweeper{ Name: "aws_licensemanager_license_configuration", F: testSweepLicenseManagerLicenseConfigurations, }) } func testSweepLicenseManagerLicenseConfigurations(region string) error { client, err := sharedClientForRegion(region) if err != nil { return fmt.Errorf("error getting client: %s", err) } conn := client.(*AWSClient).licensemanagerconn resp, err := conn.ListLicenseConfigurations(&licensemanager.ListLicenseConfigurationsInput{}) if err != nil { if testSweepSkipSweepError(err) { log.Printf("[WARN] Skipping License Manager License Configuration sweep for %s: %s", region, err) return nil } return fmt.Errorf("Error retrieving License Manager license configurations: %s", err) } if len(resp.LicenseConfigurations) == 0 { log.Print("[DEBUG] No License Manager license configurations to sweep") return nil } for _, lc := range resp.LicenseConfigurations { id := aws.StringValue(lc.LicenseConfigurationArn) log.Printf("[INFO] Deleting License Manager license configuration: %s", id) opts := &licensemanager.DeleteLicenseConfigurationInput{ LicenseConfigurationArn: aws.String(id), } _, err := conn.DeleteLicenseConfiguration(opts) if err != nil { log.Printf("[ERROR] Error deleting License Manager license configuration (%s): %s", id, err) } } return nil } func TestAccAWSLicenseManagerLicenseConfiguration_basic(t *testing.T) { var licenseConfiguration licensemanager.LicenseConfiguration resourceName := "aws_licensemanager_license_configuration.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckLicenseManagerLicenseConfigurationDestroy, Steps: []resource.TestStep{ { Config: testAccLicenseManagerLicenseConfigurationConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLicenseManagerLicenseConfigurationExists(resourceName, &licenseConfiguration), resource.TestCheckResourceAttr(resourceName, "name", "Example"), resource.TestCheckResourceAttr(resourceName, "description", "Example"), resource.TestCheckResourceAttr(resourceName, "license_count", "10"), resource.TestCheckResourceAttr(resourceName, "license_count_hard_limit", "true"), resource.TestCheckResourceAttr(resourceName, "license_counting_type", "Socket"), resource.TestCheckResourceAttr(resourceName, "license_rules.#", "1"), resource.TestCheckResourceAttr(resourceName, "license_rules.0", "#minimumSockets=3"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.foo", "barr"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSLicenseManagerLicenseConfiguration_update(t *testing.T) { var licenseConfiguration licensemanager.LicenseConfiguration resourceName := "aws_licensemanager_license_configuration.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckLicenseManagerLicenseConfigurationDestroy, Steps: []resource.TestStep{ { Config: testAccLicenseManagerLicenseConfigurationConfig_basic, Check: resource.ComposeTestCheckFunc( testAccCheckLicenseManagerLicenseConfigurationExists(resourceName, &licenseConfiguration), ), }, { Config: testAccLicenseManagerLicenseConfigurationConfig_update, Check: resource.ComposeTestCheckFunc( testAccCheckLicenseManagerLicenseConfigurationExists(resourceName, &licenseConfiguration), resource.TestCheckResourceAttr(resourceName, "name", "NewName"), resource.TestCheckResourceAttr(resourceName, "description", ""), resource.TestCheckResourceAttr(resourceName, "license_count", "123"), resource.TestCheckResourceAttr(resourceName, "license_count_hard_limit", "false"), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.test", "test"), resource.TestCheckResourceAttr(resourceName, "tags.abc", "def"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func testAccCheckLicenseManagerLicenseConfigurationExists(resourceName string, licenseConfiguration *licensemanager.LicenseConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.Meta().(*AWSClient).licensemanagerconn resp, err := conn.ListLicenseConfigurations(&licensemanager.ListLicenseConfigurationsInput{ LicenseConfigurationArns: [](*string){aws.String(rs.Primary.ID)}, }) if err != nil { return fmt.Errorf("Error retrieving License Manager license configuration (%s): %s", rs.Primary.ID, err) } if len(resp.LicenseConfigurations) == 0 { return fmt.Errorf("Error retrieving License Manager license configuration (%s): Not found", rs.Primary.ID) } *licenseConfiguration = *resp.LicenseConfigurations[0] return nil } } func testAccCheckLicenseManagerLicenseConfigurationDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).licensemanagerconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_licensemanager_license_configuration" { continue } // Try to find the resource _, err := conn.GetLicenseConfiguration(&licensemanager.GetLicenseConfigurationInput{ LicenseConfigurationArn: aws.String(rs.Primary.ID), }) if err != nil { if isAWSErr(err, licensemanager.ErrCodeInvalidParameterValueException, "") { continue } return err } } return nil } const testAccLicenseManagerLicenseConfigurationConfig_basic = ` resource "aws_licensemanager_license_configuration" "example" { name = "Example" description = "Example" license_count = 10 license_count_hard_limit = true license_counting_type = "Socket" license_rules = [ "#minimumSockets=3" ] tags = { foo = "barr" } } ` const testAccLicenseManagerLicenseConfigurationConfig_update = ` resource "aws_licensemanager_license_configuration" "example" { name = "NewName" license_count = 123 license_counting_type = "Socket" license_rules = [ "#minimumSockets=3" ] tags = { test = "test" abc = "def" } } `
Ninir/terraform-provider-aws
aws/resource_aws_licensemanager_license_configuration_test.go
GO
mpl-2.0
6,973
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * If it is not possible or desirable to put the notice in a particular * file, then You may include the notice in a location (such as a LICENSE * file in a relevant directory) where a recipient would be likely to look * for such a notice. * */ /* --------------------------------------------------------------------------- * US Government, Department of the Army * Army Materiel Command * Research Development Engineering Command * Communications Electronics Research Development and Engineering Center * --------------------------------------------------------------------------- */ using System; using System.Windows.Forms; namespace HelloWorldASPNETClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { helloworldaspnet.Service1 svc = new HelloWorldASPNETClient.helloworldaspnet.Service1(); svc.Url = textBox1.Text; MessageBox.Show(svc.HelloWorld()); } private void button2_Click(object sender, EventArgs e) { dataAccessService c = new dataAccessService(); c.GetMonitoredServiceList(new GetMonitoredServiceListRequestMsg()); } } }
mil-oss/fgsms
fgsms-netagent/Tests/services/HelloWorldASPNETClient/Form1.cs
C#
mpl-2.0
1,522
/* Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal. This Source Code Form is subject to the terms of the Appverse Public License Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf. [^] Redistribution and use in source and binary forms, with or without modification, are permitted provided that the conditions of the AppVerse Public License v2.0 are met. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.appverse.web.framework.backend.core.enterprise.converters; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.appverse.web.framework.backend.core.beans.AbstractBusinessBean; import org.appverse.web.framework.backend.core.beans.AbstractIntegrationBean; import org.dozer.Mapper; import org.dozer.spring.DozerBeanMapperFactoryBean; public abstract class AbstractDozerB2IBeanConverter<BusinessBean extends AbstractBusinessBean, IntegrationBean extends AbstractIntegrationBean> implements IB2IBeanConverter<BusinessBean, IntegrationBean> { private Class<IntegrationBean> integrationBeanClass; private Class<BusinessBean> businessBeanClass; private String SCOPE_WITHOUT_DEPENDENCIES = "default-scope-without-dependencies"; private String SCOPE_COMPLETE = "default-scope-complete"; private String SCOPE_CUSTOM = "default-scope-custom"; @Resource protected DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean; public AbstractDozerB2IBeanConverter() { } @Override public IntegrationBean convert(BusinessBean bean) throws Exception { return convert(bean, ConversionType.Complete); } @Override public IntegrationBean convert(BusinessBean businessBean, ConversionType conversionType) throws Exception { return convert(businessBean, getScope(conversionType)); } @Override public IntegrationBean convert(BusinessBean businessBean, String scope) throws Exception { return ((Mapper) dozerBeanMapperFactoryBean.getObject()).map( businessBean, integrationBeanClass, scope); } @Override public void convert(final BusinessBean businessBean, IntegrationBean integrationBean) throws Exception { convert(businessBean, integrationBean, ConversionType.Complete); } @Override public void convert(final BusinessBean businessBean, IntegrationBean integrationBean, ConversionType conversionType) throws Exception { convert(businessBean, integrationBean, getScope(conversionType)); } @Override public void convert(final BusinessBean businessBean, IntegrationBean integrationBean, String scope) throws Exception{ ((Mapper) dozerBeanMapperFactoryBean.getObject()).map(businessBean, integrationBean, scope); } @Override public BusinessBean convert(IntegrationBean bean) throws Exception { return convert(bean, ConversionType.Complete); } @Override public void convert(final IntegrationBean integrationBean, BusinessBean businessBean) throws Exception { convert(integrationBean, businessBean, ConversionType.Complete); } @Override public void convert(final IntegrationBean integrationBean, BusinessBean businessBean, ConversionType conversionType) throws Exception { convert(integrationBean, businessBean, getScope(conversionType)); } @Override public void convert(final IntegrationBean integrationBean, BusinessBean businessBean, String scope) throws Exception { ((Mapper) dozerBeanMapperFactoryBean.getObject()).map(integrationBean, businessBean, scope); } @Override public BusinessBean convert(IntegrationBean integrationBean, ConversionType conversionType) throws Exception { return convert(integrationBean, getScope(conversionType)); } @Override public BusinessBean convert(IntegrationBean integrationBean, String scope) throws Exception { return ((Mapper) dozerBeanMapperFactoryBean.getObject()).map( integrationBean, businessBeanClass, scope); } @Override public List<IntegrationBean> convertBusinessList( List<BusinessBean> businessBeans) throws Exception { List<IntegrationBean> integrationBeans = new ArrayList<IntegrationBean>(); for (BusinessBean businessBean : businessBeans) { IntegrationBean integrationBean = convert(businessBean, ConversionType.Complete); integrationBeans.add(integrationBean); } return integrationBeans; } @Override public List<IntegrationBean> convertBusinessList( List<BusinessBean> businessBeans, ConversionType conversionType) throws Exception { return convertBusinessList(businessBeans, getScope(conversionType)); } @Override public List<IntegrationBean> convertBusinessList( List<BusinessBean> businessBeans, String scope) throws Exception { List<IntegrationBean> integrationBeans = new ArrayList<IntegrationBean>(); for (BusinessBean businessBean : businessBeans) { IntegrationBean integrationBean = ((Mapper) dozerBeanMapperFactoryBean .getObject()).map(businessBean, integrationBeanClass, scope); integrationBeans.add(integrationBean); } return integrationBeans; } @Override public void convertBusinessList(final List<BusinessBean> businessBeans, List<IntegrationBean> integrationBeans) throws Exception { if (businessBeans.size() != integrationBeans.size()) { throw new ListDiffersSizeException(); } for (int i = 0; i < businessBeans.size(); i++) { convert(businessBeans.get(i), integrationBeans.get(i), ConversionType.Complete); } } @Override public void convertBusinessList(final List<BusinessBean> businessBeans, List<IntegrationBean> integrationBeans, ConversionType conversionType) throws Exception { convertBusinessList(businessBeans, integrationBeans, getScope(conversionType)); } @Override public void convertBusinessList(final List<BusinessBean> businessBeans, List<IntegrationBean> integrationBeans, String scope) throws Exception { if (businessBeans.size() != integrationBeans.size()) { throw new ListDiffersSizeException(); } for (int i = 0; i < businessBeans.size(); i++) { ((Mapper) dozerBeanMapperFactoryBean.getObject()).map( businessBeans.get(i), integrationBeans.get(i), scope); } } @Override public List<BusinessBean> convertIntegrationList( List<IntegrationBean> integrationBeans) throws Exception { List<BusinessBean> businessBeans = new ArrayList<BusinessBean>(); for (IntegrationBean integrationBean : integrationBeans) { BusinessBean businessBean = convert(integrationBean, ConversionType.Complete); businessBeans.add(businessBean); } return businessBeans; } @Override public List<BusinessBean> convertIntegrationList( List<IntegrationBean> integrationBeans, ConversionType conversionType) throws Exception { return convertIntegrationList(integrationBeans, getScope(conversionType)); } @Override public List<BusinessBean> convertIntegrationList( List<IntegrationBean> integrationBeans, String scope) throws Exception { List<BusinessBean> businessBeans = new ArrayList<BusinessBean>(); for (IntegrationBean integrationBean : integrationBeans) { BusinessBean businessBean = ((Mapper) dozerBeanMapperFactoryBean .getObject()).map(integrationBean, businessBeanClass, scope); businessBeans.add(businessBean); } return businessBeans; } @Override public void convertIntegrationList( final List<IntegrationBean> integrationBeans, List<BusinessBean> businessBeans) throws Exception { if (integrationBeans.size() != businessBeans.size()) { throw new ListDiffersSizeException(); } for (int i = 0; i < integrationBeans.size(); i++) { convert(integrationBeans.get(i), businessBeans.get(i), ConversionType.Complete); } } @Override public void convertIntegrationList( final List<IntegrationBean> integrationBeans, List<BusinessBean> businessBeans, ConversionType conversionType) throws Exception { convertIntegrationList(integrationBeans, businessBeans, getScope(conversionType)); } @Override public void convertIntegrationList( final List<IntegrationBean> integrationBeans, List<BusinessBean> businessBeans, String scope) throws Exception { if (integrationBeans.size() != businessBeans.size()) { throw new ListDiffersSizeException(); } for (int i = 0; i < integrationBeans.size(); i++) { ((Mapper) dozerBeanMapperFactoryBean.getObject()).map( integrationBeans.get(i), businessBeans.get(i), scope); } } @Override public String getScope(ConversionType conversionType) { String scope = null; if (conversionType == ConversionType.WithoutDependencies) { scope = SCOPE_WITHOUT_DEPENDENCIES; } else if (conversionType == ConversionType.Custom) { scope = SCOPE_CUSTOM; } else { scope = SCOPE_COMPLETE; } return scope; } public void setBeanClasses(Class<BusinessBean> businessBeanClass, Class<IntegrationBean> integrationBeanClass) { this.integrationBeanClass = integrationBeanClass; this.businessBeanClass = businessBeanClass; } @Override public void setScopes(String... scopes) { if (scopes.length > 0) { this.SCOPE_COMPLETE = scopes[0]; } if (scopes.length > 1) { this.SCOPE_WITHOUT_DEPENDENCIES = scopes[1]; } if (scopes.length > 2) { this.SCOPE_CUSTOM = scopes[2]; } } }
Appverse/appverse-server
framework/modules/backend/core/enterprise-converters/src/main/java/org/appverse/web/framework/backend/core/enterprise/converters/AbstractDozerB2IBeanConverter.java
Java
mpl-2.0
10,846
#region LICENSE // The contents of this file are subject to the Common Public Attribution // License Version 1.0. (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // https://github.com/NiclasOlofsson/MiNET/blob/master/LICENSE. // The License is based on the Mozilla Public License Version 1.1, but Sections 14 // and 15 have been added to cover use of software over a computer network and // provide for limited attribution for the Original Developer. In addition, Exhibit A has // been modified to be consistent with Exhibit B. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for // the specific language governing rights and limitations under the License. // // The Original Code is MiNET. // // The Original Developer is the Initial Developer. The Initial Developer of // the Original Code is Niclas Olofsson. // // All portions of the code written by Niclas Olofsson are Copyright (c) 2014-2018 Niclas Olofsson. // All Rights Reserved. #endregion namespace MiNET.Items { public class ItemSaddle : Item { protected internal ItemSaddle() : base(329) { } } }
yungtechboy1/MiNET
src/MiNET/MiNET/Items/ItemSaddle.cs
C#
mpl-2.0
1,266
/***************************************************************************************** * *** BEGIN LICENSE BLOCK ***** * * Version: MPL 2.0 * * echocat Jomon, Copyright (c) 2012-2013 echocat * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * *** END LICENSE BLOCK ***** ****************************************************************************************/ package org.echocat.jomon.resources; import javax.annotation.Nonnull; public interface UriEnabledResource extends Resource { @Nonnull public String getUri(); }
echocat/jomon
resources/src/main/java/org/echocat/jomon/resources/UriEnabledResource.java
Java
mpl-2.0
707
/** * @class PrettyJSON.view.Leaf * @extends Backbone.View * * @author #rbarriga * @version 0.1 * */ PrettyJSON.view.Leaf = Backbone.View.extend({ tagName:'span', data:null, level:0, path:'', type:'string', isLast: true, events: { "mouseover .leaf-container": "mouseover", "mouseout .leaf-container": "mouseout" }, initialize: function(){ this.data = this.options.data; this.level = this.options.level; this.path = this.options.path; this.type = this.getType(); this.isLast = _.isUndefined(this.options.isLast) ? this.isLast : this.options.isLast; this.render(); }, getType: function(){ var m = 'string'; var d = this.data; if(_.isNumber(d)) m = 'number'; else if(_.isBoolean(d)) m = 'boolean'; else if(_.isDate(d)) m = 'date'; return m; }, getState:function(){ var coma = this.isLast ? '': ','; var state = { data: this.data, level: this.level, path: this.path, type: this.type, coma: coma }; return state; }, render: function(){ var state = this.getState(); this.tpl = _.template(PrettyJSON.tpl.Leaf, state); $(this.el).html(this.tpl); return this; }, mouseover:function(e){ e.stopPropagation(); this.toggleTdPath(true); var path = this.path + '&nbsp;:&nbsp;<span class="' + this.type +'"><b>' + this.data + '</b></span>'; this.trigger("mouseover",e, path); }, mouseout:function(e){ e.stopPropagation(); this.toggleTdPath(false); this.trigger("mouseout",e); }, getTds:function(){ this.tds = []; var view = this; while (view){ var td = view.parentTd; if(td) this.tds.push(td); view = view.parent; } }, toggleTdPath:function(show){ this.getTds(); _.each(this.tds,function(td){ show ? td.addClass('node-hgl-path'): td.removeClass('node-hgl-path'); },this); } });
SmartSearch/Mashups
Event_Billboard-portlet/docroot/js/pretty-json-master/src/leaf.js
JavaScript
mpl-2.0
2,216
package org.openlca.olcatdb.ecospold2; import org.openlca.olcatdb.parsing.Context; /** * @Element childActivityDataset * @ContentModel (activityDescription, flowData, modellingAndValidation, * administrativeInformation, namespace:uri="##other") */ @Context(name = "childActivityDataset", parentName = "ecoSpold") public class ES2ChildDataset extends ES2Dataset { }
GreenDelta/olca-converter
src/main/java/org/openlca/olcatdb/ecospold2/ES2ChildDataset.java
Java
mpl-2.0
386
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * CollectorStream: transform that collects all input and makes it available as * a single string */ var readable = require('readable-stream'); var util = require('util'); module.exports = CollectorStream; function CollectorStream(options) { readable.Transform.call(this, options); this.data = ''; } util.inherits(CollectorStream, readable.Transform); CollectorStream.prototype._transform = function (chunk, encoding, done) { this.data += chunk; done(); }; CollectorStream.prototype._flush = function (callback) { callback(); };
davepacheco/sdc-manta
test/CollectorStream.js
JavaScript
mpl-2.0
799
/* Copyright (c) 2015, Digi International Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*************************************************************************** ssdac1.c This sample program is used with Smart Star products, specifically for 0-10V and +/-10V DAC boards. !!!Caution this will overwrite the calibration constants set at the factory. This program demonstrates how to recalibrate an DAC channel using two known voltages and defines the two coefficients, gain and offset, which will be rewritten into the DAC's EEPROM. Instructions: Connect a voltage meter to an output channel. Compile and run this program. Follow the prompted directions of this program during execution. ***************************************************************************/ #class auto #define LOCOUNT 400 //gives highest voltage #define HICOUNT 3695 //gives lowest voltage void main() { auto int slotnum, outputnum, msgcode; static float voltout, volt1, volt2; auto char tmpbuf[24]; brdInit(); printf("Please enter DAC board slot position, 0 thru 6...."); do { slotnum = getchar(); } while ((slotnum < '0') || (slotnum > '6')); printf("Slot %d chosen.\n", slotnum-=0x30); ///// configure all outputs to zero volts and enable output for (outputnum=0; outputnum<=7; outputnum++) { if (msgcode = anaOutEERd(ChanAddr(slotnum, outputnum))) { printf("Error %d: eeprom unreadable or empty slot; channel %d\n", msgcode,outputnum); exit(0); } else anaOutVolts(ChanAddr(slotnum, outputnum), 0.0); } anaOutEnable(); printf("Please enter an output channel, 0 thru 7...."); do { outputnum = getchar(); } while (!((outputnum >= '0') && (outputnum <= '7'))); printf("channel %d chosen.\n", outputnum-=0x30); /////get voltages from two known raw data anaOut(ChanAddr(slotnum, outputnum), HICOUNT); printf("Type first voltage reading (in Volts) from meter and press Enter "); volt1 = atof(gets(tmpbuf)); anaOut(ChanAddr(slotnum, outputnum), LOCOUNT); printf("Type second voltage reading (in Volts) from meter and press Enter "); volt2 = atof(gets(tmpbuf)); if (anaOutCalib(ChanAddr(slotnum, outputnum), HICOUNT, volt1, LOCOUNT, volt2)) printf("Cannot make coefficients\n"); else { /////store coefficients into eeprom while (anaOutEEWr(ChanAddr(slotnum, outputnum))); printf("Wrote coefficients to eeprom\n"); printf("Read coefficients from eeprom\n"); if (msgcode = anaOutEERd(ChanAddr(slotnum, outputnum))) { printf("Error %d: eeprom unreadable or empty slot; channel %d\n", msgcode,outputnum); exit(0); } while (1) { printf("\nType a desired voltage (in Volts) "); voltout = atof(gets(tmpbuf)); printf("Observe voltage on meter.....\n"); anaOutVolts(ChanAddr(slotnum, outputnum), voltout); } } }
digidotcom/DCRabbit_9
Samples/SmrtStar/dac/SSDAC1.C
C++
mpl-2.0
3,624
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os,re,sys,pprint,shutil from pathlib import Path PACKAGES_DIR = "../packages" def errorExit(msg): print(msg) sys.exit(1) def isPathDisabled(path): for part in path.parts: if part.lower().startswith("_disabled"): return True return False depsFolder = Path("_deps_split") prodFolder = Path("_prods_split") merged_deps = Path("merged_deps.py" ) merged_prods = Path("merged_prods.py") if not os.path.isfile(merged_deps): errorExit("Merged depends file does not exist") if not os.path.isfile(merged_prods): errorExit("Merged products file does not exist") if not os.path.isdir(depsFolder): os.makedirs(depsFolder) else: print("Clearing old split folder:" + str(depsFolder)) shutil.rmtree(depsFolder) os.makedirs(depsFolder) if not os.path.isdir(prodFolder): os.makedirs(prodFolder) else: print("Clearing old split folder:" + str(prodFolder)) shutil.rmtree(prodFolder) os.makedirs(prodFolder) things = { "merged_deps.py" : depsFolder, "merged_prods.py" : prodFolder, } for mergefile_name in things: mergedFile = None enableWrite = False curFile = None print("Splitting " +mergefile_name+ " into seperate files in " + str(things[mergefile_name])) with open(mergefile_name, "r", encoding="utf-8") as f: mergedFile = f.read().split("\n") fileBuffer = "" for line in mergedFile: startR = re.search("^########START:\[(.+)\]$",line) endR = re.search("^########END:\[(.+)\]$",line) if endR != None: enableWrite = False curFile.write(fileBuffer.rstrip("\n")) curFile.close() if enableWrite: fileBuffer+=line+"\n" if startR != None: enableWrite = True fileBuffer = "" curFile = open(os.path.join(things[mergefile_name],startR.groups()[0]) ,"w",encoding="utf-8") print("Done")
DeadSix27/python_cross_compile_script
tools/split.py
Python
mpl-2.0
1,806
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow import * as React from 'react'; import { Provider } from 'react-redux'; import copy from 'copy-to-clipboard'; import { render } from 'firefox-profiler/test/fixtures/testing-library'; import { CallNodeContextMenu } from '../../components/shared/CallNodeContextMenu'; import { storeWithProfile } from '../fixtures/stores'; import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile'; import { changeRightClickedCallNode, changeExpandedCallNodes, setContextMenuVisibility, } from '../../actions/profile-view'; import { selectedThreadSelectors } from '../../selectors/per-thread'; import { ensureExists } from '../../utils/flow'; import { fireFullClick } from '../fixtures/utils'; describe('calltree/CallNodeContextMenu', function () { // Provide a store with a useful profile to assert context menu operations off of. function createStore() { // Create a profile that every transform can be applied to. const { profile, funcNamesDictPerThread: [{ A, B }], } = getProfileFromTextSamples(` A A A B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] C C H D F I E E `); const store = storeWithProfile(profile); store.dispatch(changeExpandedCallNodes(0, [[A]])); store.dispatch(changeRightClickedCallNode(0, [A, B])); return store; } function setup(store = createStore(), openMenuState = true) { store.dispatch(setContextMenuVisibility(openMenuState)); const renderResult = render( <Provider store={store}> <CallNodeContextMenu /> </Provider> ); return { ...renderResult, getState: store.getState }; } describe('basic rendering', function () { it('does not render the context menu when it is closed', () => { const isContextMenuOpen = false; const { container } = setup(createStore(), isContextMenuOpen); expect(container.querySelector('.react-contextmenu')).toBeNull(); }); it('renders a full context menu when open, with many nav items', () => { const isContextMenuOpen = true; const { container } = setup(createStore(), isContextMenuOpen); expect( ensureExists( container.querySelector('.react-contextmenu'), `Couldn't find the context menu root component .react-contextmenu` ).children.length > 1 ).toBeTruthy(); expect(container.firstChild).toMatchSnapshot(); }); }); describe('clicking on call tree transforms', function () { // Iterate through each transform slug, and click things in it. const fixtures = [ { matcher: /Merge function/, type: 'merge-function' }, { matcher: /Merge node only/, type: 'merge-call-node' }, { matcher: /Focus on subtree only/, type: 'focus-subtree' }, { matcher: /Focus on function/, type: 'focus-function' }, { matcher: /Collapse function/, type: 'collapse-function-subtree' }, { matcher: /XUL/, type: 'collapse-resource' }, { matcher: /Collapse direct recursion/, type: 'collapse-direct-recursion', }, { matcher: /Drop samples/, type: 'drop-function' }, ]; fixtures.forEach(({ matcher, type }) => { it(`adds a transform for "${type}"`, function () { const { getState, getByText } = setup(); fireFullClick(getByText(matcher)); expect( selectedThreadSelectors.getTransformStack(getState())[0].type ).toBe(type); }); }); }); describe('clicking on the rest of the menu items', function () { it('can expand all call nodes in the call tree', function () { const { getState, getByText } = setup(); expect( selectedThreadSelectors.getExpandedCallNodeIndexes(getState()) ).toHaveLength(1); fireFullClick(getByText('Expand all')); // This test only asserts that a bunch of call nodes were actually expanded. expect( selectedThreadSelectors.getExpandedCallNodeIndexes(getState()) ).toHaveLength(11); }); it('can look up functions on SearchFox', function () { const { getByText } = setup(); jest.spyOn(window, 'open').mockImplementation(() => {}); fireFullClick(getByText(/Searchfox/)); expect(window.open).toBeCalledWith( 'https://searchfox.org/mozilla-central/search?q=B', '_blank' ); }); it('can copy a function name', function () { const { getByText } = setup(); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy function name')); expect(copy).toBeCalledWith('B'); }); it('can copy a script URL', function () { // Create a new profile that has JavaScript in it. const { profile, funcNamesPerThread: [funcNames], } = getProfileFromTextSamples(` A.js `); const funcIndex = funcNames.indexOf('A.js'); const [thread] = profile.threads; thread.funcTable.fileName[funcIndex] = thread.stringTable.indexForString( 'https://example.com/script.js' ); const store = storeWithProfile(profile); store.dispatch(changeRightClickedCallNode(0, [funcIndex])); const { getByText } = setup(store); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy script URL')); expect(copy).toBeCalledWith('https://example.com/script.js'); }); it('can copy a stack', function () { const { getByText } = setup(); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy stack')); expect(copy).toBeCalledWith(`B\nA\n`); }); }); });
mstange/cleopatra
src/test/components/CallNodeContextMenu.test.js
JavaScript
mpl-2.0
6,012
/*global getAccessToken*/ function notifyUser(user) { browser.notifications.create({ "type": "basic", "title": "Google info", "message": `Hi ${user.name}` });} function logError(error) { console.error(`Error: ${error}`); } /** When the button's clicked: - get an access token using the identity API - use it to get the user's info - show a notification containing some of it */ browser.browserAction.onClicked.addListener(() => { getAccessToken() .then(getUserInfo) .then(notifyUser) .catch(logError); });
mdn/webextensions-examples
google-userinfo/background/main.js
JavaScript
mpl-2.0
541
/* @flow */ /* global Navigator, navigator */ import config from 'config'; import * as React from 'react'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import NestedStatus from 'react-nested-status'; import { compose } from 'redux'; // We have to import these styles first to have them listed first in the final // CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565 // The order is important: font files need to be first, with the subset after // the full font file. import 'fonts/inter.scss'; import 'fonts/inter-subset.scss'; import 'normalize.css/normalize.css'; import './styles.scss'; /* eslint-disable import/first */ import Routes from 'amo/components/Routes'; import ScrollToTop from 'amo/components/ScrollToTop'; import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage'; import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage'; import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage'; import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils'; import { addChangeListeners } from 'amo/addonManager'; import { setClientApp as setClientAppAction, setUserAgent as setUserAgentAction, } from 'amo/reducers/api'; import { setInstallState } from 'amo/reducers/installations'; import { CLIENT_APP_ANDROID } from 'amo/constants'; import ErrorPage from 'amo/components/ErrorPage'; import translate from 'amo/i18n/translate'; import log from 'amo/logger'; import type { AppState } from 'amo/store'; import type { DispatchFunc } from 'amo/types/redux'; import type { InstalledAddon } from 'amo/reducers/installations'; import type { I18nType } from 'amo/types/i18n'; import type { ReactRouterLocationType } from 'amo/types/router'; /* eslint-enable import/first */ interface MozNavigator extends Navigator { mozAddonManager?: Object; } type PropsFromState = {| clientApp: string, lang: string, userAgent: string | null, |}; type DefaultProps = {| _addChangeListeners: (callback: Function, mozAddonManager: Object) => any, _navigator: typeof navigator | null, mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>, userAgent: string | null, |}; type Props = {| ...PropsFromState, ...DefaultProps, handleGlobalEvent: () => void, i18n: I18nType, location: ReactRouterLocationType, setClientApp: (clientApp: string) => void, setUserAgent: (userAgent: string) => void, |}; export function getErrorPage(status: number | null): () => React.Node { switch (status) { case 401: return NotAuthorizedPage; case 404: return NotFoundPage; case 500: default: return ServerErrorPage; } } export class AppBase extends React.Component<Props> { scheduledLogout: TimeoutID; static defaultProps: DefaultProps = { _addChangeListeners: addChangeListeners, _navigator: typeof navigator !== 'undefined' ? navigator : null, mozAddonManager: config.get('server') ? {} : (navigator: MozNavigator).mozAddonManager, userAgent: null, }; componentDidMount() { const { _addChangeListeners, _navigator, handleGlobalEvent, mozAddonManager, setUserAgent, userAgent, } = this.props; // Use addonManager.addChangeListener to setup and filter events. _addChangeListeners(handleGlobalEvent, mozAddonManager); // If userAgent isn't set in state it could be that we couldn't get one // from the request headers on our first (server) request. If that's the // case we try to load them from navigator. if (!userAgent && _navigator && _navigator.userAgent) { log.info( 'userAgent not in state on App load; using navigator.userAgent.', ); setUserAgent(_navigator.userAgent); } } componentDidUpdate() { const { clientApp, location, setClientApp } = this.props; const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath( location.pathname, ); if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) { setClientApp(clientAppFromURL); } } render(): React.Node { const { clientApp, i18n, lang } = this.props; const i18nValues = { locale: lang, }; let defaultTitle = i18n.sprintf( i18n.gettext('Add-ons for Firefox (%(locale)s)'), i18nValues, ); let titleTemplate = i18n.sprintf( i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'), // We inject `%s` as a named argument to avoid localizer mistakes. Helmet // will replace `%s` by the title supplied in other pages. { ...i18nValues, title: '%s' }, ); if (clientApp === CLIENT_APP_ANDROID) { defaultTitle = i18n.sprintf( i18n.gettext('Add-ons for Firefox Android (%(locale)s)'), i18nValues, ); titleTemplate = i18n.sprintf( i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'), // We inject `%s` as a named argument to avoid localizer mistakes. // Helmet will replace `%s` by the title supplied in other pages. { ...i18nValues, title: '%s' }, ); } return ( <NestedStatus code={200}> <ScrollToTop> <Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} /> <ErrorPage getErrorComponent={getErrorPage}> <Routes /> </ErrorPage> </ScrollToTop> </NestedStatus> ); } } export const mapStateToProps = (state: AppState): PropsFromState => ({ clientApp: state.api.clientApp, lang: state.api.lang, userAgent: state.api.userAgent, }); export function mapDispatchToProps(dispatch: DispatchFunc): {| handleGlobalEvent: (payload: InstalledAddon) => void, setClientApp: (clientApp: string) => void, setUserAgent: (userAgent: string) => void, |} { return { handleGlobalEvent(payload: InstalledAddon) { dispatch(setInstallState(payload)); }, setClientApp(clientApp: string) { dispatch(setClientAppAction(clientApp)); }, setUserAgent(userAgent: string) { dispatch(setUserAgentAction(userAgent)); }, }; } const App: React.ComponentType<Props> = compose( withRouter, connect(mapStateToProps, mapDispatchToProps), translate(), )(AppBase); export default App;
mozilla/addons-frontend
src/amo/components/App/index.js
JavaScript
mpl-2.0
6,317
# include "stdafx.h" /*************************************************************************** ** ** INVOCATION NAME: RET123DV ** ** PURPOSE: TO RETURN DELIMITED DATA VALUES STORED IN STRUCTURE ** ** INVOCATION METHOD: RET123DV(B_PTR,PRIM_DMS) ** ** ARGUMENT LIST: ** NAME TYPE USE DESCRIPTION ** B_PTR[] PTR I CHARACTER POINTER TO BUFFER ** PRIM_DMS INT I PRIMARY DIMENSION LENGTH ** RET123DV() LOGICAL O SUCCESS FLAG ** ** EXTERNAL FUNCTION REFERENCES: ** NAME DESCRIPTION ** STR123TOK() RETURNS A POINTER TO A STRING TOKEN ** ** INTERNAL VARIABLES: ** NAME TYPE DESCRIPTION ** LEN INT CHARACTER STRING LENGTH ** NEW_DV PTR POINTER TO DATA VALUE STRUCTURE ** ST_TMPBUF[] PTR START OF TEMPORARY BUFFER ** TMP_BUF[] PTR TEMPORARY BUFFER ** TMP_STR[] PTR TEMPORARY CHARACTER STRING ** TOK_LEN LONG LENGTH OF TOKEN RETURNED FROM STR123TOK ** VAL_CT INT NUMBER OF CURRENT VALUES IN SET ** VAL_STR[] PTR VALUE CHARACTER STRING ** ** GLOBAL REFERENCES: ** ** DATA RECORD STRUCTURE (DR) ** NAME TYPE USE DESCRIPTION ** TAG[10] CHAR N/A INTERNAL NAME OF AN ASSOCIATED FIELD ** FD_LEN INT N/A LENGTH OF DISCRIPTIVE AREA DATA RECORD ** FD_POS INT N/A POSITION OF DESCRIPTIVE AREA DATA ** RECORD ** NUM_DIM INT N/A NUMBER OF DIMENSIONS (NO LABELS) ** DIM_LPTR PTR N/A HEAD POINTER TO DIMENSION LENGTHS ** (NO LABELS) ** VALUES PTR O HEAD POINTER TO DATA VALUE SUBFIELD ** RECORDS ** NEXT PTR N/A POINTER TO NEXT DATA RECORD ** ** DR DATA VALUE SUBFIELD STRUCTURE (DV) ** NAME TYPE USE DESCRIPTION ** VALUE CHAR O DATA VALUE ** NXT_VSET PTR O POINTER TO NEXT SET OF DATA VALUES ** NXT_VAL PTR O POINTER TO NEXT DATA VALUE SUBFIELD ** RECORD ** ** FILE MANAGEMENT STRUCTURE (FM) ** NAME TYPE USE DESCRIPTION ** FP PTR N/A FILE POINTER ** F_NAME[] PTR N/A EXTERNAL FILE NAME ** OPEN_MODE CHAR N/A OPEN MODE OF FILE ** CR_HD PTR N/A HEAD POINTER TO DATA DESCRIPTIVE FILE ** CONTROL RECORD STRUCTURE ** DD_HD PTR N/A HEAD POINTER TO DATA DESCRIPTIVE ** RECORD STRUCTURE ** DL_HD PTR N/A HEAD POINTER TO DATA DESCRIPTIVE LEADER ** STRUCTURE ** DR_HD PTR N/A HEAD POINTER TO DATA RECORD STRUCTURE ** LP_HD PTR N/A HEAD POINTER TO LABELS POINTER STRUCTURE ** RL_HD PTR N/A HEAD POINTER TO DATA RECORD LEADER ** STRUCTURE ** RS_HD PTR N/A HEAD POINTER TO FORMAT REPETITION STACK ** STRUCTURE ** REC_LOC_HD PTR N/A HEAD POINTER TO RECORD POINTER STRUCTURE ** CUR_DD PTR N/A CURRENT POINTER TO DATA DESCRIPTIVE ** RECORD STRUCTURE ENTRY ** CUR_DM PTR N/A CURRENT POINTER TO DIMENSION LENGTHS ** STRUCTURE ENTRY ** CUR_DR PTR I CURRENT POINTER TO DATA RECORD STRUCTURE ** ENTRY ** CUR_DV PTR I/O CURRENT POINTER TO DR DATA VALUE SUBFIELD ** STRUCTURE ENTRY ** ROW_DVH PTR N/A CURRENT POINTER TO NEXT SET OF VALUES ** IN DR DATA VALUE SUBFIELD STRUCTURE ENTRY ** CUR_FC PTR N/A CURRENT POINTER TO FORMAT CONTROLS ** STRUCTURE ENTRY ** CUR_LP PTR N/A CURRENT POINTER TO LABELS POINTER ** STRUCTURE ENTRY ** CUR_SL PTR N/A CURRENT POINTER TO DD-LABEL SUBFIELD ** STRUCTURE ENTRY ** CUR_FCR PTR N/A CURRENT POINTER TO ROOT OF FORMAT ** CONTROLS STRUCTURE ** CUR_RP PTR N/A CURRENT POINTER TO RECORD POINTER ** STRUCTURE ** NLD_RP PTR N/A POINTER TO RECORD POINTER STRUCTURE ** WHERE CORRESPONDING DR HAS AN 'R' ** LEADER IDENTIFIER ** SF_FMT CHAR N/A FORMAT CORRESPONDING TO THE CURRENT ** DATA VALUE ** NLD INT N/A NO LEADER FLAG ** TRUE - NO LEADER ** FALSE - LEADER EXISTS ** BIT_CNT INT N/A COUNT OF BITS STORED IN MEMORY FOR ** A SUBSEQUENT READ FUNCTION ** BIT_BIN CHAR N/A BITS STORED IN MEMORY FOR SUBSEQUENT ** READ FUNCTION ** COMPRESS INT N/A FLAG TO SPECIFY COMPRESSED OR ** UNCOMPRESSED ADJACENT FIXED-LENGTH ** BIT FIELD I/O ** 0 - UNCOMPRESSED ** 1 - COMPRESSED ** SF_STATE_DD INT N/A SUBFIELD STATE (DD) ** 1 - FIELD CONTROL SUBFIELD ** 2 - NAME SUBFIELD ** 3 - LABELS SUBFIELD ** 4 - FORMATS SUBFIELD ** 5 - FINISHED ** SF_STATE_DR INT N/A SUBFIELD STATE (DR) ** 1 - NUMBER OF DIMENSIONS SUBFIELD ** 2 - LENGTH OF A DIMENSION SUBFIELD ** 3 - DATA VALUE STRING SUBFIELD ** 4 - FINISHED ** NEXT PTR N/A POINTER TO NEXT FILE MANAGEMENT ** STRUCTURE ** BACK PTR N/A POINTER TO PREVIOUS FILE MANAGEMENT ** STRUCTURE ** ** GLOBAL VARIABLES: ** NAME TYPE USE DESCRIPTION ** CUR_FM PTR I CURRENT POINTER TO FILE MANAGEMENT ** STRUCTURE ENTRY ** ** GLOBAL CONSTANTS: ** NAME TYPE DESCRIPTION ** DEL_STR[3] CHAR CHARACTER STRING CONTAINING THE FIELD AND ** UNIT TERMINATORS ** FT CHAR FIELD TERMINATOR (RS) 1/14 ** NC CHAR NULL CHARACTER ** UT_STR[2] CHAR CHARACTER STRING CONTAINING THE UNIT ** TERMINATOR ** ** CHANGE HISTORY: ** AUTHOR CHANGE_ID DATE CHANGE SUMMARY ** A. DEWITT 04/23/90 INITIAL PROLOG ** A. DEWITT 04/23/90 INITIAL PDL ** P. HODGES 06/06/90 INITIAL CODE ** A. DEWITT 06/25/90 INCLUDED DIMENSION ROW_DVH LOGIC ** L. MCMILLION 10/16/90 REPLACED CALLS TO LIBRARY FUNCTION ** STRTOK() WITH STR123TOK() DUE TO ** NESTING PROBLEMS ** J. TAYLOR 92DR005 05/20/92 CHANGED CALLING SEQUENCE TO ** STR123TOK TO RETURN TOKEN LENGTH ** J. TAYLOR 92DR012 10/30/92 MODIFIED TO REMOVE FT FROM VAL_STR ** BEFORE RETURNING ** L. MCMILLION 93DR027 04/02/93 CHANGED DELIMITER USED BY FIRST ** STR123TOK() CALL FROM UT_STR TO ** DEL_STR FOR VECTOR DATA ** L. MCMILLION 93DR033 07/23/93 UPDATED DR REFERENCE IN PROLOG ** ** PDL: ** ** SET STRING LENGTH TO LENGTH OF BUFFER ** ALLOCATE TEMPORARY BUFFER ** INITIALIZE TEMPORARY BUFFER TO NULL CHARACTER ** COPY BUFFER CONTENTS TO TEMPORARY BUFFER ** SET START OF TEMPORARY BUFFER TO BEGINNING OF TEMPORARY BUFFER ** ALLOCATE NEW_DV { SET UP DUMMY HEADER } ** SET NXT_VAL FIELD OF NEW_DV TO NULL ** SET NXT_VSET FIELD OF NEW_DV TO NULL ** SET VALUES IN CUR_DR TO NEW_DV ** SET ROW_DVH TO NEW_DV ** CALL STR123TOK() TO SEPERATE THE DELIMITED DATA AND RETURN VAL_STR ** WHILE THERE ARE MORE DATA VALUES DO ** ALLOCATE NEW_DV ** SET NXT_VAL TO NULL ** SET NXT_VSET TO NULL ** SET LENGTH TO LENGTH OF VALUE STRING PLUS 1 ** ALLOCATE TEMPORARY STRING SPACE ** SET TEMPORARY STRING TO VALUE STRING ** SET NEW_DV VALUE TO TEMPORARY STRING ** SET NXT_VSET OF ROW_DVH TO NEW_DV ** SET CUR_DV TO NEW_DV ** SET ROW_DVH TO NEW_DV ** SET VAL_CT TO 1 ** CALL STR123TOK() TO RETURN NEXT VAL_STR ** WHILE THERE ARE MORE DATA VALUES AND VAL_CT IS LESS ** THAN PRIM_DMS DO ** ALLOCATE NEW_DV ** SET NXT_VAL TO NULL ** SET NXT_VSET TO NULL ** SET LENGTH TO LENGTH OF VALUE STRING PLUS 1 ** ALLOCATE TEMPORARY STRING SPACE ** SET TEMPORARY STRING TO VALUE STRING ** SET NEW_DV VALUE TO TEMPORARY STRING ** SET CUR_DV TO NEW_DV ** INCREMENT VAL_CT ** CALL STR123TOK() TO RETURN NEXT VAL_STR ** IF VAL_STR IS TERMINATED BY FT, REMOVE IT ** END WHILE ** END WHILE ** FREE SPACE AT START OF TEMPORARY BUFFER ** ** RETURN SUCCESS ** ****************************************************************************** ** CODE SECTION ** ******************************************************************************/ #include "stc123.h" int ret123dv(char *b_ptr,long prim_dms) { /* INTERNAL VARIABLES */ struct dv *new_dv ; long val_ct ; long tok_len ; size_t len ; char *st_tmpbuf, *tmp_buf , *tmp_str , *val_str ; /* SET STRING LENGTH TO LENGTH OF BUFFER */ len = _tcslen(b_ptr) + 1; /* ALLOCATE TEMPORARY BUFFER */ if ((tmp_buf = (char *) malloc((size_t) (len * sizeof(char)))) == NULL) return(0); /* INITIALIZE TEMPORARY BUFFER TO NULL CHARACTER */ *tmp_buf = NC; /* COPY BUFFER CONTENTS TO TEMPORARY BUFFER */ strcpy(tmp_buf,b_ptr); /* SET START OF TEMPORARY BUFFER TO BEGINNING OF TEMPORARY BUFFER */ st_tmpbuf = tmp_buf; /* ALLOCATE NEW_DV { SET UP DUMMY HEADER } */ if((new_dv = (struct dv *) malloc(sizeof(struct dv))) == NULL) return(0); /* SET VALUE FIELD TO NULL */ new_dv->value = NULL; /* SET NXT_VAL FIELD OF NEW_DV TO NULL */ new_dv->nxt_val = NULL; /* SET NXT_VSET FIELD OF NEW_DV TO NULL */ new_dv->nxt_vset = NULL; /* SET VALUES IN CUR_DR TO NEW_DV */ cur_fm->cur_dr->values = new_dv; /* SET ROW_DVH TO NEW_DV */ cur_fm->row_dvh = new_dv; /* CALL STR123TOK() TO SEPARATE THE DELIMITED DATA AND RETURN VAL_STR */ val_str = str123tok(&tmp_buf,DEL_STR,&tok_len); /* WHILE THERE ARE MORE DATA VALUES DO */ while(val_str != NULL) { /* ALLOCATE NEW_DV */ if ((new_dv = (struct dv *) malloc(sizeof(struct dv))) == NULL) return(0); /* SET VALUE POINTER TO NULL */ new_dv->value = NULL; /* SET NXT_VAL TO NULL */ new_dv->nxt_val = NULL; /* SET NXT_VSET TO NULL */ new_dv->nxt_vset = NULL; /* SET LENGTH TO LENGTH OF VALUE STRING PLUS 1 */ len = (size_t) _tcslen(val_str) + 1; /* ALLOCATE TEMPORARY STRING SPACE */ if ((tmp_str = (char *) malloc(len * sizeof(char))) == NULL) return(0); /* INITIALIZE STRING */ tmp_str[0] = NC; /* SET TEMPORARY STRING TO VALUE STRING */ strcpy(tmp_str, val_str); /* SET NEW_DV VALUE TO TEMPORARY STRING */ new_dv->value = tmp_str; /* SET NXT_VSET OF ROW_DVH TO NEW_DV */ cur_fm->row_dvh->nxt_vset = new_dv; /* SET CUR_DV TO NEW_DV */ cur_fm->cur_dv = new_dv; /* SET ROW_DVH TO NEW_DV */ cur_fm->row_dvh = new_dv; /* SET VAL_CT TO 1 */ val_ct = 1; /* CALL STR123TOK() TO RETURN NEXT VAL_STR */ val_str = str123tok(&tmp_buf,DEL_STR,&tok_len); /* WHILE THERE ARE MORE DATA VALUES AND VAL_CT IS LESS THAN PRIM_DMS DO */ while(val_str != NULL && val_ct < prim_dms) { /* ALLOCATE NEW_DV */ if ((new_dv = (struct dv *) malloc(sizeof(struct dv))) == NULL) return(0); /* SET VALUE FIELD TO NULL */ new_dv->value = NULL; /* SET NXT_VAL TO NULL */ new_dv->nxt_val = NULL; /* SET NXT_VSET TO NULL */ new_dv->nxt_vset = NULL; /* SET LENGTH TO LENGTH OF VALUE STRING PLUS 1 */ len = (size_t) _tcslen(val_str) + 1; /* ALLOCATE TEMPORARY STRING SPACE */ if ((tmp_str = (char *) malloc(len * sizeof(char))) == NULL) return(0); /* INITIALIZE STRING */ tmp_str[0] = NC; /* SET TEMPORARY STRING TO VALUE STRING */ strcpy(tmp_str, val_str); /* SET NEW_DV VALUE TO TEMPORARY STRING */ new_dv->value = tmp_str; /* SET NXT_VAL OF CUR_DV TO NEW_DV */ cur_fm->cur_dv->nxt_val = new_dv; /* SET CUR_DV TO NEW_DV */ cur_fm->cur_dv = new_dv; /* INCREMENT VAL_CT */ val_ct++; /* CALL STR123TOK() TO RETURN NEXT VAL_STR */ val_str = str123tok(&tmp_buf,UT_STR,&tok_len); /* IF VAL_STR IS TERMINATED BY FT, REMOVE IT */ if (val_str != NULL) { /* SET LENGTH TO LENGTH OF VALUE STRING */ len = (size_t) _tcslen(val_str); if (val_str[len-1] == FT) { val_str[len-1] = NC; len--; } } } } /* FREE SPACE AT START OF TEMPORARY BUFFER */ free(st_tmpbuf); /* RETURN SUCCESS */ return(1); }
MapWindow/MapWinGIS
src/Grid/fip/ret_dv.cpp
C++
mpl-2.0
15,098
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace KISS { /// <summary> /// A manifest file is a file that has a version and references a bunch of patch files. /// </summary> public class ManifestFile { public string Version = ""; public List<PatchFile> PatchFiles = new List<PatchFile>(); public ManifestFile(string Path, string Version, List<PatchFile> PatchFiles) { bool HasURLs = false; BinaryWriter Writer = new BinaryWriter(File.Create(Path)); Writer.Write((string)Version); if (PatchFiles[0].URL != "") HasURLs = true; foreach (PatchFile PFile in PatchFiles) { if (!HasURLs) Writer.Write((string)PFile.Address + "," + PFile.FileHash); else Writer.Write((string)PFile.Address + "," + PFile.FileHash + PFile.URL); } Writer.Flush(); Writer.Close(); } /// <summary> /// Creates a ManifestFile instance from a downloaded stream. /// </summary> /// <param name="ManifestStream"></param> public ManifestFile(Stream ManifestStream) { BinaryReader Reader = new BinaryReader(ManifestStream); Reader.BaseStream.Position = 0; //IMPORTANT! Version = Reader.ReadString(); int NumFiles = Reader.ReadInt32(); for(int i = 0; i < NumFiles; i++) { string PatchFileStr = Reader.ReadString(); string[] SplitPatchFileStr = PatchFileStr.Split(",".ToCharArray()); PatchFiles.Add(new PatchFile() { Address = SplitPatchFileStr[0], FileHash = SplitPatchFileStr[1], URL = SplitPatchFileStr[2] }); } Reader.Close(); } } }
Afr0/KISS
src/C#/KISS.net/KISS.net/ManifestFile.cs
C#
mpl-2.0
2,020
package hs.minion; import hs.CardClass; import hs.CardSet; public class RaidLeader extends Minion { static final String Name = "Raid Leader"; static final int Cost = 3; static final CardClass Class = CardClass.NEUTRAL; static final String Text = "Your other minions have +1 Attack."; static final MinionRace Race = MinionRace.NEUTRAL; static final int Attack = 2; static final int Health = 2; static CardSet Set = CardSet.BASIC; @Override public String getName() { return Name; } @Override public int getNormalCost() { return Cost; } @Override public String getText() { return Text; } @Override public CardClass getCardClass() { return Class; } @Override public int getNormalHealth() { return Health; } @Override public int getNormalAttack() { return Attack; } @Override public CardSet getCardSet() { return Set; } }
jmmaloney4/hs2
src/main/java/hs/minion/RaidLeader.java
Java
mpl-2.0
870
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.iidm.network.impl; import com.powsybl.iidm.network.*; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ class GeneratorAdderImpl extends AbstractInjectionAdder<GeneratorAdderImpl> implements GeneratorAdder { private final VoltageLevelExt voltageLevel; private EnergySource energySource = EnergySource.OTHER; private double minP = Double.NaN; private double maxP = Double.NaN; private TerminalExt regulatingTerminal; private Boolean voltageRegulatorOn; private double targetP = Double.NaN; private double targetQ = Double.NaN; private double targetV = Double.NaN; private double ratedS = Double.NaN; GeneratorAdderImpl(VoltageLevelExt voltageLevel) { this.voltageLevel = voltageLevel; } @Override protected NetworkImpl getNetwork() { return voltageLevel.getNetwork(); } @Override protected String getTypeDescription() { return "Generator"; } @Override public GeneratorAdderImpl setEnergySource(EnergySource energySource) { this.energySource = energySource; return this; } @Override public GeneratorAdderImpl setMaxP(double maxP) { this.maxP = maxP; return this; } @Override public GeneratorAdderImpl setMinP(double minP) { this.minP = minP; return this; } @Override public GeneratorAdder setVoltageRegulatorOn(boolean voltageRegulatorOn) { this.voltageRegulatorOn = voltageRegulatorOn; return this; } @Override public GeneratorAdder setRegulatingTerminal(Terminal regulatingTerminal) { this.regulatingTerminal = (TerminalExt) regulatingTerminal; return this; } @Override public GeneratorAdderImpl setTargetP(double targetP) { this.targetP = targetP; return this; } @Override public GeneratorAdderImpl setTargetQ(double targetQ) { this.targetQ = targetQ; return this; } @Override public GeneratorAdderImpl setTargetV(double targetV) { this.targetV = targetV; return this; } @Override public GeneratorAdder setRatedS(double ratedS) { this.ratedS = ratedS; return this; } @Override public GeneratorImpl add() { NetworkImpl network = getNetwork(); if (network.getMinValidationLevel() == ValidationLevel.EQUIPMENT && voltageRegulatorOn == null) { voltageRegulatorOn = false; } String id = checkAndGetUniqueId(); TerminalExt terminal = checkAndGetTerminal(); ValidationUtil.checkMinP(this, minP); ValidationUtil.checkMaxP(this, maxP); ValidationUtil.checkActivePowerLimits(this, minP, maxP); ValidationUtil.checkRegulatingTerminal(this, regulatingTerminal, network); network.setValidationLevelIfGreaterThan(ValidationUtil.checkActivePowerSetpoint(this, targetP, network.getMinValidationLevel())); network.setValidationLevelIfGreaterThan(ValidationUtil.checkVoltageControl(this, voltageRegulatorOn, targetV, targetQ, network.getMinValidationLevel())); ValidationUtil.checkActivePowerLimits(this, minP, maxP); ValidationUtil.checkRatedS(this, ratedS); GeneratorImpl generator = new GeneratorImpl(network.getRef(), id, getName(), isFictitious(), energySource, minP, maxP, voltageRegulatorOn, regulatingTerminal != null ? regulatingTerminal : terminal, targetP, targetQ, targetV, ratedS); generator.addTerminal(terminal); voltageLevel.attach(terminal, false); network.getIndex().checkAndAdd(generator); network.getListeners().notifyCreation(generator); return generator; } }
powsybl/powsybl-core
iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/GeneratorAdderImpl.java
Java
mpl-2.0
4,274
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Enigma.Db.Store { public interface IStorage { //IStorageMaintenance Maintenance { get; } //bool TryAdd(IKey key, byte[] content); //bool TryUpdate(IKey key, byte[] content); //bool TryRemove(IKey key); //bool TryGet(IKey key, out byte[] content); } }
jaygumji/Enigma
Enigma/src/Enigma/Db/Store/IStorage.cs
C#
mpl-2.0
522
// Code generated by go-swagger; DO NOT EDIT. package users // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime/middleware" strfmt "github.com/go-openapi/strfmt" ) // NewDeleteUserByIDParams creates a new DeleteUserByIDParams object // with the default values initialized. func NewDeleteUserByIDParams() DeleteUserByIDParams { var () return DeleteUserByIDParams{} } // DeleteUserByIDParams contains all the bound params for the delete user by ID operation // typically these are obtained from a http.Request // // swagger:parameters deleteUserByID type DeleteUserByIDParams struct { // HTTP Request Object HTTPRequest *http.Request `json:"-"` /*ID of user to delete Required: true In: path */ UserID string } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface // for simple values it will use straight method calls func (o *DeleteUserByIDParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { var res []error o.HTTPRequest = r rUserID, rhkUserID, _ := route.Params.GetOK("userID") if err := o.bindUserID(rUserID, rhkUserID, route.Formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (o *DeleteUserByIDParams) bindUserID(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } o.UserID = raw return nil }
king-jam/tracker2jira
rest/server/operations/users/delete_user_by_id_parameters.go
GO
mpl-2.0
1,685
package com.gaiagps.iburn; import android.content.Context; import android.content.SharedPreferences; /** * Created by davidbrodsky on 7/1/15. */ public class PrefsHelper { private static final String SHOWED_WELCOME = "welcomed_2018"; // boolean private static final String POPULATED_DB_VERSION = "db_populated_ver"; // long private static final String VALID_UNLOCK_CODE = "unlocked_2018"; // boolean private static final String SCHEDULED_UPDATE = "sched_update"; // boolean private static final String DEFAULT_RESOURCE_VERSION = "resver"; // long private static final String RESOURCE_VERSION_PREFIX = "res-"; // long private static final String SHARED_PREFS_NAME = PrefsHelper.class.getSimpleName(); private SharedPreferences sharedPrefs; private SharedPreferences.Editor editor; public PrefsHelper(Context context) { sharedPrefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE); editor = sharedPrefs.edit(); } /** * @return whether a valid unlock code has been presented for this year */ public boolean enteredValidUnlockCode() { return sharedPrefs.getBoolean(VALID_UNLOCK_CODE, false); } public void setEnteredValidUnlockCode(boolean didEnter) { editor.putBoolean(VALID_UNLOCK_CODE, didEnter).apply(); } public boolean didShowWelcome() { return sharedPrefs.getBoolean(SHOWED_WELCOME, false); } public void setDidShowWelcome(boolean didShow) { editor.putBoolean(SHOWED_WELCOME, didShow).commit(); } public void setDatabaseVersion(long version) { editor.putLong(POPULATED_DB_VERSION, version).commit(); } public long getDatabaseVersion() { return sharedPrefs.getLong(POPULATED_DB_VERSION, 0); } /** * @return whether the application successfully registered a {@link com.gaiagps.iburn.service.DataUpdateService} task */ public boolean didScheduleUpdate() { return sharedPrefs.getBoolean(SCHEDULED_UPDATE, false); } public void setDidScheduleUpdate(boolean didScheduleUpdate) { editor.putBoolean(SCHEDULED_UPDATE, didScheduleUpdate).apply(); } public void setBaseResourcesVersion(long version) { editor.putLong(DEFAULT_RESOURCE_VERSION, version).commit(); } public long getResourceVersion(String resourceName) { return sharedPrefs.getLong(RESOURCE_VERSION_PREFIX + resourceName, sharedPrefs.getLong(DEFAULT_RESOURCE_VERSION, 0)); } public void setResourceVersion(String resourceName, long resourceVersion) { editor.putLong(RESOURCE_VERSION_PREFIX + resourceName, resourceVersion).apply(); } }
Burning-Man-Earth/iBurn-Android
iBurn/src/main/java/com/gaiagps/iburn/PrefsHelper.java
Java
mpl-2.0
2,742
package ig import "fmt" // SetTempTarget will set the temperature that the room should be kept to func (ic *IntelliClimate) SetTempTarget(target float64) error { return fmt.Errorf("not implemented") } // SetCO2Target will set the CO2 levels in PPM that the room should be kept to func (ic *IntelliClimate) SetCO2Target(target float64) error { return fmt.Errorf("not implemented") } // SetRHTarget will set the RH target that the room should be kept to func (ic *IntelliClimate) SetRHTarget(target float64) error { return fmt.Errorf("not implemented") } // EnableCO2Dosing will enable the CO2 dosing func (ic *IntelliClimate) EnableCO2Dosing() error { return fmt.Errorf("not implemented") } // DisableCO2Dosing will disable the CO2 dosing func (ic *IntelliClimate) DisableCO2Dosing() error { return fmt.Errorf("not implemented") }
AutogrowSystems/go-jelly
ig/iclimate_functions.go
GO
mpl-2.0
841
<?php namespace ICT\Core\Application; /* * *************************************************************** * Copyright © 2015 ICT Innovations Pakistan All Rights Reserved * * Developed By: Nasir Iqbal * * Website : http://www.ictinnovations.com/ * * Mail : nasir@ictinnovations.com * * *************************************************************** */ use ICT\Core\Application; use ICT\Core\Service\Fax; use ICT\Core\Service\Voice; use ICT\Core\Spool; class Originate extends Application { /** @var string */ public $name = 'originate'; /** * @property-read string $type * @var string */ protected $type = 'originate'; /** * This application, is initial application will be executed at start of transmission * @var int weight */ public $weight = Application::ORDER_INIT; /** * ************************************************ Application Parameters ** */ /** * callerid / phone number of dialing party * @var string $source */ public $source = '[transmission:source:phone]'; /** * phone number of remote party * @var int $destination */ public $destination = '[transmission:destination:phone]'; /** * ******************************************** Default Application Values ** */ /** * If this application require any special dependency * @var integer */ public $defaultSetting = Application::REQUIRE_GATEWAY; public function __construct($application_id = null, $aParameter = null) { $this->defaultSetting = (Application::REQUIRE_END_APPLICATION | Application::REQUIRE_GATEWAY | Application::REQUIRE_PROVIDER); parent::__construct($application_id, $aParameter); } /** * return a name value pair of all aditional application parameters which we need to save * @return array */ public function parameter_save() { $aParameters = array( 'source' => $this->source, 'destination' => $this->destination ); return $aParameters; } public function execute() { if ($this->oTransmission->service_flag == Voice::SERVICE_FLAG) { $oService = new Voice(); } else if ($this->oTransmission->service_flag == Fax::SERVICE_FLAG) { $oService = new Fax(); } $template_path = $oService->template_path('originate'); $oService->application_execute($this, $template_path, 'template'); } public function process() { if (!empty($this->result['result']) && $this->result['result'] == 'success') { return Spool::STATUS_CONNECTED; } else { return Spool::STATUS_FAILED; } } }
ictinnovations/ictcore
core/Application/Originate.php
PHP
mpl-2.0
2,673
package handler import ( "errors" "fmt" "html" "net/http" "strings" "github.com/HouzuoGuo/laitos/daemon/httpd/middleware" "github.com/HouzuoGuo/laitos/lalog" "github.com/HouzuoGuo/laitos/toolbox" ) const HandleCommandFormPage = `<html> <head> <title>Command Form</title> </head> <body> <form action="%s" method="post"> <p><input type="password" name="cmd" /><input type="submit" value="Exec"/></p> <pre>%s</pre> </form> </body> </html> ` // HandleCommandFormPage is the command form's HTML content // HTTPClienAppCommandTimeout is the timeout of app command execution in seconds shared by all capable HTTP endpoints. const HTTPClienAppCommandTimeout = 59 // Run feature commands in a simple web form. type HandleCommandForm struct { cmdProc *toolbox.CommandProcessor stripURLPrefixFromResponse string } func (form *HandleCommandForm) Initialise(_ lalog.Logger, cmdProc *toolbox.CommandProcessor, stripURLPrefixFromResponse string) error { if cmdProc == nil { return errors.New("HandleCommandForm.Initialise: command processor must not be nil") } if errs := cmdProc.IsSaneForInternet(); len(errs) > 0 { return fmt.Errorf("HandleCommandForm.Initialise: %+v", errs) } form.cmdProc = cmdProc form.stripURLPrefixFromResponse = stripURLPrefixFromResponse return nil } func (form *HandleCommandForm) Handle(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") NoCache(w) if r.Method == http.MethodGet { _, _ = w.Write([]byte(fmt.Sprintf(HandleCommandFormPage, strings.TrimPrefix(r.RequestURI, form.stripURLPrefixFromResponse), ""))) } else if r.Method == http.MethodPost { if cmd := r.FormValue("cmd"); cmd == "" { _, _ = w.Write([]byte(fmt.Sprintf(HandleCommandFormPage, strings.TrimPrefix(r.RequestURI, form.stripURLPrefixFromResponse), ""))) } else { result := form.cmdProc.Process(r.Context(), toolbox.Command{ DaemonName: "httpd", ClientTag: middleware.GetRealClientIP(r), Content: cmd, TimeoutSec: HTTPClienAppCommandTimeout, }, true) _, _ = w.Write([]byte(fmt.Sprintf(HandleCommandFormPage, strings.TrimPrefix(r.RequestURI, form.stripURLPrefixFromResponse), html.EscapeString(result.CombinedOutput)))) } } } func (_ *HandleCommandForm) GetRateLimitFactor() int { return 1 } func (_ *HandleCommandForm) SelfTest() error { return nil }
HouzuoGuo/laitos
daemon/httpd/handler/cmd_form.go
GO
mpl-2.0
2,391
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Umbraco.Core.Logging; namespace Jumoo.uSync.Core.Extensions { public static class XElementTrackerExtension { public static string GetSyncHash(this XElement node) { if (node == null) return string.Empty; XElement copy = new XElement(node); // strip ids and stuff. var preVals = copy.Element("PreValues"); if (preVals != null && preVals.HasElements) { foreach(var preVal in preVals.Elements("PreValue")) { preVal.SetAttributeValue("Id", ""); } } // take out any keys? // we might not want to do this, as // keys are something we can set /* foreach(var key in copy.Descendants("Key")) { key.Remove(); } */ // in content types we remove Definition for comparision, because for // custom types it can change. if (copy.Element("GenericProperties") != null) { foreach (var defId in copy.Element("GenericProperties").Descendants("Definition")) { defId.Value = ""; } } var nodes = copy.Element("Nodes"); if (nodes != null) nodes.Remove(); var tabs = copy.Element("Tab"); if (tabs != null && tabs.HasElements) { foreach(var tab in tabs.Elements("Tab")) { if (tab.Element("Id") != null) tab.Element("Id").Remove(); } } if (copy.Name.LocalName == "Language" && copy.Attribute("Id") != null) { copy.Attribute("Id").Remove(); } if (copy.Name.LocalName == "DictionaryItem") { foreach(var val in copy.Elements("Value")) { if (val.Attribute("LanguageId") != null) val.Attribute("LanguageId").Remove(); } } return MakeHash(copy); } private static string MakeHash(XElement node) { string hash = ""; MemoryStream s = new MemoryStream(); node.Save(s); s.Position = 0; using (var md5 = MD5.Create()) { hash = BitConverter.ToString(md5.ComputeHash(s)).Replace("-", "").ToLower(); } s.Close(); return hash; } } }
lucasch/uSync
Jumoo.uSync.Core/Extensions/XElementTrackerExtension.cs
C#
mpl-2.0
2,874
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; // The panel module currently supports only Firefox. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=jetpack-panel-apps module.metadata = { "stability": "stable", "engines": { "Firefox": "*" } }; const { Ci } = require("chrome"); const { Class } = require("sdk/core/heritage"); const { merge } = require("sdk/util/object"); const { WorkerHost } = require("sdk/content/utils"); const { Worker } = require("sdk/deprecated/sync-worker"); const { Disposable } = require("sdk/core/disposable"); const { WeakReference } = require('sdk/core/reference'); const { contract: loaderContract } = require("sdk/content/loader"); const { contract } = require("sdk/util/contract"); const { on, off, emit, setListeners } = require("sdk/event/core"); const { EventTarget } = require("sdk/event/target"); const domPanel = require("./panel/utils"); const { events } = require("./panel/events"); const systemEvents = require("sdk/system/events"); const { filter, pipe, stripListeners } = require("sdk/event/utils"); const { getNodeView, getActiveView } = require("sdk/view/core"); const { isNil, isObject, isNumber } = require("sdk/lang/type"); const { getAttachEventType } = require("sdk/content/utils"); const { number, boolean, object } = require('sdk/deprecated/api-utils'); const { Style } = require("sdk/stylesheet/style"); const { attach, detach } = require("sdk/content/mod"); let isRect = ({top, right, bottom, left}) => [top, right, bottom, left]. some(value => isNumber(value) && !isNaN(value)); let isSDKObj = obj => obj instanceof Class; let rectContract = contract({ top: number, right: number, bottom: number, left: number }); let position = { is: object, map: v => (isNil(v) || isSDKObj(v) || !isObject(v)) ? v : rectContract(v), ok: v => isNil(v) || isSDKObj(v) || (isObject(v) && isRect(v)), msg: 'The option "position" must be a SDK object registered as anchor; ' + 'or an object with one or more of the following keys set to numeric ' + 'values: top, right, bottom, left.' } let displayContract = contract({ width: number, height: number, focus: boolean, autohide: boolean, position: position, opacity: number }); let panelContract = contract(merge({ // contentStyle* / contentScript* are sharing the same validation constraints, // so they can be mostly reused, except for the messages. contentStyle: merge(Object.create(loaderContract.rules.contentScript), { msg: 'The `contentStyle` option must be a string or an array of strings.' }), contentStyleFile: merge(Object.create(loaderContract.rules.contentScriptFile), { msg: 'The `contentStyleFile` option must be a local URL or an array of URLs' }) }, displayContract.rules, loaderContract.rules)); function isDisposed(panel) { return !views.has(panel) } let panels = new WeakMap(); let models = new WeakMap(); let views = new WeakMap(); let workers = new WeakMap(); let styles = new WeakMap(); const viewFor = (panel) => views.get(panel); const modelFor = (panel) => models.get(panel); const panelFor = (view) => panels.get(view); const workerFor = (panel) => workers.get(panel); const styleFor = (panel) => styles.get(panel); // Utility function takes `panel` instance and makes sure it will be // automatically hidden as soon as other panel is shown. let setupAutoHide = new function() { let refs = new WeakMap(); return function setupAutoHide(panel) { // Create system event listener that reacts to any panel showing and // hides given `panel` if it's not the one being shown. function listener({subject}) { // It could be that listener is not GC-ed in the same cycle as // panel in such case we remove listener manually. let view = viewFor(panel); if (!view) systemEvents.off("popupshowing", listener); else if (subject !== view) panel.hide(); } // system event listener is intentionally weak this way we'll allow GC // to claim panel if it's no longer referenced by an add-on code. This also // helps minimizing cleanup required on unload. systemEvents.on("popupshowing", listener); // To make sure listener is not claimed by GC earlier than necessary we // associate it with `panel` it's associated with. This way it won't be // GC-ed earlier than `panel` itself. refs.set(panel, listener); } } const Panel = Class({ implements: [ // Generate accessors for the validated properties that update model on // set and return values from model on get. panelContract.properties(modelFor), EventTarget, Disposable, WeakReference ], extends: WorkerHost(workerFor), setup: function setup(options) { let model = merge({ defaultWidth: 320, defaultHeight: 220, focus: true, position: Object.freeze({}), }, panelContract(options)); models.set(this, model); if (model.contentStyle || model.contentStyleFile) { styles.set(this, Style({ uri: model.contentStyleFile, source: model.contentStyle })); } // Setup view let view = domPanel.make(); panels.set(view, this); views.set(this, view); // Load panel content. domPanel.setURL(view, model.contentURL); setupAutoHide(this); // Setup listeners. setListeners(this, options); let worker = new Worker(stripListeners(options)); workers.set(this, worker); // pipe events from worker to a panel. pipe(worker, this); }, dispose: function dispose() { this.hide(); off(this); workerFor(this).destroy(); detach(styleFor(this)); domPanel.dispose(viewFor(this)); // Release circular reference between view and panel instance. This // way view will be GC-ed. And panel as well once all the other refs // will be removed from it. views.delete(this); }, /* Public API: Panel.width */ get width() { return modelFor(this).width; }, set width(value) { return this.resize(value, this.height); }, /* Public API: Panel.height */ get height() { return modelFor(this).height; }, set height(value) { return this.resize(this.width, value); }, /* Public API: Panel.focus */ get focus() { return modelFor(this).focus; }, /* Public API: Panel.position */ get position() { return modelFor(this).position; }, get contentURL() { modelFor(this).contentURL; }, set contentURL(value) { let model = modelFor(this); model.contentURL = panelContract({ contentURL: value }).contentURL; domPanel.setURL(viewFor(this), model.contentURL); // Detach worker so that messages send will be queued until it's // reatached once panel content is ready. workerFor(this).detach(); }, /* Public API: Panel.isShowing */ get isShowing() { return !isDisposed(this) && domPanel.isOpen(viewFor(this)); }, /* Public API: Panel.show */ show: function show(options={}, anchor) { if (options instanceof Ci.nsIDOMElement) { [anchor, options] = [options, null]; } if (anchor instanceof Ci.nsIDOMElement) { console.warn( "Passing a DOM node to Panel.show() method is an unsupported " + "feature that will be soon replaced. " + "See: https://bugzilla.mozilla.org/show_bug.cgi?id=878877" ); } let model = modelFor(this); let view = viewFor(this); let anchorView = getNodeView(anchor || options.position || model.position); options = merge({ position: model.position, width: model.width, height: model.height, defaultWidth: model.defaultWidth, defaultHeight: model.defaultHeight, focus: model.focus, autohide: model.autohide, opacity: model.opacity }, displayContract(options)); if (!isDisposed(this)) domPanel.show(view, options, anchorView); return this; }, /* Public API: Panel.hide */ hide: function hide() { // Quit immediately if panel is disposed or there is no state change. domPanel.close(viewFor(this)); return this; }, /* Public API: Panel.resize */ resize: function resize(width, height) { let model = modelFor(this); let view = viewFor(this); let change = panelContract({ width: width || model.width || model.defaultWidth, height: height || model.height || model.defaultHeight }); model.width = change.width; model.height = change.height; domPanel.resize(view, model.width, model.height); return this; }, fadeOut: function fadeOut() { let view = viewFor(this); domPanel.fadeOut(view); } }); exports.Panel = Panel; // Note must be defined only after value to `Panel` is assigned. getActiveView.define(Panel, viewFor); // Filter panel events to only panels that are create by this module. let panelEvents = filter(events, ({target}) => panelFor(target)); // Panel events emitted after panel has being shown. let shows = filter(panelEvents, ({type}) => type === "popupshown"); // Panel events emitted after panel became hidden. let hides = filter(panelEvents, ({type}) => type === "popuphidden"); // Panel events emitted after content inside panel is ready. For different // panels ready may mean different state based on `contentScriptWhen` attribute. // Weather given event represents readyness is detected by `getAttachEventType` // helper function. let ready = filter(panelEvents, ({type, target}) => getAttachEventType(modelFor(panelFor(target))) === type); // Panel event emitted when the contents of the panel has been loaded. let readyToShow = filter(panelEvents, ({type}) => type === "DOMContentLoaded"); // Styles should be always added as soon as possible, and doesn't makes them // depends on `contentScriptWhen` let start = filter(panelEvents, ({type}) => type === "document-element-inserted"); // Forward panel show / hide events to panel's own event listeners. on(shows, "data", ({target}) => { let panel = panelFor(target); if (modelFor(panel).ready) emit(panel, "show"); }); on(hides, "data", ({target}) => { let panel = panelFor(target); if (modelFor(panel).ready) emit(panel, "hide"); }); on(ready, "data", ({target}) => { let panel = panelFor(target); let window = domPanel.getContentDocument(target).defaultView; workerFor(panel).attach(window); }); on(readyToShow, "data", ({target}) => { let panel = panelFor(target); if (!modelFor(panel).ready) { modelFor(panel).ready = true; if (viewFor(panel).state == "open") emit(panel, "show"); } }); on(start, "data", ({target}) => { let panel = panelFor(target); let window = domPanel.getContentDocument(target).defaultView; attach(styleFor(panel), window); });
raymak/contextualfeaturerecommender
phase2/addon/lib/panel.js
JavaScript
mpl-2.0
10,892