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
<!DOCTYPE html> <html lang="en"> <head> <title><?php if(isset($page_title)) : ?><?php echo $page_title ?> - <?php endif; ?><?php echo $this->settings->info->site_name ?></title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php if(isset($page_desc)) : ?> <meta name="description" content="<?php echo $page_desc ?>"> <?php endif; ?> <!-- Bootstrap --> <link href="<?php echo base_url();?>bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="<?php echo base_url();?>bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> <!-- Styles --> <link href="<?php echo base_url();?>styles/layouts/titan/main.css" rel="stylesheet" type="text/css"> <link href="<?php echo base_url();?>styles/layouts/titan/dashboard.css" rel="stylesheet" type="text/css"> <link href="<?php echo base_url();?>styles/layouts/titan/responsive.css" rel="stylesheet" type="text/css"> <link href="<?php echo base_url();?>styles/elements.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,500,600,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" /> <!-- SCRIPTS --> <script type="text/javascript"> var global_base_url = "<?php echo site_url('/') ?>"; var global_hash = "<?php echo $this->security->get_csrf_hash() ?>"; </script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.12/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/bs/dt-1.10.12/datatables.min.js"></script> <script type="text/javascript"> $.widget.bridge('uitooltip', $.ui.tooltip); </script> <script src="<?php echo base_url();?>bootstrap/js/bootstrap.min.js"></script> <!-- Favicon: http://realfavicongenerator.net --> <link rel="apple-touch-icon" sizes="57x57" href="<?php echo base_url() ?>images/favicon/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="<?php echo base_url() ?>images/favicon/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="<?php echo base_url() ?>images/favicon/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="<?php echo base_url() ?>images/favicon/apple-touch-icon-76x76.png"> <link rel="icon" type="image/png" href="<?php echo base_url() ?>images/favicon/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="<?php echo base_url() ?>images/favicon/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="<?php echo base_url() ?>images/favicon/manifest.json"> <link rel="mask-icon" href="<?php echo base_url() ?>images/favicon/safari-pinned-tab.svg" color="#5bbad5"> <link rel="shortcut icon" href="<?php echo base_url() ?>images/favicon/favicon.ico"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="msapplication-config" content="<?php echo base_url() ?>images/favicon/browserconfig.xml"> <meta name="theme-color" content="#ffffff"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <script type="text/javascript"> $.widget.bridge('uitooltip', $.ui.tooltip); </script> <script type="text/javascript"> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> <!-- CODE INCLUDES --> <?php echo $cssincludes ?> </head> <body> <nav class="navbar navbar-header2 navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <?php if(!$this->settings->info->logo_option) : ?> <a class="navbar-brand" href="<?php echo site_url() ?>" title="<?php echo $this->settings->info->site_name ?>"><?php echo $this->settings->info->site_name ?></a> <?php else : ?> <a class="navbar-brand-two" href="<?php echo site_url() ?>" title="<?php echo $this->settings->info->site_name ?>"><img src="<?php echo base_url() ?><?php echo $this->settings->info->upload_path_relative ?>/<?php echo $this->settings->info->site_logo ?>" width="123" height="32"></a> <?php endif; ?> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <?php if($this->user->loggedin) : ?> <li class="user_bit"><img src="<?php echo base_url() ?><?php echo $this->settings->info->upload_path_relative ?>/<?php echo $this->user->info->avatar ?>" class="user_avatar user_icon"> <a href="<?php echo site_url("user_settings") ?>"><?php echo $this->user->info->username ?></a></li> <li><a href="<?php echo site_url("login/logout/" . $this->security->get_csrf_hash()) ?>"><?php echo lang("ctn_149") ?></a></li> <?php else : ?> <li><a href="<?php echo site_url("login") ?>"><?php echo lang("ctn_150") ?></a></li> <li><a href="<?php echo site_url("register") ?>"><?php echo lang("ctn_151") ?></a></li> <?php endif; ?> </ul> </div> </div> </nav> <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <?php if(isset($sidebar)) : ?> <?php echo $sidebar ?> <?php endif; ?> <?php include("sidebar_links.php") ?> </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <?php include("mobile_links.php") ?> <?php if($this->settings->info->install) : ?> <div class="row"> <div class="col-md-12"> <div class="alert alert-info"><b><span class="glyphicon glyphicon-warning-sign"></span></b> <a href="<?php echo site_url("install") ?>">Great job on uploading all the files and setting up the site correctly! Let's now create the Admin account and set the default settings. Click here! This message will disappear once you have run the install process.</a></div> </div> </div> <?php endif; ?> <?php $gl = $this->session->flashdata('globalmsg'); ?> <?php if(!empty($gl)) :?> <div class="row"> <div class="col-md-12"> <div class="alert alert-success"><b><span class="glyphicon glyphicon-ok"></span></b> <?php echo $this->session->flashdata('globalmsg') ?></div> </div> </div> <?php endif; ?> <?php echo $content ?> <hr> <p class="align-center small-text"><?php echo lang("ctn_170") ?> <a href="https://www.fibosoft.com/">Fibosoft</a><br /> <?php echo $this->settings->info->site_name ?> V<?php echo $this->settings->version ?> - <a href="<?php echo site_url("home/change_language") ?>"><?php echo lang("ctn_171") ?></a></p> </div> </div> </div> <script type="text/javascript"> $(document).ready(function() { $('.nav-sidebar li').on('shown.bs.collapse', function () { $(this).find(".glyphicon-menu-right") .removeClass("glyphicon-menu-right") .addClass("glyphicon-menu-down"); }); $('.nav-sidebar li').on('hidden.bs.collapse', function () { $(this).find(".glyphicon-menu-down") .removeClass("glyphicon-menu-down") .addClass("glyphicon-menu-right"); }); }); </script> </body> </html>
codeamancoder/PrPollsApp
application/views/layout/titan_layout.php
PHP
gpl-3.0
8,799
// Package config is resposible for finding, parsing and merging the HTTPMS user // configuration with the default. Configuration locations should be different // depending on the host OS. // // Linux/BSD configurations should be in $HOME/.euterpe/config.json // Windows configurations should be in %APPDATA%/euterpe/config.json package config import ( "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" "log" "os/user" "path/filepath" "time" "github.com/ironsmile/euterpe/src/helpers" "github.com/spf13/afero" ) const ( // configName contains the name of the actual configuration file. This is the one // the user is supposed to change. configName = "config.json" defaultlistAddress = "localhost:9996" defaultSecretBytes = 64 ) // defaultConfig contains all the default values for the Euterpe configuration. Users // can overwrite values here with their user's configuration. var defaultConfig = Config{ Listen: defaultlistAddress, LogFile: "euterpe.log", SqliteDatabase: "euterpe.db", Gzip: true, ReadTimeout: 15, WriteTimeout: 1200, MaxHeadersSize: 1048576, } // Config contains representation for everything in config.json type Config struct { Listen string `json:"listen,omitempty"` SSL bool `json:"ssl,omitempty"` SSLCertificate Cert `json:"ssl_certificate,omitempty"` Auth bool `json:"basic_authenticate,omitempty"` Authenticate Auth `json:"authentication,omitempty"` Libraries []string `json:"libraries,omitempty"` LibraryScan ScanSection `json:"library_scan,omitempty"` LogFile string `json:"log_file,omitempty"` SqliteDatabase string `json:"sqlite_database,omitempty"` Gzip bool `json:"gzip,omitempty"` ReadTimeout int `json:"read_timeout,omitempty"` WriteTimeout int `json:"write_timeout,omitempty"` MaxHeadersSize int `json:"max_header_bytes,omitempty"` DownloadArtwork bool `json:"download_artwork,omitempty"` DiscogsAuthToken string `json:"discogs_auth_token,omitempty"` } // ScanSection is used for merging the two configs. Its purpose is to essentially // hold the default values for its properties. type ScanSection struct { Disable bool `json:"disable,omitempty"` FilesPerOperation int64 `json:"files_per_operation,omitempty"` SleepPerOperation time.Duration `json:"sleep_after_operation,omitempty"` InitialWait time.Duration `json:"initial_wait_duration,omitempty"` } // UnmarshalJSON parses a JSON and populets its ScanSection. Satisfies the // Unmrashaller interface. func (ss *ScanSection) UnmarshalJSON(input []byte) error { ssProxy := &struct { Disable bool `json:"disable"` FilesPerOperation int64 `json:"files_per_operation"` SleepPerOperation string `json:"sleep_after_operation"` InitialWait string `json:"initial_wait_duration"` }{} if err := json.Unmarshal(input, ssProxy); err != nil { return err } ss.Disable = ssProxy.Disable ss.FilesPerOperation = ssProxy.FilesPerOperation if ssProxy.SleepPerOperation != "" { spo, err := time.ParseDuration(ssProxy.SleepPerOperation) if err != nil { return err } ss.SleepPerOperation = spo } if ssProxy.InitialWait != "" { iwd, err := time.ParseDuration(ssProxy.InitialWait) if err != nil { return err } ss.InitialWait = iwd } if ss.FilesPerOperation < 0 { return errors.New("files_per_operation must be a positive integer") } return nil } // Cert represents a configuration for TLS certificate type Cert struct { Crt string `json:"crt,omitempty"` Key string `json:"key,omitempty"` } // Auth represents a configuration HTTP Basic authentication type Auth struct { User string `json:"user,omitempty"` Password string `json:"password,omitempty"` Secret string `json:"secret"` } // FindAndParse actually finds the configuration file, parsing it and merging it on // top the default configuration. func FindAndParse(appfs afero.Fs) (Config, error) { if !userConfigExists(appfs) { err := copyDefaultOverUser(appfs) if err != nil { return Config{}, err } } cfg := defaultConfig userCfgPath := UserConfigPath(appfs) fh, err := appfs.Open(userCfgPath) if err != nil { return Config{}, fmt.Errorf("opening config: %s", err) } defer fh.Close() dec := json.NewDecoder(fh) if err := dec.Decode(&cfg); err != nil { return Config{}, fmt.Errorf("decoding config: %s", err) } return cfg, nil } // UserConfigPath returns the full path to the place where the user's configuration // file should be func UserConfigPath(appfs afero.Fs) string { path, err := helpers.ProjectUserPath(appfs) if err != nil { log.Println(err) return "" } return filepath.Join(path, configName) } // userConfigExists returns true if the user configuration is present and in order. // Otherwise false. func userConfigExists(appfs afero.Fs) bool { path := UserConfigPath(appfs) st, err := appfs.Stat(path) if err != nil { return false } return !st.IsDir() } // copyDefaultOverUser will create (or replace if neccessery) the user configuration // using the default config new config. func copyDefaultOverUser(appfs afero.Fs) error { var homeDir = "~" user, err := user.Current() if err == nil { homeDir = user.HomeDir } randBuff := make([]byte, defaultSecretBytes) if _, err := rand.Read(randBuff); err != nil { return fmt.Errorf("creating random secret: %s", err) } userCfg := Config{ Listen: defaultlistAddress, Libraries: []string{ filepath.Join(homeDir, "Music"), }, Authenticate: Auth{ Secret: hex.EncodeToString(randBuff), }, } userCfgPath := UserConfigPath(appfs) fh, err := appfs.Create(userCfgPath) if err != nil { return fmt.Errorf("create config `%s`: %s", userCfgPath, err) } defer fh.Close() enc := json.NewEncoder(fh) enc.SetIndent("", " ") if err := enc.Encode(&userCfg); err != nil { return fmt.Errorf("encoding default config `%s`: %s", userCfgPath, err) } return nil }
ironsmile/httpms
src/config/config.go
GO
gpl-3.0
6,093
package net.parostroj.timetable.gui.pm; import org.beanfabrics.model.AbstractPM; import org.beanfabrics.model.OperationPM; import org.beanfabrics.model.Options; import org.beanfabrics.model.PMManager; import org.beanfabrics.support.Operation; import net.parostroj.timetable.model.LocalizedString; import net.parostroj.timetable.utils.Reference; public class LocalizationPM<T extends Reference<LocalizedString>> extends AbstractPM implements IPM<LocalizationContext<T>> { final IEnumeratedValuesPM<LocalizationType<T>> types; final LocalizedStringListPM<T> selected; final OperationPM ok; private LocalizationContext<T> context; public LocalizationPM() { ok = new OperationPM(); types = new EnumeratedValuesPM<>(new Options<>()); selected = new LocalizedStringListPM<>(); selected.setSorted(true); types.addPropertyChangeListener("text", evt -> { LocalizationType<T> item = types.getValue(); if (item != null) { selected.init(item, item.getStrings().isEmpty() ? null : item.getStrings().iterator().next()); } }); PMManager.setup(this); } @Override public void init(LocalizationContext<T> context) { this.context = context; for (LocalizationType<T> type : context) { types.addValue(type, type.getDescription()); } types.setText(types.getOptions().getValues()[0]); } @Operation(path = "ok") public boolean writeBack() { context.writeBack(); return true; } }
jub77/grafikon
grafikon-gui-components/src/main/java/net/parostroj/timetable/gui/pm/LocalizationPM.java
Java
gpl-3.0
1,579
<?php /** * @package Joomla * @subpackage glogger * @version 1.0.0 November, 2016 * @author Greg Podesta * @copyright Copyright (C) 2016 Greg Podesta * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * 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. * */ defined("_JEXEC") or die("Restricted access"); class GloggerController extends JControllerLegacy { /** * The default view for the display method. * * @var string * @since 12.2 */ protected $default_view = 'glogs'; /** * Checks whether a user can see this view. * * @param string $view The view name. * * @return boolean * @since 1.6 */ protected function canView($view) { $canDo = GloggerHelper::getActions(); return $canDo->get('core.admin'); } /** * Method to display a view. * * @param boolean If true, the view output will be cached * @param array An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}. * * @return JController This object to support chaining. * @since 1.5 */ public function display($cachable = false, $urlparams = false) { // Get the document object. $document = JFactory::getDocument(); // Set the default view name and format from the Request. $vName = $this->input->getCmd('view', 'glogs'); $vFormat = $document->getType(); $lName = $this->input->getCmd('layout', 'default'); // Check whether user is allowed to admin component if (!$this->canView($vName)) { JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR')); return; } // Get the model and the view $model = $this->getModel($vName); $view = $this->getView($vName, $vFormat); // Push the model into the view (as default). $view->setModel($model, true); $view->setLayout($lName); // Push document object into the view. $view->document = $document; // Display the view $view->display(); } } ?>
Joomla-StackExchange/glogger
com_glogger/admin/controller.php
PHP
gpl-3.0
2,170
/** * Provides the PRNG API. */ package org.dayflower.pipeline.prng;
WavePropagation/org.dayflower
src/main/org/dayflower/pipeline/prng/package-info.java
Java
gpl-3.0
73
/* * Copyright 2013, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.immutable.instruction; import org.jf.dexlib2.Format; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.ReferenceType; import org.jf.dexlib2.iface.instruction.formats.Instruction20bc; import org.jf.dexlib2.iface.reference.Reference; import org.jf.dexlib2.immutable.reference.ImmutableReference; import org.jf.dexlib2.immutable.reference.ImmutableReferenceFactory; import org.jf.dexlib2.util.Preconditions; public class ImmutableInstruction20bc extends ImmutableInstruction implements Instruction20bc { public static final Format FORMAT = Format.Format20bc; protected final int verificationError; protected final ImmutableReference reference; public ImmutableInstruction20bc(Opcode opcode, int verificationError, Reference reference) { super(opcode); this.verificationError = Preconditions.checkVerificationError(verificationError); this.reference = ImmutableReferenceFactory.of(opcode.referenceType, reference); } public static ImmutableInstruction20bc of(Instruction20bc instruction) { if (instruction instanceof ImmutableInstruction20bc) { return (ImmutableInstruction20bc) instruction; } return new ImmutableInstruction20bc( instruction.getOpcode(), instruction.getVerificationError(), instruction.getReference()); } @Override public int getVerificationError() { return verificationError; } @Override public ImmutableReference getReference() { return reference; } @Override public int getReferenceType() { return ReferenceType.getReferenceType(reference); } @Override public Format getFormat() { return FORMAT; } }
droidefense/engine
mods/memapktool/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableInstruction20bc.java
Java
gpl-3.0
3,404
<?= form_open('admin/themes/delete');?> <table border="0" class="listTable"> <thead> <tr> <th class="first"><div></div></th> <th><a href="#">Theme</a></th> <th class="last width-quater"><span>Actions</span></th> </tr> </thead> <tfoot> <tr> <td colspan="3"> <div class="inner"></div> </td> </tr> </tfoot> <tbody> <? if (!empty($themes)) { foreach ($themes as $theme) { echo '<tr> <td align="center"><input type="checkbox" name="delete[]" value="' . $theme->name . '" /></td> <td>' . $theme->name . '</td> <td>'; if($this->settings->item('default_theme') != $theme->name) echo anchor('admin/themes/setdefault/' . $theme->slug, 'Make Default') . ' | ' . anchor('admin/themes/delete/' . $theme->slug, 'Delete', array('class'=>'confirm')); else echo '<i>Default Theme</i>'; echo ' </td> </tr>'; } } else { echo '<tr><td colspan="3">There are no themes installed.</td></tr>'; } ?> </tbody> </table> <? $this->load->view('admin/layout_fragments/table_buttons', array('buttons' => array('delete') )); ?> <?=form_close(); ?>
bema2004sw/pyrocms
application/modules/themes/views/admin/index.php
PHP
gpl-3.0
1,110
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit2e778ed2e76984494f1302351c05d0ef { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit2e778ed2e76984494f1302351c05d0ef', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit2e778ed2e76984494f1302351c05d0ef', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION'); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit2e778ed2e76984494f1302351c05d0ef::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit2e778ed2e76984494f1302351c05d0ef::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire2e778ed2e76984494f1302351c05d0ef($fileIdentifier, $file); } return $loader; } } function composerRequire2e778ed2e76984494f1302351c05d0ef($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { require $file; $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } }
fzq19900228/fzq
vendor/composer/autoload_real.php
PHP
gpl-3.0
2,333
/** * */ package com.lucasbt.laboratorio.dinamizacaoenums.typesafe; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import com.lucasbt.laboratorio.dinamizacaoenums.TipoConta; import com.lucasbt.laboratorio.dinamizacaoenums.TipoContaPersonalizado; /** * @author lucas */ @RunWith(MockitoJUnitRunner.class) public class TipoContaPersonalizadoImplTest { /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } @Test public void testIsBeneficio() throws Exception { TipoContaPersonalizado tipoContaBeneficio = TipoContaPersonalizadoImpl.BENEFICIO; Assert.assertTrue(tipoContaBeneficio.isBeneficio()); } @Test public void testIsNotBeneficio() throws Exception { TipoConta<?> tipo = TipoContaPersonalizadoImpl.CORRENTE; Assert.assertTrue(tipo.isCorrente()); } }
lucasbt/dinamizacao-enum
src/test/java/com/lucasbt/laboratorio/dinamizacaoenums/typesafe/TipoContaPersonalizadoImplTest.java
Java
gpl-3.0
1,108
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 org.craftercms.deployer.impl.processors.git; import org.apache.commons.configuration2.Configuration; import org.apache.commons.lang3.BooleanUtils; import org.craftercms.commons.config.ConfigUtils; import org.craftercms.commons.config.ConfigurationException; import org.craftercms.deployer.api.ChangeSet; import org.craftercms.deployer.api.Deployment; import org.craftercms.deployer.api.ProcessorExecution; import org.craftercms.deployer.api.exceptions.DeployerException; import org.craftercms.deployer.impl.ProcessedCommitsStore; import org.craftercms.deployer.impl.processors.AbstractMainDeploymentProcessor; import org.craftercms.deployer.impl.processors.elasticsearch.ElasticsearchIndexingProcessor; import org.craftercms.deployer.utils.GitUtils; import org.craftercms.search.batch.UpdateDetail; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.LogCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.revwalk.RevCommit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import java.io.File; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static org.apache.commons.lang3.StringUtils.prependIfMissing; import static org.apache.commons.lang3.StringUtils.removeEnd; import static org.craftercms.deployer.impl.DeploymentConstants.FROM_COMMIT_ID_PARAM_NAME; import static org.craftercms.deployer.impl.DeploymentConstants.LATEST_COMMIT_ID_PARAM_NAME; import static org.craftercms.deployer.impl.DeploymentConstants.REPROCESS_ALL_FILES_PARAM_NAME; /** * Processor that, based on a previous processed commit that's stored, does a diff with the current commit of the deployment, to * find out the change set. If there is no previous processed commit, then the entire repository becomes the change set. This processor * is used basically to create the change set and should be used before other processors that actually process the change set, like * {@link ElasticsearchIndexingProcessor}. * * @author avasquez */ public class GitDiffProcessor extends AbstractMainDeploymentProcessor { private static final Logger logger = LoggerFactory.getLogger(GitDiffProcessor.class); protected static final String INCLUDE_GIT_LOG_CONFIG_KEY = "includeGitLog"; public static final String UPDATE_COMMIT_CONFIG_KEY = "updateCommitStore"; protected File localRepoFolder; protected ProcessedCommitsStore processedCommitsStore; // Config properties (populated on init) protected boolean includeGitLog; protected String blobFileExtension; protected boolean updateCommitStore; /** * Sets the local filesystem folder the contains the deployed repository. */ @Required public void setLocalRepoFolder(File localRepoFolder) { this.localRepoFolder = localRepoFolder; } /** * Sets the store for processed commits. */ @Required public void setProcessedCommitsStore(ProcessedCommitsStore processedCommitsStore) { this.processedCommitsStore = processedCommitsStore; } public void setBlobFileExtension(String blobFileExtension) { this.blobFileExtension = blobFileExtension; } @Override protected void doInit(Configuration config) throws ConfigurationException { this.includeGitLog = ConfigUtils.getBooleanProperty(config, INCLUDE_GIT_LOG_CONFIG_KEY, false); updateCommitStore = ConfigUtils.getBooleanProperty(config, UPDATE_COMMIT_CONFIG_KEY, true); // use true as default for backward compatibility failDeploymentOnFailure = config.getBoolean(FAIL_DEPLOYMENT_CONFIG_KEY, true); } @Override protected void doDestroy() throws DeployerException { // Do nothing } @Override public boolean supportsMode(Deployment.Mode mode) { return mode == Deployment.Mode.PUBLISH || mode == Deployment.Mode.SEARCH_INDEX; } @Override protected boolean shouldExecute(Deployment deployment, ChangeSet filteredChangeSet) { // Run if the deployment is running return deployment.isRunning(); } @Override protected ChangeSet doMainProcess(Deployment deployment, ProcessorExecution execution, ChangeSet filteredChangeSet, ChangeSet originalChangeSet) throws DeployerException { boolean regularPublish = deployment.getMode() == Deployment.Mode.PUBLISH; ObjectId fromCommitId = getFromCommitIdParam(deployment); boolean reprocessAllFiles = getReprocessAllFilesParam(deployment); if (fromCommitId == null && reprocessAllFiles) { if (regularPublish) { processedCommitsStore.delete(targetId); } logger.info("All files from local repo {} will be reprocessed", localRepoFolder); } try (Git git = openLocalRepository()) { ObjectId previousCommitId = null; if (fromCommitId == null) { if (!reprocessAllFiles) { previousCommitId = processedCommitsStore.load(targetId); } } else { previousCommitId = fromCommitId; } ObjectId latestCommitId = getLatestCommitId(git); ChangeSet changeSet = resolveChangeSetFromCommits(git, previousCommitId, latestCommitId); if (changeSet != null) { if (includeGitLog) { updateChangeDetails(changeSet, git, previousCommitId, latestCommitId); } execution.setStatusDetails("Changes detected and resolved successfully"); } else { execution.setStatusDetails("No changes detected"); } // Make the new commit id available for other processors deployment.addParam(LATEST_COMMIT_ID_PARAM_NAME, latestCommitId); if (updateCommitStore && regularPublish) { processedCommitsStore.store(targetId, latestCommitId); } return changeSet; } } protected void updateChangeDetails(ChangeSet changeSet, Git git, ObjectId previousCommitId, ObjectId latestCommitId) { Map<String, UpdateDetail> changeDetails = new HashMap<>(); Map<String, String> changeLog = new HashMap<>(); try { LogCommand logCmd = git.log(); if (previousCommitId != null && latestCommitId != null) { logCmd.addRange(git.getRepository().parseCommit(previousCommitId), git.getRepository().parseCommit(latestCommitId)); } Iterable<RevCommit> log = logCmd.call(); for (RevCommit commit : log) { UpdateDetail detail = new UpdateDetail(); detail.setAuthor(commit.getAuthorIdent().getName()); detail.setDate(Instant.ofEpochSecond(commit.getCommitTime())); changeDetails.put(commit.getName(), detail); try (ObjectReader reader = git.getRepository().newObjectReader()) { RevCommit parent = commit.getParentCount() > 0? commit.getParent(0) : null; List<DiffEntry> diff = GitUtils.doDiff(git, reader, parent, commit); diff.forEach(entry -> { if(entry.getChangeType() != DiffEntry.ChangeType.DELETE) { changeLog.putIfAbsent(removeEnd(entry.getNewPath(), blobFileExtension), commit.getName()); } }); } } changeSet.setUpdateDetails(changeDetails); changeSet.setUpdateLog(changeLog); } catch (Exception e) { logger.error("Error getting git log for commits {} {}", previousCommitId, latestCommitId, e); } } protected Git openLocalRepository() throws DeployerException { try { logger.debug("Opening local Git repository at {}", localRepoFolder); return GitUtils.openRepository(localRepoFolder); } catch (IOException e) { throw new DeployerException("Failed to open Git repository at " + localRepoFolder, e); } } protected ObjectId getLatestCommitId(Git git) throws DeployerException { try { return git.getRepository().resolve(Constants.HEAD); } catch (IOException e) { throw new DeployerException("Unable to retrieve HEAD commit ID", e); } } protected ChangeSet resolveChangeSetFromCommits(Git git, ObjectId fromCommitId, ObjectId toCommitId) throws DeployerException { String fromCommitIdStr = fromCommitId != null? fromCommitId.name(): "{empty}"; String toCommitIdStr = toCommitId != null? toCommitId.name(): "{empty}"; if (!Objects.equals(fromCommitId, toCommitId)) { logger.info("Calculating change set from commits: {} -> {}", fromCommitIdStr, toCommitIdStr); try (ObjectReader reader = git.getRepository().newObjectReader()) { return processDiffEntries(GitUtils.doDiff(git, reader, fromCommitId, toCommitId)); } catch (IOException | GitAPIException e) { throw new DeployerException("Failed to calculate change set from commits: " + fromCommitIdStr + " -> " + toCommitIdStr, e); } } else { logger.info("Commits are the same. No change set will be calculated"); return null; } } protected ChangeSet processDiffEntries(List<DiffEntry> diffEntries) { List<String> createdFiles = new ArrayList<>(); List<String> updatedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); String newPath; String oldPath; for (DiffEntry entry : diffEntries) { switch (entry.getChangeType()) { case MODIFY: newPath = asContentStoreUrl(entry.getNewPath()); updatedFiles.add(newPath); logger.debug("Updated file: {}", newPath); break; case DELETE: oldPath = asContentStoreUrl(entry.getOldPath()); deletedFiles.add(oldPath); logger.debug("Deleted file: {}", oldPath); break; case RENAME: oldPath = asContentStoreUrl(entry.getOldPath()); newPath = asContentStoreUrl(entry.getNewPath()); deletedFiles.add(oldPath); createdFiles.add(newPath); logger.debug("Renamed file: {} -> {}", oldPath, newPath); break; case COPY: oldPath = asContentStoreUrl(entry.getOldPath()); newPath = asContentStoreUrl(entry.getNewPath()); createdFiles.add(newPath); logger.debug("Copied file: {} -> {}", oldPath, newPath); break; default: // ADD newPath = asContentStoreUrl(entry.getNewPath()); createdFiles.add(newPath); logger.debug("New file: {}", newPath); break; } } return new ChangeSet(createdFiles, updatedFiles, deletedFiles); } protected String asContentStoreUrl(String path) { return removeEnd(prependIfMissing(path, "/"), blobFileExtension); } protected boolean getReprocessAllFilesParam(Deployment deployment) { Object value = deployment.getParam(REPROCESS_ALL_FILES_PARAM_NAME); if (value != null) { if (value instanceof Boolean) { return (Boolean)value; } else { return BooleanUtils.toBoolean(value.toString()); } } else { return false; } } protected ObjectId getFromCommitIdParam(Deployment deployment) { ObjectId objectId = null; Object value = deployment.getParam(FROM_COMMIT_ID_PARAM_NAME); if (value != null) { objectId = ObjectId.fromString((String) value); } return objectId; } }
craftercms/deployer
src/main/java/org/craftercms/deployer/impl/processors/git/GitDiffProcessor.java
Java
gpl-3.0
13,330
#ifndef WINDOW_HPP_ #define WINDOW_HPP_ /* En este archivo se describe e implementa un smob * para la clase RenderWindow de la libreria SFML 2.1 */ #include <SFML/Graphics/RenderWindow.hpp> #include <libguile.h> #include "Vector.hpp" #include "Color.hpp" #include "Event.hpp" #include "Rectangle.hpp" struct WindowSmob { sf::RenderWindow * ptr; }; static scm_t_bits WindowTag; WindowSmob * scmToWindow(SCM smob) { scm_assert_smob_type(WindowTag, smob); return (WindowSmob *) SCM_SMOB_DATA(smob); } SCM markWindow(SCM smob) { return SCM_BOOL_F; } size_t freeWindow(SCM smob) { WindowSmob * s = scmToWindow(smob); delete s->ptr; scm_gc_free(s, sizeof(WindowSmob), "Window"); return 0; } int printWindow(SCM smob, SCM port, scm_print_state * ps) { scm_puts("#<Window>", port); return 1; } SCM windowMake(SCM w, SCM h, SCM bpp, SCM t) { WindowSmob * s; s = (WindowSmob *)scm_gc_malloc(sizeof(WindowSmob), "Window"); s->ptr = new sf::RenderWindow(sf::VideoMode(scm_to_int(w), scm_to_int(h), scm_to_int(bpp)), scm_to_locale_string(t)); return scm_new_smob(WindowTag, (scm_t_bits)s); } SCM windowGetSize(SCM smob) { WindowSmob * s = scmToWindow(smob); unsigned int car = s->ptr->getSize().x; unsigned int cdr = s->ptr->getSize().y; return vector2u(car, cdr); } SCM windowCreate(SCM smob, SCM w, SCM h, SCM bpp, SCM t) { WindowSmob * s = scmToWindow(smob); s->ptr->create(sf::VideoMode(scm_to_int(w), scm_to_int(h), scm_to_int(bpp)), scm_to_locale_string(t)); return SCM_UNSPECIFIED; } SCM windowClose(SCM smob) { WindowSmob * s = scmToWindow(smob); s->ptr->close(); return SCM_UNSPECIFIED; } SCM windowIsOpen(SCM smob) { WindowSmob * s = scmToWindow(smob); if(s->ptr->isOpen()) return SCM_BOOL_T; else return SCM_BOOL_F; } SCM windowPollEvent(SCM smob, SCM event) { WindowSmob * s = scmToWindow(smob); EventSmob * e = scmToEvent(event); if(s->ptr->pollEvent(*(e->ptr))) return SCM_BOOL_T; else return SCM_BOOL_F; } SCM windowWaitEvent(SCM smob, SCM event) { WindowSmob * s = scmToWindow(smob); EventSmob * e = scmToEvent(event); if(s->ptr->waitEvent(*(e->ptr))) return SCM_BOOL_T; else return SCM_BOOL_F; } SCM windowGetPosition(SCM smob) { WindowSmob * s = scmToWindow(smob); int car = s->ptr->getPosition().x; int cdr = s->ptr->getPosition().y; return vector2i(car, cdr); } SCM windowSetPosition(SCM smob, SCM x, SCM y) { WindowSmob * s = scmToWindow(smob); s->ptr->setPosition(sf::Vector2i(scm_to_int(x), scm_to_int(y))); return SCM_UNSPECIFIED; } SCM windowSetSize(SCM smob, SCM x, SCM y) { WindowSmob * s = scmToWindow(smob); s->ptr->setSize(sf::Vector2u(scm_to_int(x), scm_to_int(y))); return SCM_UNSPECIFIED; } SCM windowSetTitle(SCM smob, SCM title) { WindowSmob * s = scmToWindow(smob); s->ptr->setTitle(scm_to_locale_string(title)); return SCM_UNSPECIFIED; } SCM windowSetVisible(SCM smob, SCM visible) { WindowSmob * s = scmToWindow(smob); s->ptr->setVisible(scm_is_true(visible)); return SCM_UNSPECIFIED; } SCM windowSetVerticalSync(SCM smob, SCM sync) { WindowSmob * s = scmToWindow(smob); s->ptr->setVerticalSyncEnabled(scm_is_true(sync)); return SCM_UNSPECIFIED; } SCM windowSetMouseCursorVisible(SCM smob, SCM visible) { WindowSmob * s = scmToWindow(smob); s->ptr->setMouseCursorVisible(scm_is_true(visible)); return SCM_UNSPECIFIED; } SCM windowSetKeyRepeat(SCM smob, SCM rep) { WindowSmob * s = scmToWindow(smob); s->ptr->setKeyRepeatEnabled(scm_is_true(rep)); return SCM_UNSPECIFIED; } SCM windowSetFramerateLimit(SCM smob, SCM limit) { WindowSmob * s = scmToWindow(smob); s->ptr->setFramerateLimit(scm_to_int(limit)); return SCM_UNSPECIFIED; } SCM windowSetActive(SCM smob, SCM active) { WindowSmob * s = scmToWindow(smob); s->ptr->setActive(scm_is_true(active)); return SCM_UNSPECIFIED; } SCM windowDisplay(SCM smob) { WindowSmob * s = scmToWindow(smob); s->ptr->display(); return SCM_UNSPECIFIED; } SCM windowClear(SCM smob, SCM color) { WindowSmob * s = scmToWindow(smob); ColorSmob * c = scmToColor(color); s->ptr->clear(sf::Color(c->ptr->r, c->ptr->g, c->ptr->b, c->ptr->a)); return SCM_UNSPECIFIED; } SCM windowMapPixelToCoords(SCM smob, SCM x, SCM y) { WindowSmob * s = scmToWindow(smob); double car = s->ptr->mapPixelToCoords(sf::Vector2i(scm_to_int(x), scm_to_int(y))).x; double cdr = s->ptr->mapPixelToCoords(sf::Vector2i(scm_to_int(x), scm_to_int(y))).y; return vector2f(car, cdr); } SCM windowMapCoordsToPixel(SCM smob, SCM x, SCM y) { WindowSmob * s = scmToWindow(smob); int car = s->ptr->mapCoordsToPixel(sf::Vector2f(scm_to_double(x), scm_to_double(y))).x; int cdr = s->ptr->mapCoordsToPixel(sf::Vector2f(scm_to_double(x), scm_to_double(y))).y; return vector2i(car, cdr); } SCM windowDrawRectangle(SCM smob, SCM rectangle) { WindowSmob * s = scmToWindow(smob); RectangleSmob * r = scmToRectangle(rectangle); s->ptr->draw(*(r->ptr)); return SCM_UNSPECIFIED; } SCM getMousePosition(SCM smob) { WindowSmob * s = scmToWindow(smob); sf::Vector2i v = sf::Mouse::getPosition(*(s->ptr)); return vector2i(v.x, v.y); } void initWindowType() { WindowTag = scm_make_smob_type("Window", sizeof(WindowSmob)); scm_set_smob_mark(WindowTag, markWindow); scm_set_smob_free(WindowTag, freeWindow); scm_set_smob_print(WindowTag, printWindow); scm_c_define_gsubr("window-make", 4, 0, 0, (void *)windowMake); scm_c_define_gsubr("window-get-size", 1, 0, 0, (void *)windowGetSize); scm_c_define_gsubr("window-create", 5, 0, 0, (void *)windowCreate); scm_c_define_gsubr("window-close", 1, 0, 0, (void *)windowClose); scm_c_define_gsubr("window-open?", 1, 0, 0, (void *)windowIsOpen); scm_c_define_gsubr("window-poll-event!", 2, 0, 0, (void *)windowPollEvent); scm_c_define_gsubr("window-wait-event!", 2, 0, 0, (void *)windowWaitEvent); scm_c_define_gsubr("window-get-position", 1, 0, 0, (void *)windowGetPosition); scm_c_define_gsubr("window-set-position!", 3, 0, 0, (void *)windowSetPosition); scm_c_define_gsubr("window-set-size!", 3, 0, 0, (void *)windowSetSize); scm_c_define_gsubr("window-set-title!", 2, 0, 0, (void *)windowSetTitle); scm_c_define_gsubr("window-set-visible!", 2, 0, 0, (void *)windowSetVisible); scm_c_define_gsubr("window-set-vertical-sync!", 2, 0, 0, (void *)windowSetVerticalSync); scm_c_define_gsubr("window-set-mouse-cursor-visible!", 2, 0, 0, (void *)windowSetMouseCursorVisible); scm_c_define_gsubr("window-set-key-repeated!", 2, 0, 0, (void *)windowSetKeyRepeat); scm_c_define_gsubr("window-set-framerate-limit!", 2, 0, 0, (void *)windowSetFramerateLimit); scm_c_define_gsubr("window-set-active!", 2, 0, 0, (void *)windowSetActive); scm_c_define_gsubr("window-display!", 1, 0, 0, (void *)windowDisplay); scm_c_define_gsubr("window-clear!", 2, 0, 0, (void *)windowClear); scm_c_define_gsubr("window-map-pixel-to-coords", 3, 0, 0, (void *)windowMapPixelToCoords); scm_c_define_gsubr("window-map-coords-to-pixel", 3, 0, 0, (void *)windowMapCoordsToPixel); scm_c_define_gsubr("window-draw-rectangle!", 2, 0, 0, (void *)windowDrawRectangle); scm_c_define_gsubr("mouse-position", 1, 0, 0, (void *)getMousePosition); } #endif // WINDOW_HPP_
eduardoacye/Guile-SFML-1
Bindings/Window.hpp
C++
gpl-3.0
7,795
/* ============================================================================== ConditionEditor.cpp Created: 21 Feb 2017 11:40:21am Author: Ben ============================================================================== */ ConditionEditor::ConditionEditor(Condition * _condition, bool isRoot) : BaseItemEditor(_condition, isRoot), condition(_condition), isCurrentInSequential(false) { condition->addAsyncConditionListener(this); repaint(); } ConditionEditor::~ConditionEditor() { if (!inspectable.wasObjectDeleted()) { condition->removeAsyncConditionListener(this); } } void ConditionEditor::paintOverChildren(Graphics & g) { if (condition->getIsValid(condition->getPreviewIndex()) || isCurrentInSequential) { g.setColour(condition->enabled->boolValue() ? (isCurrentInSequential? BLUE_COLOR : GREEN_COLOR) : LIGHTCONTOUR_COLOR); g.drawRoundedRectangle(getLocalBounds().toFloat(), 2, 2); } } void ConditionEditor::conditionSourceChangedAsync(Condition *) { updateUI(); } void ConditionEditor::newMessage(const Condition::ConditionEvent &e) { switch (e.type) { case Condition::ConditionEvent::VALIDATION_CHANGED: repaint(); break; case Condition::ConditionEvent::SOURCE_CHANGED: conditionSourceChangedAsync(e.condition); break; case Condition::ConditionEvent::MULTIPLEX_PREVIEW_CHANGED: updateUI(); break; } } void ConditionEditor::childBoundsChanged(Component *) { resized(); repaint(); }
benkuper/Chataigne
Source/Common/Processor/Action/Condition/ui/ConditionEditor.cpp
C++
gpl-3.0
1,459
# Copyright (C) 2012. Nathan Farrington <nfarring@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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/>. require File.expand_path('../redisrpc/version',__FILE__) require 'multi_json' require 'redis' module RedisRPC class RemoteException < Exception; end class TimeoutException < Exception; end class MalformedResponseException < RemoteException def initialize(response) super "Malformed RPC Response message: #{response.inspect}" end end class MalformedRequestException < ArgumentError def initialize(reason) super "Malformed RPC Request: #{reason.inspect}" end end class Client def initialize( redis_server, message_queue, timeout=0 ) @redis_server = redis_server @message_queue = message_queue @timeout = timeout end alias :send! :send def send( method_name, *args) raise MalformedRequestException, 'block not allowed over RPC' if block_given? # request setup function_call = {'name' => method_name.to_s, 'args' => args} response_queue = @message_queue + ':rpc:' + rand_string rpc_request = {'function_call' => function_call, 'response_queue' => response_queue} rpc_raw_request = MultiJson.dump rpc_request # transport @redis_server.rpush @message_queue, rpc_raw_request message_queue, rpc_raw_response = @redis_server.blpop response_queue, @timeout raise TimeoutException if rpc_raw_response.nil? # response handling rpc_response = MultiJson.load rpc_raw_response raise RemoteException, rpc_response['exception'] if rpc_response.has_key? 'exception' raise MalformedResponseException, rpc_response unless rpc_response.has_key? 'return_value' return rpc_response['return_value'] rescue TimeoutException # stale request cleanup @redis_server.lrem @message_queue, 0, rpc_raw_request raise $! end alias :method_missing :send def respond_to?( method_name ) send( :respond_to?, method_name ) end private def rand_string(size=8) return rand(36**size).to_s(36).upcase.rjust(size,'0') end end class Server def initialize( redis_server, message_queue, local_object, timeout=nil ) @redis_server = redis_server @message_queue = message_queue @local_object = local_object @timeout = timeout end def run loop{ run_one } end def run! flush_queue! run end def flush_queue! @redis_server.del @message_queue end private def run_one # request setup message_queue, rpc_raw_request = @redis_server.blpop @message_queue, timeout return nil if rpc_raw_request.nil? rpc_request = MultiJson.load rpc_raw_request response_queue = rpc_request['response_queue'] function_call = rpc_request['function_call'] # request execution begin return_value = @local_object.send( function_call['name'].to_sym, *function_call['args'] ) rpc_response = {'return_value' => return_value} rescue Object => err rpc_response = {'exception' => err.to_s, 'backtrace' => err.backtrace} end # response tansport rpc_raw_response = MultiJson.dump rpc_response @redis_server.multi do @redis_server.rpush response_queue, rpc_raw_response @redis_server.expire response_queue, 1 end true end def timeout @timeout or $REDISRPC_SERVER_TIMEOUT or 0 end end end
nfarring/redisrpc
ruby/lib/redisrpc.rb
Ruby
gpl-3.0
4,103
"""This is part of the Mouse Tracks Python application. Source: https://github.com/Peter92/MouseTracks """ #Import the local scipy if possible, otherwise fallback to the installed one from __future__ import absolute_import from ...utils.numpy import process_numpy_array try: from .gaussian import gaussian_filter from .zoom import zoom except ImportError: from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpolation import zoom @process_numpy_array def blur(array, size): return gaussian_filter(array, sigma=size) @process_numpy_array def upscale(array, factor): if factor[0] == 1 and factor[1] == 1: return array return zoom(array, factor, order=0)
Peter92/MouseTrack
mousetracks/image/scipy/__init__.py
Python
gpl-3.0
718
/* * LookAndFeelDefinition.java * * Copyright (C) 2002-2013 Takis Diakoumis * * 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 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 org.executequery.util; /* ---------------------------------------------------------- * CVS NOTE: Changes to the CVS repository prior to the * release of version 3.0.0beta1 has meant a * resetting of CVS revision numbers. * ---------------------------------------------------------- */ /** * The <code>LookAndFeelDefinition</code> describes * a custom look and feel installed by the user. It * maintains information about the location of the JAR * library containing the look and feel as well as the * class name extending <code>LookAndFeel</code>.<br> * Additional properties are also provided to support * the Skin Look and Feel and its associated requirements * for a configuration XML file. * * @author Takis Diakoumis * @version $Revision: 160 $ * @date $Date: 2013-02-08 17:15:04 +0400 (Пт, 08 фев 2013) $ */ public class LookAndFeelDefinition { /** * The look and feel name */ private String name; /** * The path to the library jar file */ private String libPath; /** * The look and feel class name */ private String className; /** * The path to the theme pack ZIP file for Skin L&F */ private String themePack; /** * Identifies whether this is a Skin L&F */ private int skinLookAndFeel; /** * Whethet this look and feel is selected */ private boolean installed; public LookAndFeelDefinition(String name) { this.name = name; } public LookAndFeelDefinition() { } public boolean isInstalled() { return installed; } public void setInstalled(boolean installed) { this.installed = installed; } public boolean isSkinLookAndFeel() { return skinLookAndFeel == 1; } public void setIsSkinLookAndFeel(int skinLookAndFeel) { this.skinLookAndFeel = skinLookAndFeel; } public String getThemePack() { return themePack; } public void setThemePack(String themePack) { this.themePack = themePack; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getLibraryPath() { return libPath; } public void setLibraryPath(String libPath) { this.libPath = libPath; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return name; } }
Black-millenium/rdb-executequery
java/src/org/executequery/util/LookAndFeelDefinition.java
Java
gpl-3.0
3,159
/* * Copyright (C) 2017 Noe Fernandez */ package io.github.nfdz.savedio.utils; import android.content.Context; import android.os.AsyncTask; import android.text.TextUtils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import io.github.nfdz.savedio.BuildConfig; import io.github.nfdz.savedio.Callbacks; import io.github.nfdz.savedio.data.PreferencesUtils; import io.github.nfdz.savedio.data.RealmUtils; import io.github.nfdz.savedio.model.Bookmark; import io.github.nfdz.savedio.sync.api.APIHelper; import io.github.nfdz.savedio.sync.api.BookmarkAPI; import io.github.nfdz.savedio.sync.api.CreateBookmarkResponse; import io.realm.Realm; import retrofit2.Call; import retrofit2.Response; /** * This class contains static methods to ease work with common application tasks. */ public class TasksUtils { /** * This method creates a new bookmark. It manages all related thing like send to server or * store in persistence. * @param context * @param realm it has to be initialized. * @param bookmark unmanaged object with bookmark information (it should not have ID or date * because it is the server that assigns it). * @param callback to be notified. */ public static void createBookmark(final Context context, final Realm realm, final Bookmark bookmark, final Callbacks.OperationCallback<Void> callback) { if (!TextUtils.isEmpty(PreferencesUtils.getUserAPIKey(context))) { // create bookmark in server new AsyncTask<Void, Void, Void>() { private String bookmarkId; private String bookmarkDate; private String errorMsg; private Throwable errorTh; @Override protected Void doInBackground(Void... params) { APIHelper helper = new APIHelper(); String devKey = BuildConfig.SAVEDIO_API_DEV_KEY; String userKey = PreferencesUtils.getUserAPIKey(context); String list = bookmark.getListName(); Call<CreateBookmarkResponse> createCall = helper.getAPI().createBookmark(devKey, userKey, bookmark.getUrl(), bookmark.getTitle(), TextUtils.isEmpty(list) ? null : list); try { Response<CreateBookmarkResponse> createRes = createCall.execute(); if (createRes.isSuccessful()) { String bmId = createRes.body().id; Call<BookmarkAPI> bmCall = helper.getAPI().retrieveSingleBookmark( bmId, devKey, userKey); Response<BookmarkAPI> bmRes = bmCall.execute(); if (bmRes.isSuccessful()) { bookmarkId = bmId; bookmarkDate = bmRes.body().date; } else { errorMsg = bmRes.raw().message(); } } else { errorMsg = createRes.raw().message(); } } catch (IOException e) { errorMsg = e.getMessage(); errorTh = e; } return null; } @Override protected void onPostExecute(Void v) { if (!TextUtils.isEmpty(bookmarkId) && !TextUtils.isEmpty(bookmarkDate)) { // set id and date bookmark.setId(bookmarkId); bookmark.setDate(bookmarkDate); // store it in persistence RealmUtils.addBookmark(realm, bookmark, callback); } else { callback.onError(errorMsg, errorTh); } } }.execute(); } else { // set id and date SimpleDateFormat sdf = new SimpleDateFormat(Bookmark.DATE_FORMAT); String currentDate = sdf.format(new Date()); bookmark.setId(UUID.randomUUID().toString()); bookmark.setDate(currentDate); // store it in persistence RealmUtils.addBookmark(realm, bookmark, callback); } } /** * This method removes a bookmark with given ID. It manages all related thing like remove in * server or persistence. * @param context * @param realm it has to be initialized. * @param bookmarkId ID of the bookmark that will be removed. * @param callback to be notified. */ public static void deleteBookmark(final Context context, final Realm realm, final String bookmarkId, final Callbacks.OperationCallback<Bookmark> callback) { if (!TextUtils.isEmpty(PreferencesUtils.getUserAPIKey(context))) { // remove bookmark in server new AsyncTask<Void, Void, Void>() { private boolean success; private String errorMsg; private Throwable errorTh; @Override protected Void doInBackground(Void... params) { APIHelper helper = new APIHelper(); String devKey = BuildConfig.SAVEDIO_API_DEV_KEY; String userKey = PreferencesUtils.getUserAPIKey(context); Call<Void> call = helper.getAPI().deleteBookmark(devKey, userKey, bookmarkId); try { Response<Void> res = call.execute(); success = res.isSuccessful(); if (!success) { errorMsg = res.raw().message(); } } catch (IOException e) { errorMsg = e.getMessage(); errorTh = e; } return null; } @Override protected void onPostExecute(Void v) { if (success) { RealmUtils.removeBookmark(realm, bookmarkId, callback); } else { callback.onError(errorMsg, errorTh); } } }.execute(); } else { RealmUtils.removeBookmark(realm, bookmarkId, callback); } } }
nfdz/saved.io-plus-plus
Saved.io++/app/src/main/java/io/github/nfdz/savedio/utils/TasksUtils.java
Java
gpl-3.0
7,020
import * as AWS from 'aws-sdk'; import {Promise} from 'es6-promise'; import * as Twit from 'twit'; import * as _ from 'lodash'; AWS.config.update({ region: 'eu-west-1' }); // -- Begin Interfaces -- export interface TwitterAccount { id: string; username: string; photo: string; token: string; secret: string; } export interface Account { ID: string; twitterAccount: TwitterAccount; actions: { twitterDM: { enabled: boolean twitterAccount?: TwitterAccount }; mail: { enabled: boolean; mailAdress?: string; }; }; followers: { [id: string]: { from?: string; // ISO date } }; unfollowers: { [id: string]: { from?: string; // ISO date to: string; // ISO date } }; inscription_date: string; // ISO date lang: 'fr' | 'en'; } export interface Follower { from?: string; // ISO date username: string; } export interface Unfollower extends Follower { to: string; // ISO date } export interface Recap { newFollowers: number; newUnfollowers: number; total: number; } // -- End Interfaces -- export class NinjaAccount { private _account: Account; private _config; private _userId: string; private docClient = new AWS.DynamoDB.DocumentClient(); constructor(config, user: string | Account) { this._config = config; if (typeof user === 'string') { // userId this._userId = user; } else { // Account this._userId = user.ID; this._account = user; } } /** * Load account data from dynamoDB * @param userId twitter ID * @return Promise<account data> */ public get(userId: string): Promise<Account> { return new Promise((resolve, reject) => { const params = { TableName: 'UnfollowNinja', Key: { 'ID': userId } }; this.docClient.get(params, (err, data: {Item: Account}) => { if (err) return reject(err); if (!data.Item) return reject(new Error('ID not found')); if (data.Item.twitterAccount.id !== userId) return reject(new Error('An error occured while loading user from DB')); resolve(data.Item); }); }); } /** * Add a new twitter account to unfollowNinja * @return Promise<> */ public set(twitterToken: string, twitterSecret: string, lang: 'fr' | 'en') { return this.getTwitterProfile(twitterToken, twitterSecret) // 1 - We get twitter account .then((twitterAccount) => { this._account = { ID: twitterAccount.id, twitterAccount: twitterAccount, actions: { twitterDM: {enabled: false}, mail: {enabled: false}, }, followers: {}, unfollowers: {}, inscription_date: new Date().toISOString(), // ISO date lang: lang }; return this.getFollowers(); // 2 - we get his followers }) .then((result) => { this._account.followers = _.zipObject(result, _.map(result, () => ({}))) as { [id: string]: { from?: string; }; }; const params = { // 3 - We add account to db TableName: 'UnfollowNinja', Item: this._account }; return new Promise((resolve, reject) => { this.docClient.put(params, function (err, data) { if (err) return reject(err); resolve(); }); }); }); } /** * Compare DB followers and twitter follower's, update DB and call sendUnfollow() for each unfollowers. * @returns Promise with no data */ public checkUnfollow(): Promise<Recap> { // TODO : after 5 unfollows the same day, we should stop sending unfollowers and a recap should be sent at the end of the day return Promise.resolve().then(() => { if (!this._account) { return this.get(this._userId) // 1 - get account data from dynamoDB .then((data: Account) => { this._account = data; }); } }) .then(() => this.getUnfollowers()) // 2 - compare DB with twitter followers .then((result) => { if (!result.newFollowers.length && !result.unfollowers.length) return {newFollowers: 0, newUnfollowers: 0, total: _.keys(this._account.followers).length}; result.newFollowers.forEach((id: string) => { // 3 - Add new followers to the DB this._account.followers[id] = { from: new Date().toISOString() }; }); const manageUnfollows = _.take(result.unfollowers, 3) // max 3 unfollows / 3 minutes .map((id) => Promise.resolve().then(() => { // 4 - remove unfollowers from DB and warn user this._account.unfollowers[id] = <Unfollower>_.defaults(this._account.followers[id], { to: new Date().toISOString()}); delete this._account.followers[id]; return this.sendUnfollow(id); })); return Promise.all(manageUnfollows) // Manage all unfollows in parallel .then(() => this.saveToDB()) // 5 - update the DB .then(() => ({newFollowers: result.newFollowers.length, newUnfollowers: result.unfollowers.length, total: _.keys(this._account.followers).length})); }); } /** * When an unfollower is detected, this method is called. It should send the DM / warn the user about this unfollower. * @param id ID of the unfollower * @returns Promise with no data */ private sendUnfollow(id: string): Promise<void> { // TODO // 1 - Ask twitter if username changed // 2 - Send a DM if twitterDM is enabled // 3 - Send a mail if mail is enabled console.log('You have been unfollowed :('); return Promise.resolve(); } /** * Save account data (followers and unfollowers) to DB * @return Promise<> */ private saveToDB(): Promise<void> { return new Promise((resolve, reject) => { const params = { TableName: 'UnfollowNinja', Key: {'ID': this._userId}, UpdateExpression: 'set followers = :f, unfollowers = :u', ExpressionAttributeValues: { ':f': this._account.followers, ':u': this._account.unfollowers } }; this.docClient.update(<any>params, function (err, data) { if (err) return reject(err); resolve(); }); }).then(() => {}); } /** * Get all followers IDs from twitter * @returns {Promise<string[]>} A promise to get all followers IDs */ private getFollowers(): Promise<string[]> { const T = new Twit({ consumer_key: this._config.app_key, consumer_secret: this._config.app_secret, access_token: this._account.twitterAccount.token, access_token_secret: this._account.twitterAccount.secret }); return this.recursiveGetFollowers(T, []); } /** * Get all followers IDs from twitter, page per page * @param T Twit object * @param ids already found IDs * @param cursor (optional) current cursor * @returns {Promise<string[]>} A promise to get all followers IDs */ private recursiveGetFollowers(T: Twit, ids: string[], cursor?: string): Promise<string[]> { return T.get('followers/ids', <Twit.Params>{stringify_ids: true, cursor: cursor || undefined}).then((result) => { if (!result.data.next_cursor) { // next_cursor = 0, next_cursor_str = '0' return ids.concat(result.data.ids); } else { return this.recursiveGetFollowers(T, ids.concat(result.data.ids), result.data.next_cursor_str); } }); } /** * Get twitter profile from tokens * @returns {Promise<TwitterAccount>} A promise to get twitter infos */ private getTwitterProfile(twitterToken: string, twitterSecret: string): Promise<TwitterAccount> { const T = new Twit({ consumer_key: this._config.app_key, consumer_secret: this._config.app_secret, access_token: twitterToken, access_token_secret: twitterSecret }); return T.get('account/verify_credentials', <Twit.Params>{include_entities: false, skip_status: true}).then((response) => { const profile = response.data; if (profile.errors) throw new Error(profile.errors[0].message); return { id: profile.id_str, username: profile.screen_name, photo: profile.profile_image_url_https, token: twitterToken, secret: twitterSecret }; }); } /** * Get followers from twitter and compare them with followers from DB * @returns {Promise<U>} {newFollowers: array of new followers's id, unfollowers: array of unfollower's ID} */ private getUnfollowers(): Promise<{newFollowers: string[], unfollowers: string[]}> { const oldFollowers = _.keys(this._account.followers); return this.getFollowers() .then((twitterFollowers) => { return { newFollowers: _.difference(twitterFollowers, oldFollowers), unfollowers: _.difference(oldFollowers, twitterFollowers) }; }); } }
PLhery/unfollowNinjaV2
BackEnd - AWS Lambda/src/ninjaAccount.ts
TypeScript
gpl-3.0
10,133
from DIRAC import S_OK from DIRAC.AccountingSystem.Client.Types.Pilot import Pilot from DIRAC.AccountingSystem.private.Plotters.BaseReporter import BaseReporter class PilotPlotter(BaseReporter): _typeName = "Pilot" _typeKeyFields = [dF[0] for dF in Pilot().definitionKeyFields] def _reportCumulativeNumberOfJobs(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", %s, %s, SUM(%s)", reportRequest["groupingFields"][1] + ["startTime", "bucketLength", "Jobs"], ) retVal = self._getTimedData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], {}, ) if not retVal["OK"]: return retVal dataDict, granularity = retVal["Value"] self.stripDataField(dataDict, 0) dataDict = self._fillWithZero(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) dataDict = self._accumulate(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableUnit( dataDict, self._getAccumulationMaxValue(dataDict), "jobs" ) return S_OK( {"data": baseDataDict, "graphDataDict": graphDataDict, "granularity": granularity, "unit": unitName} ) def _plotCumulativeNumberOfJobs(self, reportRequest, plotInfo, filename): metadata = { "title": "Cumulative Jobs by %s" % reportRequest["grouping"], "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], "span": plotInfo["granularity"], "ylabel": plotInfo["unit"], "sort_labels": "last_value", } return self._generateCumulativePlot(filename, plotInfo["graphDataDict"], metadata) def _reportNumberOfJobs(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", %s, %s, SUM(%s)", reportRequest["groupingFields"][1] + ["startTime", "bucketLength", "Jobs"], ) retVal = self._getTimedData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], {}, ) if not retVal["OK"]: return retVal dataDict, granularity = retVal["Value"] self.stripDataField(dataDict, 0) dataDict, maxValue = self._divideByFactor(dataDict, granularity) dataDict = self._fillWithZero(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableRateUnit( dataDict, self._getAccumulationMaxValue(dataDict), "jobs" ) return S_OK( {"data": baseDataDict, "graphDataDict": graphDataDict, "granularity": granularity, "unit": unitName} ) def _plotNumberOfJobs(self, reportRequest, plotInfo, filename): metadata = { "title": "Jobs by %s" % reportRequest["grouping"], "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], "span": plotInfo["granularity"], "ylabel": plotInfo["unit"], } return self._generateTimedStackedBarPlot(filename, plotInfo["graphDataDict"], metadata) def _reportCumulativeNumberOfPilots(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", %s, %s, SUM(%s)", reportRequest["groupingFields"][1] + ["startTime", "bucketLength", "entriesInBucket"], ) retVal = self._getTimedData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], {}, ) if not retVal["OK"]: return retVal dataDict, granularity = retVal["Value"] self.stripDataField(dataDict, 0) dataDict = self._fillWithZero(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) dataDict = self._accumulate(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableUnit( dataDict, self._getAccumulationMaxValue(dataDict), "jobs" ) return S_OK( {"data": baseDataDict, "graphDataDict": graphDataDict, "granularity": granularity, "unit": unitName} ) def _plotCumulativeNumberOfPilots(self, reportRequest, plotInfo, filename): metadata = { "title": "Cumulative Pilots by %s" % reportRequest["grouping"], "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], "span": plotInfo["granularity"], "ylabel": plotInfo["unit"].replace("job", "pilot"), "sort_labels": "last_value", } return self._generateCumulativePlot(filename, plotInfo["graphDataDict"], metadata) def _reportNumberOfPilots(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", %s, %s, SUM(%s)", reportRequest["groupingFields"][1] + ["startTime", "bucketLength", "entriesInBucket"], ) retVal = self._getTimedData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], {}, ) if not retVal["OK"]: return retVal dataDict, granularity = retVal["Value"] self.stripDataField(dataDict, 0) dataDict, maxValue = self._divideByFactor(dataDict, granularity) dataDict = self._fillWithZero(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) baseDataDict, graphDataDict, maxValue, unitName = self._findSuitableRateUnit( dataDict, self._getAccumulationMaxValue(dataDict), "jobs" ) return S_OK( {"data": baseDataDict, "graphDataDict": graphDataDict, "granularity": granularity, "unit": unitName} ) def _plotNumberOfPilots(self, reportRequest, plotInfo, filename): metadata = { "title": "Pilots by %s" % reportRequest["grouping"], "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], "span": plotInfo["granularity"], "ylabel": plotInfo["unit"].replace("job", "pilot"), } return self._generateTimedStackedBarPlot(filename, plotInfo["graphDataDict"], metadata) def _reportJobsPerPilot(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", %s, %s, SUM(%s), SUM(%s)", reportRequest["groupingFields"][1] + ["startTime", "bucketLength", "Jobs", "entriesInBucket"], ) retVal = self._getTimedData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], { "checkNone": True, "convertToGranularity": "sum", "calculateProportionalGauges": False, "consolidationFunction": self._averageConsolidation, }, ) if not retVal["OK"]: return retVal dataDict, granularity = retVal["Value"] self.stripDataField(dataDict, 0) dataDict = self._fillWithZero(granularity, reportRequest["startTime"], reportRequest["endTime"], dataDict) return S_OK({"data": dataDict, "granularity": granularity}) def _plotJobsPerPilot(self, reportRequest, plotInfo, filename): metadata = { "title": "Jobs per pilot by %s" % reportRequest["grouping"], "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], "span": plotInfo["granularity"], "ylabel": "jobs/pilot", "normalization": max(x for y in plotInfo["data"].values() for x in y.values()), } return self._generateQualityPlot(filename, plotInfo["data"], metadata) def _reportTotalNumberOfPilots(self, reportRequest): selectFields = ( self._getSelectStringForGrouping(reportRequest["groupingFields"]) + ", SUM(%s)", reportRequest["groupingFields"][1] + ["entriesInBucket"], ) retVal = self._getSummaryData( reportRequest["startTime"], reportRequest["endTime"], selectFields, reportRequest["condDict"], reportRequest["groupingFields"], {}, ) if not retVal["OK"]: return retVal dataDict = retVal["Value"] return S_OK({"data": dataDict}) def _plotTotalNumberOfPilots(self, reportRequest, plotInfo, filename): metadata = { "title": "Total Number of Pilots by %s" % reportRequest["grouping"], "ylabel": "Pilots", "starttime": reportRequest["startTime"], "endtime": reportRequest["endTime"], } return self._generatePiePlot(filename, plotInfo["data"], metadata)
DIRACGrid/DIRAC
src/DIRAC/AccountingSystem/private/Plotters/PilotPlotter.py
Python
gpl-3.0
9,695
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.plugin; import com.github.joschi.jadconfig.JadConfig; import com.github.joschi.jadconfig.Parameter; import com.github.joschi.jadconfig.RepositoryException; import com.github.joschi.jadconfig.ValidationException; import com.github.joschi.jadconfig.repositories.InMemoryRepository; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; public class BaseConfigurationTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public final ExpectedException expectedException = ExpectedException.none(); private class Configuration extends BaseConfiguration { @Parameter(value = "rest_listen_uri", required = true) private URI restListenUri = URI.create("http://127.0.0.1:12900/"); @Parameter(value = "web_listen_uri", required = true) private URI webListenUri = URI.create("http://127.0.0.1:9000/"); @Parameter(value = "node_id_file", required = false) private String nodeIdFile = "/etc/graylog/server/node-id"; @Override public String getNodeIdFile() { return nodeIdFile; } @Override public URI getRestListenUri() { return Tools.getUriWithPort(restListenUri, BaseConfiguration.GRAYLOG_DEFAULT_PORT); } @Override public URI getWebListenUri() { return Tools.getUriWithPort(webListenUri, BaseConfiguration.GRAYLOG_DEFAULT_WEB_PORT); } } private Map<String, String> validProperties; @Before public void setUp() throws Exception { validProperties = new HashMap<>(); // Required properties validProperties.put("password_secret", "ipNUnWxmBLCxTEzXcyamrdy0Q3G7HxdKsAvyg30R9SCof0JydiZFiA3dLSkRsbLF"); // SHA-256 of "admin" validProperties.put("root_password_sha2", "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"); } @Test public void testRestTransportUriLocalhost() throws RepositoryException, ValidationException { validProperties.put("rest_listen_uri", "http://127.0.0.1:12900"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals("http://127.0.0.1:12900", configuration.getDefaultRestTransportUri().toString()); } @Test public void testRestListenUriWildcard() throws RepositoryException, ValidationException { validProperties.put("rest_listen_uri", "http://0.0.0.0:12900"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNotEquals("http://0.0.0.0:12900", configuration.getDefaultRestTransportUri().toString()); Assert.assertNotNull(configuration.getDefaultRestTransportUri()); } @Test public void testRestTransportUriWildcard() throws RepositoryException, ValidationException { validProperties.put("rest_listen_uri", "http://0.0.0.0:12900"); validProperties.put("rest_transport_uri", "http://0.0.0.0:12900"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNotEquals(URI.create("http://0.0.0.0:12900"), configuration.getRestTransportUri()); } @Test public void testRestTransportUriWildcardKeepsPath() throws RepositoryException, ValidationException { validProperties.put("rest_listen_uri", "http://0.0.0.0:12900/api/"); validProperties.put("rest_transport_uri", "http://0.0.0.0:12900/api/"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNotEquals(URI.create("http://0.0.0.0:12900/api/"), configuration.getRestTransportUri()); Assert.assertEquals("/api/", configuration.getRestTransportUri().getPath()); } @Test public void testRestTransportUriCustom() throws RepositoryException, ValidationException { validProperties.put("rest_listen_uri", "http://10.0.0.1:12900"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals("http://10.0.0.1:12900", configuration.getDefaultRestTransportUri().toString()); } @Test public void testGetRestUriScheme() throws RepositoryException, ValidationException, IOException { validProperties.put("rest_enable_tls", "false"); final Configuration configWithoutTls = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configWithoutTls).process(); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", temporaryFolder.newFile("graylog.key").getAbsolutePath()); validProperties.put("rest_tls_cert_file", temporaryFolder.newFile("graylog.crt").getAbsolutePath()); final Configuration configWithTls = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configWithTls).process(); assertEquals("http", configWithoutTls.getRestUriScheme()); assertEquals("https", configWithTls.getRestUriScheme()); } @Test public void testGetWebUriScheme() throws RepositoryException, ValidationException, IOException { validProperties.put("web_enable_tls", "false"); final Configuration configWithoutTls = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configWithoutTls).process(); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", temporaryFolder.newFile("graylog.key").getAbsolutePath()); validProperties.put("web_tls_cert_file", temporaryFolder.newFile("graylog.crt").getAbsolutePath()); final Configuration configWithTls = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configWithTls).process(); assertEquals("http", configWithoutTls.getWebUriScheme()); assertEquals("https", configWithTls.getWebUriScheme()); } @Test public void restTlsValidationFailsIfPrivateKeyIsMissing() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.delete()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void restTlsValidationFailsIfPrivateKeyIsDirectory() throws Exception { final File privateKey = temporaryFolder.newFolder("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.isDirectory()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void restTlsValidationFailsIfPrivateKeyIsUnreadable() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.setReadable(false, false)).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void restTlsValidationFailsIfCertificateIsMissing() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.delete()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void restTlsValidationFailsIfCertificateIsDirectory() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFolder("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.isDirectory()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void restTlsValidationFailsIfCertificateIsUnreadable() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.setReadable(false, false)).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing REST API X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfPrivateKeyIsMissing() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.delete()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfPrivateKeyIsDirectory() throws Exception { final File privateKey = temporaryFolder.newFolder("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.isDirectory()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfPrivateKeyIsUnreadable() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(privateKey.setReadable(false, false)).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface private key: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfCertificateIsMissing() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.delete()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfCertificateIsDirectory() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFolder("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.isDirectory()).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void webTlsValidationFailsIfCertificateIsUnreadable() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("web_enable_tls", "true"); validProperties.put("web_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("web_tls_cert_file", certificate.getAbsolutePath()); assertThat(certificate.setReadable(false, false)).isTrue(); expectedException.expect(ValidationException.class); expectedException.expectMessage("Unreadable or missing web interface X.509 certificate: "); new JadConfig(new InMemoryRepository(validProperties), new Configuration()).process(); } @Test public void testRestTransportUriIsRelativeURI() throws RepositoryException, ValidationException { validProperties.put("rest_transport_uri", "/foo"); expectedException.expect(ValidationException.class); expectedException.expectMessage("Parameter rest_transport_uri should be an absolute URI (found /foo)"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); } @Test public void testWebEndpointUriIsRelativeURI() throws RepositoryException, ValidationException { validProperties.put("web_endpoint_uri", "/foo"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertEquals(URI.create("/foo"), configuration.getWebEndpointUri()); } @Test public void testRestTransportUriIsAbsoluteURI() throws RepositoryException, ValidationException { validProperties.put("rest_transport_uri", "http://www.example.com:12900/foo"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertEquals(URI.create("http://www.example.com:12900/foo/"), configuration.getRestTransportUri()); } @Test public void testWebEndpointUriIsAbsoluteURI() throws RepositoryException, ValidationException { validProperties.put("web_endpoint_uri", "http://www.example.com:12900/foo"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertEquals(URI.create("http://www.example.com:12900/foo"), configuration.getWebEndpointUri()); } @Test public void testRestTransportUriWithHttpDefaultPort() throws RepositoryException, ValidationException { validProperties.put("rest_transport_uri", "http://example.com/"); org.graylog2.Configuration configuration = new org.graylog2.Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertThat(configuration.getRestTransportUri()).hasPort(80); } @Test public void testRestTransportUriWithCustomPort() throws RepositoryException, ValidationException { validProperties.put("rest_transport_uri", "http://example.com:12900/"); org.graylog2.Configuration configuration = new org.graylog2.Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertThat(configuration.getRestTransportUri()).hasPort(12900); } @Test public void testRestTransportUriWithCustomScheme() throws RepositoryException, ValidationException { validProperties.put("rest_transport_uri", "https://example.com:12900/"); validProperties.put("rest_enable_tls", "false"); org.graylog2.Configuration configuration = new org.graylog2.Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertThat(configuration.getRestTransportUri()).hasScheme("https"); } @Test public void testRestListenUriAndWebListenUriWithSameScheme() throws Exception { final File privateKey = temporaryFolder.newFile("graylog.key"); final File certificate = temporaryFolder.newFile("graylog.crt"); validProperties.put("rest_listen_uri", "https://127.0.0.1:8000/api"); validProperties.put("rest_transport_uri", "https://127.0.0.1:8000/api"); validProperties.put("rest_enable_tls", "true"); validProperties.put("rest_tls_key_file", privateKey.getAbsolutePath()); validProperties.put("rest_tls_cert_file", certificate.getAbsolutePath()); validProperties.put("web_listen_uri", "https://127.0.0.1:8000/"); validProperties.put("web_enable_tls", "true"); org.graylog2.Configuration configuration = new org.graylog2.Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); assertThat(configuration.getRestListenUri()).hasScheme("https"); assertThat(configuration.getRestTransportUri()).hasScheme("https"); assertThat(configuration.getWebListenUri()).hasScheme("https"); } }
hellasmoon/graylog2-server
graylog2-server/src/test/java/org/graylog2/plugin/BaseConfigurationTest.java
Java
gpl-3.0
20,953
<? require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php"); $APPLICATION->SetTitle("Кухня"); ?><?$APPLICATION->IncludeComponent( "bitrix:catalog", "catalog", Array( "IBLOCK_TYPE" => "catalog", "IBLOCK_ID" => "12", "HIDE_NOT_AVAILABLE" => "N", "SECTION_ID_VARIABLE" => "SECTION_ID", "SEF_MODE" => "Y", "SEF_FOLDER" => "/catalog/", "AJAX_MODE" => "N", "AJAX_OPTION_JUMP" => "N", "AJAX_OPTION_STYLE" => "N", "AJAX_OPTION_HISTORY" => "N", "CACHE_TYPE" => "A", "CACHE_TIME" => "36000000", "CACHE_FILTER" => "N", "CACHE_GROUPS" => "Y", "SET_STATUS_404" => "N", "SET_TITLE" => "Y", "ADD_SECTIONS_CHAIN" => "Y", "ADD_ELEMENT_CHAIN" => "N", "USE_ELEMENT_COUNTER" => "N", "USE_FILTER" => "N", "USE_COMPARE" => "N", "PRICE_CODE" => array("BASE"), "USE_PRICE_COUNT" => "N", "SHOW_PRICE_COUNT" => "1", "PRICE_VAT_INCLUDE" => "Y", "PRICE_VAT_SHOW_VALUE" => "N", "CONVERT_CURRENCY" => "Y", "CURRENCY_ID" => "", "BASKET_URL" => "/basket/", "ACTION_VARIABLE" => "action", "PRODUCT_ID_VARIABLE" => "id", "USE_PRODUCT_QUANTITY" => "Y", "PRODUCT_QUANTITY_VARIABLE" => "quantity", "ADD_PROPERTIES_TO_BASKET" => "Y", "PRODUCT_PROPS_VARIABLE" => "prop", "PARTIAL_PRODUCT_PROPERTIES" => "N", "PRODUCT_PROPERTIES" => array(), "SHOW_TOP_ELEMENTS" => "N", "SECTION_COUNT_ELEMENTS" => "N", "SECTION_TOP_DEPTH" => "2", "SECTIONS_VIEW_MODE" => "LINE", "SECTIONS_SHOW_PARENT_NAME" => "Y", "PAGE_ELEMENT_COUNT" => "30", "LINE_ELEMENT_COUNT" => "3", "ELEMENT_SORT_FIELD" => "sort", "ELEMENT_SORT_ORDER" => "asc", "ELEMENT_SORT_FIELD2" => "name", "ELEMENT_SORT_ORDER2" => "asc", "LIST_PROPERTY_CODE" => array("",""), "INCLUDE_SUBSECTIONS" => "Y", "LIST_META_KEYWORDS" => "-", "LIST_META_DESCRIPTION" => "-", "LIST_BROWSER_TITLE" => "-", "DETAIL_PROPERTY_CODE" => array("",""), "DETAIL_META_KEYWORDS" => "-", "DETAIL_META_DESCRIPTION" => "-", "DETAIL_BROWSER_TITLE" => "NAME", "DETAIL_DISPLAY_NAME" => "Y", "DETAIL_DETAIL_PICTURE_MODE" => "IMG", "DETAIL_ADD_DETAIL_TO_SLIDER" => "N", "DETAIL_DISPLAY_PREVIEW_TEXT_MODE" => "H", "LINK_IBLOCK_TYPE" => "", "LINK_IBLOCK_ID" => "", "LINK_PROPERTY_SID" => "", "LINK_ELEMENTS_URL" => "", "USE_ALSO_BUY" => "N", "USE_STORE" => "N", "PAGER_TEMPLATE" => "", "DISPLAY_TOP_PAGER" => "N", "DISPLAY_BOTTOM_PAGER" => "Y", "PAGER_TITLE" => "Товары", "PAGER_SHOW_ALWAYS" => "N", "PAGER_DESC_NUMBERING" => "N", "PAGER_DESC_NUMBERING_CACHE_TIME" => "36000", "PAGER_SHOW_ALL" => "N", "TEMPLATE_THEME" => "", "ADD_PICT_PROP" => "-", "LABEL_PROP" => "-", "SHOW_DISCOUNT_PERCENT" => "N", "SHOW_OLD_PRICE" => "N", "DETAIL_SHOW_MAX_QUANTITY" => "N", "MESS_BTN_BUY" => "Купить", "MESS_BTN_ADD_TO_BASKET" => "Добавить", "MESS_BTN_COMPARE" => "", "MESS_BTN_DETAIL" => "Подробнее", "MESS_NOT_AVAILABLE" => "Нет в наличии", "DETAIL_USE_VOTE_RATING" => "N", "DETAIL_BRAND_USE" => "N", "AJAX_OPTION_ADDITIONAL" => "", "FILTER_VIEW_MODE" => "VERTICAL", "VARIABLE_ALIASES" => Array("sections"=>Array(),"section"=>Array(),"element"=>Array(),"compare"=>Array(),), "SEF_URL_TEMPLATES" => Array("sections"=>"","section"=>"#SECTION_ID#/","element"=>"#SECTION_ID#/#ELEMENT_ID#/","compare"=>""), "VARIABLE_ALIASES" => Array( "sections" => Array(), "section" => Array(), "element" => Array(), "compare" => Array(), ) ) );?> <!-- Yandex.Metrika counter --> <script type="text/javascript"> (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter26228259 = new Ya.Metrika({id:26228259, webvisor:true, clickmap:true, trackLinks:true, accurateTrackBounce:true}); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="//mc.yandex.ru/watch/26228259" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter --><?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>
web-izmerenie/portland
catalog/index.php
PHP
gpl-3.0
4,539
<?php /* @var $this yii\web\View */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; use app\models\Products; use yii\data\ArrayDataProvider; use kartik\grid\GridView; use yii\helpers\Url; $session = Yii::$app->session; $this->title = 'Inventory'; //get Post Request variables to update $request = Yii::$app->request->post(); //Create the Data Model for the grid view $products = $shopify_init->getProducts(); $data = new ArrayDataProvider([ 'allModels' => $products, 'key'=>'id', 'pagination' => [ 'pageSize' => 10, ], 'sort' => [ 'attributes' => [ 'id', 'product_title', 'sku', 'vendor', 'product_type', 'ShopifyPrice', 'inv_quantity', ], ], ]); //Check selected items and send to JET if ($sendToJet = Yii::$app->request->post('selection')){ foreach($sendToJet as $productID){ //$product = $shopify_init->getProducts($productID); //$JSON = $product->formatProductUploadJSON(); //$results = $shopify_init->sendToJet($productID, $JSON); echo "<pre>"; //print_r($results); echo "</pre>"; } } //Create the Table view ?> <div class="site-index"> <div class="body-content"> <div class="row"> <h2>Inventory</h2> <?php $form = ActiveForm::begin([ 'id' => 'jet-add-form', 'options' => ['class' => 'form-horizontal'], 'method' => 'post', 'action' => ['/inventory'], 'fieldConfig' => [ 'template' => "{label}\n<div class=\"col-lg-4\">{input}</div>\n<div class=\"col-lg-11\">{error}</div>", 'labelOptions' => ['class' => 'col-lg-3 control-label'], ], ]); ?> <?= GridView::widget([ 'dataProvider' => $data, 'id'=>'jet-add-grid', 'columns' => [ [ 'class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($data) { return ['value' => $data->id]; }, ], [ 'class'=>'kartik\grid\ExpandRowColumn', 'width'=>'50px', 'value'=>function ($data, $key, $index, $column) { return GridView::ROW_COLLAPSED; }, 'extraData'=>['shop'=>$session->get('shop')], 'detailUrl'=>Url::toRoute(['expand-row-inventory-details']), 'headerOptions'=>['class'=>'kartik-sheet-style'], 'expandOneOnly'=>true, 'enableRowClick'=>true, 'expandIcon'=>"+", 'collapseIcon'=>"-" ], 'product_title', 'sku', [ 'attribute'=>'ShopifyPrice', 'value' => function ($data) { return "$" . $data->ShopifyPrice; }, 'format' => 'raw' ], 'inv_quantity' ], 'responsive'=>true, 'hover'=>true ]) ?> <?=Html::submitButton('Update Selected Products Shopify Inv to Jet', ['class' => 'btn btn-primary',]);?> <?php ActiveForm::end(); ?> </div> </div> </div>
craigsirk/Shopify-Jet-Integration
views/site/inventory.php
PHP
gpl-3.0
3,194
/*jslint browser: true*/ /*global Audio, Drupal*/ /** * @file * Displays Audio viewer. */ (function ($, Drupal) { 'use strict'; /** * If initialized. * @type {boolean} */ var initialized; /** * Unique HTML id. * @type {string} */ var base; function init(context,settings){ if (!initialized){ initialized = true; if ($('audio')[0].textTracks.length > 0) { $('audio')[0].textTracks[0].oncuechange = function() { var currentCue = this.activeCues[0].text; $('#audioTrack').html(currentCue); } } } } Drupal.Audio = Drupal.Audio || {}; /** * Initialize the Audio Viewer. */ Drupal.behaviors.Audio = { attach: function (context, settings) { init(context,settings); }, detach: function () { } }; })(jQuery, Drupal);
nigelgbanks/islandora
modules/islandora_audio/js/audio.js
JavaScript
gpl-3.0
967
namespace Cecil.Decompiler.Gui.Services { public enum ActionNames { None, LoadAssembly, UnloadAssembly, UnloadActiveAssembly, Disassemble, GoBack, GoForward, Analyze } }
telerik/justdecompile-plugins
Reflexil.JustDecompile/reflexil.1.5.src/Plugins/Cecil.Decompiler.Gui.Services/Cecil.Decompiler.Gui.Services/ActionNames.cs
C#
gpl-3.0
237
<?php namespace Claroline\CoreBundle\Tests\API\Organization; use Claroline\CoreBundle\Entity\User; use Claroline\CoreBundle\Library\Testing\Persister; use Claroline\CoreBundle\Library\Testing\TransactionalTestCase; class ResourceNodeControllerTest extends TransactionalTestCase { /** @var Persister */ private $persister; /** @var User */ private $john; /** @var User */ private $admin; protected function setUp() { parent::setUp(); $this->persister = $this->client->getContainer()->get('claroline.library.testing.persister'); $this->john = $this->persister->user('john'); $roleAdmin = $this->persister->role('ROLE_ADMIN'); $this->admin = $this->persister->user('admin'); $this->admin->addRole($roleAdmin); $this->persister->persist($this->admin); $this->persister->flush(); } public function testGetResourceNodeAction() { $this->login($this->john); $resource = $this->persister->file('test', 'text/html', true, $this->john); $this->client->request('GET', "/api/resources/{$resource->getResourceNode()->getGuid()}"); $response = $this->client->getResponse(); $this->assertEquals(200, $response->getStatusCode()); } }
ClaroBot/Distribution
main/core/Tests/API/Resource/ResourceNodeControllerTest.php
PHP
gpl-3.0
1,274
<?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/>. /** * This file is used to setting the block allover the site * * @package block * @subpackage graph_stats * @copyright 2011 Éric Bugnet with help of Jean Fruitet * @copyright 2014 Wesley Ellis, Code Improvements. * @copyright 2014 Vadim Dvorovenko * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; function block_graph_stats_graph_google($courseid) { global $DB, $COURSE; $cfg = get_config('block_graph_stats'); // Number of day for the graph. if (isset($cfg->daysnb)) { $daysnb = $cfg->daysnb; } else { $daysnb = 30; } // Define type. if ($cfg->style == 'area') { $type1 = 'area'; $type2 = 'area'; } else { $type1 = 'bars'; $type2 = 'line'; } $days = array(); $visits1 = array(); $visits2 = array(); $cache = cache::make('block_graph_stats', 'visits'); // Let's get the datas. $a = 0; if ($courseid > 1) { for ($i = $daysnb; $i > -1; $i--) { // Days count. $time1 = usergetmidnight(time() - $i * 60 * 60 *24); $time2 = usergetmidnight(time() - ($i - 1) * 60 * 60 *24); $visits1[$a] = $cache->get('visits1_' . $courseid . '_' . $time1); if ($visits1[$a] === false) { $sql = "SELECT COUNT(DISTINCT(userid)) as countid FROM {logstore_standard_log} WHERE timecreated >= :time1 AND timecreated < :time2 AND eventname = :eventname AND courseid = :course"; $params = array( 'time1' => $time1, 'time2' => $time2, 'eventname' => '\core\event\course_viewed', 'course' => $COURSE->id); $visits1[$a] = $DB->get_field_sql($sql, $params); if ($i > 0) { $cache->set('visits1_' . $courseid . '_' . $time1, $visits1[$a]); } } $days[$a] = userdate($time1, get_string('strftimedaydate', 'core_langconfig')); $a = $a + 1; } } else { for ($i = $daysnb; $i > -1; $i--) { // Days count. $time1 = usergetmidnight(time() - $i * 60 * 60 *24); $time2 = usergetmidnight(time() - ($i - 1) * 60 * 60 *24); $visits2[$a] = $cache->get('visits2_' . $courseid . '_' . $time1); if ($visits2[$a] === false) { $sql = "SELECT COUNT(DISTINCT(userid)) as countid FROM {logstore_standard_log} WHERE timecreated >= :time1 AND timecreated < :time2 AND eventname = :eventname"; $params = array( 'time1' => $time1, 'time2' => $time2, 'eventname' => '\core\event\user_loggedin'); $visits2[$a] = $DB->get_field_sql($sql, $params); if ($i > 0) { // do not cache today, because visits count can change $cache->set('visits2_' . $courseid . '_' . $time1, $visits2[$a]); } } if ($cfg->multi == 1) { $visits1[$a] = $cache->get('visits1_' . $courseid . '_' . $time1); if ($visits1[$a] === false) { $sql = "SELECT COUNT(userid) as countid FROM {logstore_standard_log} WHERE timecreated >= :time1 AND timecreated < :time2 AND eventname = :eventname"; $params = array( 'time1' => $time1, 'time2' => $time2, 'eventname' => '\core\event\user_loggedin'); $visits1[$a] = $DB->get_field_sql($sql, $params); if ($i > 0) { // do not cache today, because visits count can change $cache->set('visits1_' . $courseid . '_' . $time1, $visits1[$a]); } } } else { $visits1[$a] = ''; } $days[$a] = userdate($time1, get_string('strftimedaydate', 'core_langconfig')); $a = $a + 1; } } $graph = ' <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn("string", "Day");'; if ($courseid > 1) { $graph .= 'data.addColumn("number", "'. get_string('visitors', 'block_graph_stats') . '");'; } else { $graph .= 'data.addColumn("number", "'. get_string('visitors', 'block_graph_stats') . '");'; $graph .= 'data.addColumn("number", "'. get_string('uniquevisitors', 'block_graph_stats') . '");'; } $graph .= 'data.addRows([ '; $a = 0; for ($i = $daysnb; $i > -1; $i--) { if ($courseid > 1) { $graph .= '["' . $days[$a] . '",' . $visits1[$a] . '],'; } else { $graph .= '["' . $days[$a] . '",' . $visits1[$a] . ',' . $visits2[$a] . '],'; } $a++; } $graph .= ' ]);'; $graph .= ' var options = { legend: {position: "none"}, backgroundColor: { fill: "' . $cfg->outer_background . '", stroke: "' . $cfg->inner_border . '", strokeWidth: "' . $cfg->border_width . '" }, hAxis: { textPosition: "none" }, vAxis: { gridlines: { color: "' . $cfg->axis_colour . '" } }, series: { 0: { color: "' . $cfg->color1 . '", type: "'. $type1. '" }, 1: { color: "' . $cfg->color2 .'", type: "' . $type2 . '" } } };'; $graph .= ' var chart = new google.visualization.AreaChart(document.getElementById("chart_div")); chart.draw(data, options); } $(document).ready(function(){ $(window).resize(function(){ drawChart(); }); }); </script> <div id="chart_div" style="width:100%; height:' . $cfg->graphheight .'"></div>'; return $graph; }
parksandwildlife/learning
moodle/blocks/graph_stats/locallib.php
PHP
gpl-3.0
7,276
package de.bund.bfr.knime.fsklab.v2_0.joiner; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import de.bund.bfr.knime.fsklab.v2_0.FskSimulation; import de.bund.bfr.metadata.swagger.Parameter; public class JoinerModelsData { public String firstModelType; public String secondModelType; public String thirdModelType; public String fourthModelType; public Parameter[] firstModelParameters; public Parameter[] secondModelParameters; public Parameter[] thirdModelParameters; public Parameter[] fourthModelParameters; public String firstModelName; public String secondModelName; public String thirdModelName; public String fourthModelName; public String[] firstModel; public String[] secondModel; public String[] thirdModel; public String[] fourthModel; public boolean interactiveMode = false; public int numberOfModels = 0; public List<FskSimulation> joinedSimulation = new ArrayList<>(); public Map <String, Map<String,String>> modelsParamsOriginalNames = new HashMap<>(); @Override public int hashCode() { return Objects.hash(firstModelParameters, secondModelParameters, thirdModelParameters, fourthModelParameters, firstModelName, secondModelName, thirdModelName, fourthModelName, firstModelType, secondModelType, thirdModelType, fourthModelType,modelsParamsOriginalNames); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } JoinerModelsData other = (JoinerModelsData) obj; return Arrays.deepEquals(firstModelParameters, other.firstModelParameters) && Arrays.deepEquals(secondModelParameters, other.secondModelParameters) && Arrays.deepEquals(thirdModelParameters, other.thirdModelParameters) && Arrays.deepEquals(fourthModelParameters, other.fourthModelParameters) && firstModelName.equals(other.firstModelName) && secondModelName.equals(other.secondModelName) && thirdModelName.equals(other.thirdModelName) && fourthModelName.equals(other.fourthModelName) && firstModelType.equals(other.firstModelType) && secondModelType.equals(other.secondModelType) && thirdModelType.equals(other.thirdModelType) && fourthModelType.equals(other.fourthModelType) && modelsParamsOriginalNames.equals(other.modelsParamsOriginalNames); } }
SiLeBAT/FSK-Lab
de.bund.bfr.knime.fsklab.nodes/src/de/bund/bfr/knime/fsklab/v2_0/joiner/JoinerModelsData.java
Java
gpl-3.0
2,574
(function (window) { const settings = { info: {}, user: {}, currentTime: 0, specificUser: false, init() { // default settings applyed from here const coreSettings = virtualclassSetting.settings; virtualclass.settings.info = virtualclass.settings.parseSettings(coreSettings); const userSetting = localStorage.getItem('userSettings'); if (userSetting) { // console.log('setting ', userSetting); virtualclass.settings.user = JSON.parse(userSetting); } this.recording.init(); // virtualclass.settings.info.trimRecordings = true; }, triggerSettings() { this.qaMarkNotes(virtualclass.settings.info.qaMarkNotes); this.askQuestion(virtualclass.settings.info.askQuestion); this.qaAnswer(virtualclass.settings.info.qaAnswer); this.qaComment(virtualclass.settings.info.qaComment); this.qaUpvote(virtualclass.settings.info.qaUpvote); }, // settings object values assign to array for get a hax code settingsToHex(s) { const localSettings = []; localSettings[0] = +s.allowoverride; localSettings[1] = +s.studentaudio; localSettings[2] = +s.studentvideo; localSettings[3] = +s.studentpc; localSettings[4] = +s.studentgc; localSettings[5] = +s.askQuestion; localSettings[6] = +s.userlist; localSettings[7] = +s.enableRecording; localSettings[8] = +s.recAllowpresentorAVcontrol; localSettings[9] = +s.recShowPresentorRecordingStatus; localSettings[10] = +s.attendeeAV; localSettings[11] = +s.recallowattendeeAVcontrol; localSettings[12] = +s.showAttendeeRecordingStatus; localSettings[13] = +s.trimRecordings; localSettings[14] = +s.attendeerecording; localSettings[15] = +s.qaMarkNotes; localSettings[16] = +s.qaAnswer; localSettings[17] = +s.qaComment; localSettings[18] = +s.qaUpvote; localSettings[19] = +s.upcomingSetting; return virtualclass.settings.binaryToHex(localSettings.join('')); }, // return data into true, false // student side parseSettings(s) { // console.log('====> Settings parse'); const parsedSettings = {}; let localSettings = virtualclass.settings.hexToBinary(s); localSettings = localSettings.split(''); parsedSettings.allowoverride = !!+localSettings[0]; parsedSettings.studentaudio = !!+localSettings[1]; parsedSettings.studentvideo = !!+localSettings[2]; parsedSettings.studentpc = !!+localSettings[3]; parsedSettings.studentgc = !!+localSettings[4]; parsedSettings.askQuestion = !!+localSettings[5]; parsedSettings.userlist = !!+localSettings[6]; parsedSettings.enableRecording = !!+localSettings[7]; parsedSettings.recAllowpresentorAVcontrol = !!+localSettings[8]; parsedSettings.recShowPresentorRecordingStatus = !!+localSettings[9]; parsedSettings.attendeeAV = !!+localSettings[10]; parsedSettings.recallowattendeeAVcontrol = !!+localSettings[11]; parsedSettings.showAttendeeRecordingStatus = !!+localSettings[12]; parsedSettings.trimRecordings = !!+localSettings[13]; parsedSettings.attendeerecording = !!+localSettings[14]; parsedSettings.qaMarkNotes = !!+localSettings[15]; parsedSettings.qaAnswer = !!+localSettings[16]; parsedSettings.qaComment = !!+localSettings[17]; parsedSettings.qaUpvote = !!+localSettings[18]; parsedSettings.upcomingSetting = !!+localSettings[19]; return parsedSettings; }, // Hex convert into binary hexToBinary(s) { let i; let ret = ''; // lookup table for easier conversion. '0' characters are padded for '1' to '7' const lookupTable = { 0: '0000', 1: '0001', 2: '0010', 3: '0011', 4: '0100', 5: '0101', 6: '0110', 7: '0111', 8: '1000', 9: '1001', a: '1010', b: '1011', c: '1100', d: '1101', e: '1110', f: '1111', A: '1010', B: '1011', C: '1100', D: '1101', E: '1110', F: '1111', }; for (i = 0; i < s.length; i += 1) { if (Object.prototype.hasOwnProperty.call(lookupTable, s[i])) { ret += lookupTable[s[i]]; } else { return false; } } return ret; }, // convert binary into Hex binaryToHex(s) { let i; let k; let part; let accum; let ret = ''; for (i = s.length - 1; i >= 3; i -= 4) { // extract out in substrings of 4 and convert to hex part = s.substr(i + 1 - 4, 4); accum = 0; for (k = 0; k < 4; k += 1) { if (part[k] !== '0' && part[k] !== '1') { // invalid character return false; } // compute the length 4 substring accum = accum * 2 + parseInt(part[k], 10); } if (accum >= 10) { // 'A' to 'F' ret = String.fromCharCode(accum - 10 + 'A'.charCodeAt(0)) + ret; } else { // '0' to '9' ret = String(accum) + ret; } } // remaining characters, i = 0, 1, or 2 if (i >= 0) { accum = 0; // convert from front for (k = 0; k <= i; k += 1) { if (s[k] !== '0' && s[k] !== '1') { return false; } accum = accum * 2 + parseInt(s[k], 10); } // 3 bits, value cannot exceed 2^3 - 1 = 7, just convert ret = String(accum) + ret; } return ret; }, // Object's properties value true or false into binary applySettings(value, settingName, userId) { if (roles.hasControls()) { if ((value === true || value === false) && Object.prototype.hasOwnProperty.call(virtualclass.settings.info, settingName)) { if (typeof userId === 'undefined') { virtualclass.settings.applyPresentorGlobalSetting(value, settingName); if (settingName === 'askQuestion' || settingName === 'qaMarkNotes') { this.triggerSettings(value); } // virtualclass.setPrvUser(); } else { virtualclass.settings.applySpecificAttendeeSetting(value, settingName, userId); } return true; } return false; } }, applyPresentorGlobalSetting(value, settingName) { localStorage.removeItem('userSettings'); virtualclass.settings.info[settingName] = value; const str = virtualclass.settings.settingsToHex(virtualclass.settings.info); ioAdapter.mustSend({ cf: 'settings', Hex: str, time: Date.now() }); virtualclassSetting.settings = str; // console.log('====> Settings ', str); for (const propname in virtualclass.settings.user) { virtualclass.user.control.changeAttribute(propname, virtualclass.gObj.testChatDiv.shadowRoot.getElementById(`${propname}contrAudImg`), virtualclass.settings.info.studentaudio, 'audio', 'aud'); virtualclass.user.control.changeAttribute(propname, virtualclass.gObj.testChatDiv.shadowRoot.getElementById(`${propname}contrChatImg`), virtualclass.settings.info.studentpc, 'chat', 'chat'); } virtualclass.settings.user = {}; }, applySpecificAttendeeSetting(value, settingName, userId) { let specificSettings; if (Object.prototype.hasOwnProperty.call(virtualclass.settings.user, userId)) { const user = virtualclass.settings.user[userId]; const setting = virtualclass.settings.parseSettings(user); setting[settingName] = value; specificSettings = virtualclass.settings.settingsToHex(setting); } else { const individualSetting = {}; for (const propname in virtualclass.settings.info) { individualSetting[propname] = virtualclass.settings.info[propname]; } individualSetting[settingName] = value; specificSettings = virtualclass.settings.settingsToHex(individualSetting); } ioAdapter.mustSendUser({ cf: 'settings', Hex: specificSettings, toUser: userId, time: Date.now(), }, userId); virtualclass.settings.user[userId] = specificSettings; localStorage.setItem('userSettings', JSON.stringify(virtualclass.settings.user)); }, applyAttendeeSetting(obj) { // console.log('my setting change ', JSON.stringify(obj)); const rec = ['enableRecording', 'recAllowpresentorAVcontrol', 'recShowPresentorRecordingStatus', 'attendeeAV', 'recallowattendeeAVcontrol', 'showAttendeeRecordingStatus', 'attendeerecording']; for (const propname in obj) { if (virtualclass.settings.info[propname] !== obj[propname]) { if (virtualclass.isPlayMode) { if (propname !== 'qaMarkNotes' && propname !== 'askQuestion' && propname !== 'qaAnswer' && propname !== 'qaUpvote' && propname !== 'qaComment') { virtualclass.settings.info[propname] = obj[propname]; } } else { virtualclass.settings.info[propname] = obj[propname]; } if (propname !== 'trimRecordings') { // avoid trim recordings const recSettings = rec.indexOf(propname); const value = (recSettings !== -1) ? obj : obj[propname]; if (virtualclass.isPlayMode) { if (propname !== 'qaMarkNotes' && propname !== 'askQuestion' && propname !== 'qaAnswer' && propname !== 'qaUpvote' && propname !== 'qaComment') { virtualclass.settings[propname](value); } } else { virtualclass.settings[propname](value); } } } } }, // Apply settings on student side onMessage(msg, userId) { if (roles.hasControls()) { if (typeof msg === 'string' && userId == null) { if (!virtualclass.gObj.refreshSession) { virtualclass.settings.info = virtualclass.settings.parseSettings(msg); } delete virtualclass.gObj.refreshSession; // virtualclass.settings.info = virtualclass.settings.parseSettings(msg); } } else { if (typeof msg === 'string' && roles.isStudent()) { this.specificUser = userId ? true : false; // console.log('====> Settings received ', msg); const stdSettings = virtualclass.settings.parseSettings(msg); this.applyAttendeeSetting(stdSettings); } else { this.recording.triggerSetting(msg); } } }, // Mute or Unmute all student audio or particular student mute or unmute studentaudio(value) { if (roles.isStudent()) { if (value === true) { virtualclass.user.control.audioWidgetEnable(true); virtualclass.gObj.audioEnable = true; } else if (value === false) { const speakerPressOnce = document.querySelector('#speakerPressOnce'); if (speakerPressOnce.dataset.audioPlaying === true || speakerPressOnce.dataset.audioPlaying === 'true') { virtualclass.media.audio.clickOnceSpeaker('speakerPressOnce'); } virtualclass.user.control.audioDisable(); virtualclass.gObj.audioEnable = false; } } }, allowoverride() { // console.log('TO DO'); }, studentpc(value) { // student chat enable/disable if (roles.isStudent()) { if (value === true) { virtualclass.user.control.allChatEnable('pc'); } else if (value === false) { virtualclass.user.control.disbaleAllChatBox(); } } }, studentgc(value) { // student group chat enable/disable if (roles.isStudent()) { if (value === true) { virtualclass.user.control.allChatEnable('gc'); } else { virtualclass.user.control.disableCommonChat(); } } }, studentvideo(value) { // All student video enable, disable if (roles.isStudent()) { const sw = document.querySelector('.videoSwitchCont #videoSwitch'); if (sw.classList.contains('off') && value === false) { // console.log('do nothing'); } else if (sw.classList.contains('on') && value === true) { // console.log('do nothing'); } else if (sw.classList.contains('on') && value === false) { virtualclass.vutil.videoHandler('off'); } const action = (value === false) ? 'disable' : 'enable'; virtualclass.videoHost.toggleVideoMsg(action); } }, askQuestion(value) { const askQuestion = document.querySelector('#congAskQuestion'); const rightSubContainer = document.getElementById('virtualclassAppRightPanel'); if (value === true) { askQuestion.classList.remove('askQuestionDisable'); askQuestion.classList.add('askQuestionEnable'); rightSubContainer.dataset.askQuestion = 'askQuestionEnable'; } else { // document.querySelector('#user_list').click(); askQuestion.classList.remove('askQuestionEnable'); askQuestion.classList.add('askQuestionDisable'); rightSubContainer.dataset.askQuestion = 'askQuestionDisable'; } }, userlist(value) { if (roles.isStudent()) { const userList = document.querySelector('#memlist'); if (userList !== null) { const searchUserInput = document.querySelector('#congchatBarInput #congreaUserSearch'); const vmlist = document.querySelector('#user_list.vmchat_bar_button'); // const askQuestionElem = document.querySelector('#congAskQuestion'); // const notesElem = document.querySelector('#virtualclassnote'); if (value === true) { userList.classList.remove('hideList'); searchUserInput.classList.remove('hideInput'); vmlist.classList.remove('disable'); } else { userList.classList.add('hideList'); searchUserInput.classList.add('hideInput'); vmlist.classList.add('disable'); // TODO remove commented code // if (!askQuestionElem.classList.contains('active') && !notesElem.classList.contains('active')) { // const vmchat = document.querySelector('.vmchat_room_bt .inner_bt'); // vmchat.click(); // } handleCommonChat(); } } } }, attendeerecording(obj) { virtualclass.settings.recordingSettings(obj); }, enableRecording(obj) { virtualclass.settings.recordingSettings(obj); }, recAllowpresentorAVcontrol(obj) { virtualclass.settings.recordingSettings(obj); }, recShowPresentorRecordingStatus(obj) { virtualclass.settings.recordingSettings(obj); }, attendeeAV(obj) { virtualclass.settings.recordingSettings(obj); }, recallowattendeeAVcontrol(obj) { virtualclass.settings.recordingSettings(obj); }, showAttendeeRecordingStatus(obj) { virtualclass.settings.recordingSettings(obj); }, qaMarkNotes(value) { // TODO handle on default settings const notesElem = document.querySelector('#virtualclassnote'); const rightSubContainer = document.getElementById('virtualclassAppRightPanel'); const bookmarkElem = document.querySelector('#bookmark'); if (value === true) { notesElem.classList.remove('notesDisable'); notesElem.classList.add('notesEnable'); bookmarkElem.classList.remove('bookmarkDisable'); bookmarkElem.classList.add('bookmarkEnable'); rightSubContainer.dataset.qaNote = 'enable'; } else { notesElem.classList.remove('notesEnable'); notesElem.classList.add('notesDisable'); bookmarkElem.classList.remove('bookmarkEnable'); bookmarkElem.classList.add('bookmarkDisable'); rightSubContainer.dataset.qaNote = 'disbale'; } }, qaAnswer(value) { if (!virtualclass.vutil.checkUserRole()) { // console.log('setting comp qA ', value); const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.answer = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.answer = 'disable'; } } } }, qaComment(value) { if (!virtualclass.vutil.checkUserRole()) { const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.comment = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.comment = 'disable'; } } } }, qaUpvote(value) { if (!virtualclass.vutil.checkUserRole()) { const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.upvote = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.upvote = 'disable'; } } } }, upcomingSetting() { // nothing to do }, recordingSettings(obj) { const buttonStatus = virtualclass.settings.recording.recordingStatus(obj); virtualclass.settings.recording.showRecordingButton(buttonStatus); }, recording: { recordingButton: 0, // 0 - Do not show button, 1 - show button but no click, 2 - show button and clickable attendeeButtonAction: true, init() { // recording status, button show or hide, override setting const buttonSettings = JSON.parse(localStorage.getItem('recordingButton')); if (buttonSettings === null) { this.recordingButton = this.recordingStatus(); } else { this.recordingButton = buttonSettings; } const atbuttonSettings = JSON.parse(localStorage.getItem('attendeeButtonAction')); if (atbuttonSettings !== null) { this.attendeeButtonAction = atbuttonSettings; } this.showRecordingButton(); }, toggleRecordingButton() { if (this.recordingButton === 21) { this.recordingButton = 11; } else if (this.recordingButton === 11) { this.recordingButton = 21; } ioAdapter.setRecording(); localStorage.setItem('recordingButton', this.recordingButton); this.showRecordingButton(); if (roles.hasControls()) { ioAdapter.mustSend({ ac: this.recordingButton, cf: 'recs' }); } else if (this.recordingButton === 21) { this.attendeeButtonAction = true; localStorage.setItem('attendeeButtonAction', true); } else { this.attendeeButtonAction = false; localStorage.setItem('attendeeButtonAction', false); } }, showRecordingButton(buttonStatus) { // recording button button show or hide if (typeof buttonStatus !== 'undefined') { this.recordingButton = buttonStatus; } const recordingButton = virtualclass.getTemplate('recordingButton'); let context; this.removeButton(); switch (this.recordingButton) { case 10: context = { ten: 'ten' }; break; case 11: context = { eleven: 'eleven' }; break; case 20: context = { twenty: 'twenty' }; break; case 21: context = { twentyone: 'twentyone' }; break; default: return; } const temp = recordingButton(context); const elem = document.querySelector('#virtualclassAppFooterPanel #networkStatusContainer'); // this.removeButton(); elem.insertAdjacentHTML('afterend', temp); const recording = document.getElementById('recording'); if (this.recordingButton === 21 || this.recordingButton === 11) { this.attachHandler(recording); } }, removeButton() { const recording = document.getElementById('recording'); if (recording !== null) { recording.remove(); } }, attachHandler(recording) { recording.addEventListener('click', this.recordingButtonAction.bind(this, recording)); }, recordingButtonAction() { // On recording button action send to student if (this.recordingButton === 21 || this.recordingButton === 11) { this.toggleRecordingButton(); } }, recordingStatus(obj) { let settingsInfo; if (typeof obj !== 'undefined') { settingsInfo = obj; } else { settingsInfo = virtualclass.settings.info; } if (!settingsInfo.enableRecording) { if (roles.hasControls()) { if (settingsInfo.recShowPresentorRecordingStatus) { return 10; } } else if (settingsInfo.showAttendeeRecordingStatus) { return 10; } return 0; } if (roles.hasControls()) { if (settingsInfo.recAllowpresentorAVcontrol) { return 21; } if (settingsInfo.recShowPresentorRecordingStatus) { return 20; } return 22; } if (settingsInfo.attendeerecording) { if (settingsInfo.attendeeAV) { if (settingsInfo.recallowattendeeAVcontrol) { return 21; } if (settingsInfo.showAttendeeRecordingStatus) { return 20; } return 22; } if (settingsInfo.showAttendeeRecordingStatus) { return 10; } return 0; } return 0; }, sendYesOrNo() { if (this.recordingButton === 20 || this.recordingButton === 21 || this.recordingButton === 22) { return 'yes'; } return 'no'; }, triggerSetting(message) { if (roles.isStudent()) { if (!virtualclass.settings.info.attendeeAV) { this.recordingButton = 0; ioAdapter.setRecording(); this.showRecordingButton(); return; } switch (message.ac) { case 11: this.recordingButton = 10; break; case 21: if (virtualclass.settings.info.recallowattendeeAVcontrol) { if (this.attendeeButtonAction) { this.recordingButton = 21; } else { this.recordingButton = 11; } } else { this.recordingButton = 20; } break; default: return; } ioAdapter.setRecording(); localStorage.setItem('recordingButton', this.recordingButton); if (virtualclass.settings.info.showAttendeeRecordingStatus) { this.showRecordingButton(); } } }, }, userAudioIcon() { if ((virtualclass.settings.info.studentaudio === false)) { virtualclass.gObj.audioEnable = false; virtualclass.user.control.audioDisable(true); } else if (virtualclass.settings.info.studentaudio === true) { virtualclass.gObj.audioEnable = true; virtualclass.user.control.audioWidgetEnable(true); } else if (virtualclass.settings.info.studentaudio !== true) { virtualclass.user.control.audioDisable(); } }, userVideoIcon() { if (virtualclass.settings.info.studentvideo === false && roles.isStudent()) { virtualclass.vutil.videoHandler('off'); virtualclass.user.control.videoDisable(); } else { // todo, check it properly on page refresh if (roles.isStudent() && virtualclass.settings.info.studentvideo !== true) { if (virtualclass.settings.info.studentvideo !== undefined) { virtualclass.vutil.videoHandler('off'); virtualclass.videoHost.toggleVideoMsg('disable'); } } else { virtualclass.user.control.videoEnable(); if (roles.isStudent()) { // after refresh video disable when user enable his video etc. virtualclass.vutil.videoHandler('off'); } } if (virtualclass.settings.info.studentvideo === true) { virtualclass.user.control.videoEnable(); } } }, }; window.settings = settings; }(window));
pinky28/virtualclass
src/settings.js
JavaScript
gpl-3.0
24,868
# -*- coding: utf-8 -*- from gettext import gettext as _ EXP1 = [ _('Regions'), ['lineasDepto'], [], ['deptos'] ] EXP2 = [ _('Regional capitals'), ['lineasDepto', 'capitales'], [], ['capitales'] ] EXP3 = [ _('Cities'), ['lineasDepto', 'capitales', 'ciudades'], [], ['capitales', 'ciudades'] ] EXP4 = [ _('Waterways'), ['rios'], [], ['rios'] ] EXP5 = [ _('Routes'), ['rutas', 'capitales'], ['capitales'], ['rutas'] ] EXPLORATIONS = [EXP1, EXP2, EXP3, EXP4, EXP5]
AlanJAS/iknowAmerica
recursos/0guyana/datos/explorations.py
Python
gpl-3.0
550
namespace Grove.AI.TargetingRules { using System.Collections.Generic; using System.Linq; public class EffectGiveDeathtouch : TargetingRule { protected override IEnumerable<Targets> SelectTargets(TargetingRuleParameters p) { var candidates = p.Candidates<Card>(ControlledBy.SpellOwner) .Where(c => !c.Has().Deathtouch) .Where(c => c.Power > 0) .Where(c => c.CanAttack || c.CanBlock()) .OrderBy(x => x.Power); return Group(candidates, p.TotalMinTargetCount()); } } }
pinky39/grove
source/Grove/Core/AI/TargetingRules/EffectGiveDeathtouch.cs
C#
gpl-3.0
543
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.8 (January 25, 2016) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 **[N]**/ ?> <? require_once('include/errorhandler.php'); require_once('include/sessionchecker.php'); require_once('include/sessioninfo.php'); if (getLevel() == 2) { ?> <script language="javascript"> alert('Maaf, anda tidak berhak mengakses halaman ini!'); document.location.href = "lapkeuangan.php"; </script> <? exit(); } ?> <frameset border="1" rows="70,*" frameborder="yes"> <frame name="header" src="laprugilaba_header.php" scrolling="no" noresize="noresize" style="border:1; border-bottom-color:#000000; border-bottom-style:solid"/> <frame name="content" src="laprugilaba_blank.php" /> </frameset><noframes></noframes>
dedefajriansyah/jibas
keuangan/laprugilaba_main.php
PHP
gpl-3.0
1,598
 using Foundation; using UIKit; namespace _3citi.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
adam-kida/3citi
3citi/_3citi.iOS/AppDelegate.cs
C#
gpl-3.0
399
/** * Strawberry Library * Copyright (C) 2011 - 2012 * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, see <http://www.gnu.org/licenses/>. */ package com.github.strawberry.guice; import java.lang.reflect.Field; import com.google.common.cache.LoadingCache; import com.google.inject.MembersInjector; import fj.data.Option; /** * * @author Wiehann Matthysen */ final class ConfigMembersInjector<T> implements MembersInjector<T> { private final LoadingCache<Field, Option> cache; private final Field field; ConfigMembersInjector(LoadingCache<Field, Option> cache, Field field) { this.cache = cache; this.field = field; this.field.setAccessible(true); } @Override public void injectMembers(final T object) { Option value = this.cache.getUnchecked(this.field); try { Config annotation = this.field.getAnnotation(Config.class); if (this.field.get(object) != null) { // If field is not equal to null (i.e. default value has been set) // and if value to be injected is not null, then set. // Or, if forced update has been specified, then set. if (annotation.forceUpdate() || value.isSome()) { this.field.set(object, value.toNull()); } } else { // Always set null field. this.field.set(object, value.toNull()); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
wcmatthysen/strawberry
src/main/java/com/github/strawberry/guice/ConfigMembersInjector.java
Java
gpl-3.0
2,149
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, division, print_function) import unittest from mantid.simpleapi import mtd from testhelpers import run_algorithm from mantid.api import WorkspaceGroup, MatrixWorkspace from mantid import config class IndirectILLReductionFWS(unittest.TestCase): # cache the def instrument and data search dirs _def_fac = config['default.facility'] _def_inst = config['default.instrument'] _data_dirs = config['datasearch.directories'] # EFWS+IFWS, two wing _run_two_wing_mixed = '170299:170304' # EFWS+IFWS, one wing _run_one_wing_mixed = '083072:083077' def setUp(self): # set instrument and append datasearch directory config['default.facility'] = 'ILL' config['default.instrument'] = 'IN16B' config.appendDataSearchSubDir('ILL/IN16B/') def tearDown(self): # set cached facility and datasearch directory config['default.facility'] = self._def_fac config['default.instrument'] = self._def_inst config['datasearch.directories'] = self._data_dirs def test_two_wing(self): args = {'Run': self._run_two_wing_mixed, 'OutputWorkspace': 'out'} alg_test = run_algorithm('IndirectILLReductionFWS', **args) self.assertTrue(alg_test.isExecuted(), "IndirectILLReductionFWS not executed") self._check_workspace_group(mtd['out_red'], 2, 18, 3) runs_log1 = mtd['out_red'].getItem(0).getRun().getLogData('ReducedRunsList').value runs_log2 = mtd['out_red'].getItem(1).getRun().getLogData('ReducedRunsList').value self.assertEquals(runs_log1,'170299,170301,170303',"Reduced runs list mismatch.") self.assertEquals(runs_log2,'170300,170302,170304',"Reduced runs list mismatch.") def test_one_wing(self): args = {'Run': self._run_one_wing_mixed, 'OutputWorkspace': 'out'} alg_test = run_algorithm('IndirectILLReductionFWS', **args) self.assertTrue(alg_test.isExecuted(), "IndirectILLReductionFWS not executed") self._check_workspace_group(mtd['out_red'], 3, 18, 2) def _check_workspace_group(self, wsgroup, nentries, nspectra, nbins): self.assertTrue(isinstance(wsgroup, WorkspaceGroup), "{0} should be a group workspace".format(wsgroup.getName())) self.assertEquals(wsgroup.getNumberOfEntries(), nentries, "{0} should contain {1} workspaces".format(wsgroup.getName(), nentries)) item = wsgroup.getItem(0) name = item.getName() self.assertTrue(isinstance(item, MatrixWorkspace), "{0} should be a matrix workspace".format(name)) self.assertEquals(item.getNumberHistograms(), nspectra, "{0} should contain {1} spectra".format(name, nspectra)) self.assertEquals(item.blocksize(), nbins, "{0} should contain {1} bins".format(name, nbins)) self.assertTrue(item.getSampleDetails(), "{0} should have sample logs".format(name)) self.assertTrue(item.getHistory().lastAlgorithm(), "{0} should have history".format(name)) if __name__ == "__main__": unittest.main()
mganeva/mantid
Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/IndirectILLReductionFWSTest.py
Python
gpl-3.0
3,560
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace tests\integration\Espo\Core\Select; use Espo\Core\{ Application, Container, Select\SelectManagerFactory, }; class LegacyTest extends \tests\integration\Core\BaseTestCase { /** * @var SelectManagerFactory */ private $selectManagerFactory; protected function setUp(): void { parent::setUp(); $injectableFactory = $this->getContainer()->get('injectableFactory'); $this->selectManagerFactory = $injectableFactory->create(SelectManagerFactory::class); } protected function initTest(array $aclData = [], bool $skipLogin = false, bool $isPortal = false): Application { $this->createUser('tester', [ 'data' => $aclData, ]); if (!$skipLogin) { $this->auth('tester'); } $app = $this->createApplication(); $injectableFactory = $app->getContainer()->get('injectableFactory'); $this->selectManagerFactory = $injectableFactory->create(SelectManagerFactory::class); $this->user = $app->getContainer()->get('user'); return $app; } public function testAccess1(): void { $app = $this->initTest( [ 'Account' => [ 'read' => 'own', ], ] ); $container = $app->getContainer(); $userId = $container->get('user')->getId(); $selectManager = $this->selectManagerFactory->create('Account'); $result = $selectManager->getEmptySelectParams(); $selectManager->applyAccess($result); $this->assertEquals(['assignedUserId' => $userId], $result['whereClause']); } public function testGetSelectParams(): void { $app = $this->initTest( [ 'Opportunity' => [ 'read' => 'own', ], ] ); $container = $app->getContainer(); $userId = $container->get('user')->getId(); $selectManager = $this->selectManagerFactory->create('Opportunity'); $params = [ 'primaryFilter' => 'open', ]; $result = $selectManager->getSelectParams($params, true, true, true); $this->assertEquals( [ 'assignedUserId' => $userId, 'stage!=' => ['Closed Won', 'Closed Lost'], ], $result['whereClause'] ); } }
ayman-alkom/espocrm
tests/integration/Espo/Core/Select/LegacyTest.php
PHP
gpl-3.0
3,809
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Pambudi Satria (<https://github.com/pambudisatria>). # @author Pambudi Satria <pambudi.satria@yahoo.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import fields, models, api class account_invoice_line(models.Model): _inherit = "account.invoice.line" jne_number = fields.Char('JNE #')
sumihai-tekindo/account_sicepat
sicepat_erp/invoice_line_jne_number/invoice_line_jne_number.py
Python
gpl-3.0
1,191
/* * This file is part of the VVIDE project. * * Copyright (C) 2011 Pavel Fischer rubbiroid@gmail.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package vvide.utils.xmlitems; import java.util.Vector; import javax.swing.JComponent; import javax.swing.JPopupMenu; import org.w3c.dom.Element; /** * XML Item for popUp menu */ public class PopUpMenuItem extends AbstractXMLItem { /* * ============================ Methods ================================== */ @Override public Object parseXMLElement( Element element ) { JPopupMenu popupMenu = new JPopupMenu(); // Getting subelements Vector<Element> elementNodeList = xmlUtils.getElementNodeList( element.getChildNodes() ); // fill the menu for ( Element nextElement : elementNodeList ) { if ( nextElement.getTagName().equals( "Separator" ) ) { popupMenu.addSeparator(); } else { popupMenu.add( (JComponent) xmlUtils.getItem( nextElement.getAttribute( typeAttributeName ) ) .parseXMLElement( nextElement ) ); } } return popupMenu; } }
Rubbiroid/VVIDE
src/vvide/utils/xmlitems/PopUpMenuItem.java
Java
gpl-3.0
1,731
'use strict' import { Github as GithubAPI } from '../utils/github' const Github = new GithubAPI() import Result from '../models/result' import * as utils from '../utils/utils' function _processItems (items, oncomplete, onpromise) { var users_promises = items.map((repo) => { return new Promise((resolve, reject) => { _getContributors(repo['contributors_url'], repo, (res) => { resolve(res) }, (err) => { reject(err) }) onpromise() }) }) Promise.all(users_promises) .then(oncomplete) } function _getContributors (url, repo, oncomplete, onerror) { Github.make_auth_request(url, (contribs) => { repo['total'] = contribs.reduce((memo, user) => { return user['contributions'] + memo }, 0) oncomplete({ contribs, repo }) }, (error) => { onerror(error) }) } function _createUsersData (repos) { let users = new Map() for (let repo of repos) { for (let contrib of repo['contribs']) { if (!users.contains(contrib['login'])) { users.set(contrib['login'], { 'login': contrib['login'], 'url': contrib['url'], 'repos': [] }) } users.get(contrib['login'])['repos'].push({ 'login': contrib['login'], 'url': contrib['url'], 'contributions': contrib['contributions'], 'total': repo['total'], 'repo': repo['repo'], 'author': contrib['login'] === repo['repo']['owner']['login'] }) } } return users } function _getUsersInfo (users, oncomplete) { var user_data_promises = users.vals().map((user) => { return new Promise((resolve, reject) => { Github.make_auth_request(user['url'], (value) => { users.get(user['login'])['data'] = value resolve(value) }) }) }) Promise.all(user_data_promises) .then(oncomplete) } function _getUsersScore (users, oncomplete) { for (let user of users) { user['score'] = user['repos'].reduce((memo, repo) => { let repo_score = (repo['contributions'] / repo['repo']['total']) * (repo['repo']['total'] + repo['repo']['stargazers_count'] + repo['repo']['watchers_count'] + repo['repo']['forks_count'] + repo['repo']['score'] * 2) return memo + repo_score }, user['data']['followers'] * 2) oncomplete() } } function _saveUsers (users, id, oncomplete, onerror) { for (let user of users) { let res = new Result() res.id = utils.guid() res.request = id res.score = user['score'] res.repos_count = user['repos'].length res.contributions_count = user['repos'].reduce((memo, repo) => { return memo + repo['contributions'] }, 0) res.followers = user['data']['followers'] res.object = JSON.stringify(user) res.save((err, res) => { if (err) onerror(err) else oncomplete() }) } } function _search (keywords, langs, req) { Github.search(keywords, langs, (resp) => { req.status = 'got repositories, processing results' req.percent = 0 req.save() let index = 0 _processItems(resp['items'], (res) => { let users = _createUsersData(res) _getUsersInfo(users, () => { const length = users.length req.status = 'got list of users, sorting' req.percent = 0 req.save() let index_scores = 0 _getUsersScore(users, () => { req.percent = (index_scores + 1) * 100.0 / length index_scores += 1 req.save() }) req.status = 'sorted, saving results' req.percent = 0 req.save() let index_users = 0 _saveUsers(users, req.id, () => { req.percent = (index_users + 1) * 100.0 / length index_users += 1 req.save() }, (err) => { req.status = `Error saving, ${err}` req.save() }) req.status = 'done' req.percent = 100 req.save() }) }, () => { req.percent = (index + 1) * 100.0 / resp['items'].length index += 1 req.save() }) }) } export function search (keywords, langs, req, timeout) { if (!timeout) timeout = 100 setTimeout(_search, 100, keywords, langs, req) }
AgustinCB/programmmrs_api
src/app/sources/github.js
JavaScript
gpl-3.0
4,186
/* _____________________________________________________________________________ * | | * | === WARNING: GADGET FILE === | * | Changes to this page affect many users. | * | Please discuss changes on the talk page or on [[MediaWiki_talk:Gadgets-definition]] before editing. | * |_____________________________________________________________________________| * * "join" feature, to be used by the Wikimedia Foundation's Grants Programme, */ //<nowiki> importStylesheet('User:Jeph_paul/join.css'); var joinGadget = function(){ /* Variables */ var dialog = null; //The path to the config file this.joinInterfaceMessages = 'User:Jeph_paul/joinInterfaceMessages'; this.joinConfig = 'User:Jeph_paul/joinconfig'; //The time taken for the page to scroll to the feedback (milliseconds) var feedbackScrollTime = 2000; //The time taken for the feedback to disappear (milliseconds) var feedbackDisappearDelay = 10000; var infobox = ''; var roleDict = {}; var api = new mw.Api(); var that = this; /* Functions */ //To set cookie after feedback/joinment has been added var setFeedbackCookie = function(){ $.cookie('joinFeedback',true); }; //To add the page to the user's watch list var watchPage = function (){ return api.watch(mw.config.get('wgCanonicalNamespace')+':'+mw.config.get('wgTitle')); }; //To display error message in case of an error var errorMessage = function(){ $('.joinError').show(); }; //To detect the type of grant/page type. IEG,PEG etc var grantType = function(joinConfig){ var grant = mw.config.get('wgTitle').split('/')[0]; if (grant in joinConfig){ return joinConfig[grant]; } else{ return joinConfig['default']; } }; //To add the joinment thank you message //remove hardcoding of the joinment/join id in the rendered html this.joinFeedback = function(){ var li = $('#'+$.trim(grantType(joinConfig)['section'])).parent().next().find('li').eq(-1); speechBubble = li.append($('<div class="joinSpeechBubbleContainer"></div>').html('<div class="joinSpeechBubble">\ <span localize="message-feedback">Thank You</span></div><div class="joinArrowDown"></div>')).find('.joinSpeechBubbleContainer'); var width = li.css('display','inline-block').width(); li.css('display',''); li.css('position','relative'); speechBubble.css('left',width/2+'px'); $('[localize=message-feedback]').html(grantType(joinInterfaceMessages)['message-feedback']); $("body, html").animate({ scrollTop : li[0].offsetTop}, feedbackScrollTime); setTimeout(function(){ speechBubble.hide();},feedbackDisappearDelay); }; //To check if feedback has been added & has been set so in the cookie this.checkFeedbackCookie = function(){ if($.cookie('joinFeedback')){ $.cookie('joinFeedback',null); return true; } else{ return false; } }; //To detect the language fo the page this.userLanguage = function(){ return mw.config.get('wgUserLanguage'); }; this.contentLanguage = function(){ return mw.config.get('wgContentLanguage'); }; //To localize the gadget interface messages based on the language detected above var localizeGadget = function (gadgetClass,localizeDict){ $(gadgetClass+' [localize]').each(function(){ var localizeValue = $.trim(localizeDict[$(this).attr('localize')]); if($(this).attr('value')){ $(this).attr('value',localizeValue); } else if($(this).attr('placeholder')){ $(this).attr('placeholder',localizeValue); } else if($(this).attr('data-placeholder')){ $(this).attr('data-placeholder',localizeValue); } else{ $(this).html(localizeValue); } }); }; //To remove extra spaces from the joinment string var cleanupText = function(text){ text = $.trim(text)+' '; var indexOf = text.indexOf('~~~~'); if ( indexOf == -1 ){ return text; } else{ return text.slice(0,indexOf)+text.slice(indexOf+4); } }; //To create the dialog box. It is created once on the time of page load var createDialog = function(){ dialog = $( "<div id='joinDialog'></div>" ) .html( '<select class="roleSelect" localize="placeholder-role" data-placeholder="Select a role">\ <option></option>\ </select>\ <div localize="message-description" class="joinDescription">Tell us how you would like to help</div>\ <div class="error joinHide joinError" localize="message-error">An error occured</div>\ <textarea rows="5" cols="10" placeholder="Add your comment" id="joinComment" class="" localize="placeholder-comment"></textarea>\ <span localize="message-signature" class="gadgetSignature">Your signature will be added automatically</span>\ <div class="gadgetControls">\ <a href="#" localize="button-cancel" class="mw-ui-button cancel mw-ui-quiet">Cancel</a>\ <input type="submit" localize="button-join" class="mw-ui-button mw-ui-constructive add-join" disabled localize="button" value="Join"></input>\ </div>' ).dialog({ dialogClass: 'joinGadget', autoOpen: false, title: 'join Comment', width: '495px', modal: true, closeOnEscape: true, resizable: false, draggable: false, close: function( event, ui ) { $('#joinComment').val(''); } }); $('.add-join').click(function(){ //var joinRole = grantType(joinConfig)['message']+' '+$('.roleSelect').val().replace(/_/,' ')+'.'; //var joinRole = grantType(joinConfig)['message'] + '.'; var joinRole = $('.roleSelect').val().replace(/_/,' '); joinRole=joinRole[0].toUpperCase()+joinRole.slice(1); joinRole = "'''"+ joinRole + "'''" + " "; that.addjoinment(joinRole+cleanupText($('#joinComment').val())); }); $('#joinComment').on('change keyup paste',function(){ $('.joinError').hide(); if($(this).val()){ $('.gadgetSignature').css('visibility','visible'); if($('.roleSelect').val()){ $('.add-join').attr('disabled',false); } } else{ $('.add-join').attr('disabled',true); $('.gadgetSignature').css('visibility','hidden'); } }); $('#ui-dialog-title-joinDialog').attr('localize','title'); $('.joinGadget .cancel').click(function(){ dialog.dialog('close'); }); localizeGadget('.joinGadget',grantType(joinInterfaceMessages)); $('.gadgetSignature').css('visibility','hidden'); //values in dropdown api.get({ 'format':'json', 'action':'parse', 'prop':'wikitext', 'page': mw.config.get('wgPageName'), 'section': 0 }).then(function(result){ var roles = grantType(joinInterfaceMessages)['roles']; //var roles = roleString.split(','); var wikitext = result.parse.wikitext['*']; var infobox = wikitext.slice(wikitext.indexOf('{{Probox'),wikitext.indexOf('}}')+2); that.infobox = infobox; units = infobox.split('|'); //var roleDict = {}; for (unit in units){ var roleParsedWikitext = units[unit].split('=')[0]; var individualParsedWikitext = units[unit].split('=')[1]; var role = units[unit].match(/[a-zA-z]+/)[0]; var count = units[unit].split('=')[0].match(/[0-9]+/)?units[unit].split('=')[0].match(/[0-9]+/)[0]:1; if(role in roles){ roleDict[role]=count; if ($.trim(individualParsedWikitext) == ''){ if(!$('.roleSelect option[value="'+role+'"]').length){ $('.roleSelect').append('<option value='+role+'>'+roles[role]+'</option>'); } } } } if(!$('.roleSelect option[value="volunteer"]').length){ $('.roleSelect').append('<option value="volunteer">'+roles['volunteer']+'</option>'); } $('.roleSelect').chosen({ disable_search: true, placeholder_text_single: 'Select a role', width: '50%', }); $('.roleSelect').on('change',function(){ if($(this).val() && $('#joinComment').val()){ $('.add-join').attr('disabled',false); } else{ $('.add-join').attr('disabled',true); } }); }); }; this.joinDialog = function () { if (dialog === null){ createDialog(); } else{ dialog.dialog('open'); } }; var addToInfobox = function(username){ return '[[User:' + username + '|' + username + ']]'; }; /* * The main function to add the feedback/joinment to the page. It first checks if the page has an joinment section. * If it dosent it creates a new section called joinments and appends the fedback/joinment to that section, * else it appends the feedback/joinment to existing joinments section. */ this.addjoinment = function( text ) { var joinComment = '\n*' + text + '~~~~' + '\n'; //Editing the infobox var roleSelected = $('.roleSelect').val(); var units = that.infobox.split('\n'); var emptyRoleAdded = false; for (unit in units){ if ($.trim(units[unit].split('=')[1]) == ''){ var role = units[unit].match(/[a-zA-z]+/); if (role){ role = role[0]; } if(role == roleSelected){ units[unit] = $.trim(units[unit]) + addToInfobox(mw.config.get('wgUserName')); emptyRoleAdded = true; break; } } } var modifiedInfoBox = units.join("\n"); if(!emptyRoleAdded){ var paramCount = parseInt(roleDict["volunteer"])+1; modifiedInfoBox = modifiedInfoBox.split('}}')[0]+'|volunteer'+paramCount+'='+addToInfobox(mw.config.get('wgUserName'))+'\n}}'; } //end editing the infobox api.post({ 'action' : 'edit', 'title' : mw.config.get('wgPageName'), 'text' : modifiedInfoBox, 'summary' : mw.user.getName() + ' joined the project as a ' + roleSelected, 'section': 0, 'token' : mw.user.tokens.values.editToken }).then(function(){ api.get({ 'format':'json', 'action':'parse', 'prop':'sections', 'page':mw.config.get('wgPageName'), }).then(function(result){ var sections = result.parse.sections; var sectionCount = 1; var sectionFound = false; for (var section in sections ){ if ($.trim(sections[section]['anchor']) == $.trim(grantType(joinConfig)['section']) ){ sectionFound = true; break; } sectionCount++; } if (sectionFound){ api.get({ 'format':'json', 'action':'parse', 'prop':'wikitext', 'page': mw.config.get('wgPageName'), 'section': sectionCount }).then(function(result){ var wikitext = result.parse.wikitext['*']; var joinmentSection = wikitext + joinComment; api.post({ 'action' : 'edit', 'title' : mw.config.get('wgPageName'), 'text' : joinmentSection, 'summary' : 'Joining message from ' + mw.user.getName(), 'section': sectionCount, 'token' : mw.user.tokens.values.editToken }).then(function(){ $.when(watchPage()).then(function(){ window.location.reload(true); setFeedbackCookie(); }); },errorMessage); }); } else{ var sectionHeader = grantType(joinConfig)['section']; api.post({ action: 'edit', title: mw.config.get('wgPageName'), section: 'new', summary: sectionHeader, text: joinComment, token: mw.user.tokens.get('editToken') }).then(function () { location.reload(); feedbackCookie(); }, errorMessage); } },errorMessage); },errorMessage); }; }; /* End of functions */ mw.loader.using( ['jquery.ui.dialog', 'mediawiki.api', 'mediawiki.ui','jquery.chosen'], function() { $(function() { (function(){ var namespace = mw.config.get('wgCanonicalNamespace'); /* * Fix mw.config.get('wgPageContentLanguage') == 'en') checking with a better solution, * either when pages can be tagged with arbitary language or when we set langauge markers later on. * */ if ( namespace == "Grants" ) { if(mw.config.get('wgPageContentLanguage') == 'en'){ var join = new joinGadget(); var api = new mw.Api(); var joinInterfaceMessagesTitle = join.joinInterfaceMessages+'/'+join.userLanguage(); var joinConfigTitle = join.joinConfig+'/'+join.contentLanguage(); //To detect if we have the gadget translations in the language of the page. api.get({'action':'query','titles':joinInterfaceMessagesTitle+'|'+joinConfigTitle,'format':'json'}).then(function(data){ for(id in data.query.pages){ if (data.query.pages[id].title == join.joinInterfaceMessages && id == -1){ joinInterfaceMessagesTitle = join.joinInterfaceMessages+'/en'; } if (data.query.pages[id].title == join.joinConfig && id == -1){ joinConfigTitle = join.joinConfig+'/en'; } } var joinInterfaceMessagesUrl = 'https://meta.wikimedia.org/w/index.php?title='+joinInterfaceMessagesTitle+'&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400'; var joinConfigUrl = 'https://meta.wikimedia.org/w/index.php?title='+joinConfigTitle+'&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400'; //Get the config for the detected language $.when(jQuery.getScript(joinInterfaceMessagesUrl),jQuery.getScript(joinConfigUrl)).then(function(){ join.joinDialog(); $('.wp-join-button').click(function(e){ e.preventDefault(); join.joinDialog(); }); if(join.checkFeedbackCookie()){ join.joinFeedback(); } }); }); } else{ $('.wp-join-button').hide(); } } })(); }); }); //</nowiki>
WMFGrants/joinEndorseGadget
gadget/js/join.js
JavaScript
gpl-3.0
13,692
<?php use Illuminate\Database\Seeder; use App\User; class UserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $data = array( [ 'name' => 'Admin', 'last_name' => 'Admin', 'email' => 'admin@admin.com', 'user' => 'admin', 'password' => \Hash::make('admin'), 'type' => 'admin', 'active' => 1, 'address' => 'Kings Road', 'created_at'=> new DateTime, 'updated_at'=> new DateTime ], [ 'name' => 'Demo', 'last_name' => 'User', 'email' => 'demo@demo.com', 'user' => 'demo', 'password' => \Hash::make('demo'), 'type' => 'user', 'active' => 1, 'address' => 'Abbey Road', 'created_at'=> new DateTime, 'updated_at'=> new DateTime ], ); User::insert($data); } }
Rotron/laravel5.2-ecommerce
database/seeds/UserTableSeeder.php
PHP
gpl-3.0
873
<?php /** * @file * Provides traits for specific Postgesql Queries. * * @see: https://www.postgresql.org/docs/current/static/sql-commands.html */ namespace n_koopa; require_once('common/base/classes/base_error.php'); require_once('common/base/classes/base_return.php'); require_once('common/database/classes/database_string.php'); require_once('common/database/enumerations/database_operand.php'); /** * Provide the sql (right) operand functionality. */ trait t_database_operand_right { protected $operand_right; /** * Assign the settings. * * @param int|string|null $type * The operand to assign. * Can be set to e_database_operand::NONE. * Set to NULL to disable. * * @return c_base_return_status * TRUE on success, FALSE otherwise. * FALSE with the error bit set is returned on error. */ public function set_operand_right($type) { if (is_null($type)) { $this->operand_right = NULL; return new c_base_return_true(); } if (is_int($type)) { if ($type !== e_database_operand::NONE) { $error = c_base_error::s_log(NULL, ['arguments' => [':{argument_name}' => 'type', ':{function_name}' => __CLASS__ . '->' . __FUNCTION__]], i_base_error_messages::INVALID_ARGUMENT); return c_base_return_error::s_false($error); } $this->operand_right = e_database_operand::NONE; return new c_base_return_true(); } else if (is_string($type)) { $placeholder = $this->add_placeholder($type); if ($placeholder->has_error()) { return c_base_return_error::s_false($placeholder->get_error()); } $this->operand_right = $placeholder; unset($placeholder); return new c_base_return_true(); } return new c_base_return_false(); } /** * Get the currently assigned operand_right settings. * * @return i_database_query_placeholde|c_base_return_int|c_base_return_null * The operand int or query placeholder on success. * NULL is returned if not set (operand right is not to be used). * NULL with the error bit set is returned on error. */ public function get_operand_right() { if (is_null($this->operand_right)) { return new c_base_return_null(); } if (is_int($this->operand_right)) { return c_base_return_int::s_new($this->operand_right); } else if (isset($this->operand_right)) { return clone($this->operand_right); } $error = c_base_error::s_log(NULL, ['arguments' => [':{variable_name}' => 'operand_right', ':{function_name}' => __CLASS__ . '->' . __FUNCTION__]], i_base_error_messages::INVALID_VARIABLE); return c_base_return_error::s_null($error); } /** * Perform the common build process for this trait. * * As an internal trait method, the caller is expected to perform any appropriate validation. * * @return string|null * A string is returned. * NULL is returned if there is nothing to process or there is an error. */ protected function p_do_build_operand_right() { if ($this->operand_right === e_database_operand::NONE) { return c_database_string::NONE; } return strval($this->operand_right); } }
thekevinday/koopa
common/database/traits/database_operand_right.php
PHP
gpl-3.0
3,205
package services; import criterias.AccessTokenCriteria; import criterias.UserCriteria; import models.AccessToken; import models.User; import org.junit.Test; import play.mvc.Http; import tests.AbstractDatabaseTest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** * @author resamsel * @version 28 Jan 2017 */ public class AccessTokenServiceIntegrationTest extends AbstractDatabaseTest { private AccessTokenService accessTokenService; @Test public void find() { Http.Request request = mock(Http.Request.class); assertThat(accessTokenService.findBy(new AccessTokenCriteria()).getList()).hasSize(0); User user = createUser("user1", "a@b.c"); createAccessToken(user, request); assertThat(userService.findBy(new UserCriteria()).getList()).hasSize(1); } private AccessToken createAccessToken(User user, Http.Request request) { AccessToken out = new AccessToken(); out.user = user; out.name = "accessToken1"; accessTokenService.create(out, request); return out; } @Test public void create() { Http.Request request = mock(Http.Request.class); User user = createUser("user1", "user1@resamsel.com"); AccessToken accessToken = createAccessToken(user, request); assertThat(accessToken.name).as("AccessToken.name").isEqualTo("accessToken1"); assertThat(accessToken.key).as("AccessToken.key").isNotNull(); } /** * {@inheritDoc} */ @Override protected void injectMembers() { accessTokenService = app.injector().instanceOf(AccessTokenService.class); } }
resamsel/translatr
src/it/java/services/AccessTokenServiceIntegrationTest.java
Java
gpl-3.0
1,603
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @file ExpressionClasses.cpp * @author Christian <c@ethdev.com> * @date 2015 * Container for equivalence classes of expressions for use in common subexpression elimination. */ #include <libevmasm/ExpressionClasses.h> #include <utility> #include <tuple> #include <functional> #include <boost/range/adaptor/reversed.hpp> #include <boost/noncopyable.hpp> #include <libevmasm/Assembly.h> #include <libevmasm/CommonSubexpressionEliminator.h> #include <libevmasm/SimplificationRules.h> using namespace std; using namespace dev; using namespace dev::ele; pair<Pattern, function<Pattern()> > const* Rules::findFirstMatch( Expression const& _expr, ExpressionClasses const& _classes ) { resetMatchGroups(); assertThrow(_expr.item, OptimizerException, ""); for (auto const& rule: m_rules[byte(_expr.item->instruction())]) { if (rule.first.matches(_expr, _classes)) return &rule; resetMatchGroups(); } return nullptr; } void Rules::addRules(std::vector<std::pair<Pattern, std::function<Pattern ()> > > const& _rules) { for (auto const& r: _rules) addRule(r); } void Rules::addRule(std::pair<Pattern, std::function<Pattern()> > const& _rule) { m_rules[byte(_rule.first.instruction())].push_back(_rule); } template <class S> S divWorkaround(S const& _a, S const& _b) { return (S)(bigint(_a) / bigint(_b)); } template <class S> S modWorkaround(S const& _a, S const& _b) { return (S)(bigint(_a) % bigint(_b)); } Rules::Rules() { // Multiple occurences of one of these inside one rule must match the same equivalence class. // Constants. Pattern A(Push); Pattern B(Push); Pattern C(Push); // Anything. Pattern X; Pattern Y; Pattern Z; A.setMatchGroup(1, m_matchGroups); B.setMatchGroup(2, m_matchGroups); C.setMatchGroup(3, m_matchGroups); X.setMatchGroup(4, m_matchGroups); Y.setMatchGroup(5, m_matchGroups); Z.setMatchGroup(6, m_matchGroups); addRules(vector<pair<Pattern, function<Pattern()>>>{ // arithmetics on constants {{Instruction::ADD, {A, B}}, [=]{ return A.d() + B.d(); }}, {{Instruction::MUL, {A, B}}, [=]{ return A.d() * B.d(); }}, {{Instruction::SUB, {A, B}}, [=]{ return A.d() - B.d(); }}, {{Instruction::DIV, {A, B}}, [=]{ return B.d() == 0 ? 0 : divWorkaround(A.d(), B.d()); }}, {{Instruction::SDIV, {A, B}}, [=]{ return B.d() == 0 ? 0 : s2u(divWorkaround(u2s(A.d()), u2s(B.d()))); }}, {{Instruction::MOD, {A, B}}, [=]{ return B.d() == 0 ? 0 : modWorkaround(A.d(), B.d()); }}, {{Instruction::SMOD, {A, B}}, [=]{ return B.d() == 0 ? 0 : s2u(modWorkaround(u2s(A.d()), u2s(B.d()))); }}, {{Instruction::EXP, {A, B}}, [=]{ return u256(boost::multiprecision::powm(bigint(A.d()), bigint(B.d()), bigint(1) << 256)); }}, {{Instruction::NOT, {A}}, [=]{ return ~A.d(); }}, {{Instruction::LT, {A, B}}, [=]() -> u256 { return A.d() < B.d() ? 1 : 0; }}, {{Instruction::GT, {A, B}}, [=]() -> u256 { return A.d() > B.d() ? 1 : 0; }}, {{Instruction::SLT, {A, B}}, [=]() -> u256 { return u2s(A.d()) < u2s(B.d()) ? 1 : 0; }}, {{Instruction::SGT, {A, B}}, [=]() -> u256 { return u2s(A.d()) > u2s(B.d()) ? 1 : 0; }}, {{Instruction::EQ, {A, B}}, [=]() -> u256 { return A.d() == B.d() ? 1 : 0; }}, {{Instruction::ISZERO, {A}}, [=]() -> u256 { return A.d() == 0 ? 1 : 0; }}, {{Instruction::AND, {A, B}}, [=]{ return A.d() & B.d(); }}, {{Instruction::OR, {A, B}}, [=]{ return A.d() | B.d(); }}, {{Instruction::XOR, {A, B}}, [=]{ return A.d() ^ B.d(); }}, {{Instruction::BYTE, {A, B}}, [=]{ return A.d() >= 32 ? 0 : (B.d() >> unsigned(8 * (31 - A.d()))) & 0xff; }}, {{Instruction::ADDMOD, {A, B, C}}, [=]{ return C.d() == 0 ? 0 : u256((bigint(A.d()) + bigint(B.d())) % C.d()); }}, {{Instruction::MULMOD, {A, B, C}}, [=]{ return C.d() == 0 ? 0 : u256((bigint(A.d()) * bigint(B.d())) % C.d()); }}, {{Instruction::MULMOD, {A, B, C}}, [=]{ return A.d() * B.d(); }}, {{Instruction::SIGNEXTEND, {A, B}}, [=]() -> u256 { if (A.d() >= 31) return B.d(); unsigned testBit = unsigned(A.d()) * 8 + 7; u256 mask = (u256(1) << testBit) - 1; return u256(boost::multiprecision::bit_test(B.d(), testBit) ? B.d() | ~mask : B.d() & mask); }}, // invariants involving known constants (commutative instructions will be checked with swapped operants too) {{Instruction::ADD, {X, 0}}, [=]{ return X; }}, {{Instruction::SUB, {X, 0}}, [=]{ return X; }}, {{Instruction::MUL, {X, 0}}, [=]{ return u256(0); }}, {{Instruction::MUL, {X, 1}}, [=]{ return X; }}, {{Instruction::DIV, {X, 0}}, [=]{ return u256(0); }}, {{Instruction::DIV, {0, X}}, [=]{ return u256(0); }}, {{Instruction::DIV, {X, 1}}, [=]{ return X; }}, {{Instruction::SDIV, {X, 0}}, [=]{ return u256(0); }}, {{Instruction::SDIV, {0, X}}, [=]{ return u256(0); }}, {{Instruction::SDIV, {X, 1}}, [=]{ return X; }}, {{Instruction::AND, {X, ~u256(0)}}, [=]{ return X; }}, {{Instruction::AND, {X, 0}}, [=]{ return u256(0); }}, {{Instruction::OR, {X, 0}}, [=]{ return X; }}, {{Instruction::OR, {X, ~u256(0)}}, [=]{ return ~u256(0); }}, {{Instruction::XOR, {X, 0}}, [=]{ return X; }}, {{Instruction::MOD, {X, 0}}, [=]{ return u256(0); }}, {{Instruction::MOD, {0, X}}, [=]{ return u256(0); }}, {{Instruction::EQ, {X, 0}}, [=]() -> Pattern { return {Instruction::ISZERO, {X}}; } }, // operations involving an expression and itself {{Instruction::AND, {X, X}}, [=]{ return X; }}, {{Instruction::OR, {X, X}}, [=]{ return X; }}, {{Instruction::XOR, {X, X}}, [=]{ return u256(0); }}, {{Instruction::SUB, {X, X}}, [=]{ return u256(0); }}, {{Instruction::EQ, {X, X}}, [=]{ return u256(1); }}, {{Instruction::LT, {X, X}}, [=]{ return u256(0); }}, {{Instruction::SLT, {X, X}}, [=]{ return u256(0); }}, {{Instruction::GT, {X, X}}, [=]{ return u256(0); }}, {{Instruction::SGT, {X, X}}, [=]{ return u256(0); }}, {{Instruction::MOD, {X, X}}, [=]{ return u256(0); }}, // logical instruction combinations {{Instruction::NOT, {{Instruction::NOT, {X}}}}, [=]{ return X; }}, {{Instruction::XOR, {{{X}, {Instruction::XOR, {X, Y}}}}}, [=]{ return Y; }}, {{Instruction::OR, {{{X}, {Instruction::AND, {X, Y}}}}}, [=]{ return X; }}, {{Instruction::AND, {{{X}, {Instruction::OR, {X, Y}}}}}, [=]{ return X; }}, {{Instruction::AND, {{{X}, {Instruction::NOT, {X}}}}}, [=]{ return u256(0); }}, {{Instruction::OR, {{{X}, {Instruction::NOT, {X}}}}}, [=]{ return ~u256(0); }}, }); // Double negation of opcodes with binary result for (auto const& op: vector<Instruction>{ Instruction::EQ, Instruction::LT, Instruction::SLT, Instruction::GT, Instruction::SGT }) addRule({ {Instruction::ISZERO, {{Instruction::ISZERO, {{op, {X, Y}}}}}}, [=]() -> Pattern { return {op, {X, Y}}; } }); addRule({ {Instruction::ISZERO, {{Instruction::ISZERO, {{Instruction::ISZERO, {X}}}}}}, [=]() -> Pattern { return {Instruction::ISZERO, {X}}; } }); addRule({ {Instruction::ISZERO, {{Instruction::XOR, {X, Y}}}}, [=]() -> Pattern { return { Instruction::EQ, {X, Y} }; } }); // Associative operations for (auto const& opFun: vector<pair<Instruction,function<u256(u256 const&,u256 const&)>>>{ {Instruction::ADD, plus<u256>()}, {Instruction::MUL, multiplies<u256>()}, {Instruction::AND, bit_and<u256>()}, {Instruction::OR, bit_or<u256>()}, {Instruction::XOR, bit_xor<u256>()} }) { auto op = opFun.first; auto fun = opFun.second; // Moving constants to the outside, order matters here! // we need actions that return expressions (or patterns?) here, and we need also reversed rules // (X+A)+B -> X+(A+B) addRules(vector<pair<Pattern, function<Pattern()>>>{{ {op, {{op, {X, A}}, B}}, [=]() -> Pattern { return {op, {X, fun(A.d(), B.d())}}; } }, { // X+(Y+A) -> (X+Y)+A {op, {{op, {X, A}}, Y}}, [=]() -> Pattern { return {op, {{op, {X, Y}}, A}}; } }, { // For now, we still need explicit commutativity for the inner pattern {op, {{op, {A, X}}, B}}, [=]() -> Pattern { return {op, {X, fun(A.d(), B.d())}}; } }, { {op, {{op, {A, X}}, Y}}, [=]() -> Pattern { return {op, {{op, {X, Y}}, A}}; } }}); } // move constants across subtractions addRules(vector<pair<Pattern, function<Pattern()>>>{ { // X - A -> X + (-A) {Instruction::SUB, {X, A}}, [=]() -> Pattern { return {Instruction::ADD, {X, 0 - A.d()}}; } }, { // (X + A) - Y -> (X - Y) + A {Instruction::SUB, {{Instruction::ADD, {X, A}}, Y}}, [=]() -> Pattern { return {Instruction::ADD, {{Instruction::SUB, {X, Y}}, A}}; } }, { // (A + X) - Y -> (X - Y) + A {Instruction::SUB, {{Instruction::ADD, {A, X}}, Y}}, [=]() -> Pattern { return {Instruction::ADD, {{Instruction::SUB, {X, Y}}, A}}; } }, { // X - (Y + A) -> (X - Y) + (-A) {Instruction::SUB, {X, {Instruction::ADD, {Y, A}}}}, [=]() -> Pattern { return {Instruction::ADD, {{Instruction::SUB, {X, Y}}, 0 - A.d()}}; } }, { // X - (A + Y) -> (X - Y) + (-A) {Instruction::SUB, {X, {Instruction::ADD, {A, Y}}}}, [=]() -> Pattern { return {Instruction::ADD, {{Instruction::SUB, {X, Y}}, 0 - A.d()}}; } } }); } Pattern::Pattern(Instruction _instruction, std::vector<Pattern> const& _arguments): m_type(Operation), m_instruction(_instruction), m_arguments(_arguments) { } void Pattern::setMatchGroup(unsigned _group, map<unsigned, Expression const*>& _matchGroups) { m_matchGroup = _group; m_matchGroups = &_matchGroups; } bool Pattern::matches(Expression const& _expr, ExpressionClasses const& _classes) const { if (!matchesBaseItem(_expr.item)) return false; if (m_matchGroup) { if (!m_matchGroups->count(m_matchGroup)) (*m_matchGroups)[m_matchGroup] = &_expr; else if ((*m_matchGroups)[m_matchGroup]->id != _expr.id) return false; } assertThrow(m_arguments.size() == 0 || _expr.arguments.size() == m_arguments.size(), OptimizerException, ""); for (size_t i = 0; i < m_arguments.size(); ++i) if (!m_arguments[i].matches(_classes.representative(_expr.arguments[i]), _classes)) return false; return true; } AssemblyItem Pattern::toAssemblyItem(SourceLocation const& _location) const { if (m_type == Operation) return AssemblyItem(m_instruction, _location); else return AssemblyItem(m_type, data(), _location); } string Pattern::toString() const { stringstream s; switch (m_type) { case Operation: s << instructionInfo(m_instruction).name; break; case Push: if (m_data) s << "PUSH " << hex << data(); else s << "PUSH "; break; case UndefinedItem: s << "ANY"; break; default: if (m_data) s << "t=" << dec << m_type << " d=" << hex << data(); else s << "t=" << dec << m_type << " d: nullptr"; break; } if (!m_requireDataMatch) s << " ~"; if (m_matchGroup) s << "[" << dec << m_matchGroup << "]"; s << "("; for (Pattern const& p: m_arguments) s << p.toString() << ", "; s << ")"; return s.str(); } bool Pattern::matchesBaseItem(AssemblyItem const* _item) const { if (m_type == UndefinedItem) return true; if (!_item) return false; if (m_type != _item->type()) return false; else if (m_type == Operation) return m_instruction == _item->instruction(); else if (m_requireDataMatch) return data() == _item->data(); return true; } Pattern::Expression const& Pattern::matchGroupValue() const { assertThrow(m_matchGroup > 0, OptimizerException, ""); assertThrow(!!m_matchGroups, OptimizerException, ""); assertThrow((*m_matchGroups)[m_matchGroup], OptimizerException, ""); return *(*m_matchGroups)[m_matchGroup]; } u256 const& Pattern::data() const { assertThrow(m_data, OptimizerException, ""); return *m_data; } ExpressionTemplate::ExpressionTemplate(Pattern const& _pattern, SourceLocation const& _location) { if (_pattern.matchGroup()) { hasId = true; id = _pattern.id(); } else { hasId = false; item = _pattern.toAssemblyItem(_location); } for (auto const& arg: _pattern.arguments()) arguments.push_back(ExpressionTemplate(arg, _location)); } string ExpressionTemplate::toString() const { stringstream s; if (hasId) s << id; else s << item; s << "("; for (auto const& arg: arguments) s << arg.toString(); s << ")"; return s.str(); }
elementrem/solidity
libevmasm/SimplificationRules.cpp
C++
gpl-3.0
12,729
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Timers; using ConLib; namespace ChristmasGames { class MainClass { public static List<Ornament> OList = new List<Ornament>(); public static Random _rnd = new Random(); public static Timer dropTimer = new Timer(); public static bool dead = false, win = false; public static int windowX = Console.WindowWidth - 1, windowY = Console.WindowHeight - 1; public static int activeXLeft = windowX - 59, activeXRight = windowX - 20; public static int playerX = 40, playerY = 21, score = 0, respawnCounter = 3; public static float lives = 10f; public static string name; public static string player = "‿"; public static void Main(string[] args) { bool quit = false; Console.Title = "Christmas Mini-Game: Ornament Catcher"; Console.CursorVisible = true; Console.ForegroundColor = ConsoleColor.Green; Out.Write("Please enter your name...", 0, 0); Console.SetCursorPosition(0,1); name = Console.ReadLine(); Console.Clear(); Out.Write("Welcome to Christmas Mini-Game: Ornament Catcher, " + name + "!", 0, 0); Out.Write("In this mini-game you have to save the falling Christmas Ornaments " + Environment.NewLine + "from hitting the bottom of the window and breaking.", 0, 1); Out.Write(" - You have 10 Health, you will a relevant amount of health for each ornament missed.", 0, 3); Out.Write(" - For every ornament caught, you will gain one point." + Environment.NewLine + "After 15 points you win the game!", 0, 4); Out.Write("Ornaments: ",0,7); Out.Write("o - +1 score for catching; -1 health for missing.",0,8); Out.Write("Ɵ - +2 score for catching; -2 health for missing.",0,9); Out.Write("★ - +3 score for catching; -0.5 health for missing.",0,10); Out.Write("Press any key to proceed...", 0,11); Console.Read(); Console.CursorVisible = false; //Console.Write(windowX + " " + windowY); Timer spawnTimer = new Timer(2000); spawnTimer.Elapsed += new ElapsedEventHandler(spawnOrnament); spawnTimer.Enabled = true; dropTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); dropTimer.Interval = 700; dropTimer.Enabled = true; Timer gameTimer = new Timer(); gameTimer.Elapsed += new ElapsedEventHandler(Update); gameTimer.Interval = 40; gameTimer.Enabled = true; Timer respawnTimer = new Timer(1000); respawnTimer.Elapsed += new ElapsedEventHandler(DrawRespawn); respawnTimer.Enabled= true; while ((quit == false)) { ConsoleKeyInfo keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.Escape) { quit = true; } else if ((keyInfo.Key == ConsoleKey.LeftArrow) && (playerX != activeXLeft + 1)) { playerX--; } else if ((keyInfo.Key == ConsoleKey.RightArrow) && (playerX != activeXRight - 1)) { playerX++; } } } private static void DrawBorders() { for (int i = 0; i <39; i++) { Out.Write("#",activeXLeft + i, 0); } for (int j = 0; j < windowY; j++) { Out.Write("#",activeXLeft, j); Out.Write("#",activeXRight, j); } for (int i = 0; i<40; i++) { Out.Write("#", activeXLeft + i, windowY); } } private static void spawnOrnament(object source, ElapsedEventArgs e) { OList.Add(new Ornament()); } private static void OnTimedEvent(object source, ElapsedEventArgs e) { player = "‿"; for (int j = 0; j < OList.Count; j++) { if (!OList [j].windowYCheck()) { OList [j].moveDown(); } } } private static void Update(object source, ElapsedEventArgs e) { // if (lives == 0) dead = true; else dead = false; if (score >= 30) win = true; else win = false; if (!win && !dead) { Console.Clear(); DrawBorders(); DrawCursor(); DrawData(); OrnamentDrawLoop(); } } private static void DrawRespawn(object source, ElapsedEventArgs e) { if (dead) { Console.Clear(); OList.Clear(); Console.SetCursorPosition(windowX / 2 - 19, windowY / 2); Console.Write("Oh, you appear to have died, " + name + ". "); Console.SetCursorPosition(windowX / 2 - 17, windowY / 2 + 1); Console.Write("Starting new game..."); Console.SetCursorPosition(windowX / 2 - 17, windowY / 2 + 2); Console.WriteLine(respawnCounter + "..."); respawnCounter--; if (respawnCounter == 0) { dead = false; lives = 10; score = 0; } } else if (win) { Console.Clear(); OList.Clear(); Console.SetCursorPosition(windowX / 2 - 14, windowY / 2); Console.Write("Merry Christmas " + name + "! You have won!"); Console.SetCursorPosition(windowX / 2 - 12, windowY / 2 + 1); Console.Write("Starting new game..."); Console.SetCursorPosition(windowX / 2 - 10, windowY / 2 + 2); Console.WriteLine(respawnCounter + "..."); respawnCounter--; if (respawnCounter == 0) { win = false; lives = 10; score = 0; } } } private static void OrnamentDrawLoop() { for (int i = 0; i < OList.Count; i++) { if (OList [i].windowYCheck() || PlayerOrnamentCollisionCheck(i)) { if(OList [i].windowYCheck()) { lives-=OList[i].damage; } OList.RemoveAt(i); } else { OList [i].DrawOrnament(); } } } private static void DrawCursor() { Console.SetCursorPosition(playerX, playerY); Console.Write(player); } private static void DrawData() { Out.Write("Player: " + name, 1, 0); Out.Write("Score: " + score, 1, 1); Out.Write("Lives: " + lives, 1, 2); //Console.WriteLine(windowX + " " + windowY); } private static bool PlayerOrnamentCollisionCheck(int i) { bool hit; if ((playerX == OList [i].oX) && (playerY == OList [i].oY )) { hit = true; score+= OList [i].worth; player = "X"; dropTimer.Interval = dropTimer.Interval - 25; } else if ((playerY < OList [i].oY) && (playerY > OList [i].oldOY)) { hit = true; score+= OList [i].worth; player = "X"; dropTimer.Interval = dropTimer.Interval - 25; } else hit = false; return hit; } } }
ZedsTed/christmas-game-2013
ChristmasGames/Main.cs
C#
gpl-3.0
8,244
#! /usr/bin/env node 'use strict'; let SlackClient = require('slack-api-client'); export class SlackAPI { constructor(token) { this.slackToken = token; this.slack = SlackAPI.initSlack(this.slackToken); } static initSlack(token) { return new SlackClient(token); } users() { return new Promise((resolve, reject) => { this.slack.api.users.list((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } channels() { return new Promise((resolve, reject) => { this.slack.api.channels.list({}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } channelsHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.channels.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } groups() { return new Promise((resolve, reject) => { this.slack.api.groups.list({}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } groupHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.groups.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } im() { return new Promise((resolve, reject) => { this.slack.api.im.list((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } imHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.im.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } getSelfData() { return new Promise((resolve, reject) => { this.slack.api.auth.test((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } }
SouthPoleTelescope/slacklogging
slack-history-export/src/slack.api.js
JavaScript
gpl-3.0
2,141
using System; using Stagio.Web.Automation.Selenium; using Stagio.TestUtilities; using OpenQA.Selenium; namespace Stagio.Web.Automation.PageObjects.InternshipApplicationPages { public class CreateInternshipApplicationPage { public static void GoTo() { const int OFFER_ID = 1; InternshipOfferPages.StudentIndexInternshipOfferPage.CreateInternshipApplication(OFFER_ID); } public static bool IsDisplayed() { try { Driver.Instance.FindElement(By.Id("application-create-page")); return true; } catch (Exception) { return false; } } public static void UploadFile(string pdfFile) { UploadTestFiles(pdfFile); Driver.Instance.FindElement(By.Id("confirm-button")).Click(); } private static void UploadTestFiles(String filename) { var fullPath = FileUtilities.GetPathFromFileName(filename); Driver.Instance.FindElement(By.Id("Resume")).SendKeys(fullPath); Driver.Instance.FindElement(By.Id("CoverLetter")).SendKeys(fullPath); } } }
csf-dept-info/stagio
Stagio.Web.Automation/PageObjects/InternshipApplicationPages/CreateInternshipApplicationPage.cs
C#
gpl-3.0
1,241
const commander = require('commander'); const dnode = require('dnode'); commander .description('returnes the storj status for a given host and port as JSON') .option('--host <hostname>') .option('--port <port>') .parse(process.argv); let sock = dnode.connect(commander.host, commander.port); sock.on('error', () => { sock = null; console.log(JSON.stringify({result: false, error: 'failed to connect to storjshare-daemon', data: null})); }); sock.on('remote', (remote) => { remote.status((err, result) => { sock.end(); sock = null; if (err) { console.log(JSON.stringify({result: false, error: err.toString(), data: null})); return; } console.log(JSON.stringify({result:true, error: null, data: result})); }); });
felixbrucker/storjshare-daemon-proxy
storj-status-json.js
JavaScript
gpl-3.0
764
package io.rong.methods; import java.net.HttpURLConnection; import java.net.URLEncoder; import io.rong.models.*; import io.rong.util.GsonUtil; import io.rong.util.HttpUtil; import io.rong.util.HostType; public class SMS { private static final String UTF8 = "UTF-8"; private String appKey; private String appSecret; public SMS(String appKey, String appSecret) { this.appKey = appKey; this.appSecret = appSecret; } /** * 获取图片验证码方法 * * @param appKey:应用Id * * @return SMSImageCodeReslut **/ public SMSImageCodeReslut getImageCode(String appKey) throws Exception { if (appKey == null) { throw new IllegalArgumentException("Paramer 'appKey' is required"); } StringBuilder sb = new StringBuilder(HostType.SMS.getStrType()+"/getImgCode.json"); sb.append("?appKey=").append(URLEncoder.encode(appKey, UTF8)); HttpURLConnection conn = HttpUtil.CreateGetHttpConnection(sb.toString()); return (SMSImageCodeReslut) GsonUtil.fromJson(HttpUtil.returnResult(conn), SMSImageCodeReslut.class); } /** * 发送短信验证码方法。 * * @param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 次。(必传) * @param templateId:短信模板 Id,在开发者后台->短信服务->服务设置->短信模版中获取。(必传) * @param region:手机号码所属国家区号,目前只支持中图区号 86) * @param verifyId:图片验证标识 Id ,开启图片验证功能后此参数必传,否则可以不传。在获取图片验证码方法返回值中获取。 * @param verifyCode:图片验证码,开启图片验证功能后此参数必传,否则可以不传。 * * @return SMSSendCodeReslut **/ public SMSSendCodeReslut sendCode(String mobile, String templateId, String region, String verifyId, String verifyCode) throws Exception { if (mobile == null) { throw new IllegalArgumentException("Paramer 'mobile' is required"); } if (templateId == null) { throw new IllegalArgumentException("Paramer 'templateId' is required"); } if (region == null) { throw new IllegalArgumentException("Paramer 'region' is required"); } StringBuilder sb = new StringBuilder(); sb.append("&mobile=").append(URLEncoder.encode(mobile.toString(), UTF8)); sb.append("&templateId=").append(URLEncoder.encode(templateId.toString(), UTF8)); sb.append("&region=").append(URLEncoder.encode(region.toString(), UTF8)); if (verifyId != null) { sb.append("&verifyId=").append(URLEncoder.encode(verifyId.toString(), UTF8)); } if (verifyCode != null) { sb.append("&verifyCode=").append(URLEncoder.encode(verifyCode.toString(), UTF8)); } String body = sb.toString(); if (body.indexOf("&") == 0) { body = body.substring(1, body.length()); } HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(HostType.SMS, appKey, appSecret, "/sendCode.json", "application/x-www-form-urlencoded"); HttpUtil.setBodyParameter(body, conn); return (SMSSendCodeReslut) GsonUtil.fromJson(HttpUtil.returnResult(conn), SMSSendCodeReslut.class); } /** * 验证码验证方法 * * @param sessionId:短信验证码唯一标识,在发送短信验证码方法,返回值中获取。(必传) * @param code:短信验证码内容。(必传) * * @return CodeSuccessReslut **/ public CodeSuccessReslut verifyCode(String sessionId, String code) throws Exception { if (sessionId == null) { throw new IllegalArgumentException("Paramer 'sessionId' is required"); } if (code == null) { throw new IllegalArgumentException("Paramer 'code' is required"); } StringBuilder sb = new StringBuilder(); sb.append("&sessionId=").append(URLEncoder.encode(sessionId.toString(), UTF8)); sb.append("&code=").append(URLEncoder.encode(code.toString(), UTF8)); String body = sb.toString(); if (body.indexOf("&") == 0) { body = body.substring(1, body.length()); } HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(HostType.SMS, appKey, appSecret, "/verifyCode.json", "application/x-www-form-urlencoded"); HttpUtil.setBodyParameter(body, conn); return (CodeSuccessReslut) GsonUtil.fromJson(HttpUtil.returnResult(conn), CodeSuccessReslut.class); } }
klhdy/im-indepartment
src/io/rong/methods/SMS.java
Java
gpl-3.0
4,444
<?php /** * @package Arastta eCommerce * @copyright 2015-2018 Arastta Association. All rights reserved. * @copyright See CREDITS.txt for credits and other copyright notices. * @license GNU GPL version 3; see LICENSE.txt * @link https://arastta.org */ // Text $_['text_register_subject'] = '%s - Your Account has been created!'; $_['text_register_message'] = '%s - Your Account has been created!'; $_['text_approve_subject'] = 'Welcome and thank you for registering at %s'; $_['text_approve_welcome'] = 'Welcome and thank you for registering at %s!'; $_['text_approve_login'] = 'Your account has now been created and you can log in by using your email address and password by visiting our website or at the following URL:'; $_['text_approve_services'] = 'Upon logging in, you will be able to access other services including reviewing past orders, printing invoices and editing your account information.'; $_['text_approve_thanks'] = 'Thanks,'; $_['text_credit_subject'] = '%s - Account Credit'; $_['text_credit_received'] = 'You have received %s credit!'; $_['text_credit_total'] = 'Your total amount of credit is now %s.' . "\n\n" . 'Your account credit will be automatically deducted from your next purchase.'; $_['text_reward_subject'] = '%s - Reward Points'; $_['text_reward_received'] = 'You have received %s Reward Points!'; $_['text_reward_total'] = 'Your total number of reward points is now %s.'; $_['text_approve_wait_subject'] = '%s - Your Account approved!'; $_['text_register_email'] = 'Your user name : %s'; $_['text_register_password'] = 'Your password : %s'; $_['text_register_password_message'] = '%s %s change your password'; $_['text_register_reset_password'] = '%s Reset Password %s %s';
arastta/arastta
admin/language/en-GB/mail/customer.php
PHP
gpl-3.0
1,953
# Copyright (C) 2010-2012, InSTEDD # # This file is part of Verboice. # # Verboice 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. # # Verboice 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 Verboice. If not, see <http://www.gnu.org/licenses/>. class Compiler attr_accessor :first attr_accessor :labels attr_accessor :variables attr_accessor :external_service_guids def initialize @labels = {} @variables = Set.new @external_service_guids = Set.new end def parse &blk if block_given? if blk.arity == 1 yield self else instance_eval &blk end end self end def make &blk parse &blk resolve_gotos @first end def self.parse &blk Compiler.new.parse &blk end def self.make &blk Compiler.new.make &blk end def If(condition, if_true = nil, &blk) append Commands::IfCommand.new(condition, inner_block(if_true, &blk)) end def Else(block = nil, &blk) @last.else = inner_block(block, &blk) self end def While(condition, block = nil, &blk) append Commands::WhileCommand.new(condition, inner_block(block, &blk)) end def Label(name) label = Label.new(name) @labels[name] = label append label end def Goto(label) append Goto.new(label) end def End Goto nil end def PersistVariable(variable, expression) @variables.add variable append Commands::PersistVariableCommand.new(variable, expression) end def Callback url=nil, options={} @external_service_guids.add options[:external_service_guid] if options[:external_service_guid].present? append Commands::CallbackCommand.new(url, options) end def Assign(*args) append Commands::AssignExpressionCommand.new(*args) end def method_missing(method, *args) cmd_class = "Commands::#{method.to_s}Command".constantize append cmd_class.new *args end def append(cmd) if cmd cmd = inner_block(cmd) if cmd.is_a? Compiler @first ||= cmd @last.next = cmd if @last @last = cmd.last end self end private def resolve_gotos nodes_to_visit = [] visited_nodes = Set.new nodes_to_visit.push parent: self, node: first, variable: :@first while !nodes_to_visit.empty? do context = nodes_to_visit.shift parent = context[:parent] node = context[:node] variable = context[:variable] next unless node if node.is_a? Label parent.instance_variable_set variable, node.next nodes_to_visit.push parent: parent, node: node.next, variable: variable elsif node.is_a? Goto next_node = if node.label label_node = @labels[node.label] if label_node label_node.next else raise "Unmatched Goto label #{node.label}" end else nil end parent.instance_variable_set variable, next_node nodes_to_visit.push parent: parent, node: next_node, variable: variable elsif ! visited_nodes.include? node visited_nodes.add node node.instance_variables.each do |var| val = node.instance_variable_get var if val.is_a? Command nodes_to_visit.push parent: node, node: val, variable: var end end end end end def inner_block(block = nil, &blk) block ||= Compiler.parse(&blk) if block.is_a? Compiler @labels.merge! block.labels @variables.merge block.variables @external_service_guids.merge block.external_service_guids block.first else block end end class CompilerCommand < Command def run(session) raise "Unexpected command. This command (#{self}) should not be in the flow. Did you forget to call the 'make' method?" end end class Goto < CompilerCommand attr_accessor :label def initialize(label) @label = label end end class Label < CompilerCommand attr_accessor :name def initialize(name) @name = name end end end
waj/verboice
app/models/compiler.rb
Ruby
gpl-3.0
4,501
<div id="angularEnableServiceNotificationsModal" class="modal z-index-2500" role="dialog"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <i class="far fa-envelope"></i> <?php echo __('Enable service notifications'); ?> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"><i class="fa fa-times"></i></span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-lg-12 text-center padding-top-10"> <div class="card card-body"> <span class="hintmark"> <?php echo __('Yes, I would like to temporarily <strong>enable</strong> notifications.'); ?> </span> <div class="padding-left-10 padding-top-10"> <span class="note hintmark_before"> <?php echo __('This option is only temporary. It does not affect your configuration. This is an external command and only saved in the memory of your monitoring engine.'); ?> </span> </div> </div> </div> </div> <div class="row" ng-show="isEnableingServiceNotifications"> <div class="col-lg-12 margin-top-10"> <div class="progress progress-striped active"> <div class="progress-bar bg-primary" style="width: {{percentage}}%"></div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" ng-click="doEnableServiceNotifications()"> <?php echo __('Execute'); ?> </button> <button type="button" class="btn btn-default" data-dismiss="modal"> <?php echo __('Close'); ?> </button> </div> </div> </div> </div>
it-novum/openITCOCKPIT
src/Template/Angular/enable_service_notifications.php
PHP
gpl-3.0
2,384
/******************************************************************************* * 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 org.worldgrower.conversation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.worldgrower.Constants; import org.worldgrower.World; import org.worldgrower.WorldObject; import org.worldgrower.actions.Actions; import org.worldgrower.goal.FacadeUtils; import org.worldgrower.goal.RelationshipPropertyUtils; import org.worldgrower.text.TextId; import org.worldgrower.util.SentenceUtils; public class WhyNotIntelligentConversation implements InterceptedConversation { private static final int WHY_NOT_INTELLIGENT = -1; private static final int SEE_THROUGH = -2; @Override public Response getReplyPhrase(ConversationContext conversationContext) { WorldObject performer = conversationContext.getPerformer(); WorldObject target = conversationContext.getTarget(); World world = conversationContext.getWorld(); if (isConversationAvailable(performer, target, world)) { int replyId; if (FacadeUtils.performerIsSuccessFullyDisguised(performer)) { replyId = WHY_NOT_INTELLIGENT; } else { replyId = SEE_THROUGH; } return getReply(getReplyPhrases(conversationContext), replyId); } return null; } @Override public List<Response> getReplyPhrases(ConversationContext conversationContext) { WorldObject performer = conversationContext.getPerformer(); WorldObject target = conversationContext.getTarget(); World world = conversationContext.getWorld(); if (isConversationAvailable(performer, target, world)) { String performerName = performer.getProperty(Constants.NAME); String article = SentenceUtils.getArticle(performerName); return Arrays.asList( new Response(WHY_NOT_INTELLIGENT, TextId.WHY_NOT_INTELLIGENT, article, performerName), new Response(SEE_THROUGH, TextId.SEE_THROUGH, performerName) ); } else { return new ArrayList<>(); } } @Override public boolean isConversationAvailable(WorldObject performer, WorldObject target, World world) { WorldObject facade = performer.getProperty(Constants.FACADE); return ((facade != null) && (facade.getProperty(Constants.ID) != null) && (!world.findWorldObjectById(facade.getProperty(Constants.ID)).hasIntelligence())); } @Override public void handleResponse(int replyIndex, ConversationContext conversationContext, Conversation originalConversation) { WorldObject performer = conversationContext.getPerformer(); WorldObject target = conversationContext.getTarget(); World world = conversationContext.getWorld(); if (isConversationAvailable(performer, target, world)) { if (replyIndex == SEE_THROUGH) { RelationshipPropertyUtils.changeRelationshipValue(performer, target, -50, Actions.TALK_ACTION, Conversations.createArgs(originalConversation), world); } } } }
WorldGrower/WorldGrower
src/org/worldgrower/conversation/WhyNotIntelligentConversation.java
Java
gpl-3.0
3,705
# vim: ts=8:sts=8:sw=8:noexpandtab # # This file is part of ReText # Copyright: 2017-2021 Dmitry Shachnev # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from os.path import exists import time from PyQt5.QtCore import QDir, QUrl from PyQt5.QtGui import QDesktopServices, QTextCursor, QTextDocument from PyQt5.QtWidgets import QTextBrowser from ReText import globalSettings class ReTextPreview(QTextBrowser): def __init__(self, tab): QTextBrowser.__init__(self) self.tab = tab # if set to True, links to other files will unsuccessfully be opened as anchors self.setOpenLinks(False) self.anchorClicked.connect(self.openInternal) self.lastRenderTime = 0 self.distToBottom = None self.verticalScrollBar().rangeChanged.connect(self.updateScrollPosition) def disconnectExternalSignals(self): pass def openInternal(self, link): url = link.url() if url.startswith('#'): self.scrollToAnchor(url[1:]) return elif link.isRelative(): fileToOpen = QDir.current().filePath(url) else: fileToOpen = link.toLocalFile() if link.isLocalFile() else None if fileToOpen is not None: if exists(fileToOpen): link = QUrl.fromLocalFile(fileToOpen) if globalSettings.handleWebLinks and fileToOpen.endswith('.html'): self.setSource(link) return # This is outside the "if exists" block because we can prompt for # creating the file if self.tab.openSourceFile(fileToOpen): return QDesktopServices.openUrl(link) def findText(self, text, flags, wrap=False): cursor = self.textCursor() if wrap and flags & QTextDocument.FindFlag.FindBackward: cursor.movePosition(QTextCursor.MoveOperation.End) elif wrap: cursor.movePosition(QTextCursor.MoveOperation.Start) newCursor = self.document().find(text, cursor, flags) if not newCursor.isNull(): self.setTextCursor(newCursor) return True if not wrap: return self.findText(text, flags, wrap=True) return False def updateScrollPosition(self, minimum, maximum): """Called when vertical scroll bar range changes. If this happened during preview rendering (less than 0.5s since it was started), set the position such that distance to bottom is the same as before refresh. """ timeSinceRender = time.time() - self.lastRenderTime if timeSinceRender < 0.5 and self.distToBottom is not None and maximum: newValue = maximum - self.distToBottom if newValue >= minimum: self.verticalScrollBar().setValue(newValue) def setFont(self, font): self.document().setDefaultFont(font)
retext-project/retext
ReText/preview.py
Python
gpl-3.0
3,107
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * 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 org.obiba.opal.web.magma.view; import java.util.List; import javax.validation.constraints.NotNull; import org.obiba.magma.MagmaEngine; import org.obiba.magma.ValueTable; import org.obiba.magma.js.views.JavascriptClause; import org.obiba.magma.support.ValueTableReference; import org.obiba.magma.support.ValueTableWrapper; import org.obiba.magma.views.JoinTable; import org.obiba.magma.views.SelectClause; import org.obiba.magma.views.View; import org.obiba.magma.views.View.Builder; import org.obiba.magma.views.WhereClause; import org.obiba.magma.views.support.NoneClause; import org.obiba.opal.web.model.Magma; import org.obiba.opal.web.model.Magma.JavaScriptViewDto; import org.obiba.opal.web.model.Magma.TableDto; import org.obiba.opal.web.model.Magma.ViewDto; import org.springframework.stereotype.Component; /** * An implementation of {@Code ViewDtoExtension} for {@code View} instances that have a {@code SelectClause}. */ @Component public class JavaScriptViewDtoExtension implements ViewDtoExtension { @Override public boolean isExtensionOf(@NotNull ViewDto viewDto) { return viewDto.hasExtension(JavaScriptViewDto.view); } @Override public boolean isDtoOf(@NotNull View view) { return view.getListClause() instanceof NoneClause; } @Override public View fromDto(ViewDto viewDto, Builder viewBuilder) { JavaScriptViewDto jsDto = viewDto.getExtension(JavaScriptViewDto.view); if(jsDto.hasSelect()) { SelectClause selectClause = new JavascriptClause(jsDto.getSelect()); viewBuilder.select(selectClause); } return viewBuilder.build(); } @Override public ViewDto asDto(View view) { ViewDto.Builder viewDtoBuilder = ViewDto.newBuilder(); viewDtoBuilder.setDatasourceName(view.getDatasource().getName()); viewDtoBuilder.setName(view.getName()); if(view.getWhereClause() instanceof JavascriptClause) { viewDtoBuilder.setWhere(((JavascriptClause) view.getWhereClause()).getScript()); } setFromTables(view, viewDtoBuilder); JavaScriptViewDto.Builder jsDtoBuilder = JavaScriptViewDto.newBuilder(); if(view.getSelectClause() instanceof JavascriptClause) { jsDtoBuilder.setSelect(((JavascriptClause) view.getSelectClause()).getScript()); } viewDtoBuilder.setExtension(JavaScriptViewDto.view, jsDtoBuilder.build()); return viewDtoBuilder.build(); } private void setFromTables(ValueTableWrapper view, ViewDto.Builder viewDtoBuilder) { ValueTable from = view.getWrappedValueTable(); if(from instanceof JoinTable) { List<ValueTable> fromTables = ((JoinTable) from).getTables(); for(ValueTable vt : fromTables) { if(hasTableAccess(vt)) viewDtoBuilder.addFrom(toStringReference(vt)); } } else { if(hasTableAccess(from)) viewDtoBuilder.addFrom(toStringReference(from)); } } String toStringReference(ValueTable vt) { if(vt instanceof ValueTableReference) { return ((ValueTableReference) vt).getReference(); } return vt.getDatasource().getName() + "." + vt.getName(); } @Override public TableDto asTableDto(ViewDto viewDto, Magma.TableDto.Builder tableDtoBuilder) { throw new UnsupportedOperationException(); } private boolean hasTableAccess(ValueTable vt) { return vt != null && vt.getDatasource() != null && MagmaEngine.get().hasDatasource(vt.getDatasource().getName()) && MagmaEngine.get().getDatasource(vt.getDatasource().getName()).hasValueTable(vt.getName()); } }
apruden/opal
opal-core-ws/src/main/java/org/obiba/opal/web/magma/view/JavaScriptViewDtoExtension.java
Java
gpl-3.0
3,990
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sarfDic.Midleware.Verbs.trilateral; import sarfDic.Midleware.Generator; import java.util.ArrayList; import java.util.List; import sarfDic.Midleware.KovRulesManager; import sarfDic.Midleware.SarfDictionary; import sarf.Validator; /** * * @author riad */ public class ActivePresentGeneratorUn implements Generator { public static ActivePresentGeneratorUn getInstance() { return new ActivePresentGeneratorUn(); } public List<String> presentVerps = new ArrayList<String>(); public List<String> NominativePresent = new ArrayList<String>(); public List<String> EmphasizedPresent = new ArrayList<String>(); public List<String> JussivePresent = new ArrayList<String>(); public List<String> AccusativePresent = new ArrayList<String>(); public List<String> executeSimpleGenerator(String root, String conjugation) { List<String> result = new ArrayList<String>(); List alefAlternatives = Validator.getInstance().getTrilateralAlefAlternatives(root); if (!alefAlternatives.isEmpty()) { root = alefAlternatives.get(0).toString(); } generateNominative(root, conjugation); generateEmphasized(root, conjugation); generateJussive(root, conjugation); generateAccusative(root, conjugation); return result; } public List<String> executeDetailedGenerator(String root) { throw new UnsupportedOperationException("Not supported yet."); } public List generateNominative(String rootStr, String conjugation) { //Active Present Conjugator API: sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator api = sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator.getInstance(); presentVerps = new ArrayList<String>(); //extract the root from dictionary: //the result will be a list of available forms for this unagmented verb(1st, 2nd, ....,6th). List list = SarfDictionary.getInstance().getUnaugmentedTrilateralRoots(rootStr); sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot root; String presentRoot; for (int i = 0; i < list.size(); i++) { root = (sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot) list.get(i); if (root.getConjugation().equals(conjugation)) { // presentRoot= api.createNominativeVerb(7, root).toString(); //presentVerps.add(presentRoot); List apvList1 = api.createNominativeVerbList(root); //modification sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier modifier = sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier.getInstance(); String tense = "Present"; boolean active = true; sarfDic.Midleware.KovRulesManager kovManager = KovRulesManager.getInstance(); int kov = kovManager.getTrilateralKov(root.getC1(), root.getC2(), root.getC3()); sarf.verb.trilateral.unaugmented.ConjugationResult conjResult = modifier.build(root, kov, apvList1, tense, active); List apvList = conjResult.getFinalResult(); presentRoot = apvList.get(7).toString(); presentVerps.add(presentRoot); //apvList.size=12 <==> 12 Arabic pronoun, each item in this list is ActivePresentVerb int n = apvList.size(); for (int j = 0; j < n; j++) { if (apvList.get(j) == null) { NominativePresent.add(""); continue; } //sarf.verb.trilateral.unaugmented.active.ActivePresentVerb apv1 = (sarf.verb.trilateral.unaugmented.active.ActivePresentVerb) apvList.get(j); String apv1Str = apvList.get(j).toString(); //if( ! result.contains(apv1Str)) NominativePresent.add(apv1Str); } } } return NominativePresent; } public List generateAccusative(String rootStr, String conjugation) { //Active Present Conjugator API: sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator api = sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator.getInstance(); //extract the root from dictionary: //the result will be a list of available forms for this unagmented verb(1st, 2nd, ....,6th). List list = SarfDictionary.getInstance().getUnaugmentedTrilateralRoots(rootStr); sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot root; for (int i = 0; i < list.size(); i++) { root = (sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot) list.get(i); if (root.getConjugation().equals(conjugation)) { List apvList1 = api.createAccusativeVerbList(root); //modification sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier modifier = sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier.getInstance(); String tense = "Present"; boolean active = true; sarfDic.Midleware.KovRulesManager kovManager = KovRulesManager.getInstance(); int kov = kovManager.getTrilateralKov(root.getC1(), root.getC2(), root.getC3()); sarf.verb.trilateral.unaugmented.ConjugationResult conjResult = modifier.build(root, kov, apvList1, tense, active); List apvList = conjResult.getFinalResult(); //apvList.size=12 <==> 12 Arabic pronoun, each item in this list is ActivePresentVerb int n = apvList.size(); for (int j = 0; j < n; j++) { if (apvList.get(j) == null) { AccusativePresent.add(""); continue; } //sarf.verb.trilateral.unaugmented.active.ActivePresentVerb apv1 = (sarf.verb.trilateral.unaugmented.active.ActivePresentVerb) apvList.get(j); String apv1Str = apvList.get(j).toString(); // if( ! result.contains(apv1Str)) AccusativePresent.add(apv1Str); } } } return AccusativePresent; } public List generateEmphasized(String rootStr, String conjugation) { //Active Present Conjugator API: sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator api = sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator.getInstance(); //extract the root from dictionary: //the result will be a list of available forms for this unagmented verb(1st, 2nd, ....,6th). List list = SarfDictionary.getInstance().getUnaugmentedTrilateralRoots(rootStr); sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot root; for (int i = 0; i < list.size(); i++) { root = (sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot) list.get(i); if (root.getConjugation().equals(conjugation)) { List apvList1 = api.createEmphasizedVerbList(root); //modification sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier modifier = sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier.getInstance(); String tense = "Present"; boolean active = true; sarfDic.Midleware.KovRulesManager kovManager = KovRulesManager.getInstance(); int kov = kovManager.getTrilateralKov(root.getC1(), root.getC2(), root.getC3()); sarf.verb.trilateral.unaugmented.ConjugationResult conjResult = modifier.build(root, kov, apvList1, tense, active); List apvList = conjResult.getFinalResult(); //apvList.size=12 <==> 12 Arabic pronoun, each item in this list is ActivePresentVerb int n = apvList.size(); for (int j = 0; j < n; j++) { if (apvList.get(j) == null) { EmphasizedPresent.add(""); continue; } //sarf.verb.trilateral.unaugmented.active.ActivePresentVerb apv1 = (sarf.verb.trilateral.unaugmented.active.ActivePresentVerb) apvList.get(j); String apv1Str = apvList.get(j).toString(); // if( ! result.contains(apv1Str)) EmphasizedPresent.add(apv1Str); } } } return EmphasizedPresent; } public List generateJussive(String rootStr, String conjugation) { //Active Present Conjugator API: sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator api = sarf.verb.trilateral.unaugmented.active.ActivePresentConjugator.getInstance(); //extract the root from dictionary: //the result will be a list of available forms for this unagmented verb(1st, 2nd, ....,6th). List list = SarfDictionary.getInstance().getUnaugmentedTrilateralRoots(rootStr); sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot root; for (int i = 0; i < list.size(); i++) { root = (sarf.verb.trilateral.unaugmented.UnaugmentedTrilateralRoot) list.get(i); if (root.getConjugation().equals(conjugation)) { List apvList1 = api.createJussiveVerbList(root); //modification sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier modifier = sarf.verb.trilateral.unaugmented.modifier.UnaugmentedTrilateralModifier.getInstance(); String tense = "Present"; boolean active = true; sarfDic.Midleware.KovRulesManager kovManager = KovRulesManager.getInstance(); int kov = kovManager.getTrilateralKov(root.getC1(), root.getC2(), root.getC3()); sarf.verb.trilateral.unaugmented.ConjugationResult conjResult = modifier.build(root, kov, apvList1, tense, active); List apvList = conjResult.getFinalResult(); //apvList.size=12 <==> 12 Arabic pronoun, each item in this list is ActivePresentVerb int n = apvList.size(); for (int j = 0; j < n; j++) { if (apvList.get(j) == null) { JussivePresent.add(""); continue; } //sarf.verb.trilateral.unaugmented.active.ActivePresentVerb apv1 = (sarf.verb.trilateral.unaugmented.active.ActivePresentVerb) apvList.get(j); String apv1Str = apvList.get(j).toString(); if(kov==2){// مضعف if (j == 0 || j == 1 || j == 2 || j == 7 || j == 8) { apv1Str += " / " + apvList1.get(j).toString(); } } //if( ! result.contains(apv1Str)) JussivePresent.add(apv1Str); } } } return JussivePresent; } public List<String> executeSimpleGenerator(String root) { throw new UnsupportedOperationException("Not supported yet."); } public static void main(String[] args) { List<String> tests = ActivePresentGeneratorUn.getInstance().executeSimpleGenerator("قلل","2"); for (int i = 0; i < tests.size(); i++) { System.out.println(tests.get(i)); } } }
oghalawinji/InteractiveArabicDictionary
IAD/src/java/sarfDic/Midleware/Verbs/trilateral/ActivePresentGeneratorUn.java
Java
gpl-3.0
11,789
import { equals } from 'angular'; import Chartist from 'chartist'; import jquery from 'jquery'; import { forEach, map } from 'lodash'; import { getShortInteger } from '../utils/index'; // todo: common interface interface IBucket { term: string; count: number; label: string; } export default function(app) { app.component('searchDropdown', { bindings: { description: '@', aggregation: '<', selected: '<', onAdd: '&', onRemove: '&', }, controller: class SearchDropdownCtrl { aggregation: { buckets: IBucket[]; other: number; }; selected: string[]; onAdd: (o: {term: string}) => Promise<void>; onRemove: (o: {term: string}) => Promise<void>; items: Array<{ term: string, count: number, countShort: number, label: string, selected: boolean} >; other: number; otherShort: string; static $inject = ['$scope']; constructor($scope) { $scope.$watchCollection('$ctrl.selected', this.updateItems.bind(this)); } $onChanges() { this.updateItems(); } toggle(item) { if (item.selected) { this.onRemove({term: item.term}); } else { this.onAdd({term: item.term}); } } updateItems() { const selectedAggregationTerms = []; this.items = []; if (this.aggregation) { this.other = this.aggregation.other; this.otherShort = getShortInteger(this.other); this.aggregation.buckets.forEach(bucket => { const selected = this.selected && this.selected.indexOf(bucket.term) !== -1; if (selected) selectedAggregationTerms.push(bucket.term); this.items.push({ term: bucket.term, count: bucket.count, countShort: getShortInteger(bucket.count), label: bucket.label || bucket.term, selected, }); }); } if (this.selected) { this.selected.forEach(term => { if (selectedAggregationTerms.indexOf(term) !== -1) return; this.items.unshift({ term, count: undefined, countShort: undefined, label: term, selected: true, }); }); } } }, template: require('./search-dropdown.html'), }); }
paperhive/paperhive-frontend
app/components/search-dropdown.ts
TypeScript
gpl-3.0
2,469
#!/usr/bin/python ''' Argument parser for infile/outfile for converters ''' import argparse import sys import os.path class Parser: def __init__(self): self.args = self.parse() self.verify() def parse(self): p = argparse.ArgumentParser(description="Convert SLAB6 VOX files to DCMMO .vox json") p.add_argument('infile') p.add_argument('outfile') p.add_argument('-f', '--force', action='store_true') args = p.parse_args() return args def get_overwrite_command(self): return raw_input('Overwrite? [Y/n]').lower() def verify(self): p = self.args err = False if not os.path.exists(p.infile): print '%s file does not exist' % (p.infile,) err = True if not p.force: if os.path.exists(p.outfile): print '%s file exists' % (p.outfile,) while True: over = self.get_overwrite_command() if over in ['y', 'n']: break if over == 'n': print 'Aborting' err = True else: print 'Overwriting %s' % (p.outfile,) if err: sys.exit()
Gnomescroll/Gnomescroll
tools/vox_lib/converters/converter_args.py
Python
gpl-3.0
1,296
using System; namespace OrigindLauncher.Resources.Server { public static class AccountExtension { public static LoginStatus Login(this Account account) { return AccountManager.Login(account.Username, account.Password); } [Obsolete] public static LoginStatus UpdateLoginStatus(this Account account) { return AccountManager.UpdateLoginStatus(account.Username, account.Password); } public static RegisterStatus Register(this Account account)// 对没错 说的就是你 看代码的那位 请不要调用我们的私有接口 蟹蟹 请加群609600081 { return AccountManager.Register(account); } } }
The-GregTech-Team/OrigindLauncher
OrigindLauncher.Resources/Server/AccountExtension.cs
C#
gpl-3.0
731
<?php /* Gibbon, Flexible & Open School System Copyright (C) 2010, Ross Parker 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/>. */ use Gibbon\Domain\School\SchoolYearGateway; use Gibbon\Domain\Timetable\TimetableDayGateway; use Gibbon\Domain\Timetable\TimetableDayDateGateway; include '../../gibbon.php'; $gibbonSchoolYearID = $_GET['gibbonSchoolYearID'] ?? ''; $dates = $_POST['dates'] ?? []; $gibbonTTDayID = $_POST['gibbonTTDayID'] ?? ''; $overwrite = $_POST['overwrite'] ?? 'N'; $URL = $session->get('absoluteURL').'/index.php?q=/modules/'.getModuleName($_POST['q'])."/ttDates.php&gibbonSchoolYearID=$gibbonSchoolYearID"; if (isActionAccessible($guid, $connection2, '/modules/Timetable Admin/ttDates_edit_add.php') == false) { $URL .= '&return=error0'; header("Location: {$URL}"); } else { // Proceed! $partialFail = false; // Validate Inputs if (empty($gibbonSchoolYearID) or empty($dates) or empty($gibbonTTDayID)) { $URL .= '&return=error1'; header("Location: {$URL}"); exit; } $timetableDayGateway = $container->get(TimetableDayGateway::class); $timetableDayDateGateway = $container->get(TimetableDayDateGateway::class); // Validate records exist $schoolYear = $container->get(SchoolYearGateway::class)->getByID($gibbonSchoolYearID); $gibbonTTDay = $timetableDayGateway->getTTDayByID($gibbonTTDayID); if (empty($schoolYear) || empty($gibbonTTDay)) { $URL .= '&return=error2'; header("Location: {$URL}"); exit(); } foreach ($dates as $date) { if (!isSchoolOpen($guid, date('Y-m-d', $date), $connection2, true)) { $partialFail = true; continue; } // Remove existing TT Day Dates if overwriting if ($overwrite == 'Y') { $timetableDayDateGateway->deleteWhere(['date' => date('Y-m-d', $date)]); } // Check if a day from the TT is already set $days = $timetableDayGateway->selectDaysByDate(date('Y-m-d', $date), $gibbonTTDay['gibbonTTID']); if ($days->rowCount() > 0) { $partialFail = true; } else { $data = ['gibbonTTDayID' => $gibbonTTDayID, 'date' => date('Y-m-d', $date)]; $inserted = $timetableDayDateGateway->insert($data); $partialFail &= !$inserted; } } $URL .= $partialFail ? '&return=warning1' : '&return=success0'; header("Location: {$URL}"); }
rossdotparker/core
modules/Timetable Admin/ttDates_addMultiProcess.php
PHP
gpl-3.0
3,048
using System; namespace BaiRong.Core.Model { public class ConfigInfo { public ConfigInfo() { IsInitialized = false; DatabaseVersion = string.Empty; UpdateDate = DateTime.Now; SystemConfig = string.Empty; } public ConfigInfo(bool isInitialized, string databaseVersion, DateTime updateDate, string systemConfig) { IsInitialized = isInitialized; DatabaseVersion = databaseVersion; UpdateDate = updateDate; SystemConfig = systemConfig; } public bool IsInitialized { get; set; } public string DatabaseVersion { get; set; } public DateTime UpdateDate { get; set; } public string SystemConfig { get; set; } private SystemConfigInfo _systemConfigInfo; public SystemConfigInfo SystemConfigInfo => _systemConfigInfo ?? (_systemConfigInfo = new SystemConfigInfo(SystemConfig)); } }
ColgateKas/cms
source/BaiRong.Core/Model/ConfigInfo.cs
C#
gpl-3.0
932
package net.seabears.stats.football; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class ParseDateTest extends TestCase { /** * Create the test case * * @param testName * name of the test case */ public ParseDateTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(ParseDateTest.class); } public void testParseDate() throws ParseException { Date date = parseDate("MMMM d, yyyy"); System.err.println(date); Date time = parseTime("h:mm a"); System.err.println(time); date.setTime(date.getTime() + time.getTime()); System.err.println(date); } public void testParseTime() throws ParseException { } private final static String DATE_TEXT = "8:30 PM ET, September 23, 2013"; private Date parseTime(String format) throws ParseException { System.err.println(format); SimpleDateFormat timeFormat = new SimpleDateFormat(format); timeFormat.setLenient(true); timeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return timeFormat.parse(DATE_TEXT); } private Date parseDate(String format) throws ParseException { System.err.println(format); SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.setLenient(true); return dateFormat.parse(DATE_TEXT.replaceFirst("^.*?,\\s*", "")); } }
cberes/sport-stats
src/test/java/net/seabears/stats/football/ParseDateTest.java
Java
gpl-3.0
1,643
<?php namespace GFG\DTOContext\DataWrapper; interface DataWrapperInterface { /** * @return array */ public function toArray(); }
GFG/dto-context
src/DTOContext/DataWrapper/DataWrapperInterface.php
PHP
gpl-3.0
149
import psycopg2 as dbapi2 import datetime class Favorite: def __init__(self, app): self.app = app def initialize_Favorite(self): with dbapi2.connect(self.app.config['dsn']) as connection: try: cursor = connection.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS FAVORITES( ID SERIAL PRIMARY KEY, HYPE_ID INTEGER NOT NULL REFERENCES HYPES (HYPE_ID) ON DELETE CASCADE, USER_ID INTEGER NOT NULL REFERENCES USERS (USER_ID) ON DELETE CASCADE, DATE DATE NOT NULL, RATE INTEGER NOT NULL, UNIQUE(HYPE_ID,USER_ID) )""") connection.commit() except dbapi2.DatabaseError: connection.rollback() finally: connection.commit() def drop_Favorite(self): with dbapi2.connect(self.app.config['dsn']) as connection: try: cursor = connection.cursor() query = """DROP TABLE IF EXISTS FAVORITES""" cursor.execute(query) except dbapi2.DatabaseError: connection.rollback() finally: connection.commit() def List_Favorites(self, user_ids): with dbapi2.connect(self.app.config['dsn']) as connection: user_ids = str(user_ids) cursor = connection.cursor() query = """ SELECT * FROM FAVORITES WHERE USER_ID = %s ORDER BY DATE ASC""" cursor.execute(query,(user_ids)) favorites = cursor.fetchall() return favorites def List_FavoritesID(self, favorite_id): with dbapi2.connect(self.app.config['dsn']) as connection: cursor = connection.cursor() query = """ SELECT * FROM FAVORITES WHERE ID = %s ORDER BY DATE ASC""" cursor.execute(query,(favorite_id)) favorites = cursor.fetchall() return favorites def Delete_Favorite(self, favorite_id): with dbapi2.connect(self.app.config['dsn']) as connection: try: cursor = connection.cursor() query = """DELETE FROM FAVORITES WHERE (ID = %s)""" cursor.execute(query, (favorite_id,)) connection.commit() cursor.close() except dbapi2.DatabaseError: connection.rollback() finally: connection.commit() def Add_Favorite(self, user_ids, hype_id): with dbapi2.connect(self.app.config['dsn']) as connection: try: date = datetime.date.today() rate = 1 cursor = connection.cursor() query = """INSERT INTO FAVORITES(HYPE_ID, USER_ID, DATE, RATE) VALUES (%s, %s, %s, %s)""" cursor.execute(query, (hype_id, user_ids, date, rate)) connection.commit() cursor.close() except dbapi2.DatabaseError: connection.rollback() finally: connection.commit() def Update_Favorite(self, favorite_id, rate): with dbapi2.connect(self.app.config['dsn']) as connection: try: cursor = connection.cursor() query = """UPDATE FAVORITES SET RATE = %s WHERE (ID = %s)""" cursor.execute(query, (rate, favorite_id)) connection.commit() cursor.close() except dbapi2.DatabaseError: connection.rollback() finally: connection.commit()
itucsdb1618/itucsdb1618
favorite.py
Python
gpl-3.0
3,818
package com.xxl.job.dao.impl; import com.xxl.job.admin.core.model.XxlJobGroup; import com.xxl.job.admin.dao.XxlJobGroupDao; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:spring/applicationcontext-*.xml") public class XxlJobGroupDaoTest { @Resource private XxlJobGroupDao xxlJobGroupDao; @Test public void test(){ List<XxlJobGroup> list = xxlJobGroupDao.findAll(); List<XxlJobGroup> list2 = xxlJobGroupDao.findByAddressType(0); XxlJobGroup group = new XxlJobGroup(); group.setAppName("setAppName"); group.setTitle("setTitle"); group.setOrder(1); group.setAddressType(0); group.setAddressList("setAddressList"); int ret = xxlJobGroupDao.save(group); XxlJobGroup group2 = xxlJobGroupDao.load(group.getId()); group2.setAppName("setAppName2"); group2.setTitle("setTitle2"); group2.setOrder(2); group2.setAddressType(2); group2.setAddressList("setAddressList2"); int ret2 = xxlJobGroupDao.update(group2); int ret3 = xxlJobGroupDao.remove(group.getId()); } }
dupengcheng/xxl-job
xxl-job-admin/src/test/java/com/xxl/job/dao/impl/XxlJobGroupDaoTest.java
Java
gpl-3.0
1,407
// Copyright 2013, Durachenko Aleksey V. <durachenko.aleksey@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 "cstatuswidget.h" #include "ciamreply.h" #include "cvk.h" CStatusWidget::CStatusWidget(CVk *vk, QWidget *parent) : QPushButton(parent) { // button settings setFlat(true); // init m_vk = vk; m_iAmReply = 0; setAnonymouse(); connect(m_vk, SIGNAL(accessTokenChanged(QString)), this, SLOT(slot_accessTokenChanged(QString))); } void CStatusWidget::setOnline() { setIcon(QIcon(":/icons/online.png")); } void CStatusWidget::setOffline() { setIcon(QIcon(":/icons/offline.png")); } void CStatusWidget::slot_accessTokenChanged(const QString &accessToken) { if (m_iAmReply) { m_iAmReply->abort(); m_iAmReply = 0; } if (!accessToken.isEmpty()) { m_iAmReply = new CIAmReply(m_vk, this); connect(m_iAmReply, SIGNAL(finished()), this, SLOT(slot_iamreply_finished())); m_iAmReply->start(); } else { setAnonymouse(); } } void CStatusWidget::slot_iamreply_finished() { if (m_iAmReply->hasError()) { setAnonymouse(); setToolTip(m_iAmReply->errorString()); } else { setYouAre(m_iAmReply->myName()); setToolTip(QString()); } m_iAmReply->deleteLater(); m_iAmReply = 0; } void CStatusWidget::setYouAre(const QString &text) { setText(tr("You are %1").arg(text)); setIcon(QIcon(":/icons/online.png")); } void CStatusWidget::setAnonymouse() { setYouAre(tr("Anonymouse")); setIcon(QIcon(":/icons/anonymouse.png")); }
AlekseyDurachenko/vkPhotoSync
src/cstatuswidget.cpp
C++
gpl-3.0
2,235
/* * Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved. * Use is subject to license terms. */ /* * QuoteRequestMsg40.java * * $Id: QuoteRequestMsg40.java,v 1.8 2010-08-25 05:30:31 vrotaru Exp $ */ package net.hades.fix.message.impl.v40; import net.hades.fix.message.struct.Tag; import net.hades.fix.message.type.ApplVerID; import net.hades.fix.message.type.PutOrCall; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Set; import net.hades.fix.message.Header; import net.hades.fix.message.QuoteRequestMsg; import net.hades.fix.message.exception.BadFormatMsgException; import net.hades.fix.message.exception.InvalidMsgException; import net.hades.fix.message.exception.TagNotPresentException; import net.hades.fix.message.type.BeginString; import net.hades.fix.message.type.OrdType; import net.hades.fix.message.type.Side; import net.hades.fix.message.type.TagNum; import net.hades.fix.message.util.MsgUtil; import net.hades.fix.message.util.TagEncoder; import java.util.logging.Level; /** * FIX version 4.0 QuoteRequestMsg implementation. * * @author <a href="mailto:support@marvisan.com">Support Team</a> * @version $Revision: 1.8 $ * @created 05/04/2009, 10:17:46 AM */ public class QuoteRequestMsg40 extends QuoteRequestMsg { // <editor-fold defaultstate="collapsed" desc="Constants"> private static final long serialVersionUID = 1L; protected static final Set<Integer> TAGS_V40 = new HashSet<Integer>(Arrays.asList(new Integer[] { TagNum.QuoteReqID.getValue(), TagNum.RFQReqID.getValue(), TagNum.ClOrdID.getValue(), TagNum.BookingType.getValue(), TagNum.OrderCapacity.getValue(), TagNum.OrderRestrictions.getValue(), TagNum.PrivateQuote.getValue(), TagNum.RespondentType.getValue(), TagNum.PreTradeAnonymity.getValue(), TagNum.Symbol.getValue(), TagNum.SymbolSfx.getValue(), TagNum.SecurityID.getValue(), TagNum.SecurityIDSource.getValue(), TagNum.SecurityType.getValue(), TagNum.MaturityMonthYear.getValue(), TagNum.MaturityDay.getValue(), TagNum.PutOrCall.getValue(), TagNum.StrikePrice.getValue(), TagNum.OptAttribute.getValue(), TagNum.SecurityExchange.getValue(), TagNum.Issuer.getValue(), TagNum.SecurityDesc.getValue(), TagNum.PrevClosePx.getValue(), TagNum.Side.getValue(), TagNum.OrderQty.getValue(), TagNum.SettlDate.getValue(), TagNum.OrdType.getValue(), TagNum.SettlDate2.getValue(), TagNum.OrderQty2.getValue(), TagNum.Text.getValue() })); protected static final Set<Integer> START_COMP_TAGS = null; protected static final Set<Integer> ALL_TAGS; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Static Block"> static { ALL_TAGS = new HashSet<Integer>(TAGS_V40); ALL_TAGS.addAll(START_DATA_TAGS); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Attributes"> protected Set<Integer> STANDARD_SECURED_TAGS = TAGS; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> public QuoteRequestMsg40(Header header, ByteBuffer rawMsg) throws InvalidMsgException, TagNotPresentException, BadFormatMsgException { super(header, rawMsg); SECURED_TAGS = STANDARD_SECURED_TAGS; } public QuoteRequestMsg40(BeginString beginString) throws InvalidMsgException { super(beginString); SECURED_TAGS = STANDARD_SECURED_TAGS; } public QuoteRequestMsg40(BeginString beginString, ApplVerID applVerID) throws InvalidMsgException { super(beginString, applVerID); SECURED_TAGS = STANDARD_SECURED_TAGS; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Public Methods"> @Override public Set<Integer> getFragmentTags() { return TAGS_V40; } @Override public Set<Integer> getFragmentAllTags() { return ALL_TAGS; } // ACCESSOR METHODS ////////////////////////////////////////// @Override public String getQuoteReqID() { return quoteReqID; } @Override public void setQuoteReqID(String quoteReqID) { this.quoteReqID = quoteReqID; } @Override public String getSymbol() { return symbol; } @Override public void setSymbol(String symbol) { this.symbol = symbol; } @Override public String getSymbolSfx() { return symbolSfx; } @Override public void setSymbolSfx(String symbolSfx) { this.symbolSfx = symbolSfx; } @Override public String getSecurityID() { return securityID; } @Override public void setSecurityID(String securityID) { this.securityID = securityID; } @Override public String getSecurityIDSource() { return securityIDSource; } @Override public void setSecurityIDSource(String securityIDSource) { this.securityIDSource = securityIDSource; } @Override public String getSecurityType() { return securityType; } @Override public void setSecurityType(String securityType) { this.securityType = securityType; } @Override public String getMaturityMonthYear() { return maturityMonthYear; } @Override public void setMaturityMonthYear(String maturityMonthYear) { this.maturityMonthYear = maturityMonthYear; } @Override public Integer getMaturityDay() { return maturityDay; } @Override public void setMaturityDay(Integer maturityDay) { this.maturityDay = maturityDay; } @Override public PutOrCall getPutOrCall() { return putOrCall; } @Override public void setPutOrCall(PutOrCall putOrCall) { this.putOrCall = putOrCall; } @Override public Double getStrikePrice() { return strikePrice; } @Override public void setStrikePrice(Double strikePrice) { this.strikePrice = strikePrice; } @Override public Character getOptAttribute() { return optAttribute; } @Override public void setOptAttribute(Character optAttribute) { this.optAttribute = optAttribute; } @Override public String getSecurityExchange() { return securityExchange; } @Override public void setSecurityExchange(String securityExchange) { this.securityExchange = securityExchange; } @Override public String getIssuer() { return issuer; } @Override public void setIssuer(String issuer) { this.issuer = issuer; } @Override public String getSecurityDesc() { return securityDesc; } @Override public void setSecurityDesc(String securityDesc) { this.securityDesc = securityDesc; } @Override public Double getPrevClosePx() { return prevClosePx; } @Override public void setPrevClosePx(Double prevClosePx) { this.prevClosePx = prevClosePx; } @Override public Side getSide() { return side; } @Override public void setSide(Side side) { this.side = side; } @Override public Double getOrderQty() { return orderQty; } @Override public void setOrderQty(Double orderQty) { this.orderQty = orderQty; } @Override public Date getSettlDate() { return settlDate; } @Override public void setSettlDate(Date settlDate) { this.settlDate = settlDate; } @Override public OrdType getOrdType() { return ordType; } @Override public void setOrdType(OrdType ordType) { this.ordType = ordType; } @Override public Date getSettlDate2() { return settlDate2; } @Override public void setSettlDate2(Date settlDate2) { this.settlDate2 = settlDate2; } @Override public Double getOrderQty2() { return orderQty2; } @Override public void setOrderQty2(Double orderQty2) { this.orderQty2 = orderQty2; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Protected Methods"> @Override protected void validateRequiredTags() throws TagNotPresentException { StringBuilder errorMsg = new StringBuilder("Tag value(s) for"); boolean hasMissingTag = false; if (quoteReqID == null || quoteReqID.trim().isEmpty()) { errorMsg.append(" [QuoteReqID]"); hasMissingTag = true; } if (symbol == null || symbol.trim().isEmpty()) { errorMsg.append(" [Symbol]"); hasMissingTag = true; } errorMsg.append(" is missing."); if (hasMissingTag) { throw new TagNotPresentException(errorMsg.toString()); } } @Override protected byte[] encodeFragmentSecured(boolean secured) throws TagNotPresentException, BadFormatMsgException { byte[] result = new byte[0]; ByteArrayOutputStream bao = new ByteArrayOutputStream(); try { if (MsgUtil.isTagInList(TagNum.QuoteReqID, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.QuoteReqID, quoteReqID); } if (MsgUtil.isTagInList(TagNum.Symbol, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.Symbol, symbol); } if (MsgUtil.isTagInList(TagNum.SymbolSfx, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.SymbolSfx, symbolSfx); } if (MsgUtil.isTagInList(TagNum.SecurityID, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.SecurityID, securityID); } if (MsgUtil.isTagInList(TagNum.SecurityIDSource, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.SecurityIDSource, securityIDSource); } if (MsgUtil.isTagInList(TagNum.SecurityType, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.SecurityType, securityType); } if (MsgUtil.isTagInList(TagNum.Issuer, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.Issuer, issuer); } if (MsgUtil.isTagInList(TagNum.SecurityDesc, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.SecurityDesc, securityDesc); } if (MsgUtil.isTagInList(TagNum.PrevClosePx, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.PrevClosePx, prevClosePx); } if (side != null && MsgUtil.isTagInList(TagNum.Side, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.Side, side.getValue()); } if (MsgUtil.isTagInList(TagNum.OrderQty, SECURED_TAGS, secured)) { TagEncoder.encode(bao, TagNum.OrderQty, orderQty); } result = bao.toByteArray(); } catch (IOException ex) { String error = "Error writing to the byte array."; LOGGER.log(Level.SEVERE, "{0} Error was : {1}", new Object[] { error, ex.toString() }); throw new BadFormatMsgException(error, ex); } return result; } @Override protected void setFragmentCompTagValue(Tag tag, ByteBuffer message) throws BadFormatMsgException, InvalidMsgException, TagNotPresentException { } @Override protected String getUnsupportedTagMessage() { return "This tag is not supported in [QuoteRequestMsg] message version [4.0]."; } @Override protected Set<Integer> getFragmentCompTags() { return START_COMP_TAGS; } @Override protected Set<Integer> getFragmentSecuredTags() { return SECURED_TAGS; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Package Methods"> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Private Methods"> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Inner Classes"> // </editor-fold> }
marvisan/HadesFIX
Model/src/main/java/net/hades/fix/message/impl/v40/QuoteRequestMsg40.java
Java
gpl-3.0
12,395
<?php namespace go\modules\community\calendar\model; use go\core\acl\model\AclEntity; class Calendar extends AclEntity { public $id; public $name; protected static function defineMapping() { return parent::defineMapping() ->addTable("cal_calendars") ->setQuery((new \go\core\db\Query)->select('acl_id AS aclId')); //temporary hack } }
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.3/go/modules/community/calendar/model/Calendar.php
PHP
gpl-3.0
359
// Copyright 2014-2021, University of Colorado Boulder /** * Model for the beaker in 'Acid-Base Solutions' sim. * Origin is at bottom center. * * @author Andrey Zelenkov (Mlearner) * @author Chris Malley (PixelZoom, Inc.) */ import Bounds2 from '../../../../dot/js/Bounds2.js'; import Dimension2 from '../../../../dot/js/Dimension2.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import merge from '../../../../phet-core/js/merge.js'; import acidBaseSolutions from '../../acidBaseSolutions.js'; class Beaker { /** * @param {Object} [options] */ constructor( options ) { options = merge( { size: new Dimension2( 360, 270 ), position: new Vector2( 230, 410 ) }, options ); this.size = options.size; // @public this.position = options.position; // @public // @public convenience coordinates this.left = this.position.x - this.size.width / 2; this.right = this.left + this.size.width; this.bottom = this.position.y; this.top = this.bottom - this.size.height; this.bounds = new Bounds2( this.left, this.top, this.right, this.bottom ); // @public } } acidBaseSolutions.register( 'Beaker', Beaker ); export default Beaker;
phetsims/acid-base-solutions
js/common/model/Beaker.js
JavaScript
gpl-3.0
1,204
#!/usr/bin/python import logging import argparse import os import os.path import re from datetime import datetime from datetime import timedelta BasePOSIXTime = datetime(1970, 1, 1) def GetPOSIXTimestamp(dateTimeObj): return int((dateTimeObj - BasePOSIXTime) / timedelta(seconds = 1)) def ListPhotos(): return def main(): parser = argparse.ArgumentParser(description = 'Flickr RESTful APIs Client') parser.add_argument('option', nargs='?', default='list', choices=['list']) parser.add_argument('-v', '--verbose', help='verbose messages', action='store_true', dest='verbose') args = parser.parse_args() CurrentDebugLevel = logging.INFO if args.verbose: CurrentDebugLevel = logging.DEBUG logging.basicConfig(level=CurrentDebugLevel, datefmt='%Y.%m.%d %H:%M:%S', format='%(asctime)s %(message)s') logging.debug(args) #now = datetime.utcnow() now = datetime.now() logging.info('Start working ... Now={}[{}]'.format(now.isoformat(), GetPOSIXTimestamp(now))) option = args.option.lower() if option == 'list': ListPhotos() else: parser.print_help() return if __name__ == '__main__': main()
WesleyLight/FlickrREST
python/flickr.py
Python
gpl-3.0
1,192
<?php /** * This file is part of php-simple-cache. * * php-simple-cache 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. * * php-simple-cache 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 php-simple-cache. If not, see <http://www.gnu.org/licenses/>. */ namespace Mcustiel\SimpleCache\Drivers\file; use Mcustiel\SimpleCache\Interfaces\CacheInterface; use Mcustiel\SimpleCache\Drivers\file\Exceptions\FilesCachePathNotAssigned; use Mcustiel\SimpleCache\Drivers\file\Utils\FileService; use Mcustiel\SimpleCache\Drivers\file\Utils\FileCacheRegister; use Mcustiel\SimpleCache\Interfaces\KeyInterface; class Cache implements CacheInterface { private $fileService; /** * @param \Mcustiel\SimpleCache\Drivers\file\Utils\FileService $fileService */ public function __construct(FileService $fileService = null) { $this->fileService = $fileService === null ? new FileService() : $fileService; } /** * {@inheritDoc} * @see \Mcustiel\SimpleCache\Interfaces\CacheInterface::init() */ public function init(\stdClass $initData = null) { if (!isset($initData->filesPath)) { throw new FilesCachePathNotAssigned(); } $this->fileService->setFilesPath( rtrim($initData->filesPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR ); } /** * {@inheritDoc} * @see \Mcustiel\SimpleCache\Interfaces\CacheInterface::get() */ public function get(KeyInterface $key) { if ($this->exists($key)) { $register = unserialize($this->fileService->getFrom($key->getKeyName())); if ($register->getExpiration() == 0 || $register->getExpiration() >= microtime()) { return $register->getData(); } $this->delete($key); } return null; } /** * {@inheritDoc} * @see \Mcustiel\SimpleCache\Interfaces\CacheInterface::set() */ public function set(KeyInterface $key, $value, $ttlInMillis) { $this->fileService->saveIn( $key->getKeyName(), serialize(new FileCacheRegister( $value, $ttlInMillis == 0 ? 0 : microtime() + $ttlInMillis * 1000 )) ); } /** * {@inheritDoc} * @see \Mcustiel\SimpleCache\Interfaces\CacheInterface::delete() */ public function delete(KeyInterface $key) { if ($this->exists($key)) { $this->fileService->delete($key->getKeyName()); } } /** * {@inheritDoc} * @see \Mcustiel\SimpleCache\Interfaces\CacheInterface::finish() */ public function finish() { } /** * @param \Mcustiel\SimpleCache\Types\Key $key * @return boolean */ private function exists(KeyInterface $key) { return $this->fileService->exists($key->getKeyName()); } }
mcustiel/php-simple-cache
src/Drivers/file/Cache.php
PHP
gpl-3.0
3,362
<?php echo '<h1>' . $this->route->label . '</h1>'; if ($this->step == 1) { echo '<p>Para importar usuarios se toman en cuenta las siguientes filas:</p>'; echo '<ul><li>Código (Imprescindible)</li><li>Nombre Completo (Imprescindible, útil para exportación de datos)</li>'; echo '<li>Correo electrónico</li><li>Rol (Si no se especifica, se usa el rol especificado mas abajo)</li>'; echo '<li>Usuario (Si no se especifica, se usa el código)</li><li>Apellidos</li><li>Nombres</li><li>Carrera</li></ul>'; echo '<form method="post" action="" enctype="multipart/form-data" accept-charset="utf-8">'; echo '<input type="hidden" name="return" value="' . $this->lastPage() . '" />'; echo '<table><tr><td><b>Archivo (.csv) (2 MiB max.) (*):</b></td>'; echo '<td>' . $this->formFile('file') . '</td></tr>'; $first = true; foreach ($this->options as $key => $option) { echo '<tr><td>' . $option . '</td>'; echo '<td><input type="radio"' . ($first ? ' checked="checked" ' : ' ') . 'name="type" value="' . $key . '" /></td></tr>'; $first = false; } echo '<tr><td><b>Rol:</b></td>'; echo '<td>' . $this->role('role', 'role') . '</td></tr>'; echo '<tr><td><b>Generador de contraseña:</b></td>'; echo '<td>' . $this->password('password', 'password') . '</td>'; echo '</tr><tr><td colspan="2">(*) Campos obligatorios.</td></tr><tr><td>&nbsp;</td><td><input type="submit" value="Importar usuarios" /> '; echo '<a href="' . $this->lastPage() . '">Cancelar</a>'; echo '</td></tr></table></form>'; } else { echo '<p>Por favor, revise la información siguiente, si la presentación no es correcta, por favor corrija su fichero y vuelva a subirlo:</p>'; echo '<form method="post" action="" accept-charset="utf-8">'; echo '<a href="' . $this->url(array(), 'users_import') . '">Subir nuevamente</a> '; echo '<input type="submit" value="Importar usuarios" /><hr />'; echo '<p><b>Modalidad: </b>' . $this->options[$this->type] . '<br />'; echo '<b>Generador de contraseña: </b>' . $this->password(NULL, NULL, $this->password); echo '</p><table width="100%" border=1>'; foreach ($this->results as $results) { echo '<tr><td rowspan="5" valign="top" width="18px">'; echo '<input type="checkbox" name="users[]"' . ($results['CHECKED'] && (isset($results['ROL_OBJ'])) ? ' checked="checked" ' : ' ') . 'value="' . $results['CODIGO'] . '" />'; echo '</td><td colspan="2"><b>[' . $results['CODIGO'] . '] ' . $results['NOMBRE COMPLETO'] . '</b></td>'; echo '<td align="right">'; if ($results['CODIGO_NUE']) { echo '[NUEVO]&nbsp;'; if ($this->acl('users', 'new')) { echo '<b>[OK]</b>'; } else { echo 'No tienes permiso para crear usuarios.&bnsp;<b>FALLO</b>'; } } else { echo '<a href="' . $this->url(array('user' => $results['USUARIO_OBJ']->url), 'users_user_view') . '" target="_BLANK">Ver Usuario</a>'; echo '&nbsp;[EDICION]&nbsp;'; if ($this->acl('users', 'edit')) { echo '<b>[OK]</b>'; } else { echo 'No tienes permiso para editar usuarios.&nbsp;<b>FALLO</b>'; } } echo '</td></tr><tr>'; echo '<td colspan="2"><b>Rol: </b>' . $results['ROL'] . '</td>'; echo '<td align="right">'; if (isset($results['ROL_OBJ'])) { echo '<a href="' . $this->url(array('role' => $results['ROL_OBJ']->url), 'roles_role_view') . '" target="_BLANK">Ver Rol</a>&nbsp;<b>[OK]</b>'; } else { echo '<b>[FALLO]</b>'; } echo '</tr>'; echo '<tr><td colspan="2"><b>Carrera: </b>'; if (!empty($results['CARRERA'])) { echo $results['CARRERA']->label; echo '</td><td align="right">'; echo '<a href="' . $this->url(array('career' => $results['CARRERA']->url), 'careers_career_view') . '" target="_BLANK">Ver Carrera</a>&nbsp;<b>[OK]</b>'; } else { echo $this->none(); echo '</td><td align="right">'; //<?php echo $this->none($results['CARRERA']) } echo '</td></tr>'; echo '<tr><td width="30%">'; echo '<b>Usuario: </b>' . $results['USUARIO'] . '</td><td>'; echo '<b>Correo electrónico: </b>' . $this->none($results['CORREO ELECTRONICO']) . '</td><td>&nbsp;</td></tr><tr><td width="30%">'; echo '<b>Apellidos: </b>' . $this->none($results['APELLIDOS']) . '</td><td>'; echo '<b>Nombres: </b>' . $this->none($results['NOMBRES']) . '</td><td>&nbsp;</td></tr>'; } echo '</table><hr />'; echo '<a href="' . $this->url(array(), 'users_import') . '">Subir nuevamente</a> '; echo '<input type="submit" value="Importar usuarios" /></form>'; }
ccaballero/yachay
apps/users/views/scripts/manager/import.php
PHP
gpl-3.0
4,890
// $Id: CrInvalidBranch.java 15512 2008-08-05 17:33:53Z maurelio1234 $ // Copyright (c) 1996-2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.cognitive.critics; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.argouml.cognitive.Designer; import org.argouml.model.Model; import org.argouml.uml.cognitive.UMLDecision; /** * A critic to detect when a Branch (i.e. Choice or Junction) * state has the wrong number of transitions. * Implements constraint [5] and [6] on PseudoState in the UML * Semantics v1.3, p. 2-140: * * [5] A junction vertex must have at least one incoming and * one outgoing transition. * (self.kind = #junction) implies * ((self.incoming->size >= 1) and (self.outgoing->size >= 1)) * * [6] A choice vertex must have at least one incoming and * one outgoing transition. * (self.kind = #choice) implies * ((self.incoming->size >= 1) and (self.outgoing->size >= 1)) * * Well-formedness rule [7] and [8] for PseudoState. See page 138 of UML 1.4 * Semantics. OMG document UML 1.4.2 formal/04-07-02. * * @author jrobbins */ public class CrInvalidBranch extends CrUML { /** * The constructor. */ public CrInvalidBranch() { setupHeadAndDesc(); addSupportedDecision(UMLDecision.STATE_MACHINES); addTrigger("incoming"); } /* * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(java.lang.Object, org.argouml.cognitive.Designer) */ public boolean predicate2(Object dm, Designer dsgr) { if (!(Model.getFacade().isAPseudostate(dm))) { return NO_PROBLEM; } Object k = Model.getFacade().getKind(dm); if ((!Model.getFacade().equalsPseudostateKind(k, Model.getPseudostateKind().getChoice())) && (!Model.getFacade().equalsPseudostateKind(k, Model.getPseudostateKind().getJunction()))) { return NO_PROBLEM; } Collection outgoing = Model.getFacade().getOutgoings(dm); Collection incoming = Model.getFacade().getIncomings(dm); int nOutgoing = outgoing == null ? 0 : outgoing.size(); int nIncoming = incoming == null ? 0 : incoming.size(); if (nIncoming < 1) { return PROBLEM_FOUND; } if (nOutgoing < 1) { return PROBLEM_FOUND; } return NO_PROBLEM; } /* * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials() */ public Set<Object> getCriticizedDesignMaterials() { Set<Object> ret = new HashSet<Object>(); ret.add(Model.getMetaTypes().getPseudostate()); return ret; } }
ckaestne/LEADT
workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/cognitive/critics/CrInvalidBranch.java
Java
gpl-3.0
4,138
using UnityEngine; // Class that handles touches on the interface // Referenced in ParentGUI public class PlayerGUI : ParentGUI { Rect joyRect; PlayerController controller; PlayerActions actions; Player plr; float scale = 1; int w = 1; int h = 1; int bw = 1; int bh = 1; GUITexture invButton; GUITexture healthPot; GUITexture manaPot; GUITexture aButton; GUITexture bButton; GUITexture joyPad; TextMesh healthText; TextMesh manaText; void Awake(){ this.isShowing = true; controller = (PlayerController)GetComponent("PlayerController"); actions = (PlayerActions)GetComponent("PlayerActions"); plr = (Player)GetComponent<Player>(); scale = Screen.dpi / 160; if (scale == 0) scale = 1; w = Screen.width; h = Screen.height; bw = (int)(64 * scale); bh = (int)(64 * scale); invButton = GameObject.Find("GUIComponents/ButtonBackpack").guiTexture; healthPot = GameObject.Find("GUIComponents/ButtonHealth").guiTexture; manaPot = GameObject.Find("GUIComponents/ButtonMana").guiTexture; aButton = GameObject.Find("GUIComponents/ButtonA").guiTexture; bButton = GameObject.Find("GUIComponents/ButtonB").guiTexture; joyPad = GameObject.Find("GUIComponents/JoyPad").guiTexture; healthText = GameObject.Find("Player/HealthText").GetComponent<TextMesh>(); manaText = GameObject.Find("Player/ManaText").GetComponent<TextMesh>(); InitGUI(); joyRect = joyPad.pixelInset; } void Start(){} void Update(){} public override void InitGUI(){ PositionButtons(); RefreshBars(); } public void RefreshBars(){ healthText.text = "" + actions.health + " / " + actions.maxHealth; manaText.text = "" + actions.mana + " / " + actions.maxMana; } void PositionButtons(){ int hw = bw / 2; int hh = bh / 2; Rect temp = new Rect((int)(w * 0.1f) - hw, (int)(h * 0.7f) - hh, bw, bh); invButton.pixelInset = temp; temp = new Rect((int)(w * 0.05f), (int)(w * 0.05f), (int)(w * 0.1f) + bw, (int)(w * 0.1f) + bh); joyPad.pixelInset = temp; temp = new Rect((int)(w * 0.8f) - hw, (int)(h * 0.85f) - hh, bw, bh); manaPot.pixelInset = temp; temp = new Rect((int)(w * 0.9f) - hw, (int)(h * 0.72f) - hh, bw, bh); healthPot.pixelInset = temp; temp = new Rect((int)(w * 0.8f) - hw, (int)(h * 0.15f) - hh, bw, bh); aButton.pixelInset = temp; temp = new Rect((int)(w * 0.9f) - hw, (int)(h * 0.28f) - hh, bw, bh); bButton.pixelInset = temp; } public override void HandleTouch(Touch t){ Vector2 pos = t.position; if (t.fingerId == controller.GetJoyFinger() || joyRect.Contains(pos)){ controller.HandleTouch(t); } else { if (t.phase == TouchPhase.Began){ TouchBegin(t); } } } public override void TouchBegin(Touch t){ Vector2 pos = t.position; if (invButton.pixelInset.Contains(pos)){ // INVENTORY BUTTON } if (healthPot.pixelInset.Contains(pos)){ // HEALTH POT } if (manaPot.pixelInset.Contains(pos)){ // MANA POT } if (aButton.pixelInset.Contains(pos)){ if (actions.ApplyManaSilent(plr.manaCostA)){ actions.PerformRanged(controller.mDirection); } } if (bButton.pixelInset.Contains(pos)){ // BUTTON B } } public override void TouchMove(Touch t){ // STUB } public override void TouchEnd(Touch t){ // STUB } public override void TouchStationary(Touch t){ // STUB } }
NormantasKudzma/RoomFighter
Assets/Scripts/PlayerGUI.cs
C#
gpl-3.0
3,331
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "lua_api/l_noise.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "log.h" #include "porting.h" #include "util/numeric.h" /////////////////////////////////////// /* LuaPerlinNoise */ LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : np(*params) { } int LuaPerlinNoise::l_get_2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoise *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); lua_Number val = NoisePerlin2D(&o->np, p.X, p.Y, 0); lua_pushnumber(L, val); return 1; } int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoise *o = checkobject(L, 1); v3f p = check_v3f(L, 2); lua_Number val = NoisePerlin3D(&o->np, p.X, p.Y, p.Z, 0); lua_pushnumber(L, val); return 1; } int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; NoiseParams params; if (lua_istable(L, 1)) { read_noiseparams(L, 1, &params); } else { params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam<float>(L, 3); params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); } LuaPerlinNoise *o = new LuaPerlinNoise(&params); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); return *(LuaPerlinNoise **)ud; } void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaPerlinNoise::className[] = "PerlinNoise"; luaL_Reg LuaPerlinNoise::methods[] = { luamethod_aliased(LuaPerlinNoise, get_2d, get2d), luamethod_aliased(LuaPerlinNoise, get_3d, get3d), {0,0} }; /////////////////////////////////////// /* LuaPerlinNoiseMap */ LuaPerlinNoiseMap::LuaPerlinNoiseMap(NoiseParams *params, s32 seed, v3s16 size) { m_is3d = size.Z > 1; np = *params; try { noise = new Noise(&np, seed, size.X, size.Y, size.Z); } catch (InvalidNoiseParamsException &e) { throw LuaError(e.what()); } } LuaPerlinNoiseMap::~LuaPerlinNoiseMap() { delete noise; } int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t i = 0; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); lua_createtable(L, n->sy, 0); for (u32 y = 0; y != n->sy; y++) { lua_createtable(L, n->sx, 0); for (u32 x = 0; x != n->sx; x++) { lua_pushnumber(L, n->result[i++]); lua_rawseti(L, -2, x + 1); } lua_rawseti(L, -2, y + 1); } return 1; } int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); bool use_buffer = lua_istable(L, 3); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); size_t maplen = n->sx * n->sy; if (use_buffer) lua_pushvalue(L, 3); else lua_createtable(L, maplen, 0); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, n->result[i]); lua_rawseti(L, -2, i + 1); } return 1; } int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t i = 0; LuaPerlinNoiseMap *o = checkobject(L, 1); v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); lua_createtable(L, n->sz, 0); for (u32 z = 0; z != n->sz; z++) { lua_createtable(L, n->sy, 0); for (u32 y = 0; y != n->sy; y++) { lua_createtable(L, n->sx, 0); for (u32 x = 0; x != n->sx; x++) { lua_pushnumber(L, n->result[i++]); lua_rawseti(L, -2, x + 1); } lua_rawseti(L, -2, y + 1); } lua_rawseti(L, -2, z + 1); } return 1; } int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v3f p = check_v3f(L, 2); bool use_buffer = lua_istable(L, 3); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); size_t maplen = n->sx * n->sy * n->sz; if (use_buffer) lua_pushvalue(L, 3); else lua_createtable(L, maplen, 0); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, n->result[i]); lua_rawseti(L, -2, i + 1); } return 1; } int LuaPerlinNoiseMap::l_calc_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); return 0; } int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); return 0; } int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v3s16 slice_offset = read_v3s16(L, 2); v3s16 slice_size = read_v3s16(L, 3); bool use_buffer = lua_istable(L, 4); Noise *n = o->noise; if (use_buffer) lua_pushvalue(L, 4); else lua_newtable(L); write_array_slice_float(L, lua_gettop(L), n->result, v3u16(n->sx, n->sy, n->sz), v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), v3u16(slice_size.X, slice_size.Y, slice_size.Z)); return 1; } int LuaPerlinNoiseMap::create_object(lua_State *L) { NoiseParams np; if (!read_noiseparams(L, 1, &np)) return 0; v3s16 size = read_v3s16(L, 2); LuaPerlinNoiseMap *o = new LuaPerlinNoiseMap(&np, 0, size); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); return *(LuaPerlinNoiseMap **)ud; } void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap"; luaL_Reg LuaPerlinNoiseMap::methods[] = { luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), {0,0} }; /////////////////////////////////////// /* LuaPseudoRandom */ int LuaPseudoRandom::l_next(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPseudoRandom *o = checkobject(L, 1); int min = 0; int max = 32767; lua_settop(L, 3); if (lua_isnumber(L, 2)) min = luaL_checkinteger(L, 2); if (lua_isnumber(L, 3)) max = luaL_checkinteger(L, 3); if (max < min) { errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl; throw LuaError("PseudoRandom.next(): max < min"); } if(max - min != 32767 && max - min > 32767/5) throw LuaError("PseudoRandom.next() max-min is not 32767" " and is > 32768/5. This is disallowed due to" " the bad random distribution the" " implementation would otherwise make."); PseudoRandom &pseudo = o->m_pseudo; int val = pseudo.next(); val = (val % (max-min+1)) + min; lua_pushinteger(L, val); return 1; } int LuaPseudoRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); LuaPseudoRandom *o = new LuaPseudoRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); return *(LuaPseudoRandom **)ud; } void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaPseudoRandom::className[] = "PseudoRandom"; const luaL_Reg LuaPseudoRandom::methods[] = { luamethod(LuaPseudoRandom, next), {0,0} }; /////////////////////////////////////// /* LuaPcgRandom */ int LuaPcgRandom::l_next(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPcgRandom *o = checkobject(L, 1); u32 min = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : o->m_rnd.RANDOM_MIN; u32 max = lua_isnumber(L, 3) ? lua_tointeger(L, 3) : o->m_rnd.RANDOM_MAX; lua_pushinteger(L, o->m_rnd.range(min, max)); return 1; } int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPcgRandom *o = checkobject(L, 1); u32 min = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : o->m_rnd.RANDOM_MIN; u32 max = lua_isnumber(L, 3) ? lua_tointeger(L, 3) : o->m_rnd.RANDOM_MAX; int num_trials = lua_isnumber(L, 4) ? lua_tointeger(L, 4) : 6; lua_pushinteger(L, o->m_rnd.randNormalDist(min, max, num_trials)); return 1; } int LuaPcgRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); LuaPcgRandom *o = lua_isnumber(L, 2) ? new LuaPcgRandom(seed, lua_tointeger(L, 2)) : new LuaPcgRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPcgRandom::gc_object(lua_State *L) { LuaPcgRandom *o = *(LuaPcgRandom **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); return *(LuaPcgRandom **)ud; } void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaPcgRandom::className[] = "PcgRandom"; const luaL_Reg LuaPcgRandom::methods[] = { luamethod(LuaPcgRandom, next), luamethod(LuaPcgRandom, rand_normal_dist), {0,0} }; /////////////////////////////////////// /* LuaSecureRandom */ bool LuaSecureRandom::fillRandBuf() { return porting::secure_rand_fill_buf(m_rand_buf, RAND_BUF_SIZE); } int LuaSecureRandom::l_next_bytes(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaSecureRandom *o = checkobject(L, 1); u32 count = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : 1; // Limit count count = MYMIN(RAND_BUF_SIZE, count); // Find out whether we can pass directly from our array, or have to do some gluing size_t count_remaining = RAND_BUF_SIZE - o->m_rand_idx; if (count_remaining >= count) { lua_pushlstring(L, o->m_rand_buf + o->m_rand_idx, count); o->m_rand_idx += count; } else { char output_buf[RAND_BUF_SIZE]; // Copy over with what we have left from our current buffer memcpy(output_buf, o->m_rand_buf + o->m_rand_idx, count_remaining); // Refill buffer and copy over the remainder of what was requested o->fillRandBuf(); memcpy(output_buf + count_remaining, o->m_rand_buf, count - count_remaining); // Update index o->m_rand_idx = count - count_remaining; lua_pushlstring(L, output_buf, count); } return 1; } int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); // Fail and return nil if we can't securely fill the buffer if (!o->fillRandBuf()) { delete o; return 0; } *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); delete o; return 0; } LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); return *(LuaSecureRandom **)ud; } void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaSecureRandom::className[] = "SecureRandom"; const luaL_Reg LuaSecureRandom::methods[] = { luamethod(LuaSecureRandom, next_bytes), {0,0} };
MrCerealGuy/Stonecraft
src/script/lua_api/l_noise.cpp
C++
gpl-3.0
15,781
<?php /** * @package HikaShop for Joomla! * @version 2.5.0 * @author hikashop.com * @copyright (C) 2010-2015 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php class BadgeViewBadge extends hikashopView { var $ctrl= 'badge'; var $nameListing = 'HIKA_BADGES'; var $nameForm = 'HIKA_BADGES'; var $icon = 'badge'; function display($tpl = null){ $this->paramBase = HIKASHOP_COMPONENT.'.'.$this->getName(); $function = $this->getLayout(); if(method_exists($this,$function)) $this->$function(); parent::display($tpl); } function listing(){ $app = JFactory::getApplication(); $pageInfo = new stdClass(); $pageInfo->filter = new stdClass(); $pageInfo->filter->order = new stdClass(); $pageInfo->limit = new stdClass(); $pageInfo->search = $app->getUserStateFromRequest( $this->paramBase.".search", 'search', '', 'string' ); $pageInfo->filter->order->value = $app->getUserStateFromRequest( $this->paramBase.".filter_order", 'filter_order', 'a.badge_id','cmd' ); $pageInfo->filter->order->dir = $app->getUserStateFromRequest( $this->paramBase.".filter_order_Dir", 'filter_order_Dir', 'desc', 'word' ); $pageInfo->limit->value = $app->getUserStateFromRequest( $this->paramBase.'.list_limit', 'limit', $app->getCfg('list_limit'), 'int' ); $pageInfo->limit->start = $app->getUserStateFromRequest( $this->paramBase.'.limitstart', 'limitstart', 0, 'int' ); if(JRequest::getVar('search')!=$app->getUserState($this->paramBase.".search")){ $app->setUserState( $this->paramBase.'.limitstart',0); $pageInfo->limit->start = 0; }else{ $pageInfo->limit->start = $app->getUserStateFromRequest( $this->paramBase.'.limitstart', 'limitstart', 0, 'int' ); } $database = JFactory::getDBO(); $filters = array(); $searchMap = array('a.badge_id','a.badge_name','a.badge_position'); if(!empty($pageInfo->search)){ $searchVal = '\'%'.hikashop_getEscaped(JString::strtolower(trim($pageInfo->search)),true).'%\''; $filters[] = implode(" LIKE $searchVal OR ",$searchMap)." LIKE $searchVal"; } $order = ''; if(!empty($pageInfo->filter->order->value)){ $order = ' ORDER BY '.$pageInfo->filter->order->value.' '.$pageInfo->filter->order->dir; } if(!empty($filters)){ $filters = ' WHERE ('. implode(') AND (',$filters).')'; }else{ $filters = ''; } $query = ' FROM '.hikashop_table('badge').' AS a'.$filters.$order; $database->setQuery('SELECT a.*'.$query,$pageInfo->limit->start,$pageInfo->limit->value); $rows = $database->loadObjectList(); if(!empty($pageInfo->search)){ $rows = hikashop_search($pageInfo->search,$rows,'badge_id'); } $database->setQuery('SELECT count(*)'.$query ); $pageInfo->elements = new stdClass(); $pageInfo->elements->total = $database->loadResult(); $pageInfo->elements->page = count($rows); if($pageInfo->elements->page){ $types = array('product','category','discount'); foreach($types as $type){ $ids = array(); $key = 'badge_'.$type.'_id'; foreach($rows as $row){ if(empty($row->$key)) continue; $row->$key = explode(',',$row->$key); foreach($row->$key as $v){ if(is_numeric($v)){ $ids[$v]=$v; }else{ $ids[$v]=$database->Quote($v); } } } if(!count($ids)){ continue; } $primary = $type.'_id'; if($type=='discount'){ $name = $type.'_code'; }else{ $name = $type.'_name'; } $query = 'SELECT * FROM '.hikashop_table($type).' WHERE '.$primary.' IN ('.implode(',',$ids).')'; $database->setQuery($query); $elements = $database->loadObjectList(); foreach($rows as $k => $row){ if(empty($row->$key)){ continue; } $display = array(); foreach($row->$key as $el){ foreach($elements as $element){ if($element->$primary==$el){ $display[] = $element->$name; $found = true; break; } } } if(!count($display)){ $display = array(JText::_(strtoupper($type).'_NOT_FOUND')); } $rows[$k]->$key = implode(', ',$display); } } } $toggleClass = hikashop_get('helper.toggle'); $this->assignRef('toggleClass',$toggleClass); $image=hikashop_get('helper.image'); $this->assignRef('image',$image); $this->assignRef('rows',$rows); $this->assignRef('pageInfo',$pageInfo); $order = new stdClass(); $order->ordering = true; $order->orderUp = 'orderup'; $order->orderDown = 'orderdown'; $order->reverse = false; if($pageInfo->filter->order->value == 'a.badge_ordering'){ if($pageInfo->filter->order->dir == 'desc'){ $order->orderUp = 'orderdown'; $order->orderDown = 'orderup'; $order->reverse = true; } } $this->assignRef('order',$order); hikashop_setTitle(JText::_($this->nameListing),$this->icon,$this->ctrl); $this->getPagination(); $config =& hikashop_config(); $manage = hikashop_isAllowed($config->get('acl_badge_manage','all')); $this->assignRef('manage',$manage); $this->toolbar = array( array('name' => 'addNew', 'display' => $manage), array('name' => 'editList', 'display' => $manage), array('name' => 'deleteList', 'check' => JText::_('HIKA_VALIDDELETEITEMS'), 'display' => hikashop_isAllowed($config->get('acl_badge_delete','all'))), '|', array('name' => 'pophelp', 'target' => $this->ctrl.'-listing'), 'dashboard' ); } function form(){ $badge_id = hikashop_getCID('badge_id'); $class = hikashop_get('class.badge'); if(!empty($badge_id)){ $element = $class->get($badge_id,true); $task='edit'; }else{ $element = new stdClass(); $element->banner_published = 1; $task='add'; } $database = JFactory::getDBO(); if(!empty($element->badge_discount_id)){ $query = 'SELECT * FROM '.hikashop_table('discount').' WHERE discount_id = '.(int)$element->badge_discount_id; $database->setQuery($query); $discount = $database->loadObject(); if(!empty($discount)){ foreach(get_object_vars($discount) as $key => $val){ $element->$key = $val; } } } if(empty($element->discount_code)){ $element->discount_code = JText::_('DISCOUNT_NOT_FOUND'); } if(!empty($element->badge_category_id)){ $query = 'SELECT * FROM '.hikashop_table('category').' WHERE category_id = '.(int)$element->badge_category_id; $database->setQuery($query); $category = $database->loadObject(); if(!empty($category)){ foreach(get_object_vars($category) as $key => $val){ $element->$key = $val; } } } if(empty($element->category_name)){ $element->category_name = JText::_('CATEGORY_NOT_FOUND'); } hikashop_setTitle(JText::_($this->nameForm),$this->icon,$this->ctrl.'&task='.$task.'&badge_id='.$badge_id); $this->toolbar = array( 'save', array('name' => 'save2new', 'display' => version_compare(JVERSION,'1.7','>=')), 'apply', 'cancel', '|', array('name' => 'pophelp', 'target' => $this->ctrl.'-listing') ); $js = " function hikashopSizeUpdate(keep_size){ if(keep_size>0){ displayStatus ='none'; }else{ displayStatus = ''; } var el = document.getElementById('field_size'); if(el){ el.style.display=displayStatus; } } window.hikashop.ready( function(){ hikashopSizeUpdate(".(int)@$element->badge_keep_size."); }); "; $document= JFactory::getDocument(); $document->addScriptDeclaration($js); $this->assignRef('element',$element); $translation = false; $transHelper = hikashop_get('helper.translation'); if($transHelper && $transHelper->isMulti()){ $translation = true; $transHelper->load('hikashop_badge',@$element->badge_id,$element); jimport('joomla.html.pane'); $config =& hikashop_config(); $multilang_display=$config->get('multilang_display','tabs'); if($multilang_display=='popups') $multilang_display = 'tabs'; $tabs = hikashop_get('helper.tabs'); $this->assignRef('tabs',$tabs); $this->assignRef('transHelper',$transHelper); } $toggle=hikashop_get('helper.toggle'); $this->assignRef('toggle',$toggle); $image=hikashop_get('helper.image'); $this->assignRef('image',$image); $badge=hikashop_get('type.badge'); $this->assignRef('badge',$badge); $this->assignRef('translation',$translation); $popup = hikashop_get('helper.popup'); $this->assignRef('popup', $popup); $nameboxType = hikashop_get('type.namebox'); $this->assignRef('nameboxType', $nameboxType); } }
vaibhav1607/com_hikashop_starter_v2.5.0_2015-08-06_18-17-26
back/views/badge/view.html.php
PHP
gpl-3.0
8,453
import os import shutil import pytest import __builtin__ from libturpial.config import * from libturpial.exceptions import EmptyOAuthCredentials from tests.helpers import DummyFileHandler class DummyConfigParser: def read(self, value): pass def sections(self): return [] def options(self): return [] def add_section(self, value): pass def set(self, x, y, z): pass def write(self, value): pass def has_section(self, value): return True class DummyGenerator: def __init__(self, array): self.array = array def __iter__(self): return iter(self.array) class TestConfigBase: @classmethod @pytest.fixture(autouse=True) def setup_class(self, monkeypatch): self.default = { 'foo': { 'bar': 987, }, 'bla': { 'ble': 'on', 'bli': 'off', } } self.config_base = ConfigBase(self.default) monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler()) monkeypatch.setattr(self.config_base.cfg, 'add_section', lambda x: None) monkeypatch.setattr(self.config_base.cfg, 'set', lambda x, y, z: None) monkeypatch.setattr(self.config_base.cfg, 'write', lambda x: None) self.config_base.configpath = '/tmp/foo' def test_default_values(self): assert 'General' in APP_CFG assert 'update-interval' in APP_CFG['General'] assert 'queue-interval' in APP_CFG['General'] assert 'minimize-on-close' in APP_CFG['General'] assert 'statuses' in APP_CFG['General'] assert 'Columns' in APP_CFG assert 'Services' in APP_CFG assert 'shorten-url' in APP_CFG['Services'] assert 'upload-pic' in APP_CFG['Services'] assert 'Proxy' in APP_CFG assert 'username' in APP_CFG['Proxy'] assert 'password' in APP_CFG['Proxy'] assert 'server' in APP_CFG['Proxy'] assert 'port' in APP_CFG['Proxy'] assert 'protocol' in APP_CFG['Proxy'] assert 'Advanced' in APP_CFG assert 'socket-timeout' in APP_CFG['Advanced'] assert 'show-user-avatars' in APP_CFG['Advanced'] assert 'Window' in APP_CFG assert 'size' in APP_CFG['Window'] assert 'Notifications' in APP_CFG assert 'on-updates' in APP_CFG['Notifications'] assert 'on-actions' in APP_CFG['Notifications'] assert 'Sounds' in APP_CFG assert 'on-login' in APP_CFG['Sounds'] assert 'on-updates' in APP_CFG['Sounds'] assert 'Browser' in APP_CFG assert 'cmd' in APP_CFG['Browser'] assert 'OAuth' in ACCOUNT_CFG assert 'key' in ACCOUNT_CFG['OAuth'] assert 'secret' in ACCOUNT_CFG['OAuth'] assert 'Login' in ACCOUNT_CFG assert 'username' in ACCOUNT_CFG['Login'] assert 'protocol' in ACCOUNT_CFG['Login'] def test_init_config_base(self): config_base = ConfigBase(self.default) assert config_base.filepath == '' assert config_base.extra_sections == {} assert 'foo' in config_base.default config_base = ConfigBase(None) assert 'Advanced' in config_base.default def test_register_extra_option(self, monkeypatch): monkeypatch.setattr(self.config_base, 'write', lambda x, y, z: None) self.config_base.register_extra_option('foo', 'baz', 000) assert 'baz' in self.config_base.extra_sections['foo'] assert self.config_base.extra_sections['foo']['baz'] == 000 def test_create(self, monkeypatch): self.config_base.create() assert self.config_base._ConfigBase__config['foo']['bar'] == 987 def test_load(self, monkeypatch): default = { 'foo': { 'bar': 987, }, 'bla': { 'ble': 'on', 'bli': 'off', }, 'dummy': {}, } monkeypatch.setattr(self.config_base.cfg, 'read', lambda x: None) monkeypatch.setattr(self.config_base, 'default', default) monkeypatch.setattr(self.config_base, 'save', lambda: None) # TODO: How to test this? assert self.config_base.load() == None def test_load_failsafe(self): config_base = ConfigBase(self.default) config_base.load_failsafe() assert config_base._ConfigBase__config == self.default def test_save(self, monkeypatch): self.config_base.save({'foo2': {'bar2': 2}}) assert self.config_base._ConfigBase__config['foo2']['bar2'] == 2 def test_write(self, monkeypatch): monkeypatch.setattr(self.config_base.cfg, 'has_section', lambda x: False) self.config_base.write('foo', 'qux', -1) assert self.config_base._ConfigBase__config['foo']['qux'] == -1 monkeypatch.setattr(self.config_base.cfg, 'has_section', lambda x: True) self.config_base.write('foo', 'qux', 99) assert self.config_base._ConfigBase__config['foo']['qux'] == 99 def test_write_section(self, monkeypatch): monkeypatch.setattr(self.config_base.cfg, 'remove_section', lambda x: None) monkeypatch.setattr(self.config_base.cfg, 'has_section', lambda x: False) self.config_base.write_section('foo', {'ble': 2}) assert len(self.config_base._ConfigBase__config['foo']) == 1 assert self.config_base._ConfigBase__config['foo']['ble'] == 2 monkeypatch.setattr(self.config_base.cfg, 'has_section', lambda x: True) self.config_base.write_section('foo', {'ble': 2}) assert len(self.config_base._ConfigBase__config['foo']) == 1 assert self.config_base._ConfigBase__config['foo']['ble'] == 2 def test_read(self): self.config_base.create() value = self.config_base.read('foo', 'bar') assert value == 987 value = self.config_base.read('bla', 'ble', True) assert value == True value = self.config_base.read('bla', 'bli', False) assert value == 'off' value = self.config_base.read('bla', 'bli', True) assert value == False value = self.config_base.read('dummy', 'var') assert value == None value = self.config_base.read('foo', 'bar', True) assert value == 987 def test_read_section(self): self.config_base.create() section = self.config_base.read_section('foo') assert section == self.default['foo'] section = self.config_base.read_section('faa') assert section is None def test_read_all(self, monkeypatch): self.config_base.create() assert self.config_base.read_all() == self.default monkeypatch.delattr(self.config_base, '_ConfigBase__config') assert self.config_base.read_all() == None class TestAppConfig: @classmethod @pytest.fixture(autouse=True) def setup_class(self, monkeypatch): self.default = { 'foo': { 'bar': 987, }, 'bla': { 'ble': 'on', 'bli': 'off', } } monkeypatch.setattr(os, 'makedirs', lambda x: None) monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler()) monkeypatch.setattr(ConfigParser, 'ConfigParser', lambda: DummyConfigParser()) self.app_config = AppConfig('/tmp/user', self.default) def test_init(self): assert self.app_config.configpath == '/tmp/user/config' assert self.app_config.filterpath == '/tmp/user/filtered' assert self.app_config.friendspath == '/tmp/user/friends' def test_load_filters(self, monkeypatch): monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler(['@foo', 'bar', "\n"])) filters = self.app_config.load_filters() assert filters[0] == '@foo' assert len(filters) == 2 # TODO: How to test that this works? Return 0 maybe? def test_save_filters(self): assert self.app_config.save_filters(['foo', 'bar']) == ['foo', 'bar'] # TODO: How to test that this works? Return 0 maybe? def test_append_filter(self, monkeypatch): assert self.app_config.append_filter('@dummy') == None monkeypatch.setattr(self.app_config, 'load_filters', lambda: ['@dummy']) with pytest.raises(ExpressionAlreadyFiltered): self.app_config.append_filter('@dummy') # TODO: How to test that this works? Return 0 maybe? def test_remove_filter(self, monkeypatch): monkeypatch.setattr(self.app_config, 'load_filters', lambda: ['@foo', 'bar', '@dummy']) monkeypatch.setattr(self.app_config, 'save_filters', lambda x: None) assert self.app_config.remove_filter('bar') == None def test_load_friends(self, monkeypatch): monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler(['foo', 'bar\n', "\n"])) friends = self.app_config.load_friends() assert friends == ['foo', 'bar'] # TODO: How to test that this works? Return 0 maybe? def test_save_friends(self): assert self.app_config.save_friends(['foo', 'bar']) == ['foo', 'bar'] def test_get_stored_accounts(self, monkeypatch): monkeypatch.setattr(os, 'walk', lambda x: DummyGenerator([('foopath', ['dirpath1', 'dirpath2'], ['filename1'])])) monkeypatch.setattr(os.path, 'isfile', lambda x: True) accounts = self.app_config.get_stored_accounts() assert accounts == ['dirpath1', 'dirpath2'] def test_get_stored_columns(self, monkeypatch): temp = {'column3': 'foo-twitter-timeline', 'column1': 'foo-twitter-directs', 'column2': 'foo-twitter-sent'} monkeypatch.setattr(self.app_config, 'read_section', lambda x: temp) columns = self.app_config.get_stored_columns() assert columns[0] == 'foo-twitter-directs' assert columns[1] == 'foo-twitter-sent' assert columns[2] == 'foo-twitter-timeline' temp = {'column1': '', 'column2': ''} monkeypatch.setattr(self.app_config, 'read_section', lambda x: temp) columns = self.app_config.get_stored_columns() assert len(columns) == 0 def test_get_proxy(self, monkeypatch): proxy_temp = {'server': '127.0.0.1', 'port': 80, 'protocol': 'http', 'username': '', 'password': ''} monkeypatch.setattr(self.app_config, 'read_section', lambda x: proxy_temp) proxy = self.app_config.get_proxy() assert proxy.secure == False assert proxy.host == '127.0.0.1' assert proxy.port == 80 assert proxy.username == '' assert proxy.password == '' proxy_temp['protocol'] = 'https' proxy = self.app_config.get_proxy() assert proxy.secure == True def test_get_socket_timeout(self, monkeypatch): monkeypatch.setattr(self.app_config, 'read', lambda x, y: 9999) assert self.app_config.get_socket_timeout() == 9999 # TODO: How to test that this works? Return 0 maybe? def test_delete(self, monkeypatch): monkeypatch.setattr(os, 'remove', lambda x: None) assert self.app_config.delete() == True class TestAccountConfig: @classmethod @pytest.fixture(autouse=True) def setup_class(self, monkeypatch): monkeypatch.setattr(os, 'makedirs', lambda x: None) monkeypatch.setattr(os.path, 'isdir', lambda x: False) monkeypatch.setattr(os, 'remove', lambda x: None) monkeypatch.setattr(__builtin__, 'open', lambda x, y: DummyFileHandler()) monkeypatch.setattr('libturpial.config.AccountConfig.write', lambda w, x, y, z: None) monkeypatch.setattr('libturpial.config.AccountConfig.exists', lambda x, y: False) monkeypatch.setattr('libturpial.config.AccountConfig.create', lambda x: None) self.account_config = AccountConfig('foo-twitter') def test_init(self, monkeypatch): assert isinstance(self.account_config, AccountConfig) def test_save_oauth_credentials(self, monkeypatch): monkeypatch.setattr(self.account_config, 'write', lambda x, y, z: None) assert self.account_config.save_oauth_credentials('123', '456', '789') == None def test_load_oauth_credentials(self, monkeypatch): monkeypatch.setattr(self.account_config, 'read', lambda x, y: 'dummy') key, secret = self.account_config.load_oauth_credentials() assert (key == 'dummy' and secret == 'dummy') monkeypatch.setattr(self.account_config, 'read', lambda x, y: None) with pytest.raises(EmptyOAuthCredentials): self.account_config.load_oauth_credentials() def test_forget_oauth_credentials(self, monkeypatch): monkeypatch.setattr(self.account_config, 'write', lambda x, y, z: None) assert self.account_config.forget_oauth_credentials() == None def test_transform(self): assert self.account_config.transform('123', 'foo') == 'm1TP9YzVa10RTpVTDRlWZ10b' def test_revert(self): assert self.account_config.revert('m1TP9YzVa10RTpVTDRlWZ10b', 'foo') == '123' assert self.account_config.revert('', 'foo') == None def test_dismiss(self, monkeypatch): monkeypatch.setattr(os.path, 'isdir', lambda x: True) monkeypatch.setattr(os.path, 'isfile', lambda x: True) monkeypatch.setattr(shutil, 'rmtree', lambda x: None) # TODO: How to test this? assert self.account_config.dismiss() == None def test_delete_cache(self, monkeypatch): monkeypatch.setattr(os, 'walk', lambda x: [('/tmp', ['my_dir'], ['file1', 'file2'])]) # TODO: How to test this? assert self.account_config.delete_cache() == list() def test_calculate_cache_size(self, monkeypatch): monkeypatch.setattr(os, 'walk', lambda x: [('/tmp', ['my_dir'], ['file1', 'file2'])]) monkeypatch.setattr(os.path, 'getsize', lambda x: 10) assert self.account_config.calculate_cache_size() == 20
satanas/libturpial
tests/test_config.py
Python
gpl-3.0
14,032
# encoding: utf-8 # # Statistical Analysis of Polling Results (SAPoR) # Copyright (C) 2020 Filip van Laenen <f.a.vanlaenen@ieee.org> # # This file is part of SAPoR. # # SAPoR 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. # # SAPoR 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 can find a copy of the GNU General Public License in /doc/gpl.txt # module Sapor # # Class representing an electoral system based on the First-Past-The-Post # system. # class FirstPastThePost def initialize(last_election_result, last_detailed_election_result) @last_election_result = last_election_result @last_detailed_election_result = last_detailed_election_result end def project(simulation) multiplicators = calculate_multiplicators(simulation) result = create_empty_result(simulation) @last_detailed_election_result.each_value do |local_last_result| winner = local_winner(local_last_result, multiplicators) if result.key?(winner) result[winner] += 1 else result[winner] = 1 end end result end private def calculate_multiplicators(simulation) simulation_sum = simulation.values.inject(:+) last_election_sum = @last_election_result.values.inject(:+) multiplicators = {} simulation.each_key do |choice| new_fraction = simulation[choice].to_f / simulation_sum last_fraction = @last_election_result[choice].to_f / last_election_sum multiplicators[choice] = new_fraction / last_fraction end multiplicators end def create_empty_result(simulation) result = {} simulation.each_key do |choice| result[choice] = 0 end result[OTHER] = 0 result end def local_winner(local_last_result, multiplicators) new_local_result = {} local_last_result.each_pair do |choice, votes| if multiplicators.key?(choice) new_local_result[choice] = votes * multiplicators[choice] else new_local_result[choice] = votes end end max_votes = new_local_result.values.max winner = new_local_result.select { |_k, v| v.equal?(max_votes) }.keys.first multiplicators.key?(winner) ? winner : OTHER end end end
filipvanlaenen/sapor
lib/sapor/first_past_the_post.rb
Ruby
gpl-3.0
2,656
from django import forms from .models import Client, Contact class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('first_name', 'last_name', 'city', 'email', 'phone_number', 'comment', ) class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('way', 'date', 'comment')
rklimcza/not-yet-crm
crm/forms.py
Python
gpl-3.0
407
using Quantum.Math; namespace Quantum.Emulate { public class PhaseZGate : Gate { #region Constructors public PhaseZGate(double theta) : base(GetPhaseShift(theta)) { } #endregion #region Private Methods private static ComplexMatrix GetPhaseShift(double theta) { return new ComplexMatrix(new Complex[][] { new Complex[] { new Complex(-System.Math.Cos(theta / 2), -System.Math.Sin(theta / 2)), new Complex(0, 0) }, new Complex[] { new Complex(0, 0), new Complex(System.Math.Cos(theta / 2), System.Math.Sin(theta / 2)) } }); } #endregion } }
shabegger/quantum-emulate
Quantum.Emulate/PhaseZGate.cs
C#
gpl-3.0
679
""" """ from __future__ import absolute_import import logging import json from datetime import datetime from flask import render_template from flask import request from flask import make_response from . import app from ..utils.slack import Slack from ..models.breakfast import Breakfast def datetime_handler(x): if isinstance(x, datetime): return x.isoformat() raise TypeError("Unknown type") def addBreakfast(userid, channelid, channelname): slack = Slack(token=app.config['SLACK_APP_TOKEN']) userresult = slack.getUserInfos(userid=userid) if userresult.status_code != 200: return 'Cant\' retrieve user infos' if channelname == 'directmessage': return 'Breakfast command need to be triggered in a public or private channel !' elif channelname == 'privategroup': groupinfo = slack.getGroupInfos(channelid=channelid) if userresult.status_code != 200: return 'Cant\' retrieve user infos' group = json.loads(groupinfo.content) channelname = group['group']['name'] user = json.loads(userresult.content) fullname = user['user']['real_name'] avatar = user['user']['profile']['image_512'] username = user['user']['name'] date = Breakfast.getNextAvailableDate(channelid) bt = Breakfast( username=username, date=date, userid=userid, fullname=fullname, avatar=avatar, channelid=channelid, channelname=channelname ) bt.put() text = '@' + username + ' merci pour le petit dej, le ' + date.strftime('%A %d %B %Y') slack.postMessage(channelid, text) return 'Merci pour ce moment !' def listNextBreakfasts(channel=None): nextBreakfasts = Breakfast.getNextBreakfasts(channel) text = 'Breakfast planning : \n' for b in nextBreakfasts: text += b['date'].strftime('%d/%m/%Y') + ' : ' + b['fullname'] text += ' pour #' + b['channelname'] if channel is None and b.has_key('channelname') and b['channelname'] is not None else '' text += '\n' resp = make_response(json.dumps({ 'text': text })) resp.headers['Content-Type'] = 'application/json' return resp @app.route('/breakfast-cmd', methods=['POST']) def breakfast(): text = request.form.get('text', type=str) userid = request.form.get('user_id', type=str) command = request.form.get('command', type=str) channelid = request.form.get('channel_id', type=str) channelname = request.form.get('channel_name', type=str) if command == '/bt': return addBreakfast(userid, channelid, channelname) elif command == '/breakfast': if text == 'list': return listNextBreakfasts(channel=channelid) elif text == 'all': return listNextBreakfasts() return 'Bad command'
jeremlb/breakfast-tracker
server/controllers/index.py
Python
gpl-3.0
2,838
// This is a generated file. Not intended for manual editing. package net.progressum.latex.lang.psi; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public interface LatexBraceOptions extends PsiElement { @NotNull LatexParameters getParameters(); }
mawolf/Progressum-LaTeX
src/net/progressum/latex/lang/psi/LatexBraceOptions.java
Java
gpl-3.0
287
<?php /** * TrcIMPLAN Sitio Web - SMIIndicadoresLaLaguna SociedadCasosAcumuladosDeCovid19Positivos * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 TrcIMPLANSitioWeb */ namespace SMIIndicadoresLaLaguna; /** * Clase SociedadCasosAcumuladosDeCovid19Positivos */ class SociedadCasosAcumuladosDeCovid19Positivos extends \SMIBase\PublicacionWeb { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título y fecha $this->nombre = 'Casos acumulados de COVID-19 positivos en La Laguna'; $this->fecha = '2020-04-15T13:06:07'; // El nombre del archivo a crear $this->archivo = 'sociedad-casos-acumulados-de-covid-19-positivos'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'Acumulado de casos positivos de la enfermedad COVID-19 según el Sistema de Vigilancia Epidemiológica de Enfermedades Respiratoria Viral.'; $this->claves = 'IMPLAN, La Laguna, Salud'; // Para el Organizador $this->categorias = array('Salud'); $this->fuentes = array('Secretaría de Salud'); $this->regiones = array('La Laguna'); } // constructor /** * Datos Estructura * * @return array Arreglo con arreglos asociativos */ public function datos_estructura() { return array( 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'cantidad'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // datos_estructura /** * Datos * * @return array Arreglo con arreglos asociativos */ public function datos() { return array( array('fecha' => '2020-04-13', 'valor' => '38', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-14', 'valor' => '40', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-15', 'valor' => '41', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-16', 'valor' => '43', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-17', 'valor' => '44', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-18', 'valor' => '44', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-19', 'valor' => '44', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-20', 'valor' => '50', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-21', 'valor' => '50', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-22', 'valor' => '48', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-23', 'valor' => '52', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-24', 'valor' => '55', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-25', 'valor' => '61', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-26', 'valor' => '64', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-27', 'valor' => '67', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-28', 'valor' => '71', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-29', 'valor' => '71', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-04-30', 'valor' => '81', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-01', 'valor' => '83', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-02', 'valor' => '83', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-03', 'valor' => '83', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-04', 'valor' => '92', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-05', 'valor' => '93', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-06', 'valor' => '98', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-07', 'valor' => '113', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-08', 'valor' => '126', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-09', 'valor' => '131', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-10', 'valor' => '139', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-11', 'valor' => '147', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-12', 'valor' => '149', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-13', 'valor' => '158', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-14', 'valor' => '170', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-15', 'valor' => '182', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-16', 'valor' => '198', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-17', 'valor' => '208', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-18', 'valor' => '218', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-19', 'valor' => '227', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-20', 'valor' => '261', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-21', 'valor' => '269', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-22', 'valor' => '288', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-23', 'valor' => '294', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-24', 'valor' => '294', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-25', 'valor' => '328', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-26', 'valor' => '348', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-27', 'valor' => '405', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-28', 'valor' => '422', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-29', 'valor' => '444', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-30', 'valor' => '501', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-05-31', 'valor' => '516', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-01', 'valor' => '525', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-02', 'valor' => '559', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-03', 'valor' => '617', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-04', 'valor' => '670', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-05', 'valor' => '714', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-06', 'valor' => '749', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-07', 'valor' => '824', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-08', 'valor' => '863', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-09', 'valor' => '885', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-10', 'valor' => '931', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-11', 'valor' => '1066', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-12', 'valor' => '1113', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-13', 'valor' => '1134', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-14', 'valor' => '1186', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-15', 'valor' => '1217', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-16', 'valor' => '1383', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-17', 'valor' => '1463', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-18', 'valor' => '1559', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-19', 'valor' => '1666', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-20', 'valor' => '1747', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-21', 'valor' => '1803', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-22', 'valor' => '1815', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-23', 'valor' => '1878', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-24', 'valor' => '1921', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-25', 'valor' => '2080', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-26', 'valor' => '2198', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-27', 'valor' => '2256', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-28', 'valor' => '2450', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-29', 'valor' => '2601', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-06-30', 'valor' => '2766', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-01', 'valor' => '3028', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-02', 'valor' => '3207', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-03', 'valor' => '3292', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-04', 'valor' => '3426', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-05', 'valor' => '3560', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-06', 'valor' => '3649', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-07', 'valor' => '3752', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-08', 'valor' => '3832', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-09', 'valor' => '3911', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-10', 'valor' => '3989', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-11', 'valor' => '4124', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-12', 'valor' => '4192', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-13', 'valor' => '4259', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-14', 'valor' => '4336', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-15', 'valor' => '4405', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-16', 'valor' => '4540', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-17', 'valor' => '4617', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-18', 'valor' => '4819', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-19', 'valor' => '4960', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-20', 'valor' => '4969', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-21', 'valor' => '4982', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-22', 'valor' => '5100', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-23', 'valor' => '5236', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-24', 'valor' => '5306', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-25', 'valor' => '5393', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-26', 'valor' => '5468', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-27', 'valor' => '5511', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-28', 'valor' => '5637', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-29', 'valor' => '5673', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-30', 'valor' => '5728', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-07-31', 'valor' => '5811', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-08-01', 'valor' => '5947', 'fuente_nombre' => 'Secretaría de Salud'), array('fecha' => '2020-08-02', 'valor' => '5994', 'fuente_nombre' => 'Secretaría de Salud')); // formateado 0, valor 224, crudo 112 } // datos /** * Otras Regiones Estructura * * @return array Arreglo con arreglos asociativos */ public function otras_regiones_estructura() { return array( 'region_nombre' => array('enca' => 'Región', 'formato' => 'texto'), 'fecha' => array('enca' => 'Fecha', 'formato' => 'fecha'), 'valor' => array('enca' => 'Dato', 'formato' => 'cantidad'), 'fuente_nombre' => array('enca' => 'Fuente', 'formato' => 'texto'), 'notas' => array('enca' => 'Notas', 'formato' => 'texto')); } // otras_regiones_estructura /** * Otras regiones * * @return array Arreglo con arreglos asociativos */ public function otras_regiones() { return array( array('region_nombre' => 'Torreón', 'fecha' => '2020-08-02', 'valor' => '3585', 'fuente_nombre' => 'Secretaría de Salud'), array('region_nombre' => 'Gómez Palacio', 'fecha' => '2020-08-02', 'valor' => '1643', 'fuente_nombre' => 'Secretaría de Salud'), array('region_nombre' => 'Lerdo', 'fecha' => '2020-08-02', 'valor' => '398', 'fuente_nombre' => 'Secretaría de Salud'), array('region_nombre' => 'Matamoros', 'fecha' => '2020-08-02', 'valor' => '368', 'fuente_nombre' => 'Secretaría de Salud'), array('region_nombre' => 'La Laguna', 'fecha' => '2020-08-02', 'valor' => '5994', 'fuente_nombre' => 'Secretaría de Salud'), array('region_nombre' => 'Coahuila', 'fecha' => '2020-05-19', 'valor' => '227', 'fuente_nombre' => 'Secretaría de Salud')); } // otras_regiones /** * Mapas * * @return string Código HTML con el iframe de Carto */ public function mapas() { return NULL; } // mapas /** * Observaciones * * @return string Markdown */ public function observaciones() { return NULL; } // observaciones } // Clase SociedadCasosAcumuladosDeCovid19Positivos ?>
TRCIMPLAN/trcimplan.github.io
lib/SMIIndicadoresLaLaguna/SociedadCasosAcumuladosDeCovid19Positivos.php
PHP
gpl-3.0
16,451
/* * Copyright (C) 2012-2013 Arctium <http://arctium.org> * * 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 Framework.Configuration; using Framework.Database; using Framework.Logging; using Framework.Network.Realm; using Framework.ObjectDefines; using System; namespace RealmServer { class RealmServer { static void Main() { Log.ServerType = "Realm"; Log.Message(LogType.INIT, "___________________________________________"); Log.Message(LogType.INIT, " __ "); Log.Message(LogType.INIT, " / | , "); Log.Message(LogType.INIT, "---/__|---)__----__--_/_--------------_--_-"); Log.Message(LogType.INIT, " / | / ) / ' / / / / / / )"); Log.Message(LogType.INIT, "_/____|_/_____(___ _(_ __/___(___(__/_/__/_"); Log.Message(LogType.INIT, "___________________________________________"); Log.Message(); Log.Message(LogType.NORMAL, "Starting Arctium RealmServer..."); DB.Realms.Init(RealmConfig.RealmDBHost, RealmConfig.RealmDBUser, RealmConfig.RealmDBPassword, RealmConfig.RealmDBDataBase, RealmConfig.RealmDBPort); RealmClass.realm = new RealmNetwork(); // Add realms from database. Log.Message(LogType.NORMAL, "Updating Realm List..."); SQLResult result = DB.Realms.Select("SELECT * FROM realms"); for (int i = 0; i < result.Count; i++) { RealmClass.Realms.Add(new Realm() { Id = result.Read<uint>(i, "id"), Name = result.Read<string>(i, "name"), IP = result.Read<string>(i, "ip"), Port = result.Read<uint>(i, "port"), }); Log.Message(LogType.NORMAL, "Added Realm \"{0}\"", RealmClass.Realms[i].Name); } if (RealmClass.realm.Start(RealmConfig.BindIP, (int)RealmConfig.BindPort)) { RealmClass.realm.AcceptConnectionThread(); Log.Message(LogType.NORMAL, "RealmServer listening on {0} port {1}.", RealmConfig.BindIP, RealmConfig.BindPort); Log.Message(LogType.NORMAL, "RealmServer successfully started!"); } else Log.Message(LogType.ERROR, "RealmServer couldn't be started: "); Log.Message(LogType.NORMAL, "Total Memory: {0} Kilobytes", GC.GetTotalMemory(false) / 1024); } } }
AnthoDevMoP/Mop-5.1.0-Core
RealmServer/RealmServer.cs
C#
gpl-3.0
3,209
/* * Copyright (C) 2016 Riccardo De Benedictis <riccardo.debenedictis@istc.cnr.it> * * 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 it.cnr.istc.core; import java.util.LinkedList; /** * * @author Riccardo De Benedictis <riccardo.debenedictis@istc.cnr.it> */ public abstract class Predicate extends Type { public Predicate(Core c, IScope s, String n, Field... pars) { super(c, s, n); if (scope instanceof Type) { this.fields.put(THIS, new Field((Type) scope, THIS, true)); } for (Field par : pars) { this.fields.put(par.name, par); } } @Override public Atom newInstance(IEnv env) { Atom atom = new Atom(core, env, this); LinkedList<Type> queue = new LinkedList<>(); queue.add(this); while (!queue.isEmpty()) { Type c_type = queue.pollFirst(); c_type.instances.add(atom); queue.addAll(c_type.superclasses); } return atom; } public abstract boolean apply(Atom atom); }
oRatioSolver/oRatio
src/it/cnr/istc/core/Predicate.java
Java
gpl-3.0
1,713
<?php /** * The template for displaying search results pages. */ get_header(); ?> <main id="main" class="site-main" role="main"> <header class='page-title' role="heading"> <h1>Resultado da Busca</h1> <?php if ( function_exists('yoast_breadcrumb') ) { yoast_breadcrumb(' <p class="page-breadcrumbs">','</p>'); } ?> </header> <section class="page-container"> <div class="row content-area "> <div id="search" class="col-9 page-content bg-default "> <?php if (have_posts()) : while(have_posts()) : the_post() ?> <div class="page-search"> <a href="<?php the_permalink(); ?>" rel="bookmark"> <?php the_title('<h6>','</h6>'); ?> <?php the_excerpt(); ?> </a> </div> <?php endwhile; // Paginação wp_pagination(); else : ?> <h3><?php _e( 'Não existe resultados ', 'ralifla' ) ?></h3> <?php _e( 'Desculpe, mas nada corresponde aos seus critérios de busca. Por favor, tente novamente com algumas palavras diferentes.', 'ralifla' ); ?> <?php get_search_form(); endif; ?> </div> <aside class="col-3"> <?php get_sidebar(); ?> </aside> </div> </section> <?php get_footer(); ?>
Ralifla/artemis
site/wp-content/themes/ralifla/search.php
PHP
gpl-3.0
1,350
<?php require_once ("include/setup.inc.php"); require_once ("include/auth.inc.php"); require_once ("include/fpdf.php"); class PDF extends FPDF // Klasse für FPDF-Tabelle { function FancyTable($header, $data) { // Colors, line width and bold font $this->SetFillColor(255, 0, 0); $this->SetTextColor(255); $this->SetDrawColor(128, 0, 0); $this->SetLineWidth(.3); $this->SetFont('', 'B'); // Header $w = array( 10, 45, 80, 35 ); for($i = 0; $i < count($header); $i ++) $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', true); $this->Ln(); // Color and font restoration $this->SetFillColor(224, 235, 255); $this->SetTextColor(0); $this->SetFont(''); // Data $fill = false; foreach($data as $row) { $this->Cell($w[0], 6, $row[0], 'LR', 0, 'C', $fill); $this->SetFont('Arial', '', 12); // $this->SetFont('isonorm_becker','',12); $this->Cell($w[1], 6, $row[1], 'LR', 0, 'C', $fill); $this->SetFont('Arial', '', 14); $this->Cell($w[2], 6, '', 'LR', 0, 'R', $fill); $this->Cell($w[3], 6, '', 'LR', 0, 'R', $fill); $this->Ln(); $fill = !$fill; } // Closing line $this->Cell(array_sum($w), 0, '', 'T'); } } $pdf = new PDF(); // Neues PDF-Objekt // $pdf->AddFont('isonorm_becker','','isonorm_becker.php'); //Schriftart hinzufügen if(is_numeric($_POST['number'])) { $count = $_POST['number']; // Wenn übergebene Voucheranzahl numerisch ist, übernehme diese } else { $count = 24; // sonst 24 (eine DIN-A4-Seite) } $data = $db->activateTickets($_POST['select_print'], $count); // PDF-Tabelle generieren $pdf->SetFont('Arial', '', 14); $pdf->AddPage(); $pdf->FancyTable($config->get('tbl_header'), $data); // PDF-Voucher generieren $rows = 8; $cols = 3; $width = 179; // Genutzte Breite in mm $height = 269; // Genutzte Höhe in mm $pdf->SetAutoPageBreak(false); $pdf->SetMargins(15, 15); while(true) { $pdf->AddPage(); for($row = 1; $row <= $rows; $row ++) { for($col = 1; $col <= $cols; $col ++) { $x = $pdf->GetX(); $y = $pdf->GetY(); $w = $width / $cols; $h = $height / $rows; $dataEntry = array_shift($data); $pdf->SetFont('Arial', 'U', 15); $pdf->Cell($w, 10, $config->get('vou_header'), 0, 2, 'C'); $pdf->SetFont('Arial', '', 9); $pdf->Cell($w, 8, $config->get('vou_text'), 0, 2, 'C'); $pdf->SetFont('Arial', '', 12); // $pdf->SetFont('isonorm_becker','',12); $pdf->Cell($w, 8, $config->get('vou_label') . $dataEntry[1], 0, 2, 'C'); $pdf->SetFont('Arial', '', 8); $pdf->Cell($w, 8, $config->get('dbtables')[$_POST['select_print']] . ' ID ' . $dataEntry[0], 0, 2, 'R'); $pdf->SetXY($x, $y); $pdf->Cell($w, $h, '', 1, $col == $cols); if(count($data) == 0) { break 3; } } } } $pdf->Output(); ?>
creichlin/captivout
captivout/print.php
PHP
gpl-3.0
2,923
/*************************************************************************** * Copyright (C) 2009 by Georg Hennig <georg.hennig@web.de> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ #include <QDomDocument> #include <QTemporaryFile> #include <QTimer> #include <QTextCodec> #include <KDebug> #include <KShell> #include <KIO/Job> #include "plasma-cwp-data-provider.h" Data_Provider::Data_Provider( QObject *parent, const QString &path, const uint identifier ) : QObject( parent ), local_data_path( path ), local_data_identifier( identifier ) { locale = "C"; encoding = ""; data_update_time = ""; data_provider_update_time = ""; xmlFile = ""; int i; url_follow_command_list.clear(); for ( i=0; i<8; i++ ) { url_follow_command_list.push_back( NULL ); } data_command_list.clear(); for ( i=0; i<DATA_COMMAND_NUMBER; i++ ) { data_command_list.push_back( NULL ); } url_follow_command_data_string.clear(); url_follow_command_command.clear(); for ( i=0; i<8; i++ ) { url_follow_command_data_string.push_back( "" ); url_follow_command_command.push_back( "" ); } data_command_data_string.clear(); data_command_command.clear(); data_command_data_result.clear(); for ( i=0; i<DATA_COMMAND_NUMBER; i++ ) { data_command_data_string.push_back( "" ); data_command_command.push_back( "" ); data_command_data_result.push_back( "" ); } data_job_list.clear(); for ( i=0; i<8; i++ ) data_job_list.push_back( NULL ); url_follow_job_list.clear(); for ( i=0; i<8; i++ ) url_follow_job_list.push_back( NULL ); image_job_list.clear(); icon_job_list.clear(); for ( i=0; i<8; i++ ) icon_job_list.push_back( NULL ); data_job_success_list.clear(); for ( i=0; i<8; i++ ) data_job_success_list.push_back( true ); url_follow_job_success_list.clear(); for ( i=0; i<8; i++ ) url_follow_job_success_list.push_back( true ); image_job_success_list.clear(); icon_job_success_list.clear(); for ( i=0; i<8; i++ ) icon_job_success_list.push_back( true ); urlFollowCommandRunning = -1; dataCommandRunning = -1; last_download_succeeded = false; connect( this, SIGNAL( signalLoadLocalData() ), this, SLOT( loadLocalData() ) ); // load weather data saved inside <path> using <identifier> emit( signalLoadLocalData() ); // Get updates whenever networking status was changed connect( Solid::Networking::notifier(), SIGNAL( statusChanged( Solid::Networking::Status ) ), this, SLOT( solidNetworkingStatusChanged( Solid::Networking::Status ) ) ); } Data_Provider::~Data_Provider() { // save weather data saved inside <path> using <identifier> saveLocalData(); int i; for ( i=0; i<8; i++ ) { if ( url_follow_command_list[i] ) url_follow_command_list[i]->kill(); delete url_follow_command_list[i]; } for ( i=0; i<DATA_COMMAND_NUMBER; i++ ) { if ( data_command_list[i] ) data_command_list[i]->kill(); delete data_command_list[i]; } } void Data_Provider::solidNetworkingStatusChanged( Solid::Networking::Status status ) { if ( status == Solid::Networking::Connected && !last_download_succeeded ) { reloadData(); } } void Data_Provider::loadLocalData() { if ( local_data_path == "" || local_data_identifier == 0 ) { return; } KConfig cf( local_data_path + QString( "cwp_local_data_%1.cfg" ).arg( local_data_identifier ), KConfig::SimpleConfig ); KConfigGroup cfg( &cf, "" ); data_update_time = cfg.readEntry( "data_update_time", "" ); data_provider_update_time = cfg.readEntry( "data_provider_update_time", "" ); data_location_location = cfg.readEntry( "data_location_location", "" ); data_location_country = cfg.readEntry( "data_location_country", "" ); data_sun_sunrise = cfg.readEntry( "data_sun_sunrise", "" ); data_sun_sunset = cfg.readEntry( "data_sun_sunset", "" ); data_current_temperature = cfg.readEntry( "data_current_temperature", "" ); data_current_temperature_felt = cfg.readEntry( "data_current_temperature_felt", "" ); data_current_wind_code = cfg.readEntry( "data_current_wind_code", "" ); data_current_wind_speed = cfg.readEntry( "data_current_wind_speed", "" ); data_current_wind = cfg.readEntry( "data_current_wind", "" ); data_current_humidity = cfg.readEntry( "data_current_humidity", "" ); data_current_icon_code = cfg.readEntry( "data_current_icon_code", -1 ); data_current_icon_text = cfg.readEntry( "data_current_icon_text", "" ); data_current_rain = cfg.readEntry( "data_current_rain", "" ); data_current_dew_point = cfg.readEntry( "data_current_dew_point", "" ); data_current_visibility = cfg.readEntry( "data_current_visibility", "" ); data_current_pressure = cfg.readEntry( "data_current_pressure", "" ); data_current_uv_index = cfg.readEntry( "data_current_uv_index", "" ); data_day_name[0] = cfg.readEntry( "data_day_name[0]", "" ); data_day_temperature_high[0] = cfg.readEntry( "data_day_temperature_high[0]", "" ); data_day_temperature_low[0] = cfg.readEntry( "data_day_temperature_low[0]", "" ); data_day_icon_code[0] = cfg.readEntry( "data_day_icon_code[0]", -1 ); data_day_icon_text[0] = cfg.readEntry( "data_day_icon_text[0]", "" ); data_day_name[1] = cfg.readEntry( "data_day_name[1]", "" ); data_day_temperature_high[1] = cfg.readEntry( "data_day_temperature_high[1]", "" ); data_day_temperature_low[1] = cfg.readEntry( "data_day_temperature_low[1]", "" ); data_day_icon_code[1] = cfg.readEntry( "data_day_icon_code[1]", -1 ); data_day_icon_text[1] = cfg.readEntry( "data_day_icon_text[1]", "" ); data_day_name[2] = cfg.readEntry( "data_day_name[2]", "" ); data_day_temperature_high[2] = cfg.readEntry( "data_day_temperature_high[2]", "" ); data_day_temperature_low[2] = cfg.readEntry( "data_day_temperature_low[2]", "" ); data_day_icon_code[2] = cfg.readEntry( "data_day_icon_code[2]", -1 ); data_day_icon_text[2] = cfg.readEntry( "data_day_icon_text[2]", "" ); data_day_name[3] = cfg.readEntry( "data_day_name[3]", "" ); data_day_temperature_high[3] = cfg.readEntry( "data_day_temperature_high[3]", "" ); data_day_temperature_low[3] = cfg.readEntry( "data_day_temperature_low[3]", "" ); data_day_icon_code[3] = cfg.readEntry( "data_day_icon_code[3]", -1 ); data_day_icon_text[3] = cfg.readEntry( "data_day_icon_text[3]", "" ); data_day_name[4] = cfg.readEntry( "data_day_name[4]", "" ); data_day_temperature_high[4] = cfg.readEntry( "data_day_temperature_high[4]", "" ); data_day_temperature_low[4] = cfg.readEntry( "data_day_temperature_low[4]", "" ); data_day_icon_code[4] = cfg.readEntry( "data_day_icon_code[4]", -1 ); data_day_icon_text[4] = cfg.readEntry( "data_day_icon_text[4]", "" ); data_day_name[5] = cfg.readEntry( "data_day_name[5]", "" ); data_day_temperature_high[5] = cfg.readEntry( "data_day_temperature_high[5]", "" ); data_day_temperature_low[5] = cfg.readEntry( "data_day_temperature_low[5]", "" ); data_day_icon_code[5] = cfg.readEntry( "data_day_icon_code[5]", -1 ); data_day_icon_text[5] = cfg.readEntry( "data_day_icon_text[5]", "" ); data_day_name[6] = cfg.readEntry( "data_day_name[6]", "" ); data_day_temperature_high[6] = cfg.readEntry( "data_day_temperature_high[6]", "" ); data_day_temperature_low[6] = cfg.readEntry( "data_day_temperature_low[6]", "" ); data_day_icon_code[6] = cfg.readEntry( "data_day_icon_code[6]", -1 ); data_day_icon_text[6] = cfg.readEntry( "data_day_icon_text[6]", "" ); // png must be used, as images (icons nearly always) contain transparent parts. jpg doesn't support transparency. int i; data_custom_image_list.clear(); for ( i=0; i<100; i++ ) // random maximum location image number { QFile file( local_data_path + QString( "cwp_custom_image_%1_%2.img" ).arg( i ).arg( local_data_identifier ) ); if ( !file.open(QIODevice::ReadOnly) ) break; data_custom_image_list.push_back( file.readAll() ); } data_current_icon = QImage( local_data_path + QString( "cwp_icon_current_%1.png" ).arg( local_data_identifier ) ); data_day_icon[0] = QImage( local_data_path + QString( "cwp_icon_0_%1.png" ).arg( local_data_identifier ) ); data_day_icon[1] = QImage( local_data_path + QString( "cwp_icon_1_%1.png" ).arg( local_data_identifier ) ); data_day_icon[2] = QImage( local_data_path + QString( "cwp_icon_2_%1.png" ).arg( local_data_identifier ) ); data_day_icon[3] = QImage( local_data_path + QString( "cwp_icon_3_%1.png" ).arg( local_data_identifier ) ); data_day_icon[4] = QImage( local_data_path + QString( "cwp_icon_4_%1.png" ).arg( local_data_identifier ) ); data_day_icon[5] = QImage( local_data_path + QString( "cwp_icon_5_%1.png" ).arg( local_data_identifier ) ); data_day_icon[6] = QImage( local_data_path + QString( "cwp_icon_6_%1.png" ).arg( local_data_identifier ) ); if ( data_update_time != "" ) emit( data_fetched() ); } void Data_Provider::saveLocalData() { if ( local_data_path == "" || local_data_identifier == 0 ) { return; } KConfig cf( local_data_path + QString( "cwp_local_data_%1.cfg" ).arg( local_data_identifier ), KConfig::SimpleConfig ); KConfigGroup cfg( &cf, "" ); cfg.writeEntry( "data_update_time", data_update_time ); cfg.writeEntry( "data_provider_update_time", data_provider_update_time ); cfg.writeEntry( "data_location_location", data_location_location ); cfg.writeEntry( "data_location_country", data_location_country ); cfg.writeEntry( "data_sun_sunrise", data_sun_sunrise ); cfg.writeEntry( "data_sun_sunset", data_sun_sunset ); cfg.writeEntry( "data_current_temperature", data_current_temperature ); cfg.writeEntry( "data_current_temperature_felt", data_current_temperature_felt ); cfg.writeEntry( "data_current_wind_code", data_current_wind_code ); cfg.writeEntry( "data_current_wind_speed", data_current_wind_speed ); cfg.writeEntry( "data_current_wind", data_current_wind ); cfg.writeEntry( "data_current_humidity", data_current_humidity ); cfg.writeEntry( "data_current_icon_code", data_current_icon_code ); cfg.writeEntry( "data_current_icon_text", data_current_icon_text ); cfg.writeEntry( "data_current_rain", data_current_rain ); cfg.writeEntry( "data_current_dew_point", data_current_dew_point ); cfg.writeEntry( "data_current_visibility", data_current_visibility ); cfg.writeEntry( "data_current_pressure", data_current_pressure ); cfg.writeEntry( "data_current_uv_index", data_current_uv_index ); cfg.writeEntry( "data_day_name[0]", data_day_name[0] ); cfg.writeEntry( "data_day_temperature_high[0]", data_day_temperature_high[0] ); cfg.writeEntry( "data_day_temperature_low[0]", data_day_temperature_low[0] ); cfg.writeEntry( "data_day_icon_code[0]", data_day_icon_code[0] ); cfg.writeEntry( "data_day_icon_text[0]", data_day_icon_text[0] ); cfg.writeEntry( "data_day_name[1]", data_day_name[1] ); cfg.writeEntry( "data_day_temperature_high[1]", data_day_temperature_high[1] ); cfg.writeEntry( "data_day_temperature_low[1]", data_day_temperature_low[1] ); cfg.writeEntry( "data_day_icon_code[1]", data_day_icon_code[1] ); cfg.writeEntry( "data_day_icon_text[1]", data_day_icon_text[1] ); cfg.writeEntry( "data_day_name[2]", data_day_name[2] ); cfg.writeEntry( "data_day_temperature_high[2]", data_day_temperature_high[2] ); cfg.writeEntry( "data_day_temperature_low[2]", data_day_temperature_low[2] ); cfg.writeEntry( "data_day_icon_code[2]", data_day_icon_code[2] ); cfg.writeEntry( "data_day_icon_text[2]", data_day_icon_text[2] ); cfg.writeEntry( "data_day_name[3]", data_day_name[3] ); cfg.writeEntry( "data_day_temperature_high[3]", data_day_temperature_high[3] ); cfg.writeEntry( "data_day_temperature_low[3]", data_day_temperature_low[3] ); cfg.writeEntry( "data_day_icon_code[3]", data_day_icon_code[3] ); cfg.writeEntry( "data_day_icon_text[3]", data_day_icon_text[3] ); cfg.writeEntry( "data_day_name[4]", data_day_name[4] ); cfg.writeEntry( "data_day_temperature_high[4]", data_day_temperature_high[4] ); cfg.writeEntry( "data_day_temperature_low[4]", data_day_temperature_low[4] ); cfg.writeEntry( "data_day_icon_code[4]", data_day_icon_code[4] ); cfg.writeEntry( "data_day_icon_text[4]", data_day_icon_text[4] ); cfg.writeEntry( "data_day_name[5]", data_day_name[5] ); cfg.writeEntry( "data_day_temperature_high[5]", data_day_temperature_high[5] ); cfg.writeEntry( "data_day_temperature_low[5]", data_day_temperature_low[5] ); cfg.writeEntry( "data_day_icon_code[5]", data_day_icon_code[5] ); cfg.writeEntry( "data_day_icon_text[5]", data_day_icon_text[5] ); cfg.writeEntry( "data_day_name[6]", data_day_name[6] ); cfg.writeEntry( "data_day_temperature_high[6]", data_day_temperature_high[6] ); cfg.writeEntry( "data_day_temperature_low[6]", data_day_temperature_low[6] ); cfg.writeEntry( "data_day_icon_code[6]", data_day_icon_code[6] ); cfg.writeEntry( "data_day_icon_text[6]", data_day_icon_text[6] ); // png must be used, as images (icons nearly always) contain transparent parts. jpg doesn't support transparency. int i; for ( i=0; i<data_custom_image_list.size(); i++ ) { QFile file( local_data_path + QString( "cwp_custom_image_%1_%2.img" ).arg( i ).arg( local_data_identifier ) ); file.open( QIODevice::WriteOnly ); file.write( data_custom_image_list.at( i ) ); } data_current_icon.save( local_data_path + QString( "cwp_icon_current_%1.png" ).arg( local_data_identifier ) ); data_day_icon[0].save( local_data_path + QString( "cwp_icon_0_%1.png" ).arg( local_data_identifier ) ); data_day_icon[1].save( local_data_path + QString( "cwp_icon_1_%1.png" ).arg( local_data_identifier ) ); data_day_icon[2].save( local_data_path + QString( "cwp_icon_2_%1.png" ).arg( local_data_identifier ) ); data_day_icon[3].save( local_data_path + QString( "cwp_icon_3_%1.png" ).arg( local_data_identifier ) ); data_day_icon[4].save( local_data_path + QString( "cwp_icon_4_%1.png" ).arg( local_data_identifier ) ); data_day_icon[5].save( local_data_path + QString( "cwp_icon_5_%1.png" ).arg( local_data_identifier ) ); data_day_icon[6].save( local_data_path + QString( "cwp_icon_6_%1.png" ).arg( local_data_identifier ) ); } void Data_Provider::get_weather_values( QString &data_location_location_tmp, QString &data_location_country_tmp, QString &data_sun_sunrise_tmp, QString &data_sun_sunset_tmp, QString &data_current_temperature_tmp, QString &data_current_temperature_felt_tmp, QString &data_current_wind_code_tmp, QString &data_current_wind_speed_tmp, QString &data_current_wind_tmp, QString &data_current_humidity_tmp, QString &data_current_dew_point_tmp, QString &data_current_visibility_tmp, QString &data_current_pressure_tmp, QString &data_current_uv_index_tmp, int &data_current_icon_code_tmp, QImage &data_current_icon_tmp, QString &data_current_icon_text_tmp, QString &data_current_rain_tmp, QString *data_day_name_tmp, QString *data_day_temperature_high_tmp, QString *data_day_temperature_low_tmp, int *data_day_icon_code_tmp, QImage *data_day_icon_tmp, QString *data_day_icon_text_tmp, QString &data_update_time_tmp, QString &data_provider_update_time_tmp, QString &tempType_tmp, QList<QByteArray> &data_custom_image_list_tmp, bool &last_download_succeeded_tmp, QString &provider_url_tmp ) { data_update_time_tmp = data_update_time; data_provider_update_time_tmp = data_provider_update_time; data_location_location_tmp = data_location_location; data_location_country_tmp = data_location_country; data_sun_sunrise_tmp = data_sun_sunrise; data_sun_sunset_tmp = data_sun_sunset; data_current_temperature_tmp = data_current_temperature; data_current_temperature_felt_tmp = data_current_temperature_felt; data_current_wind_code_tmp = data_current_wind_code; data_current_wind_speed_tmp = data_current_wind_speed; data_current_wind_tmp = data_current_wind; data_current_humidity_tmp = data_current_humidity; data_current_icon_code_tmp = data_current_icon_code; data_current_icon_tmp = data_current_icon; data_current_icon_text_tmp = data_current_icon_text; data_current_rain_tmp = data_current_rain; data_current_dew_point_tmp = data_current_dew_point; data_current_visibility_tmp = data_current_visibility; data_current_pressure_tmp = data_current_pressure; data_current_uv_index_tmp = data_current_uv_index; tempType_tmp = tempType; data_custom_image_list_tmp = data_custom_image_list; int i; for( i=0; i<7; i++ ) { data_day_name_tmp[i] = data_day_name[i]; data_day_temperature_high_tmp[i] = data_day_temperature_high[i]; data_day_temperature_low_tmp[i] = data_day_temperature_low[i]; data_day_icon_code_tmp[i] = data_day_icon_code[i]; data_day_icon_tmp[i] = data_day_icon[i]; data_day_icon_text_tmp[i] = data_day_icon_text[i]; } last_download_succeeded_tmp = last_download_succeeded; if ( data_current_temperature_url_xml == "urlc" ) { if ( urlc_follow_xml != "" ) provider_url_tmp = urlc_new; else provider_url_tmp = urlc_prefix_xml + zip + urlc_suffix_xml; } else if ( data_current_temperature_url_xml == "url1" ) { if ( url1_follow_xml != "" ) provider_url_tmp = url1_new; else provider_url_tmp = url1_prefix_xml + zip + url1_suffix_xml; } else if ( data_current_temperature_url_xml == "url2" ) { if ( url2_follow_xml != "" ) provider_url_tmp = url2_new; else provider_url_tmp = url2_prefix_xml + zip + url2_suffix_xml; } else if ( data_current_temperature_url_xml == "url3" ) { if ( url3_follow_xml != "" ) provider_url_tmp = url3_new; else provider_url_tmp = url3_prefix_xml + zip + url3_suffix_xml; } else if ( data_current_temperature_url_xml == "url4" ) { if ( url4_follow_xml != "" ) provider_url_tmp = url4_new; else provider_url_tmp = url4_prefix_xml + zip + url4_suffix_xml; } else if ( data_current_temperature_url_xml == "url5" ) { if ( url5_follow_xml != "" ) provider_url_tmp = url5_new; else provider_url_tmp = url5_prefix_xml + zip + url5_suffix_xml; } else if ( data_current_temperature_url_xml == "url6" ) { if ( url6_follow_xml != "" ) provider_url_tmp = url6_new; else provider_url_tmp = url6_prefix_xml + zip + url6_suffix_xml; } else if ( data_current_temperature_url_xml == "url7" ) { if ( url7_follow_xml != "" ) provider_url_tmp = url7_new; else provider_url_tmp = url7_prefix_xml + zip + url7_suffix_xml; } } void Data_Provider::set_config_values( const QString &updateFrequency_tmp, const QString &xmlFile_tmp, const QString &zip_tmp, const QString &feelsLike_tmp, const QString &humidity_tmp, const QString &wind_tmp, const QString &tempType_tmp, const QList<KUrl> &customImageList_tmp ) { updateFrequency = updateFrequency_tmp; xmlFile = xmlFile_tmp; zip = zip_tmp; feelsLike = feelsLike_tmp; humidity = humidity_tmp; wind = wind_tmp; tempType = tempType_tmp; customImageList = customImageList_tmp; } void Data_Provider::reloadData() { int i; for ( i=0; i<data_job_list.size(); i++ ) { if ( data_job_list[i] ) { disconnect( data_job_list[i], SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); disconnect( data_job_list[i], SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); delete data_job_list[i]; data_job_list[i] = NULL; } } for ( i=0; i<url_follow_job_list.size(); i++ ) { if ( data_job_list[i] ) { disconnect( url_follow_job_list[i], SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); disconnect( url_follow_job_list[i], SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); delete url_follow_job_list[i]; url_follow_job_list[i] = NULL; } } for ( i=0; i<image_job_list.size(); i++ ) { if ( image_job_list[i] ) { disconnect( image_job_list[i], SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( imageDownloadedData( KIO::Job *, const QByteArray & ) ) ); disconnect( image_job_list[i], SIGNAL( result( KJob * ) ), this, SLOT( imageDownloadFinished( KJob * ) ) ); delete image_job_list[i]; image_job_list[i] = NULL; } } for ( i=0; i<icon_job_list.size(); i++ ) { if ( icon_job_list[i] ) { disconnect( icon_job_list[i], SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( iconDownloadedData( KIO::Job *, const QByteArray & ) ) ); disconnect( icon_job_list[i], SIGNAL( result( KJob * ) ), this, SLOT( iconDownloadFinished( KJob * ) ) ); delete icon_job_list[i]; icon_job_list[i] = NULL; } } for ( i=0; i<8; i++ ) { if ( url_follow_command_list[i] ) { url_follow_command_list[i]->kill(); } } for ( i=0; i<DATA_COMMAND_NUMBER; i++ ) { if ( data_command_list[i] ) { data_command_list[i]->kill(); } } for ( i=0; i<WEATHER_CODE_TRANSFORM_SIZE; i++ ) { data_icon_transform_in_xml[i] = ""; data_icon_transform_out_xml[i] = ""; } for ( i=0; i<WIND_TRANSFORM_SIZE; i++ ) { data_wind_transform_in_xml[i] = ""; data_wind_transform_out_xml[i] = ""; } QDomDocument doc( "weather_xml" ); QFile file( xmlFile ); //read the data into the XML parser and close the file doc.setContent( &file ); file.close(); QDomElement root = doc.documentElement(); QDomNode n = root.firstChild(); QDomNode n_old; while( !n.isNull() ) { QDomElement e = n.toElement(); if( e.tagName() == "locale_settings" ) { locale_xml = e.attribute( "locale", "" ); encoding_xml = e.attribute( "encoding", "" ); } if( e.tagName() == "urlc" ) { urlc_prefix_xml = e.attribute( "urlc_prefix", "" ); urlc_suffix_xml = e.attribute( "urlc_suffix", "" ); urlc_follow_xml = e.attribute( "urlc_follow", "" ); } if( e.tagName() == "url1" ) { url1_prefix_xml = e.attribute( "url1_prefix", "" ); url1_suffix_xml = e.attribute( "url1_suffix", "" ); url1_follow_xml = e.attribute( "url1_follow", "" ); } if( e.tagName() == "url2" ) { url2_prefix_xml = e.attribute( "url2_prefix", "" ); url2_suffix_xml = e.attribute( "url2_suffix", "" ); url2_follow_xml = e.attribute( "url2_follow", "" ); } if( e.tagName() == "url3" ) { url3_prefix_xml = e.attribute( "url3_prefix", "" ); url3_suffix_xml = e.attribute( "url3_suffix", "" ); url3_follow_xml = e.attribute( "url3_follow", "" ); } if( e.tagName() == "url4" ) { url4_prefix_xml = e.attribute( "url4_prefix", "" ); url4_suffix_xml = e.attribute( "url4_suffix", "" ); url4_follow_xml = e.attribute( "url4_follow", "" ); } if( e.tagName() == "url5" ) { url5_prefix_xml = e.attribute( "url5_prefix", "" ); url5_suffix_xml = e.attribute( "url5_suffix", "" ); url5_follow_xml = e.attribute( "url5_follow", "" ); } if( e.tagName() == "url6" ) { url6_prefix_xml = e.attribute( "url6_prefix", "" ); url6_suffix_xml = e.attribute( "url6_suffix", "" ); url6_follow_xml = e.attribute( "url6_follow", "" ); } if( e.tagName() == "url7" ) { url7_prefix_xml = e.attribute( "url7_prefix", "" ); url7_suffix_xml = e.attribute( "url7_suffix", "" ); url7_follow_xml = e.attribute( "url7_follow", "" ); } if( e.tagName() == "data_location" ) { data_location_url_xml = e.attribute( "url", "" ); data_location_location_xml = e.attribute( "location", "" ); data_location_country_xml = e.attribute( "country", "" ); } if( e.tagName() == "data_sun" ) { data_sun_url_xml = e.attribute( "url", "" ); data_sun_sunrise_xml = e.attribute( "sunrise", "" ); data_sun_sunset_xml = e.attribute( "sunset", "" ); } if( e.tagName() == "data_current_temperature" ) { data_current_temperature_url_xml = e.attribute( "url", "" ); data_provider_update_time_xml = e.attribute( "update_time", "" ); data_current_temperature_xml = e.attribute( "temperature", "" ); data_current_temperature_felt_xml = e.attribute( "temperature_felt", "" ); } if( e.tagName() == "data_current_wind" ) { data_current_wind_url_xml = e.attribute( "url", "" ); data_current_wind_code_xml = e.attribute( "wind_code", "" ); data_current_wind_speed_xml = e.attribute( "wind_speed", "" ); data_current_wind_xml = e.attribute( "wind", "" ); } if( e.tagName() == "data_current_icon" ) { data_current_icon_url_xml = e.attribute( "url", "" ); data_current_icon_code_xml = e.attribute( "icon_code", "" ); data_current_icon_xml = e.attribute( "icon", "" ); data_current_icon_text_xml = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_current_additional" ) { data_current_additional_url_xml = e.attribute( "url", "" ); data_current_humidity_xml = e.attribute( "humidity", "" ); data_current_rain_xml = e.attribute( "rain", "" ); data_current_dew_point_xml = e.attribute( "dew_point", "" ); data_current_visibility_xml = e.attribute( "visibility", "" ); data_current_pressure_xml = e.attribute( "pressure", "" ); data_current_uv_index_xml = e.attribute( "uv_index", "" ); } if( e.tagName() == "data_day1" ) { data_day_url_xml[0] = e.attribute( "url", "" ); data_day_name_xml[0] = e.attribute( "name", "" ); data_day_temperature_high_xml[0] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[0] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[0] = e.attribute( "icon_code", "" ); data_day_icon_xml[0] = e.attribute( "icon", "" ); data_day_icon_text_xml[0] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day2" ) { data_day_url_xml[1] = e.attribute( "url", "" ); data_day_name_xml[1] = e.attribute( "name", "" ); data_day_temperature_high_xml[1] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[1] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[1] = e.attribute( "icon_code", "" ); data_day_icon_xml[1] = e.attribute( "icon", "" ); data_day_icon_text_xml[1] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day3" ) { data_day_url_xml[2] = e.attribute( "url", "" ); data_day_name_xml[2] = e.attribute( "name", "" ); data_day_temperature_high_xml[2] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[2] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[2] = e.attribute( "icon_code", "" ); data_day_icon_xml[2] = e.attribute( "icon", "" ); data_day_icon_text_xml[2] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day4" ) { data_day_url_xml[3] = e.attribute( "url", "" ); data_day_name_xml[3] = e.attribute( "name", "" ); data_day_temperature_high_xml[3] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[3] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[3] = e.attribute( "icon_code", "" ); data_day_icon_xml[3] = e.attribute( "icon", "" ); data_day_icon_text_xml[3] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day5" ) { data_day_url_xml[4] = e.attribute( "url", "" ); data_day_name_xml[4] = e.attribute( "name", "" ); data_day_temperature_high_xml[4] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[4] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[4] = e.attribute( "icon_code", "" ); data_day_icon_xml[4] = e.attribute( "icon", "" ); data_day_icon_text_xml[4] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day6" ) { data_day_url_xml[5] = e.attribute( "url", "" ); data_day_name_xml[5] = e.attribute( "name", "" ); data_day_temperature_high_xml[5] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[5] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[5] = e.attribute( "icon_code", "" ); data_day_icon_xml[5] = e.attribute( "icon", "" ); data_day_icon_text_xml[5] = e.attribute( "icon_text", "" ); } if( e.tagName() == "data_day7" ) { data_day_url_xml[6] = e.attribute( "url", "" ); data_day_name_xml[6] = e.attribute( "name", "" ); data_day_temperature_high_xml[6] = e.attribute( "temperature_high", "" ); data_day_temperature_low_xml[6] = e.attribute( "temperature_low", "" ); data_day_icon_code_xml[6] = e.attribute( "icon_code", "" ); data_day_icon_xml[6] = e.attribute( "icon", "" ); data_day_icon_text_xml[6] = e.attribute( "icon_text", "" ); } if( e.tagName() == "icon_transform" ) { QString transform_number; int n; for ( n=0; n<WEATHER_CODE_TRANSFORM_SIZE; n++ ) { transform_number.setNum( n+1 ); data_icon_transform_in_xml[n] = e.attribute(QString( "i" ) + transform_number, "" ); data_icon_transform_out_xml[n] = e.attribute(QString( "o" ) + transform_number, "" ); } } if( e.tagName() == "wind_transform" ) { QString transform_number; int n; for ( n=0; n<WIND_TRANSFORM_SIZE; n++ ) { transform_number.setNum( n+1 ); data_wind_transform_in_xml[n] = e.attribute(QString( "i" ) + transform_number, "" ); data_wind_transform_out_xml[n] = e.attribute(QString( "o" ) + transform_number, "" ); } } n = n.nextSibling(); } data_download_data_list.clear(); for ( i=0; i<8; i++ ) { data_download_data_list.push_back( QByteArray() ); } data_image_list.clear(); data_icon_list.clear(); for ( i=0; i<8; i++ ) { data_icon_list.push_back( QByteArray() ); } startDownloadData(); } void Data_Provider::startDownloadData() { url_followed = false; url_follow_command_run = false; data_command_run = false; int i; data_job_success_list.clear(); for ( i=0; i<8; i++ ) data_job_success_list.push_back( true ); url_follow_job_success_list.clear(); for ( i=0; i<8; i++ ) url_follow_job_success_list.push_back( true ); image_job_success_list.clear(); icon_job_success_list.clear(); for ( i=0; i<8; i++ ) icon_job_success_list.push_back( true ); if ( urlc_prefix_xml != "" ) { data_job_success_list[0] = false; KIO::Job *jobc = KIO::get( KUrl( urlc_prefix_xml + zip + urlc_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( jobc, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( jobc, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[0] = jobc; jobc->start(); } if ( url1_prefix_xml != "" ) { data_job_success_list[1] = false; KIO::Job *job1 = KIO::get( KUrl( url1_prefix_xml + zip + url1_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job1, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job1, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[1] = job1; job1->start(); } if ( url2_prefix_xml != "" ) { data_job_success_list[2] = false; KIO::Job *job2 = KIO::get( KUrl( url2_prefix_xml + zip + url2_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job2, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job2, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[2] = job2; job2->start(); } if ( url3_prefix_xml != "" ) { data_job_success_list[3] = false; KIO::Job *job3 = KIO::get( KUrl( url3_prefix_xml + zip + url3_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job3, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job3, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[3] = job3; job3->start(); } if ( url4_prefix_xml != "" ) { data_job_success_list[4] = false; KIO::Job *job4 = KIO::get( KUrl( url4_prefix_xml + zip + url4_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job4, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job4, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[4] = job4; job4->start(); } if ( url5_prefix_xml != "" ) { data_job_success_list[5] = false; KIO::Job *job5 = KIO::get( KUrl( url5_prefix_xml + zip + url5_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job5, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job5, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[5] = job5; job5->start(); } if ( url6_prefix_xml != "" ) { data_job_success_list[6] = false; KIO::Job *job6 = KIO::get( KUrl( url6_prefix_xml + zip + url6_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job6, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job6, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[6] = job6; job6->start(); } if ( url7_prefix_xml != "" ) { data_job_success_list[7] = false; KIO::Job *job7 = KIO::get( KUrl( url7_prefix_xml + zip + url7_suffix_xml ), KIO::Reload, KIO::HideProgressInfo ); connect( job7, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( dataDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job7, SIGNAL( result( KJob * ) ), this, SLOT( dataDownloadFinished( KJob * ) ) ); data_job_list[7] = job7; job7->start(); } } void Data_Provider::parseData() { if ( !url_followed ) { if ( urlc_follow_xml == "" && url1_follow_xml == "" && url2_follow_xml == "" && url3_follow_xml == "" && url4_follow_xml == "" && url5_follow_xml == "" && url6_follow_xml == "" && url7_follow_xml == "" ) { url_followed = true; } else { if ( !url_follow_command_run ) { urlFollowCommandAppend( urlc_follow_xml, "urlc", 0 ); urlFollowCommandAppend( url1_follow_xml, "url1", 1 ); urlFollowCommandAppend( url2_follow_xml, "url2", 2 ); urlFollowCommandAppend( url3_follow_xml, "url3", 3 ); urlFollowCommandAppend( url4_follow_xml, "url4", 4 ); urlFollowCommandAppend( url5_follow_xml, "url5", 5 ); urlFollowCommandAppend( url6_follow_xml, "url6", 6 ); urlFollowCommandAppend( url7_follow_xml, "url7", 7 ); urlFollowCommandStartExecution(); return; } else { if ( urlc_follow_xml != "" ) { url_follow_job_success_list[0] = false; data_download_data_list[0] = QByteArray(); KIO::Job *jobc = KIO::get( KUrl( urlc_new ), KIO::Reload, KIO::HideProgressInfo ); connect( jobc, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( jobc, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[0] = jobc; jobc->start(); } if ( url1_follow_xml != "" ) { url_follow_job_success_list[1] = false; data_download_data_list[1] = QByteArray(); KIO::Job *job1 = KIO::get( KUrl( url1_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job1, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job1, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[1] = job1; job1->start(); } if ( url2_follow_xml != "" ) { url_follow_job_success_list[2] = false; data_download_data_list[2] = QByteArray(); KIO::Job *job2 = KIO::get( KUrl( url2_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job2, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job2, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[2] = job2; job2->start(); } if ( url3_follow_xml != "" ) { url_follow_job_success_list[3] = false; data_download_data_list[3] = QByteArray(); KIO::Job *job3 = KIO::get( KUrl( url3_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job3, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job3, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[3] = job3; job3->start(); } if ( url4_follow_xml != "" ) { url_follow_job_success_list[4] = false; data_download_data_list[4] = QByteArray(); KIO::Job *job4 = KIO::get( KUrl( url4_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job4, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job4, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[4] = job4; job4->start(); } if ( url5_follow_xml != "" ) { url_follow_job_success_list[5] = false; data_download_data_list[5] = QByteArray(); KIO::Job *job5 = KIO::get( KUrl( url5_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job5, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job5, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[5] = job5; job5->start(); } if ( url6_follow_xml != "" ) { url_follow_job_success_list[6] = false; data_download_data_list[6] = QByteArray(); KIO::Job *job6 = KIO::get( KUrl( url6_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job6, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job6, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[6] = job6; job6->start(); } if ( url7_follow_xml != "" ) { url_follow_job_success_list[7] = false; data_download_data_list[7] = QByteArray(); KIO::Job *job7 = KIO::get( KUrl( url7_new ), KIO::Reload, KIO::HideProgressInfo ); connect( job7, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( urlFollowDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job7, SIGNAL( result( KJob * ) ), this, SLOT( urlFollowDownloadFinished( KJob * ) ) ); url_follow_job_list[7] = job7; job7->start(); } return; } } } // was download of data successful? int i; last_download_succeeded = true; for ( i=0; i<8; i++ ) { if ( !data_job_success_list[i] ) last_download_succeeded = false; } for ( i=0; i<8; i++ ) { if ( !url_follow_job_success_list[i] ) last_download_succeeded = false; } if ( !last_download_succeeded ) { qDebug() << "Data download failed!" << endl; return; } if ( !data_command_run ) { // run commands from xml file on weather files locale = locale_xml; encoding = encoding_xml; qDebug() << "setting locale to " << locale << " and encoding to " << encoding; dataCommandAppend( data_location_location_xml, data_location_url_xml, 0 ); dataCommandAppend( data_location_country_xml, data_location_url_xml, 1 ); dataCommandAppend( data_sun_sunrise_xml, data_sun_url_xml, 2 ); dataCommandAppend( data_sun_sunset_xml, data_sun_url_xml, 3 ); dataCommandAppend( data_provider_update_time_xml, data_current_temperature_url_xml, 4 ); dataCommandAppend( data_current_temperature_xml, data_current_temperature_url_xml, 5 ); dataCommandAppend( data_current_temperature_felt_xml, data_current_temperature_url_xml, 6 ); dataCommandAppend( data_current_wind_code_xml, data_current_wind_url_xml, 7 ); dataCommandAppend( data_current_wind_speed_xml, data_current_wind_url_xml, 8 ); dataCommandAppend( data_current_wind_xml, data_current_wind_url_xml, 9 ); dataCommandAppend( data_current_icon_code_xml, data_current_icon_url_xml, 10 ); dataCommandAppend( data_current_icon_xml, data_current_icon_url_xml, 11 ); dataCommandAppend( data_current_icon_text_xml, data_current_icon_url_xml, 12 ); dataCommandAppend( data_current_humidity_xml, data_current_additional_url_xml, 13 ); dataCommandAppend( data_current_rain_xml, data_current_additional_url_xml, 14 ); dataCommandAppend( data_current_dew_point_xml, data_current_additional_url_xml, 15 ); dataCommandAppend( data_current_visibility_xml, data_current_additional_url_xml, 16 ); dataCommandAppend( data_current_pressure_xml, data_current_additional_url_xml, 17 ); dataCommandAppend( data_current_uv_index_xml, data_current_additional_url_xml, 18 ); for(i=0; i<7; i++) { dataCommandAppend( data_day_name_xml[i], data_day_url_xml[i], 19 + i * 6 + 0 ); dataCommandAppend( data_day_temperature_high_xml[i], data_day_url_xml[i], 19 + i * 6 + 1 ); dataCommandAppend( data_day_temperature_low_xml[i], data_day_url_xml[i], 19 + i * 6 + 2 ); dataCommandAppend( data_day_icon_code_xml[i], data_day_url_xml[i], 19 + i * 6 + 3 ); dataCommandAppend( data_day_icon_xml[i], data_day_url_xml[i], 19 + i * 6 + 4 ); dataCommandAppend( data_day_icon_text_xml[i], data_day_url_xml[i], 19 + i * 6 + 5 ); } // download custom images data_image_list.clear(); for ( i=0; i<customImageList.size(); i++ ) { data_image_list.push_back( QByteArray() ); } image_job_list.clear(); for ( i=0; i<customImageList.size(); i++ ) { image_job_list.push_back( NULL ); } image_job_success_list.clear(); for ( i=0; i<customImageList.size(); i++ ) { image_job_success_list.push_back( false ); } KIO::Job *job_image = NULL; bool job_started = false; for ( i=0; i<customImageList.size(); i++ ) { if ( customImageList.at( i ).isLocalFile() ) { QFile file( customImageList.at( i ).toLocalFile() ); if ( file.open( QIODevice::ReadOnly ) ) { data_image_list[i] = file.readAll(); image_job_success_list[i] = true; } } else { job_started = true; image_job_success_list.push_back( false ); job_image = KIO::get( KUrl( customImageList.at( i ) ), KIO::Reload, KIO::HideProgressInfo ); connect( job_image, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( imageDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job_image, SIGNAL( result( KJob * ) ), this, SLOT( imageDownloadFinished( KJob * ) ) ); image_job_list[i] = job_image; job_image->start(); } } if ( !job_started ) { data_custom_image_list.clear(); for ( i=0; i<image_job_success_list.size(); i++ ) { if ( image_job_success_list[i] ) { data_custom_image_list.push_back( data_image_list[i] ); } } data_image_list.clear(); } dataCommandStartExecution(); return; } data_location_location = dataFromIdentifier( 0 ); qDebug() << "data_location_location: " << data_location_location; data_location_country = dataFromIdentifier( 1 ); qDebug() << "data_location_country: " << data_location_country; data_sun_sunrise = dataFromIdentifier( 2 ); qDebug() << "data_sun_sunrise: " << data_sun_sunrise; data_sun_sunset = dataFromIdentifier( 3 ); qDebug() << "data_sun_sunset: " << data_sun_sunset; data_provider_update_time = dataFromIdentifier( 4 ); qDebug() << "data_provider_update_time: " << data_provider_update_time; data_current_temperature = dataFromIdentifier( 5 ); qDebug() << "data_current_temperature: " << data_current_temperature; data_current_temperature_felt = dataFromIdentifier( 6 ); qDebug() << "data_current_temperature_felt: " << data_current_temperature_felt; data_current_wind_code = dataFromIdentifier( 7 ); int j; for ( j=0; j<WIND_TRANSFORM_SIZE; j++ ) { if ( QString::compare( dataFromIdentifier( 7 ), data_wind_transform_in_xml[j], Qt::CaseInsensitive ) == 0 ) data_current_wind_code = data_wind_transform_out_xml[j]; } qDebug() << "data_current_wind_code: " << data_current_wind_code; data_current_wind_speed = dataFromIdentifier( 8 ); qDebug() << "data_current_wind_speed: " << data_current_wind_speed; data_current_wind = dataFromIdentifier( 9 ); qDebug() << "data_current_wind: " << data_current_wind; qDebug() << "data_current_icon_code (orig): " << dataFromIdentifier( 10 ); data_current_icon_code = dataFromIdentifier( 10 ).toInt(); for ( j=0; j<WEATHER_CODE_TRANSFORM_SIZE; j++ ) { if ( QString::compare( dataFromIdentifier( 10 ), data_icon_transform_in_xml[j], Qt::CaseInsensitive ) == 0 ) { data_current_icon_code = data_icon_transform_out_xml[j].toInt(); } } qDebug() << "data_current_icon_code: " << data_current_icon_code; data_current_icon_text = dataFromIdentifier( 12 ); qDebug() << "data_current_icon_text: " << data_current_icon_text; data_current_humidity = dataFromIdentifier( 13 ); qDebug() << "data_current_humidity: " << data_current_humidity; data_current_rain = dataFromIdentifier( 14 ); qDebug() << "data_current_rain: " << data_current_rain; data_current_dew_point = dataFromIdentifier( 15 ); qDebug() << "data_current_dew_point: " << data_current_dew_point; data_current_visibility = dataFromIdentifier( 16 ); qDebug() << "data_current_visibility: " << data_current_visibility; data_current_pressure = dataFromIdentifier( 17 ); qDebug() << "data_current_pressure: " << data_current_pressure; data_current_uv_index = dataFromIdentifier( 18 ); qDebug() << "data_current_uv_index: " << data_current_uv_index; for( i=0; i<7; i++ ) { data_day_name[i] = dataFromIdentifier( 19 + i * 6 + 0 ); qDebug() << "data_day_name[" << i << "]: " << data_day_name[i]; data_day_temperature_high[i] = dataFromIdentifier( 19 + i * 6 + 1 ); qDebug() << "data_day_temperature_high[" << i << "]: " << data_day_temperature_high[i]; data_day_temperature_low[i] = dataFromIdentifier( 19 + i * 6 + 2 ); qDebug() << "data_day_temperature_low[" << i << "]: " << data_day_temperature_low[i]; qDebug() << "data_current_icon_code (orig): " << dataFromIdentifier( 19 + i * 6 + 3 ); data_day_icon_code[i] = dataFromIdentifier( 19 + i * 6 + 3 ).toInt(); for ( j=0; j<WEATHER_CODE_TRANSFORM_SIZE; j++ ) { if ( QString::compare( dataFromIdentifier( 19 + i * 6 + 3 ), data_icon_transform_in_xml[j], Qt::CaseInsensitive ) == 0 ) { data_day_icon_code[i] = data_icon_transform_out_xml[j].toInt(); } } qDebug() << "data_day_icon_code[" << i << "]: " << data_day_icon_code[i]; data_day_icon_text[i] = dataFromIdentifier( 19 + i * 6 + 5 ); qDebug() << "data_day_icon_text[" << i << "]: " << data_day_icon_text[i]; } // start download of icons icon_job_success_list[0] = false; KIO::Job *job_icon = KIO::get( KUrl( dataFromIdentifier( 11 ) ), KIO::Reload, KIO::HideProgressInfo ); connect( job_icon, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( iconDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job_icon, SIGNAL( result( KJob * ) ), this, SLOT( iconDownloadFinished( KJob * ) ) ); icon_job_list[0] = job_icon; job_icon->start(); for ( i=0; i<7; i++ ) { icon_job_success_list[i+1] = false; job_icon = KIO::get( KUrl( dataFromIdentifier( 19 + i * 6 + 4 ) ), KIO::Reload, KIO::HideProgressInfo ); connect( job_icon, SIGNAL( data( KIO::Job *, const QByteArray & ) ), this, SLOT( iconDownloadedData( KIO::Job *, const QByteArray & ) ) ); connect( job_icon, SIGNAL( result( KJob * ) ), this, SLOT( iconDownloadFinished( KJob * ) ) ); icon_job_list[i+1] = job_icon; job_icon->start(); } data_update_time = KGlobal::locale()->formatTime( QTime::currentTime(), false, false ); // shot, quick and dirty sanity check of downloaded value, if they're empty we better display nothing than that if ( !data_current_temperature.contains(QRegExp( "[0-9]" )) || data_current_temperature.length() > 6 /* too long temperature string? -21.5 has length=5 */ ) { qDebug() << "Current temperature is invalid: Download didn't fail, but (all?) values are obviously invalid."; // data_update_time = ""; } emit ( data_fetched() ); } void Data_Provider::urlFollowCommandAppend( const QString command, const QString data, int identifier ) { if ( identifier < 0 || identifier > 7 ) return; url_follow_command_command[identifier] = command; url_follow_command_data_string[identifier] = data; } void Data_Provider::urlFollowCommandStartExecution() { urlFollowCommandRunning = 0; urlFollowCommandStart( url_follow_command_command[urlFollowCommandRunning], urlFollowCommandRunning ); } void Data_Provider::urlFollowCommandStart( const QString command, int identifier ) { if ( identifier < 0 || identifier > 7 ) return; delete url_follow_command_list[identifier]; url_follow_command_list[identifier] = new KProcess; connect( url_follow_command_list[identifier], SIGNAL( started() ), this, SLOT( urlFollowCommandStarted() ) ); connect( url_follow_command_list[identifier], SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( urlFollowCommandFinished( int, QProcess::ExitStatus ) ) ); if ( locale != "" ) url_follow_command_list[identifier]->setEnv( "LC_ALL", locale, true ); url_follow_command_list[identifier]->setOutputChannelMode( KProcess::SeparateChannels ); url_follow_command_list[identifier]->setShellCommand( QString( "sh -c " ) + KShell::quoteArg( command ) ); url_follow_command_list[identifier]->start(); } void Data_Provider::urlFollowCommandStarted() { url_follow_command_list[urlFollowCommandRunning]->write( rawDataFromUrl( url_follow_command_data_string[urlFollowCommandRunning] ) ); url_follow_command_list[urlFollowCommandRunning]->closeWriteChannel(); } void Data_Provider::urlFollowCommandFinished( int exitCode, QProcess::ExitStatus exitStatus ) { Q_UNUSED( exitCode ); Q_UNUSED( exitStatus ); urlFollowCommandRunning++; if ( urlFollowCommandRunning < 0 || urlFollowCommandRunning >= 7 ) { QString ret; QByteArray err; QByteArray arr; int i; for ( i=0; i<8; i++ ) { if ( ( i == 0 && urlc_follow_xml != "" ) || ( i == 1 && url1_follow_xml != "" ) || ( i == 2 && url2_follow_xml != "" ) || ( i == 3 && url3_follow_xml != "" ) || ( i == 4 && url4_follow_xml != "" ) || ( i == 5 && url5_follow_xml != "" ) || ( i == 6 && url6_follow_xml != "" ) || ( i == 7 && url7_follow_xml != "" ) ) { ret = ""; err = url_follow_command_list[i]->readAllStandardError(); if ( !err.isEmpty() ) qDebug() << "error running command on input data: " << err << endl; arr = url_follow_command_list[i]->readAllStandardOutput(); if ( !arr.isEmpty() ) { if ( encoding == "ascii" ) ret = QString::fromAscii( arr ); else if ( encoding == "latin1" ) ret = QString::fromLatin1( arr ); else if ( encoding == "local8bit" ) ret = QString::fromLocal8Bit( arr ); else if ( encoding == "ucs4" ) ret = QString::fromUtf8( arr ); else if ( encoding == "utf8" ) ret = QString::fromUtf8( arr ); else if ( encoding == "utf16" ) ret = QString::fromUtf8( arr ); else if ( encoding == "latin2" ) { QTextCodec *inp = QTextCodec::codecForName( "ISO8859-2" ); ret = inp->toUnicode(arr); } else ret = arr; } int pos; pos = ret.indexOf( "\r\n" ); if ( pos != -1 ) ret = ret.left(pos); pos = ret.indexOf( "\n" ); if ( pos != -1 ) ret = ret.left(pos); ret = ret.simplified(); ret = ret.trimmed(); if ( i == 0 ) urlc_new = ret; else if ( i == 1 ) url1_new = ret; else if ( i == 2 ) url2_new = ret; else if ( i == 3 ) url3_new = ret; else if ( i == 4 ) url4_new = ret; else if ( i == 5 ) url5_new = ret; else if ( i == 6 ) url6_new = ret; else if ( i == 7 ) url7_new = ret; } } url_follow_command_run = true; parseData(); } else { urlFollowCommandStart( url_follow_command_command[urlFollowCommandRunning], urlFollowCommandRunning ); } } void Data_Provider::dataCommandAppend( const QString command, const QString data, int identifier ) { if ( identifier < 0 || identifier > DATA_COMMAND_NUMBER ) return; data_command_command[identifier] = command; data_command_data_string[identifier] = data; } void Data_Provider::dataCommandStartExecution() { dataCommandRunning = 0; dataCommandStart( data_command_command[dataCommandRunning], dataCommandRunning ); } void Data_Provider::dataCommandStart( const QString command, int identifier ) { if ( identifier < 0 || identifier > DATA_COMMAND_NUMBER ) return; delete data_command_list[identifier]; data_command_list[identifier] = new KProcess; connect( data_command_list[identifier], SIGNAL( started() ), this, SLOT( dataCommandStarted() ) ); connect( data_command_list[identifier], SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( dataCommandFinished( int, QProcess::ExitStatus ) ) ); if ( locale != "" ) data_command_list[identifier]->setEnv( "LC_ALL", locale, true ); data_command_list[identifier]->setOutputChannelMode( KProcess::SeparateChannels ); data_command_list[identifier]->setShellCommand( QString( "sh -c " ) + KShell::quoteArg( command ) ); data_command_list[identifier]->start(); } void Data_Provider::dataCommandStarted() { data_command_list[dataCommandRunning]->write( rawDataFromUrl( data_command_data_string[dataCommandRunning] ) ); data_command_list[dataCommandRunning]->closeWriteChannel(); } void Data_Provider::dataCommandFinished( int exitCode, QProcess::ExitStatus exitStatus ) { Q_UNUSED( exitCode ); Q_UNUSED( exitStatus ); dataCommandRunning++; if ( dataCommandRunning < 0 || dataCommandRunning >= DATA_COMMAND_NUMBER ) { QString ret; QByteArray err; QByteArray arr; int i; for ( i=0; i<DATA_COMMAND_NUMBER; i++ ) { ret = ""; err = data_command_list[i]->readAllStandardError(); if ( !err.isEmpty() ) qDebug() << "error running command on input data: " << err << endl; arr = data_command_list[i]->readAllStandardOutput(); if ( !arr.isEmpty() ) { if ( encoding == "ascii" ) ret = QString::fromAscii( arr ); else if ( encoding == "latin1" ) ret = QString::fromLatin1( arr ); else if ( encoding == "local8bit" ) ret = QString::fromLocal8Bit( arr ); else if ( encoding == "ucs4" ) ret = QString::fromUtf8( arr ); else if ( encoding == "utf8" ) ret = QString::fromUtf8( arr ); else if ( encoding == "utf16" ) ret = QString::fromUtf8( arr ); else if ( encoding == "latin2" ) { QTextCodec *inp = QTextCodec::codecForName( "ISO8859-2" ); ret = inp->toUnicode( arr ); } else ret = arr; } int pos; pos = ret.indexOf( "\r\n" ); if ( pos != -1 ) ret = ret.left(pos); pos = ret.indexOf( "\n" ); if ( pos != -1 ) ret = ret.left(pos); ret = ret.simplified(); ret = ret.trimmed(); data_command_data_result[i] = ret; } data_command_run = true; parseData(); } else { dataCommandStart( data_command_command[dataCommandRunning], dataCommandRunning ); } } QString Data_Provider::dataFromIdentifier( int identifier ) { if ( identifier < 0 || identifier > DATA_COMMAND_NUMBER ) return ""; return data_command_data_result[identifier]; } void Data_Provider::dataDownloadedData( KIO::Job *job, const QByteArray &arr ) { int i; if ( data_job_list.size() != data_download_data_list.size() ) return; for ( i=0; i<data_job_list.size(); i++ ) { if ( job == data_job_list[i] ) { data_download_data_list[i] += arr; } } } void Data_Provider::dataDownloadFinished( KJob *job ) { int i; for ( i=0; i<data_job_list.size(); i++ ) { if ( job == (KJob *)data_job_list[i] ) { data_job_list[i] = NULL; if ( job->error() == 0 ) data_job_success_list[i] = true; } } bool all_null = true; for ( i=0; i<data_job_list.size(); i++ ) { if ( data_job_list[i] ) { all_null = false; break; } } if ( all_null ) { parseData(); } } void Data_Provider::urlFollowDownloadedData( KIO::Job *job, const QByteArray &arr ) { int i; if ( url_follow_job_list.size() != data_download_data_list.size() ) return; for ( i=0; i<data_download_data_list.size(); i++ ) { if ( job == url_follow_job_list[i] ) { data_download_data_list[i] += arr; } } } void Data_Provider::urlFollowDownloadFinished( KJob *job ) { int i; for ( i=0; i<url_follow_job_list.size(); i++ ) { if ( job == (KJob *)url_follow_job_list[i] ) { url_follow_job_list[i] = NULL; if ( job->error() == 0 ) url_follow_job_success_list[i] = true; } } bool all_null = true; for ( i=0; i<url_follow_job_list.size(); i++ ) { if ( url_follow_job_list[i] ) { all_null = false; break; } } if ( all_null ) { url_followed = true; parseData(); } } void Data_Provider::imageDownloadedData( KIO::Job *job, const QByteArray &arr ) { int i; for ( i=0; i<image_job_list.size(); i++ ) { if ( job == image_job_list[i] ) { data_image_list[i] += arr; } } } void Data_Provider::imageDownloadFinished( KJob *job ) { int i; for ( i=0; i<image_job_list.size(); i++ ) { if ( job == (KJob *)image_job_list[i] ) { if ( job->error() == 0 ) image_job_success_list[i] = true; image_job_list[i] = NULL; } } bool all_null = true; for ( i=0; i<image_job_list.size(); i++ ) { if ( image_job_list[i] ) { all_null = false; break; } } if ( all_null ) { data_custom_image_list.clear(); for ( i=0; i<image_job_success_list.size(); i++ ) { if ( image_job_success_list[i] ) { data_custom_image_list.push_back( data_image_list[i] ); } } data_image_list.clear(); emit( data_fetched() ); } } void Data_Provider::iconDownloadedData( KIO::Job *job, const QByteArray &arr ) { int i; for ( i=0; i<icon_job_list.size(); i++ ) { if ( job == icon_job_list[i] ) { data_icon_list[i] += arr; } } } void Data_Provider::iconDownloadFinished( KJob *job ) { int i; for ( i=0; i<icon_job_list.size(); i++ ) { if ( job == (KJob *)icon_job_list[i] ) { icon_job_list[i] = NULL; if ( job->error() == 0 ) icon_job_success_list[i] = true; } } bool all_null = true; for ( i=0; i<icon_job_list.size(); i++ ) { if ( icon_job_list[i] ) { all_null = false; break; } } if ( all_null ) { QImage icon_tmp = data_current_icon; if ( !data_current_icon.loadFromData( data_icon_list[0] ) || job->error() != 0 ) data_current_icon = icon_tmp; int j; for ( j=0; j<7; j++ ) { icon_tmp = data_day_icon[j]; if ( !data_day_icon[j].loadFromData( data_icon_list[j+1] ) || job->error() != 0 ) data_day_icon[j] = icon_tmp; } emit( data_fetched() ); } } const QByteArray &Data_Provider::rawDataFromUrl( const QString &url ) { if ( url == "urlc" ) return data_download_data_list[0]; else if ( url == "url1" ) return data_download_data_list[1]; else if ( url == "url2" ) return data_download_data_list[2]; else if ( url == "url3" ) return data_download_data_list[3]; else if ( url == "url4" ) return data_download_data_list[4]; else if ( url == "url5" ) return data_download_data_list[5]; else if ( url == "url6" ) return data_download_data_list[6]; else if ( url == "url7" ) return data_download_data_list[7]; return data_download_data_list[0]; } #include "plasma-cwp-data-provider.moc"
pkt/plasma-widget-cwp-1.5.14-el
plasma-cwp-data-provider.cpp
C++
gpl-3.0
60,125
/* * This file is part of the Code::Blocks IDE and licensed under the GNU General Public License, version 3 * http://www.gnu.org/licenses/gpl-3.0.html * * $Revision$ * $Id$ * $HeadURL$ */ #include <sdk.h> #include "gdb_driver.h" #include "gdb_commands.h" #include "debuggeroptionsdlg.h" #include "debuggerstate.h" #include <cbdebugger_interfaces.h> #include <manager.h> #include <macrosmanager.h> #include <configmanager.h> #include <globals.h> #include <infowindow.h> #ifdef __WXMSW__ // for Registry detection of Cygwin #include "wx/msw/wrapwin.h" // Wraps windows.h #endif // the ">>>>>>" is a hack: sometimes, especially when watching uninitialized char* // some random control codes in the stream (like 'delete') will mess-up our prompt and the debugger // will seem like frozen (only "stop" button available). Using this dummy prefix, // we allow for a few characters to be "eaten" this way and still get our // expected prompt back. #define GDB_PROMPT _T("cb_gdb:") #define FULL_GDB_PROMPT _T(">>>>>>") GDB_PROMPT //[Switching to thread 2 (Thread 1082132832 (LWP 12298))]#0 0x00002aaaac5a2aca in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0 static wxRegEx reThreadSwitch(_T("^\\[Switching to thread .*\\]#0[ \t]+(0x[A-Fa-f0-9]+) in (.*) from (.*)")); static wxRegEx reThreadSwitch2(_T("^\\[Switching to thread .*\\]#0[ \t]+(0x[A-Fa-f0-9]+) in (.*) from (.*):([0-9]+)")); // Regular expresion for breakpoint. wxRegEx don't want to recognize '?' command, so a bit more general rule is used // here. // ([A-Za-z]*[:]*) corresponds to windows disk name. Under linux it can be none empty in crosscompiling sessions; // ([^:]+) corresponds to the path in linux or to the path within windows disk in windows to current file; // ([0-9]+) corresponds to line number in current file; // (0x[0-9A-Fa-f]+) correponds to current memory address. static wxRegEx reBreak(_T("\032*([A-Za-z]*[:]*)([^:]+):([0-9]+):[0-9]+:[begmidl]+:(0x[0-9A-Fa-f]+)")); static wxRegEx reBreak2(_T("^(0x[A-Fa-f0-9]+) in (.*) from (.*)")); static wxRegEx reBreak3(_T("^(0x[A-Fa-f0-9]+) in (.*)")); // Catchpoint 1 (exception thrown), 0x00007ffff7b982b0 in __cxa_throw () from /usr/lib/gcc/x86_64-pc-linux-gnu/4.4.4/libstdc++.so.6 static wxRegEx reCatchThrow(_T("^Catchpoint ([0-9]+) \\(exception thrown\\), (0x[0-9a-f]+) in (.+) from (.+)$")); // Catchpoint 1 (exception thrown), 0x00401610 in __cxa_throw () static wxRegEx reCatchThrowNoFile(_T("^Catchpoint ([0-9]+) \\(exception thrown\\), (0x[0-9a-f]+) in (.+)$")); // easily match cygwin paths //static wxRegEx reCygwin(_T("/cygdrive/([A-Za-z])/")); // Pending breakpoint "C:/Devel/libs/irr_svn/source/Irrlicht/CSceneManager.cpp:1077" resolved #ifdef __WXMSW__ static wxRegEx rePendingFound(_T("^Pending[ \t]+breakpoint[ \t]+[\"]+([A-Za-z]:)([^:]+):([0-9]+)\".*")); #else static wxRegEx rePendingFound(_T("^Pending[ \t]+breakpoint[ \t]+[\"]+([^:]+):([0-9]+)\".*")); #endif // Breakpoint 2, irr::scene::CSceneManager::getSceneNodeFromName (this=0x3fa878, name=0x3fbed8 "MainLevel", start=0x3fa87c) at CSceneManager.cpp:1077 static wxRegEx rePendingFound1(_T("^Breakpoint[ \t]+([0-9]+),.*")); // Temporary breakpoint 2, main () at /path/projects/tests/main.cpp:136 static wxRegEx reTempBreakFound(wxT("^[Tt]emporary[ \t]breakpoint[ \t]([0-9]+),.*")); // [Switching to Thread -1234655568 (LWP 18590)] // [New Thread -1234655568 (LWP 18590)] static wxRegEx reChildPid1(_T("Thread[ \t]+[xA-Fa-f0-9-]+[ \t]+\\(LWP ([0-9]+)\\)]")); // MinGW GDB 6.8 and later // [New Thread 2684.0xf40] or [New thread 2684.0xf40] static wxRegEx reChildPid2(_T("\\[New [tT]hread[ \t]+[0-9]+\\.[xA-Fa-f0-9-]+\\]")); static wxRegEx reInferiorExited(wxT("^\\[Inferior[ \\t].+[ \\t]exited normally\\]$"), wxRE_EXTENDED); static wxRegEx reInferiorExitedWithCode(wxT("^\\[[Ii]nferior[ \\t].+[ \\t]exited[ \\t]with[ \\t]code[ \\t]([0-9]+)\\]$"), wxRE_EXTENDED); GDB_driver::GDB_driver(DebuggerGDB* plugin) : DebuggerDriver(plugin), m_CygwinPresent(false), m_BreakOnEntry(false), m_ManualBreakOnEntry(false), m_IsStarted(false), m_GDBVersionMajor(0), m_GDBVersionMinor(0), m_attachedToProcess(false), m_catchThrowIndex(-1) { //ctor m_needsUpdate = false; m_forceUpdate = false; } GDB_driver::~GDB_driver() { //dtor } wxString GDB_driver::GetCommandLine(const wxString& debugger, const wxString& debuggee, const wxString &userArguments) { wxString cmd; cmd << debugger; if (m_pDBG->GetActiveConfigEx().GetFlag(DebuggerConfiguration::DisableInit)) cmd << _T(" -nx"); // don't run .gdbinit cmd << _T(" -fullname"); // report full-path filenames when breaking cmd << _T(" -quiet"); // don't display version on startup cmd << wxT(" ") << userArguments; cmd << _T(" -args ") << debuggee; return cmd; } wxString GDB_driver::GetCommandLine(const wxString& debugger, cb_unused int pid, const wxString &userArguments) { wxString cmd; cmd << debugger; if (m_pDBG->GetActiveConfigEx().GetFlag(DebuggerConfiguration::DisableInit)) cmd << _T(" -nx"); // don't run .gdbinit cmd << _T(" -fullname"); // report full-path filenames when breaking cmd << _T(" -quiet"); // don't display version on startup cmd << wxT(" ") << userArguments; return cmd; } void GDB_driver::SetTarget(ProjectBuildTarget* target) { // init for remote debugging m_pTarget = target; } void GDB_driver::Prepare(bool isConsole, int printElements, const RemoteDebugging &remoteDebugging) { // default initialization // for the possibility that the program to be debugged is compiled under Cygwin if (platform::windows) DetectCygwinMount(); // make sure we 're using the prompt that we know and trust ;) QueueCommand(new DebuggerCmd(this, wxString("set prompt ") + FULL_GDB_PROMPT)); // debugger version QueueCommand(new DebuggerCmd(this, "show version")); // no confirmation QueueCommand(new DebuggerCmd(this, "set confirm off")); // no wrapping lines QueueCommand(new DebuggerCmd(this, "set width 0")); // no pagination QueueCommand(new DebuggerCmd(this, "set height 0")); // allow pending breakpoints QueueCommand(new DebuggerCmd(this, "set breakpoint pending on")); // show pretty function names in disassembly QueueCommand(new DebuggerCmd(this, "set print asm-demangle on")); // unwind stack on signal QueueCommand(new DebuggerCmd(this, "set unwindonsignal on")); // disable result string truncations QueueCommand(new DebuggerCmd(this, wxString::Format("set print elements %d", printElements))); // Make sure backtraces use absolute paths, so it is more reliable to find where the sources // file when trying to open it in the editor. QueueCommand(new DebuggerCmd(this, "set filename-display absolute")); if (platform::windows && isConsole) QueueCommand(new DebuggerCmd(this, "set new-console on")); flavour = m_pDBG->GetActiveConfigEx().GetDisassemblyFlavorCommand(); QueueCommand(new DebuggerCmd(this, flavour)); if (m_pDBG->GetActiveConfigEx().GetFlag(DebuggerConfiguration::CatchExceptions)) { m_catchThrowIndex = -1; // catch exceptions QueueCommand(new GdbCmd_SetCatch(this, "throw", &m_catchThrowIndex)); } // pass user init-commands wxString init = m_pDBG->GetActiveConfigEx().GetInitCommands(); MacrosManager *macrosManager = Manager::Get()->GetMacrosManager(); macrosManager->ReplaceMacros(init); // commands are passed in one go, in case the user defines functions in there // or else it would lock up... if (!init.empty()) QueueCommand(new DebuggerCmd(this, init)); // add search dirs for (unsigned int i = 0; i < m_Dirs.GetCount(); ++i) QueueCommand(new GdbCmd_AddSourceDir(this, m_Dirs[i])); // set arguments if (!m_Args.IsEmpty()) QueueCommand(new DebuggerCmd(this, "set args " + m_Args)); // Send additional gdb commands before establishing remote connection. // These are executed no matter if doing remote debugging or not. if (!remoteDebugging.additionalCmdsBefore.IsEmpty()) { wxArrayString initCmds = GetArrayFromString(remoteDebugging.additionalCmdsBefore, _T('\n')); for (unsigned int i = 0; i < initCmds.GetCount(); ++i) { macrosManager->ReplaceMacros(initCmds[i]); QueueCommand(new DebuggerCmd(this, initCmds[i])); } } if (!remoteDebugging.additionalShellCmdsBefore.IsEmpty()) { wxArrayString initCmds = GetArrayFromString(remoteDebugging.additionalShellCmdsBefore, _T('\n')); for (unsigned int i = 0; i < initCmds.GetCount(); ++i) { macrosManager->ReplaceMacros(initCmds[i]); QueueCommand(new DebuggerCmd(this, "shell " + initCmds[i])); } } // if performing remote debugging, now is a good time to try and connect to the target :) m_isRemoteDebugging = remoteDebugging.IsOk(); if (m_isRemoteDebugging) { if (remoteDebugging.connType == RemoteDebugging::Serial) QueueCommand(new GdbCmd_RemoteBaud(this, remoteDebugging.serialBaud)); QueueCommand(new GdbCmd_RemoteTarget(this, &remoteDebugging)); } // run per-target additional commands (remote debugging) // moved after connection to remote target (if any) if (!remoteDebugging.additionalCmds.IsEmpty()) { wxArrayString initCmds = GetArrayFromString(remoteDebugging.additionalCmds, _T('\n')); for (unsigned int i = 0; i < initCmds.GetCount(); ++i) { macrosManager->ReplaceMacros(initCmds[i]); QueueCommand(new DebuggerCmd(this, initCmds[i])); } } if (!remoteDebugging.additionalShellCmdsAfter.IsEmpty()) { wxArrayString initCmds = GetArrayFromString(remoteDebugging.additionalShellCmdsAfter, _T('\n')); for (unsigned int i = 0; i < initCmds.GetCount(); ++i) { macrosManager->ReplaceMacros(initCmds[i]); QueueCommand(new DebuggerCmd(this, "shell " + initCmds[i])); } } } // Cygwin check code #ifdef __WXMSW__ enum{ BUFSIZE = 64 }; // routines to handle cygwin compiled programs on a Windows compiled C::B IDE void GDB_driver::DetectCygwinMount(void) { LONG lRegistryAPIresult; HKEY hKey_CU; HKEY hKey_LM; TCHAR szCygwinRoot[BUFSIZE]; DWORD dwBufLen=BUFSIZE*sizeof(TCHAR); // checking if cygwin mounts are present under HKCU lRegistryAPIresult = RegOpenKeyEx( HKEY_CURRENT_USER, TEXT("Software\\Cygnus Solutions\\Cygwin\\mounts v2"), 0, KEY_QUERY_VALUE, &hKey_CU ); if ( lRegistryAPIresult == ERROR_SUCCESS ) { // try to readback cygwin root (might not exist!) lRegistryAPIresult = RegQueryValueEx( hKey_CU, TEXT("cygdrive prefix"), NULL, NULL, (LPBYTE) szCygwinRoot, &dwBufLen); } // lRegistryAPIresult can be erroneous for two reasons: // 1.) Cygwin entry is not present (could not be opened) in HKCU // 2.) "cygdrive prefix" is not present (could not be read) in HKCU if ( lRegistryAPIresult != ERROR_SUCCESS ) { // Now check if probably present under HKLM lRegistryAPIresult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2"), 0, KEY_QUERY_VALUE, &hKey_LM ); if ( lRegistryAPIresult != ERROR_SUCCESS ) { // cygwin definitely not installed m_CygwinPresent = false; return; } // try to readback cygwin root (now it really should exist here) lRegistryAPIresult = RegQueryValueEx( hKey_LM, TEXT("cygdrive prefix"), NULL, NULL, (LPBYTE) szCygwinRoot, &dwBufLen); } // handle a possible query error if ( (lRegistryAPIresult != ERROR_SUCCESS) || (dwBufLen > BUFSIZE*sizeof(TCHAR)) ) { // bit of an assumption, but we won't be able to find the root without it m_CygwinPresent = false; return; } // close opened keys RegCloseKey( hKey_CU ); // ignore key close errors RegCloseKey( hKey_LM ); // ignore key close errors m_CygwinPresent = true; // if we end up here all was OK m_CygdrivePrefix = (szCygwinRoot); // convert to wxString type for later use } void GDB_driver::CorrectCygwinPath(wxString& path) { unsigned int i=0, EscCount=0; // preserve any escape characters at start of path - this is true for // breakpoints - value is 2, but made dynamic for safety as we // are only checking for the CDprefix not any furthur correctness if (path.GetChar(0)==g_EscapeChar) { while ( (i<path.Len()) && (path.GetChar(i)==g_EscapeChar) ) { // get character EscCount++; i++; } } // prepare to convert to a valid path if Cygwin is being used // step over the escape characters wxString PathWithoutEsc(path); PathWithoutEsc.Remove(0, EscCount); if (PathWithoutEsc.StartsWith(m_CygdrivePrefix)) { // remove cygwin prefix if (m_CygdrivePrefix.EndsWith(_T("/"))) // for the case "/c/path" PathWithoutEsc.Remove(0, m_CygdrivePrefix.Len() ); else // for cases e.g. "/cygdrive/c/path" PathWithoutEsc.Remove(0, m_CygdrivePrefix.Len()+1); // insert ':' after drive label by reading and removing drive the label // and adding ':' and the drive label back wxString DriveLetter = PathWithoutEsc.GetChar(0); PathWithoutEsc.Replace(DriveLetter, DriveLetter + _T(":"), false); } // Compile corrected path path = wxEmptyString; for (i=0; i<EscCount; i++) path += g_EscapeChar; path += PathWithoutEsc; } #else void GDB_driver::DetectCygwinMount(void){/* dummy */} void GDB_driver::CorrectCygwinPath(cb_unused wxString& path){/* dummy */} #endif #ifdef __WXMSW__ bool GDB_driver::UseDebugBreakProcess() { return !m_isRemoteDebugging; } #endif wxString GDB_driver::GetDisassemblyFlavour(void) { return flavour; } // Only called from DebuggerGDB::Debug // breakOnEntry was always false. Changed by HC. void GDB_driver::Start(bool breakOnEntry) { m_attachedToProcess = false; ResetCursor(); // reset other states GdbCmd_DisassemblyInit::Clear(); if (Manager::Get()->GetDebuggerManager()->UpdateDisassembly()) { cbDisassemblyDlg *disassembly_dialog = Manager::Get()->GetDebuggerManager()->GetDisassemblyDialog(); disassembly_dialog->Clear(cbStackFrame()); } m_BreakOnEntry = breakOnEntry && !m_isRemoteDebugging; // if performing remote debugging, use "continue" command if (!m_pDBG->GetActiveConfigEx().GetFlag(DebuggerConfiguration::DoNotRun)) { m_ManualBreakOnEntry = !m_isRemoteDebugging; // start the process if (breakOnEntry) QueueCommand(new GdbCmd_Start(this, m_isRemoteDebugging ? _T("continue") : _T("start"))); else { // if breakOnEntry is not set, we need to use 'run' to make gdb stop at a breakpoint at first instruction m_ManualBreakOnEntry=false; // must be reset or gdb does not stop at first breakpoint QueueCommand(new GdbCmd_Start(this, m_isRemoteDebugging ? _T("continue") : _T("run"))); } m_IsStarted = true; } } // Start void GDB_driver::Stop() { ResetCursor(); if (m_pDBG->IsAttachedToProcess()) QueueCommand(new DebuggerCmd(this, wxT("kill"))); QueueCommand(new DebuggerCmd(this, _T("quit"))); m_IsStarted = false; m_attachedToProcess = false; } void GDB_driver::Continue() { ResetCursor(); if (m_IsStarted) QueueCommand(new GdbCmd_Continue(this)); else { // if performing remote debugging, use "continue" command if (m_isRemoteDebugging) QueueCommand(new GdbCmd_Continue(this)); else QueueCommand(new GdbCmd_Start(this, m_ManualBreakOnEntry ? wxT("start") : wxT("run"))); m_ManualBreakOnEntry = false; m_IsStarted = true; m_attachedToProcess = false; } } void GDB_driver::Step() { ResetCursor(); QueueCommand(new DebuggerContinueBaseCmd(this, _T("next"))); } void GDB_driver::StepInstruction() { ResetCursor(); QueueCommand(new GdbCmd_StepInstruction(this)); } void GDB_driver::StepIntoInstruction() { ResetCursor(); QueueCommand(new GdbCmd_StepIntoInstruction(this)); } void GDB_driver::StepIn() { ResetCursor(); QueueCommand(new DebuggerContinueBaseCmd(this, _T("step"))); } void GDB_driver::StepOut() { ResetCursor(); QueueCommand(new DebuggerContinueBaseCmd(this, _T("finish"))); } void GDB_driver::SetNextStatement(const wxString& filename, int line) { ResetCursor(); QueueCommand(new DebuggerCmd(this, wxString::Format(wxT("tbreak %s:%d"), filename.c_str(), line))); QueueCommand(new DebuggerContinueBaseCmd(this, wxString::Format(wxT("jump %s:%d"), filename.c_str(), line))); } void GDB_driver::Backtrace() { QueueCommand(new GdbCmd_Backtrace(this)); } void GDB_driver::Disassemble() { if (platform::windows) QueueCommand(new GdbCmd_DisassemblyInit(this, flavour)); else QueueCommand(new GdbCmd_DisassemblyInit(this)); } void GDB_driver::CPURegisters() { if (platform::windows) QueueCommand(new GdbCmd_InfoRegisters(this, flavour)); else QueueCommand(new GdbCmd_InfoRegisters(this)); } void GDB_driver::SwitchToFrame(size_t number) { ResetCursor(); QueueCommand(new DebuggerCmd(this, wxString(_T("frame ")) << number)); } void GDB_driver::SetVarValue(const wxString& var, const wxString& value) { const wxString &cleanValue=CleanStringValue(value); QueueCommand(new DebuggerCmd(this, wxString::Format(_T("set variable %s=%s"), var.c_str(), cleanValue.c_str()))); } void GDB_driver::SetMemoryRangeValue(uint64_t addr, const wxString& value) { const size_t size = value.size(); if(size == 0) return; wxString dataStr = wxT("{"); const wxCharBuffer &data = value.To8BitData(); for (size_t i = 0; i < size; i++) { if (i != 0) dataStr << wxT(","); dataStr << wxString::Format(wxT("0x%x"), uint8_t(data[i])); } dataStr << wxT("}"); wxString commandStr; #ifdef __WXMSW__ commandStr.Printf(wxT("set {char [%ul]} 0x%" PRIx64 "="), size, addr); #else commandStr.Printf(wxT("set {char [%zu]} 0x%" PRIx64 "="), size, addr); #endif // __WXMSW__ commandStr << dataStr; QueueCommand(new DebuggerCmd(this, commandStr)); } void GDB_driver::MemoryDump() { QueueCommand(new GdbCmd_ExamineMemory(this)); } void GDB_driver::RunningThreads() { if (Manager::Get()->GetDebuggerManager()->UpdateThreads()) QueueCommand(new GdbCmd_Threads(this)); } void GDB_driver::InfoFrame() { QueueCommand(new DebuggerInfoCmd(this, _T("info frame"), _("Selected frame"))); } void GDB_driver::InfoDLL() { if (platform::windows) QueueCommand(new DebuggerInfoCmd(this, _T("info dll"), _("Loaded libraries"))); else QueueCommand(new DebuggerInfoCmd(this, _T("info sharedlibrary"), _("Loaded libraries"))); } void GDB_driver::InfoFiles() { QueueCommand(new DebuggerInfoCmd(this, _T("info files"), _("Files and targets"))); } void GDB_driver::InfoFPU() { QueueCommand(new DebuggerInfoCmd(this, _T("info float"), _("Floating point unit"))); } void GDB_driver::InfoSignals() { QueueCommand(new DebuggerInfoCmd(this, _T("info signals"), _("Signals handling"))); } void GDB_driver::EnableCatchingThrow(bool enable) { if (enable) QueueCommand(new GdbCmd_SetCatch(this, wxT("throw"), &m_catchThrowIndex)); else if (m_catchThrowIndex != -1) { QueueCommand(new DebuggerCmd(this, wxString::Format(wxT("delete %d"), m_catchThrowIndex))); m_catchThrowIndex = -1; } } void GDB_driver::SwitchThread(size_t threadIndex) { ResetCursor(); QueueCommand(new DebuggerCmd(this, wxString::Format(_T("thread %lu"), static_cast<unsigned long>(threadIndex)))); if (Manager::Get()->GetDebuggerManager()->UpdateBacktrace()) QueueCommand(new GdbCmd_Backtrace(this)); } void GDB_driver::AddBreakpoint(cb::shared_ptr<DebuggerBreakpoint> bp) { if (bp->type == DebuggerBreakpoint::bptData) QueueCommand(new GdbCmd_AddDataBreakpoint(this, bp)); //Workaround for GDB to break on C++ constructor/destructor else { if (bp->func.IsEmpty() && !bp->lineText.IsEmpty()) { wxRegEx reCtorDtor(_T("([0-9A-z_]+)::([~]?)([0-9A-z_]+)[ \t\(]*")); if (reCtorDtor.Matches(bp->lineText)) { wxString strBase = reCtorDtor.GetMatch(bp->lineText, 1); wxString strDtor = reCtorDtor.GetMatch(bp->lineText, 2); wxString strMethod = reCtorDtor.GetMatch(bp->lineText, 3); if (strBase.IsSameAs(strMethod)) { bp->func = strBase; bp->func << _T("::"); bp->func << strDtor; bp->func << strMethod; // if (bp->temporary) // bp->temporary = false; NotifyCursorChanged(); // to force breakpoints window update } } } //end GDB workaround QueueCommand(new GdbCmd_AddBreakpoint(this, bp)); } } void GDB_driver::RemoveBreakpoint(cb::shared_ptr<DebuggerBreakpoint> bp) { if (bp && bp->index != -1) QueueCommand(new GdbCmd_RemoveBreakpoint(this, bp)); } void GDB_driver::EvaluateSymbol(const wxString& symbol, const wxRect& tipRect) { QueueCommand(new GdbCmd_FindTooltipType(this, symbol, tipRect)); } void GDB_driver::UpdateWatches(cb::shared_ptr<GDBWatch> localsWatch, cb::shared_ptr<GDBWatch> funcArgsWatch, WatchesContainer &watches, bool ignoreAutoUpdate) { if (!m_FileName.IsSameAs(m_Cursor.file)) { m_FileName = m_Cursor.file; m_pDBG->DetermineLanguage(); } bool updateWatches = false; if (localsWatch && (localsWatch->IsAutoUpdateEnabled() || ignoreAutoUpdate)) { QueueCommand(new GdbCmd_LocalsFuncArgs(this, localsWatch, true)); updateWatches = true; } if (funcArgsWatch && (funcArgsWatch->IsAutoUpdateEnabled() || ignoreAutoUpdate)) { QueueCommand(new GdbCmd_LocalsFuncArgs(this, funcArgsWatch, false)); updateWatches = true; } for (WatchesContainer::iterator it = watches.begin(); it != watches.end(); ++it) { WatchesContainer::reference watch = *it; if (watch->IsAutoUpdateEnabled() || ignoreAutoUpdate) { QueueCommand(new GdbCmd_FindWatchType(this, watch)); updateWatches = true; } } if (updateWatches) { // run this action-only command to update the tree QueueCommand(new DbgCmd_UpdateWindow(this, cbDebuggerPlugin::DebugWindows::Watches)); } } void GDB_driver::UpdateMemoryRangeWatches(MemoryRangeWatchesContainer &watches, bool ignoreAutoUpdate) { bool updateWatches = false; for (cb::shared_ptr<GDBMemoryRangeWatch> &watch : watches) { if (watch->IsAutoUpdateEnabled() || ignoreAutoUpdate) { QueueCommand(new GdbCmd_MemoryRangeWatch(this, watch)); updateWatches = true; } } if (updateWatches) QueueCommand(new DbgCmd_UpdateWindow(this, cbDebuggerPlugin::DebugWindows::MemoryRange)); } void GDB_driver::UpdateWatch(const cb::shared_ptr<GDBWatch> &watch) { QueueCommand(new GdbCmd_FindWatchType(this, watch)); QueueCommand(new DbgCmd_UpdateWindow(this, cbDebuggerPlugin::DebugWindows::Watches)); } void GDB_driver::UpdateMemoryRangeWatch(const cb::shared_ptr<GDBMemoryRangeWatch> &watch) { QueueCommand(new GdbCmd_MemoryRangeWatch(this, watch)); QueueCommand(new DbgCmd_UpdateWindow(this, cbDebuggerPlugin::DebugWindows::MemoryRange)); } void GDB_driver::UpdateWatchLocalsArgs(cb::shared_ptr<GDBWatch> const &watch, bool locals) { QueueCommand(new GdbCmd_LocalsFuncArgs(this, watch, locals)); QueueCommand(new DbgCmd_UpdateWindow(this, cbDebuggerPlugin::DebugWindows::Watches)); } void GDB_driver::Attach(int pid) { m_IsStarted = true; m_attachedToProcess = true; SetChildPID(pid); QueueCommand(new GdbCmd_AttachToProcess(this, pid)); } void GDB_driver::Detach() { QueueCommand(new GdbCmd_Detach(this)); } void GDB_driver::ParseOutput(const wxString& output) { m_Cursor.changed = false; if (platform::windows && m_ChildPID == 0) { if (reChildPid2.Matches(output)) // [New Thread 2684.0xf40] or [New thread 2684.0xf40] { wxString pidStr = reChildPid2.GetMatch(output, 0); pidStr = pidStr.BeforeFirst(_T('.')); //[New Thread 2684.0xf40] -> [New Thread 2684 pidStr = pidStr.AfterFirst(_T('d')); //[New Thread 2684 -> 2684 long pid = 0; pidStr.ToLong(&pid); SetChildPID(pid); m_pDBG->Log(wxString::Format(_("Child process PID: %ld"), pid)); } } else if (!platform::windows && m_ChildPID == 0) { if (reChildPid1.Matches(output)) // [Switching to Thread -1234655568 (LWP 18590)] { wxString pidStr = reChildPid1.GetMatch(output, 1); long pid = 0; pidStr.ToLong(&pid); SetChildPID(pid); m_pDBG->Log(wxString::Format(_("Child process PID: %ld"), pid)); } } if ( output.StartsWith(_T("gdb: ")) || output.StartsWith(_T("warning: ")) || output.StartsWith(_T("Warning: ")) || output.StartsWith(_T("ContinueDebugEvent ")) ) { return; } static wxString buffer; buffer << output << _T('\n'); m_pDBG->DebugLog(output); int idx = buffer.First(GDB_PROMPT); const bool foundPrompt = (idx != wxNOT_FOUND); if (!foundPrompt) { // don't uncomment the following line // m_ProgramIsStopped is set to false in DebuggerDriver::RunQueue() // m_ProgramIsStopped = false; return; // come back later } m_QueueBusy = false; int changeFrameAddr = 0 ; DebuggerCmd* cmd = CurrentCommand(); if (cmd) { // DebugLog(wxString::Format(_T("Command parsing output (cmd: %s): %s"), cmd->m_Cmd.c_str(), buffer.Left(idx).c_str())); RemoveTopCommand(false); buffer.Remove(idx); // remove the '>>>>>>' part of the prompt (or what's left of it) int cnt = 6; // max 6 '>' while (!buffer.empty() && buffer.Last() == _T('>') && cnt--) buffer.RemoveLast(); if (!buffer.empty() && buffer.Last() == _T('\n')) buffer.RemoveLast(); cmd->ParseOutput(buffer.Left(idx)); //We do NOT want default output processing for a changed frame as it can result //in disassembly being done for a non-current location, since some of the frame //response lines are in the pattern of breakpoint output. GdbCmd_ChangeFrame *changeFrameCmd = dynamic_cast<GdbCmd_ChangeFrame*>(cmd); if (changeFrameCmd) changeFrameAddr = changeFrameCmd->AddrChgMode(); delete cmd; RunQueue(); } m_needsUpdate = false; m_forceUpdate = false; // non-command messages (e.g. breakpoint hits) // break them up in lines wxArrayString lines = GetArrayFromString(buffer, _T('\n')); for (unsigned int i = 0; i < lines.GetCount(); ++i) { // Log(_T("DEBUG: ") + lines[i]); // write it in the full debugger log // Check for possibility of a cygwin compiled program // convert to valid path if (platform::windows && m_CygwinPresent) CorrectCygwinPath(lines.Item(i)); // log GDB's version if (lines[i].StartsWith(_T("GNU gdb"))) { // it's the gdb banner. Just display the version and "eat" the rest m_pDBG->Log(_("Debugger name and version: ") + lines[i]); // keep major and minor version numbers handy wxRegEx re(_T("([0-9.]+)")); if (!re.Matches(lines[i])) { m_pDBG->Log(_T("Unable to determine the version of gdb")); break; } wxString major = re.GetMatch(lines[i],0); wxString minor = major; major = major.BeforeFirst(_T('.')); // 6.3.2 -> 6 minor = minor.AfterFirst(_T('.')); // 6.3.2 -> 3.2 minor = minor.BeforeFirst(_T('.')); // 3.2 -> 3 major.ToLong(&m_GDBVersionMajor); minor.ToLong(&m_GDBVersionMinor); // wxString log; // log.Printf(_T("Line: %s\nMajor: %s (%d)\nMinor: %s (%d)"), // lines[i].c_str(), // major.c_str(), // m_GDBVersionMajor, // minor.c_str(), // m_GDBVersionMinor); // m_pDBG->Log(log); break; } // Is the program exited? else if ( lines[i].StartsWith(_T("Error creating process")) || lines[i].StartsWith(_T("Program exited")) || lines[i].StartsWith(wxT("Program terminated with signal")) || lines[i].StartsWith(wxT("During startup program exited")) || lines[i].Contains(_T("program is not being run")) || lines[i].Contains(_T("Target detached")) || reInferiorExited.Matches(lines[i]) || reInferiorExitedWithCode.Matches(lines[i]) ) { m_pDBG->Log(lines[i]); m_ProgramIsStopped = true; QueueCommand(new DebuggerCmd(this, _T("quit"))); m_IsStarted = false; } // no debug symbols? else if (lines[i].Contains(_T("(no debugging symbols found)"))) m_pDBG->Log(lines[i]); // signal else if (lines[i].StartsWith(_T("Program received signal SIG"))) { m_ProgramIsStopped = true; m_QueueBusy = false; if ( lines[i].StartsWith(_T("Program received signal SIGINT")) || lines[i].StartsWith(_T("Program received signal SIGTRAP")) || lines[i].StartsWith(_T("Program received signal SIGSTOP")) ) { // these are break/trace signals, just log them Log(lines[i]); } else { Log(lines[i]); m_pDBG->BringCBToFront(); if (Manager::Get()->GetDebuggerManager()->ShowBacktraceDialog()) m_forceUpdate = true; InfoWindow::Display(_("Signal received"), _T("\n\n") + lines[i] + _T("\n\n")); m_needsUpdate = true; // the backtrace will be generated when NotifyPlugins() is called // and only if the backtrace window is shown } } // general errors // we don't deal with them, just relay them back to the user else if ( lines[i].StartsWith(_T("Error ")) || lines[i].StartsWith(_T("No such")) || lines[i].StartsWith(_T("Cannot evaluate")) ) { m_pDBG->Log(lines[i]); } else if ( (lines[i].StartsWith(_T("Cannot find bounds of current function"))) || (lines[i].StartsWith(_T("No stack"))) ) { m_pDBG->Log(lines[i]); m_ProgramIsStopped = true; } // pending breakpoint resolved? // e.g. // Pending breakpoint "C:/Devel/libs/irr_svn/source/Irrlicht/CSceneManager.cpp:1077" resolved // Breakpoint 2, irr::scene::CSceneManager::getSceneNodeFromName (this=0x3fa878, name=0x3fbed8 "MainLevel", start=0x3fa87c) at CSceneManager.cpp:1077 else if (lines[i].StartsWith(_T("Pending breakpoint "))) { m_pDBG->Log(lines[i]); // we face a problem here: // gdb sets a *new* breakpoint when the pending address is resolved. // this means we must update the breakpoint index we have stored // or else we can never remove this (because the breakpoint index doesn't match)... // Pending breakpoint "C:/Devel/libs/irr_svn/source/Irrlicht/CSceneManager.cpp:1077" resolved wxString bpstr = lines[i]; if (rePendingFound.Matches(bpstr)) { // there are cases where 'newbpstr' is not the next message // e.g. [Switching to thread...] // so we 'll loop over lines starting with [ // Breakpoint 2, irr::scene::CSceneManager::getSceneNodeFromName (this=0x3fa878, name=0x3fbed8 "MainLevel", start=0x3fa87c) at CSceneManager.cpp:1077 wxString newbpstr = lines[++i]; while (i < lines.GetCount() - 1 && newbpstr.StartsWith(_T("["))) newbpstr = lines[++i]; if (rePendingFound1.Matches(newbpstr)) { // m_pDBG->Log(_T("MATCH")); wxString file; wxString lineStr; if (platform::windows) { file = rePendingFound.GetMatch(bpstr, 1) + rePendingFound.GetMatch(bpstr, 2); lineStr = rePendingFound.GetMatch(bpstr, 3); } else { file = rePendingFound.GetMatch(bpstr, 1); lineStr = rePendingFound.GetMatch(bpstr, 2); } file = UnixFilename(file); // m_pDBG->Log(wxString::Format(_T("file: %s, line: %s"), file.c_str(), lineStr.c_str())); long line; lineStr.ToLong(&line); DebuggerState& state = m_pDBG->GetState(); int bpindex = state.HasBreakpoint(file, line - 1, false); cb::shared_ptr<DebuggerBreakpoint> bp = state.GetBreakpoint(bpindex); if (bp) { // m_pDBG->Log(_T("Found BP!!! Updating index...")); long index; wxString indexStr = rePendingFound1.GetMatch(newbpstr, 1); indexStr.ToLong(&index); // finally! update the breakpoint index bp->index = index; } } } } else if (lines[i].StartsWith(wxT("Breakpoint "))) { if (rePendingFound1.Matches(lines[i])) { long index; rePendingFound1.GetMatch(lines[i],1).ToLong(&index); DebuggerState& state = m_pDBG->GetState(); cb::shared_ptr<DebuggerBreakpoint> bp = state.GetBreakpointByNumber(index); if (bp && bp->wantsCondition) { bp->wantsCondition = false; QueueCommand(new GdbCmd_AddBreakpointCondition(this, bp)); m_needsUpdate = true; } } } else if (lines[i].StartsWith(wxT("Temporary breakpoint"))) { if (reTempBreakFound.Matches(lines[i])) { long index; reTempBreakFound.GetMatch(lines[i],1).ToLong(&index); DebuggerState& state = m_pDBG->GetState(); cb::shared_ptr<DebuggerBreakpoint> bp = state.GetBreakpointByNumber(index); state.RemoveBreakpoint(bp, false); Manager::Get()->GetDebuggerManager()->GetBreakpointDialog()->Reload(); } } // cursor change else if (lines[i].StartsWith(g_EscapeChar)) // ->-> { // breakpoint, e.g. // C:/Devel/tmp/test_console_dbg/tmp/main.cpp:14:171:beg:0x401428 // Main breakpoint handler is wrapped into a function so we can use // the same code with different regular expressions - depending on // the platform. //NOTE: This also winds up matching response to a frame command which is generated as //part of a backtrace with autoswitch enabled, (from gdb7.2 mingw) as in: //(win32, x86, mingw gdb 7.2) //>>>>>>cb_gdb: //> frame 1 //#1 0x6f826722 in wxInitAllImageHandlers () at ../../src/common/imagall.cpp:29 //^Z^ZC:\dev\wxwidgets\wxWidgets-2.8.10\build\msw/../../src/common/imagall.cpp:29:961:beg:0x6f826722 //>>>>>>cb_gdb: HandleMainBreakPoint(reBreak, lines[i]); } else { // other break info, e.g. // 0x7c9507a8 in ntdll!KiIntSystemCall () from C:\WINDOWS\system32\ntdll.dll wxRegEx* re = 0; if ( reBreak2.Matches(lines[i]) ) re = &reBreak2; else if (reThreadSwitch.Matches(lines[i])) re = &reThreadSwitch; if ( re ) { m_Cursor.file = re->GetMatch(lines[i], 3); m_Cursor.function = re->GetMatch(lines[i], 2); wxString lineStr = _T(""); m_Cursor.address = re->GetMatch(lines[i], 1); m_Cursor.line = -1; m_Cursor.changed = true; m_needsUpdate = true; } else if ( reThreadSwitch2.Matches(lines[i]) ) { m_Cursor.file = reThreadSwitch2.GetMatch(lines[i], 3); m_Cursor.function = reThreadSwitch2.GetMatch(lines[i], 2); wxString lineStr = reThreadSwitch2.GetMatch(lines[i], 4); m_Cursor.address = reThreadSwitch2.GetMatch(lines[i], 1); m_Cursor.line = -1; m_Cursor.changed = true; m_needsUpdate = true; } else if (reBreak3.Matches(lines[i]) ) { m_Cursor.file=_T(""); m_Cursor.function= reBreak3.GetMatch(lines[i], 2); m_Cursor.address = reBreak3.GetMatch(lines[i], 1); m_Cursor.line = -1; m_Cursor.changed = true; m_needsUpdate = true; } else if (reCatchThrow.Matches(lines[i]) ) { m_Cursor.file = reCatchThrow.GetMatch(lines[i], 4); m_Cursor.function= reCatchThrow.GetMatch(lines[i], 3); m_Cursor.address = reCatchThrow.GetMatch(lines[i], 2); m_Cursor.line = -1; m_Cursor.changed = true; m_needsUpdate = true; } else if (reCatchThrowNoFile.Matches(lines[i]) ) { m_Cursor.file = wxEmptyString; m_Cursor.function= reCatchThrowNoFile.GetMatch(lines[i], 3); m_Cursor.address = reCatchThrowNoFile.GetMatch(lines[i], 2); m_Cursor.line = -1; m_Cursor.changed = true; m_needsUpdate = true; } } } buffer.Clear(); if (foundPrompt && m_DCmds.empty() && !m_ProgramIsStopped && !m_Cursor.changed) { QueueCommand(new GdbCmd_FindCursor(this)); m_ProgramIsStopped = true; } // if program is stopped, update various states if (m_needsUpdate) { if (1 == changeFrameAddr) { // clear to avoid change of disassembly address on (auto) frame change // when NotifyCursorChanged() executes m_Cursor.address.clear(); } if (m_Cursor.changed) { m_ProgramIsStopped = true; m_QueueBusy = false; } if (m_Cursor.changed || m_forceUpdate) NotifyCursorChanged(); } if (m_ProgramIsStopped) RunQueue(); } void GDB_driver::HandleMainBreakPoint(const wxRegEx& reBreak_in, wxString line) { if ( reBreak_in.Matches(line) ) { if (m_ManualBreakOnEntry) QueueCommand(new GdbCmd_InfoProgram(this), DebuggerDriver::High); if (m_ManualBreakOnEntry && !m_BreakOnEntry) Continue(); else { m_ManualBreakOnEntry = false; wxString lineStr; if (platform::windows) { m_Cursor.file = reBreak_in.GetMatch(line, 1) + reBreak_in.GetMatch(line, 2); } else { // For debuging of usual linux application 'GetMatch(line, 1)' is empty. // While for debuging of application under wine the name of the disk is useless. m_Cursor.file = reBreak_in.GetMatch( line, 2); } lineStr = reBreak_in.GetMatch(line, 3); m_Cursor.address = reBreak_in.GetMatch(line, 4); lineStr.ToLong(&m_Cursor.line); m_Cursor.changed = true; m_needsUpdate = true; } } else { m_pDBG->Log(_("The program has stopped on a breakpoint but the breakpoint format is not recognized:")); m_pDBG->Log(line); m_Cursor.changed = true; m_needsUpdate = true; } } void GDB_driver::DetermineLanguage() { QueueCommand(new GdbCmd_DebugLanguage(this)); }
bluehazzard/codeblocks_sf
src/plugins/debuggergdb/gdb_driver.cpp
C++
gpl-3.0
41,875
# Dictionary data structure in python # Dictionary sample_dict = {"Roll": 50, "Name": "Nityan"} # Looping to get key and values from dictionary for key in sample_dict: print(key, sample_dict[key]) # List of keys keys = list(sample_dict.keys()) print("Keys = ", keys) # List of values values = list(sample_dict.values()) print("values = ", values) name_dict = dict() name_list = list() # Taking input of names and add into the list, enter 'done' to stop the loop while True: a = input("Enter a name: ") if a == "done": break else: name_list.append(a) print("Names in the list = ", name_list) # Form a dictionary using the created list # If a lebel is prsent more than once keep increamenting the value, starting from 1 for name in name_list: if name not in name_dict: name_dict[name] = 1 else: name_dict[name] += 1 print("Name Dictionary = ", name_dict) name_dict2 = dict() name_list2 = list()
nityansuman/Python-3
data_structures/dictionary.py
Python
gpl-3.0
995
using System; using System.Collections.Generic; using System.Linq; using static PKHeX.Core.GameVersion; namespace PKHeX.Core { /// <summary> /// Object representing a <see cref="PKM"/>'s data and derived properties. /// </summary> public abstract class PKM : ISpeciesForm, ITrainerID, IGeneration, IShiny, ILangNick, IGameValueLimit, INature { public static readonly string[] Extensions = PKX.GetPKMExtensions(); public abstract int SIZE_PARTY { get; } public abstract int SIZE_STORED { get; } public string Extension => GetType().Name.ToLowerInvariant(); public abstract PersonalInfo PersonalInfo { get; } public virtual IReadOnlyList<ushort> ExtraBytes => Array.Empty<ushort>(); // Internal Attributes set on creation public readonly byte[] Data; // Raw Storage protected PKM(byte[] data) => Data = data; protected PKM(int size) => Data = new byte[size]; public virtual byte[] EncryptedPartyData => Encrypt().AsSpan()[..SIZE_PARTY].ToArray(); public virtual byte[] EncryptedBoxData => Encrypt().AsSpan()[..SIZE_STORED].ToArray(); public virtual byte[] DecryptedPartyData => Write().AsSpan()[..SIZE_PARTY].ToArray(); public virtual byte[] DecryptedBoxData => Write().AsSpan()[..SIZE_STORED].ToArray(); /// <summary> /// Rough indication if the data is junk or not. /// </summary> public abstract bool Valid { get; set; } // Trash Bytes public abstract Span<byte> Nickname_Trash { get; } public abstract Span<byte> OT_Trash { get; } public virtual Span<byte> HT_Trash => Span<byte>.Empty; protected abstract byte[] Encrypt(); public abstract int Format { get; } private byte[] Write() { RefreshChecksum(); return Data; } // Surface Properties public abstract int Species { get; set; } public abstract string Nickname { get; set; } public abstract int HeldItem { get; set; } public abstract int Gender { get; set; } public abstract int Nature { get; set; } public virtual int StatNature { get => Nature; set => Nature = value; } public abstract int Ability { get; set; } public abstract int CurrentFriendship { get; set; } public abstract int Form { get; set; } public abstract bool IsEgg { get; set; } public abstract bool IsNicknamed { get; set; } public abstract uint EXP { get; set; } public abstract int TID { get; set; } public abstract string OT_Name { get; set; } public abstract int OT_Gender { get; set; } public abstract int Ball { get; set; } public abstract int Met_Level { get; set; } // Battle public abstract int Move1 { get; set; } public abstract int Move2 { get; set; } public abstract int Move3 { get; set; } public abstract int Move4 { get; set; } public abstract int Move1_PP { get; set; } public abstract int Move2_PP { get; set; } public abstract int Move3_PP { get; set; } public abstract int Move4_PP { get; set; } public abstract int Move1_PPUps { get; set; } public abstract int Move2_PPUps { get; set; } public abstract int Move3_PPUps { get; set; } public abstract int Move4_PPUps { get; set; } public abstract int EV_HP { get; set; } public abstract int EV_ATK { get; set; } public abstract int EV_DEF { get; set; } public abstract int EV_SPE { get; set; } public abstract int EV_SPA { get; set; } public abstract int EV_SPD { get; set; } public abstract int IV_HP { get; set; } public abstract int IV_ATK { get; set; } public abstract int IV_DEF { get; set; } public abstract int IV_SPE { get; set; } public abstract int IV_SPA { get; set; } public abstract int IV_SPD { get; set; } public abstract int Status_Condition { get; set; } public abstract int Stat_Level { get; set; } public abstract int Stat_HPMax { get; set; } public abstract int Stat_HPCurrent { get; set; } public abstract int Stat_ATK { get; set; } public abstract int Stat_DEF { get; set; } public abstract int Stat_SPE { get; set; } public abstract int Stat_SPA { get; set; } public abstract int Stat_SPD { get; set; } // Hidden Properties public abstract int Version { get; set; } public abstract int SID { get; set; } public abstract int PKRS_Strain { get; set; } public abstract int PKRS_Days { get; set; } public abstract uint EncryptionConstant { get; set; } public abstract uint PID { get; set; } // Misc Properties public abstract int Language { get; set; } public abstract bool FatefulEncounter { get; set; } public abstract int TSV { get; } public abstract int PSV { get; } public abstract int Characteristic { get; } public abstract int MarkValue { get; protected set; } public abstract int Met_Location { get; set; } public abstract int Egg_Location { get; set; } public abstract int OT_Friendship { get; set; } public virtual bool Japanese => Language == (int)LanguageID.Japanese; public virtual bool Korean => Language == (int)LanguageID.Korean; // Future Properties public virtual int Met_Year { get => 0; set { } } public virtual int Met_Month { get => 0; set { } } public virtual int Met_Day { get => 0; set { } } public virtual string HT_Name { get => string.Empty; set { } } public virtual int HT_Gender { get => 0; set { } } public virtual int HT_Friendship { get => 0; set { } } public virtual byte Enjoyment { get => 0; set { } } public virtual byte Fullness { get => 0; set { } } public virtual int AbilityNumber { get => 0; set { } } /// <summary> /// The date the Pokémon was met. /// </summary> /// <returns> /// A DateTime representing the date the Pokémon was met. /// Returns null if either the <see cref="PKM"/> format does not support dates or the stored date is invalid.</returns> /// <remarks> /// Not all <see cref="PKM"/> types support the <see cref="MetDate"/> property. In these cases, this property will return null. /// If null is assigned to this property, it will be cleared. /// </remarks> public DateTime? MetDate { get { // Check to see if date is valid if (!DateUtil.IsDateValid(2000 + Met_Year, Met_Month, Met_Day)) return null; return new DateTime(2000 + Met_Year, Met_Month, Met_Day); } set { if (value.HasValue) { // Only update the properties if a value is provided. Met_Year = value.Value.Year - 2000; Met_Month = value.Value.Month; Met_Day = value.Value.Day; } else { // Clear the Met Date. // If code tries to access MetDate again, null will be returned. Met_Year = 0; Met_Month = 0; Met_Day = 0; } } } public virtual int Egg_Year { get => 0; set { } } public virtual int Egg_Month { get => 0; set { } } public virtual int Egg_Day { get => 0; set { } } /// <summary> /// The date a Pokémon was met as an egg. /// </summary> /// <returns> /// A DateTime representing the date the Pokémon was met as an egg. /// Returns null if either the <see cref="PKM"/> format does not support dates or the stored date is invalid.</returns> /// <remarks> /// Not all <see cref="PKM"/> types support the <see cref="EggMetDate"/> property. In these cases, this property will return null. /// If null is assigned to this property, it will be cleared. /// </remarks> public DateTime? EggMetDate { get { // Check to see if date is valid if (!DateUtil.IsDateValid(2000 + Egg_Year, Egg_Month, Egg_Day)) return null; return new DateTime(2000 + Egg_Year, Egg_Month, Egg_Day); } set { if (value.HasValue) { // Only update the properties if a value is provided. Egg_Year = value.Value.Year - 2000; Egg_Month = value.Value.Month; Egg_Day = value.Value.Day; } else { // Clear the Met Date. // If code tries to access MetDate again, null will be returned. Egg_Year = 0; Egg_Month = 0; Egg_Day = 0; } } } public virtual int RelearnMove1 { get => 0; set { } } public virtual int RelearnMove2 { get => 0; set { } } public virtual int RelearnMove3 { get => 0; set { } } public virtual int RelearnMove4 { get => 0; set { } } // Exposed but not Present in all public abstract int CurrentHandler { get; set; } // Maximums public abstract int MaxMoveID { get; } public abstract int MaxSpeciesID { get; } public abstract int MaxItemID { get; } public abstract int MaxAbilityID { get; } public abstract int MaxBallID { get; } public abstract int MaxGameID { get; } public virtual int MinGameID => 0; public abstract int MaxIV { get; } public abstract int MaxEV { get; } public abstract int OTLength { get; } public abstract int NickLength { get; } // Derived public int SpecForm { get => Species + (Form << 11); set { Species = value & 0x7FF; Form = value >> 11; } } public virtual int SpriteItem => HeldItem; public virtual bool IsShiny => TSV == PSV; public int TrainerID7 { get => (int)((uint)(TID | (SID << 16)) % 1000000); set => SetID7(TrainerSID7, value); } public int TrainerSID7 { get => (int)((uint)(TID | (SID << 16)) / 1000000); set => SetID7(value, TrainerID7); } public uint ShinyXor { get { var pid = PID; var upper = (pid >> 16) ^ (uint)SID; return (pid & 0xFFFF) ^ (uint)TID ^ upper; } } public int DisplayTID { get => Generation >= 7 ? TrainerID7 : TID; set { if (Generation >= 7) TrainerID7 = value; else TID = value; } } public int DisplaySID { get => Generation >= 7 ? TrainerSID7 : SID; set { if (Generation >= 7) TrainerSID7 = value; else SID = value; } } private void SetID7(int sid7, int tid7) { var oid = (sid7 * 1_000_000) + (tid7 % 1_000_000); TID = (ushort)oid; SID = oid >> 16; } public bool E => Version == (int)GameVersion.E; public bool FRLG => Version is (int)FR or (int)LG; public bool Pt => (int)GameVersion.Pt == Version; public bool HGSS => Version is (int)HG or (int)SS; public bool BW => Version is (int)B or (int)W; public bool B2W2 => Version is (int)B2 or (int)W2; public bool XY => Version is (int)X or (int)Y; public bool AO => Version is (int)AS or (int)OR; public bool SM => Version is (int)SN or (int)MN; public bool USUM => Version is (int)US or (int)UM; public bool GO => Version is (int)GameVersion.GO; public bool VC1 => Version is >= (int)RD and <= (int)YW; public bool VC2 => Version is >= (int)GD and <= (int)C; public bool LGPE => Version is (int)GP or (int)GE; public bool SWSH => Version is (int)SW or (int)SH; public bool BDSP => Version is (int)BD or (int)SP; public bool GO_LGPE => GO && Met_Location == Locations.GO7; public bool GO_HOME => GO && Met_Location == Locations.GO8; public bool VC => VC1 || VC2; public bool GG => LGPE || GO_LGPE; public bool Gen8 => Version is >= 44 and <= 49 || GO_HOME; public bool Gen7 => Version is >= 30 and <= 33 || GG; public bool Gen6 => Version is >= 24 and <= 29; public bool Gen5 => Version is >= 20 and <= 23; public bool Gen4 => Version is >= 7 and <= 12 and not 9; public bool Gen3 => Version is >= 1 and <= 5 or 15; public bool Gen2 => Version == (int)GSC; // Fixed value set by the Gen2 PKM classes public bool Gen1 => Version == (int)RBY; // Fixed value set by the Gen1 PKM classes public bool GenU => Generation <= 0; public int Generation { get { if (Gen8) return 8; if (Gen7) return 7; if (Gen6) return 6; if (Gen5) return 5; if (Gen4) return 4; if (Gen3) return 3; if (Gen2) return Format; // 2 if (Gen1) return Format; // 1 if (VC1) return 1; if (VC2) return 2; return -1; } } public int DebutGeneration => Legal.GetDebutGeneration(Species); public bool PKRS_Infected { get => PKRS_Strain != 0; set => PKRS_Strain = value ? Math.Max(PKRS_Strain, 1) : 0; } public bool PKRS_Cured { get => PKRS_Days == 0 && PKRS_Strain > 0; set { PKRS_Days = value ? 0 : 1; PKRS_Infected = true; } } public int CurrentLevel { get => Experience.GetLevel(EXP, PersonalInfo.EXPGrowth); set => EXP = Experience.GetEXP(Stat_Level = value, PersonalInfo.EXPGrowth); } public int MarkCircle { get => Markings[0]; set { var marks = Markings; marks[0] = value; Markings = marks; } } public int MarkTriangle { get => Markings[1]; set { var marks = Markings; marks[1] = value; Markings = marks; } } public int MarkSquare { get => Markings[2]; set { var marks = Markings; marks[2] = value; Markings = marks; } } public int MarkHeart { get => Markings[3]; set { var marks = Markings; marks[3] = value; Markings = marks; } } public int MarkStar { get => Markings[4]; set { var marks = Markings; marks[4] = value; Markings = marks; } } public int MarkDiamond { get => Markings[5]; set { var marks = Markings; marks[5] = value; Markings = marks; } } public int IVTotal => IV_HP + IV_ATK + IV_DEF + IV_SPA + IV_SPD + IV_SPE; public int EVTotal => EV_HP + EV_ATK + EV_DEF + EV_SPA + EV_SPD + EV_SPE; public int MaximumIV => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(IV_HP, IV_ATK), IV_DEF), IV_SPA), IV_SPD), IV_SPE); public int FlawlessIVCount { get { int max = MaxIV; int ctr = 0; if (IV_HP == max) ++ctr; if (IV_ATK == max) ++ctr; if (IV_DEF == max) ++ctr; if (IV_SPA == max) ++ctr; if (IV_SPD == max) ++ctr; if (IV_SPE == max) ++ctr; return ctr; } } public string FileName => $"{FileNameWithoutExtension}.{Extension}"; public string FileNameWithoutExtension => EntityFileNamer.GetName(this); public int[] IVs { get => new[] { IV_HP, IV_ATK, IV_DEF, IV_SPE, IV_SPA, IV_SPD }; set => SetIVs(value); } public void SetIVs(ReadOnlySpan<int> value) { if (value.Length != 6) return; IV_HP = value[0]; IV_ATK = value[1]; IV_DEF = value[2]; IV_SPE = value[3]; IV_SPA = value[4]; IV_SPD = value[5]; } public int[] EVs { get => new[] { EV_HP, EV_ATK, EV_DEF, EV_SPE, EV_SPA, EV_SPD }; set { if (value.Length != 6) return; EV_HP = value[0]; EV_ATK = value[1]; EV_DEF = value[2]; EV_SPE = value[3]; EV_SPA = value[4]; EV_SPD = value[5]; } } public int[] Stats { get => new[] { Stat_HPCurrent, Stat_ATK, Stat_DEF, Stat_SPE, Stat_SPA, Stat_SPD }; set { if (value.Length != 6) return; Stat_HPCurrent = value[0]; Stat_ATK = value[1]; Stat_DEF = value[2]; Stat_SPE = value[3]; Stat_SPA = value[4]; Stat_SPD = value[5]; } } public int[] Moves { get => new[] { Move1, Move2, Move3, Move4 }; set => SetMoves(value); } public void SetMoves(IReadOnlyList<int> value) { Move1 = value.Count > 0 ? value[0] : 0; Move2 = value.Count > 1 ? value[1] : 0; Move3 = value.Count > 2 ? value[2] : 0; Move4 = value.Count > 3 ? value[3] : 0; } public int[] RelearnMoves { get => new[] { RelearnMove1, RelearnMove2, RelearnMove3, RelearnMove4 }; set => SetRelearnMoves(value); } public void SetRelearnMoves(IReadOnlyList<int> value) { RelearnMove1 = value.Count > 0 ? value[0] : 0; RelearnMove2 = value.Count > 1 ? value[1] : 0; RelearnMove3 = value.Count > 2 ? value[2] : 0; RelearnMove4 = value.Count > 3 ? value[3] : 0; } public int PIDAbility { get { if (Generation > 5 || Format > 5) return -1; if (Version == (int) CXD) return PersonalInfo.GetAbilityIndex(Ability); // Can mismatch; not tied to PID return (int)((Gen5 ? PID >> 16 : PID) & 1); } } public virtual int[] Markings { get { int[] mark = new int[8]; for (int i = 0; i < 8; i++) mark[i] = (MarkValue >> i) & 1; return mark; } set { if (value.Length > 8) return; byte b = 0; for (int i = 0; i < value.Length; i++) b |= (byte)(Math.Min(value[i], 1) << i); MarkValue = b; } } private int HPBitValPower => ((IV_HP & 2) >> 1) | ((IV_ATK & 2) >> 0) | ((IV_DEF & 2) << 1) | ((IV_SPE & 2) << 2) | ((IV_SPA & 2) << 3) | ((IV_SPD & 2) << 4); public virtual int HPPower => Format < 6 ? ((40 * HPBitValPower) / 63) + 30 : 60; private int HPBitValType => ((IV_HP & 1) >> 0) | ((IV_ATK & 1) << 1) | ((IV_DEF & 1) << 2) | ((IV_SPE & 1) << 3) | ((IV_SPA & 1) << 4) | ((IV_SPD & 1) << 5); public virtual int HPType { get => 15 * HPBitValType / 63; set { var arr = HiddenPower.DefaultLowBits; var bits = (uint)value >= arr.Length ? 0 : arr[value]; IV_HP = (IV_HP & ~1) + ((bits >> 0) & 1); IV_ATK = (IV_ATK & ~1) + ((bits >> 1) & 1); IV_DEF = (IV_DEF & ~1) + ((bits >> 2) & 1); IV_SPE = (IV_SPE & ~1) + ((bits >> 3) & 1); IV_SPA = (IV_SPA & ~1) + ((bits >> 4) & 1); IV_SPD = (IV_SPD & ~1) + ((bits >> 5) & 1); } } // Misc Egg Facts public bool WasEgg => IsEgg || !Locations.IsNoneLocation((GameVersion)Version, Egg_Location); public bool WasTradedEgg => Egg_Location == GetTradedEggLocation(); public bool IsTradedEgg => Met_Location == GetTradedEggLocation(); private int GetTradedEggLocation() => Locations.TradedEggLocation(Generation, (GameVersion)Version); public virtual bool IsUntraded => false; public bool IsNative => Generation == Format; public bool IsOriginValid => Species <= MaxSpeciesID; /// <summary> /// Checks if the <see cref="PKM"/> could inhabit a set of games. /// </summary> /// <param name="generation">Set of games.</param> /// <param name="species"></param> /// <returns>True if could inhabit, False if not.</returns> public bool InhabitedGeneration(int generation, int species = -1) { if (species < 0) species = Species; var format = Format; if (format == generation) return true; if (!IsOriginValid) return false; // Sanity Check Species ID if (species > Legal.GetMaxSpeciesOrigin(generation) && !EvolutionLegality.GetFutureGenEvolutions(generation).Contains(species)) return false; // Trade generation 1 -> 2 if (format == 2 && generation == 1 && !Korean) return true; // Trade generation 2 -> 1 if (format == 1 && generation == 2 && ParseSettings.AllowGen1Tradeback) return true; if (format < generation) return false; // Future int gen = Generation; return generation switch { 1 => format == 1 || VC, // species compat checked via sanity above 2 => format == 2 || VC, 3 => Gen3, 4 => gen is >= 3 and <= 4, 5 => gen is >= 3 and <= 5, 6 => gen is >= 3 and <= 6, 7 => gen is >= 3 and <= 7 || VC, 8 => gen is >= 3 and <= 8 || VC, _ => false, }; } /// <summary> /// Checks if the PKM has its original met location. /// </summary> /// <returns>Returns false if the Met Location has been overwritten via generational transfer.</returns> public virtual bool HasOriginalMetLocation => !(Format < 3 || VC || (Generation <= 4 && Format != Generation)); /// <summary> /// Checks if the current <see cref="Gender"/> is valid. /// </summary> /// <returns>True if valid, False if invalid.</returns> public virtual bool IsGenderValid() { int gender = Gender; int gv = PersonalInfo.Gender; if (gv == PersonalInfo.RatioMagicGenderless) return gender == 2; if (gv == PersonalInfo.RatioMagicFemale) return gender == 1; if (gv == PersonalInfo.RatioMagicMale) return gender == 0; int gen = Generation; if (gen is <= 2 or >= 6) // not 3-5 return gender == (gender & 1); return gender == PKX.GetGenderFromPIDAndRatio(PID, gv); } /// <summary> /// Updates the checksum of the <see cref="PKM"/>. /// </summary> public abstract void RefreshChecksum(); /// <summary> /// Indicates if the data has a proper checksum. /// </summary> /// <remarks>Returns true for structures that do not compute or contain a checksum in the structure.</remarks> public abstract bool ChecksumValid { get; } /// <summary> /// Reorders moves and fixes PP if necessary. /// </summary> public void FixMoves() { ReorderMoves(); if (Move1 == 0) Move1_PP = Move1_PPUps = 0; if (Move2 == 0) Move2_PP = Move2_PPUps = 0; if (Move3 == 0) Move3_PP = Move3_PPUps = 0; if (Move4 == 0) Move4_PP = Move4_PPUps = 0; } /// <summary> /// Reorders moves to put Empty entries last. /// </summary> private void ReorderMoves() { if (Move1 == 0 && Move2 != 0) { Move1 = Move2; Move1_PP = Move2_PP; Move1_PPUps = Move2_PPUps; Move2 = 0; } if (Move2 == 0 && Move3 != 0) { Move2 = Move3; Move2_PP = Move3_PP; Move2_PPUps = Move3_PPUps; Move3 = 0; } if (Move3 == 0 && Move4 != 0) { Move3 = Move4; Move3_PP = Move4_PP; Move3_PPUps = Move4_PPUps; Move4 = 0; } } /// <summary> /// Applies the desired Ability option. /// </summary> /// <param name="n">Ability Number (0/1/2)</param> public virtual void RefreshAbility(int n) { AbilityNumber = 1 << n; var abilities = PersonalInfo.Abilities; if ((uint)n < abilities.Count) Ability = abilities[n]; } /// <summary> /// Gets the IV Judge Rating value. /// </summary> /// <remarks>IV Judge scales his response 0 (worst) to 3 (best).</remarks> public int PotentialRating => IVTotal switch { <= 90 => 0, <= 120 => 1, <= 150 => 2, _ => 3, }; /// <summary> /// Gets the current Battle Stats. /// </summary> /// <param name="p"><see cref="PersonalInfo"/> entry containing Base Stat Info</param> /// <returns>Battle Stats (H/A/B/S/C/D)</returns> public virtual ushort[] GetStats(PersonalInfo p) { int level = CurrentLevel; ushort[] stats = this is IHyperTrain t ? GetStats(p, t, level) : GetStats(p, level); // Account for nature PKX.ModifyStatsForNature(stats, StatNature); return stats; } private ushort[] GetStats(PersonalInfo p, IHyperTrain t, int level) { ushort[] stats = new ushort[6]; stats[0] = (ushort)(p.HP == 1 ? 1 : (((t.HT_HP ? 31 : IV_HP) + (2 * p.HP) + (EV_HP / 4) + 100) * level / 100) + 10); stats[1] = (ushort)((((t.HT_ATK ? 31 : IV_ATK) + (2 * p.ATK) + (EV_ATK / 4)) * level / 100) + 5); stats[2] = (ushort)((((t.HT_DEF ? 31 : IV_DEF) + (2 * p.DEF) + (EV_DEF / 4)) * level / 100) + 5); stats[4] = (ushort)((((t.HT_SPA ? 31 : IV_SPA) + (2 * p.SPA) + (EV_SPA / 4)) * level / 100) + 5); stats[5] = (ushort)((((t.HT_SPD ? 31 : IV_SPD) + (2 * p.SPD) + (EV_SPD / 4)) * level / 100) + 5); stats[3] = (ushort)((((t.HT_SPE ? 31 : IV_SPE) + (2 * p.SPE) + (EV_SPE / 4)) * level / 100) + 5); return stats; } private ushort[] GetStats(PersonalInfo p, int level) { ushort[] stats = new ushort[6]; stats[0] = (ushort)(p.HP == 1 ? 1 : ((IV_HP + (2 * p.HP) + (EV_HP / 4) + 100) * level / 100) + 10); stats[1] = (ushort)(((IV_ATK + (2 * p.ATK) + (EV_ATK / 4)) * level / 100) + 5); stats[2] = (ushort)(((IV_DEF + (2 * p.DEF) + (EV_DEF / 4)) * level / 100) + 5); stats[4] = (ushort)(((IV_SPA + (2 * p.SPA) + (EV_SPA / 4)) * level / 100) + 5); stats[5] = (ushort)(((IV_SPD + (2 * p.SPD) + (EV_SPD / 4)) * level / 100) + 5); stats[3] = (ushort)(((IV_SPE + (2 * p.SPE) + (EV_SPE / 4)) * level / 100) + 5); return stats; } /// <summary> /// Applies the specified stats to the <see cref="PKM"/>. /// </summary> /// <param name="stats">Battle Stats (H/A/B/S/C/D)</param> public void SetStats(ushort[] stats) { Stat_HPMax = Stat_HPCurrent = stats[0]; Stat_ATK = stats[1]; Stat_DEF = stats[2]; Stat_SPE = stats[3]; Stat_SPA = stats[4]; Stat_SPD = stats[5]; } /// <summary> /// Indicates if Party Stats are present. False if not initialized (from stored format). /// </summary> public bool PartyStatsPresent => Stat_HPMax != 0; /// <summary> /// Clears any status condition and refreshes the stats. /// </summary> public void ResetPartyStats() { SetStats(GetStats(PersonalInfo)); Stat_Level = CurrentLevel; Status_Condition = 0; } public void Heal() { ResetPartyStats(); HealPP(); } /// <summary> /// Restores PP to maximum based on the current PP Ups for each move. /// </summary> public void HealPP() { Move1_PP = GetMovePP(Move1, Move1_PPUps); Move2_PP = GetMovePP(Move2, Move2_PPUps); Move3_PP = GetMovePP(Move3, Move3_PPUps); Move4_PP = GetMovePP(Move4, Move4_PPUps); } /// <summary> /// Enforces that Party Stat values are present. /// </summary> /// <returns>True if stats were refreshed, false if stats were already present.</returns> public bool ForcePartyData() { if (PartyStatsPresent) return false; ResetPartyStats(); return true; } /// <summary> /// Checks if the <see cref="PKM"/> can hold its <see cref="HeldItem"/>. /// </summary> /// <param name="valid">Items that the <see cref="PKM"/> can hold.</param> /// <returns>True/False if the <see cref="PKM"/> can hold its <see cref="HeldItem"/>.</returns> public virtual bool CanHoldItem(IReadOnlyList<ushort> valid) => valid.Contains((ushort)HeldItem); /// <summary> /// Deep clones the <see cref="PKM"/> object. The clone will not have any shared resources with the source. /// </summary> /// <returns>Cloned <see cref="PKM"/> object</returns> public abstract PKM Clone(); /// <summary> /// Sets Link Trade data for an <see cref="IsEgg"/>. /// </summary> /// <param name="day">Day the <see cref="PKM"/> was traded.</param> /// <param name="month">Month the <see cref="PKM"/> was traded.</param> /// <param name="y">Day the <see cref="PKM"/> was traded.</param> /// <param name="location">Link Trade location value.</param> protected void SetLinkTradeEgg(int day, int month, int y, int location) { Met_Day = day; Met_Month = month; Met_Year = y - 2000; Met_Location = location; } /// <summary> /// Gets the PP of a Move ID with consideration of the amount of PP Ups applied. /// </summary> /// <param name="move">Move ID</param> /// <param name="ppUpCount">PP Ups count</param> /// <returns>Current PP for the move.</returns> public virtual int GetMovePP(int move, int ppUpCount) => GetBasePP(move) * (5 + ppUpCount) / 5; /// <summary> /// Gets the base PP of a move ID depending on the <see cref="PKM"/>'s format. /// </summary> /// <param name="move">Move ID</param> /// <returns>Amount of PP the move has by default (no PP Ups).</returns> private int GetBasePP(int move) { var table = Legal.GetPPTable(this, Format); if (move >= table.Count) move = 0; return table[move]; } /// <summary> /// Applies a shiny <see cref="PID"/> to the <see cref="PKM"/>. /// </summary> /// <remarks> /// If a <see cref="PKM"/> originated in a generation prior to Generation 6, the <see cref="EncryptionConstant"/> is updated. /// If a <see cref="PKM"/> is in the <see cref="GBPKM"/> format, it will update the <see cref="IVs"/> instead. /// </remarks> public virtual void SetShiny() { var rnd = Util.Rand; do { PID = PKX.GetRandomPID(rnd, Species, Gender, Version, Nature, Form, PID); } while (!IsShiny); if (Format >= 6 && (Gen3 || Gen4 || Gen5)) EncryptionConstant = PID; } /// <summary> /// Applies a shiny <see cref="SID"/> to the <see cref="PKM"/>. /// </summary> public void SetShinySID(Shiny shiny = Shiny.Random) { if (IsShiny && shiny.IsValid(this)) return; var xor = TID ^ (PID >> 16) ^ (PID & 0xFFFF); var bits = shiny switch { Shiny.AlwaysSquare => 0, Shiny.AlwaysStar => 1, _ => Util.Rand.Next(8), }; SID = (int)xor ^ bits; } /// <summary> /// Applies a <see cref="PID"/> to the <see cref="PKM"/> according to the specified <see cref="Gender"/>. /// </summary> /// <param name="gender"><see cref="Gender"/> to apply</param> /// <remarks> /// If a <see cref="PKM"/> originated in a generation prior to Generation 6, the <see cref="EncryptionConstant"/> is updated. /// </remarks> public void SetPIDGender(int gender) { var rnd = Util.Rand; do PID = PKX.GetRandomPID(rnd, Species, gender, Version, Nature, Form, PID); while (IsShiny); if (Format >= 6 && (Gen3 || Gen4 || Gen5)) EncryptionConstant = PID; } /// <summary> /// Applies a <see cref="PID"/> to the <see cref="PKM"/> according to the specified <see cref="Gender"/>. /// </summary> /// <param name="nature"><see cref="Nature"/> to apply</param> /// <remarks> /// If a <see cref="PKM"/> originated in a generation prior to Generation 6, the <see cref="EncryptionConstant"/> is updated. /// </remarks> public void SetPIDNature(int nature) { var rnd = Util.Rand; do PID = PKX.GetRandomPID(rnd, Species, Gender, Version, nature, Form, PID); while (IsShiny); if (Format >= 6 && (Gen3 || Gen4 || Gen5)) EncryptionConstant = PID; } /// <summary> /// Applies a <see cref="PID"/> to the <see cref="PKM"/> according to the specified <see cref="Form"/>. /// </summary> /// <param name="form"><see cref="Form"/> to apply</param> /// <remarks> /// This method should only be used for Unown originating in Generation 3 games. /// If a <see cref="PKM"/> originated in a generation prior to Generation 6, the <see cref="EncryptionConstant"/> is updated. /// </remarks> public void SetPIDUnown3(int form) { var rnd = Util.Rand; do PID = Util.Rand32(rnd); while (PKX.GetUnownForm(PID) != form); if (Format >= 6 && (Gen3 || Gen4 || Gen5)) EncryptionConstant = PID; } /// <summary> /// Randomizes the IVs within game constraints. /// </summary> /// <param name="flawless">Count of flawless IVs to set. If none provided, a count will be detected.</param> /// <returns>Randomized IVs if desired.</returns> public int[] SetRandomIVs(int? flawless = null) { if (Version == (int)GameVersion.GO && flawless != 6) return SetRandomIVsGO(); int[] ivs = new int[6]; var rnd = Util.Rand; for (int i = 0; i < 6; i++) ivs[i] = rnd.Next(MaxIV + 1); int count = flawless ?? GetFlawlessIVCount(); if (count != 0) { for (int i = 0; i < count; i++) ivs[i] = MaxIV; Util.Shuffle(ivs.AsSpan(), 0, ivs.Length, rnd); // Randomize IV order } return IVs = ivs; } public int[] SetRandomIVsGO(int minIV = 0, int maxIV = 15) { int[] ivs = new int[6]; var rnd = Util.Rand; ivs[0] = (rnd.Next(minIV, maxIV + 1) << 1) | 1; // hp ivs[1] = ivs[4] = (rnd.Next(minIV, maxIV + 1) << 1) | 1; // attack ivs[2] = ivs[5] = (rnd.Next(minIV, maxIV + 1) << 1) | 1; // defense ivs[3] = rnd.Next(MaxIV + 1); // speed return IVs = ivs; } /// <summary> /// Randomizes the IVs within game constraints. /// </summary> /// <param name="template">IV template to generate from</param> /// <param name="flawless">Count of flawless IVs to set. If none provided, a count will be detected.</param> /// <returns>Randomized IVs if desired.</returns> public int[] SetRandomIVs(IReadOnlyList<int> template, int? flawless = null) { int count = flawless ?? GetFlawlessIVCount(); int[] ivs = new int[6]; var rnd = Util.Rand; do { for (int i = 0; i < 6; i++) ivs[i] = template[i] < 0 ? rnd.Next(MaxIV + 1) : template[i]; } while (ivs.Count(z => z == MaxIV) < count); IVs = ivs; return ivs; } /// <summary> /// Gets the amount of flawless IVs that the <see cref="PKM"/> should have. /// </summary> /// <returns>Count of IVs that should be max.</returns> public int GetFlawlessIVCount() { if (Generation >= 6 && (Legal.Legends.Contains(Species) || Legal.SubLegends.Contains(Species))) return 3; if (XY) { if (PersonalInfo.EggGroup1 == 15) // Undiscovered return 3; if (Met_Location == 148 && Met_Level == 30) // Friend Safari return 2; } if (VC) return Species is (int)Core.Species.Mew or (int)Core.Species.Celebi ? 5 : 3; return 0; } /// <summary> /// Applies all shared properties from the current <see cref="PKM"/> to <see cref="Destination"/> <see cref="PKM"/>. /// </summary> /// <param name="Destination"><see cref="PKM"/> that receives property values.</param> public void TransferPropertiesWithReflection(PKM Destination) { // Only transfer declared properties not defined in PKM.cs but in the actual type var srcType = GetType(); var destType = Destination.GetType(); var srcProperties = ReflectUtil.GetPropertiesCanWritePublicDeclared(srcType); var destProperties = ReflectUtil.GetPropertiesCanWritePublicDeclared(destType); // Transfer properties in the order they are defined in the destination PKM format for best conversion var shared = destProperties.Intersect(srcProperties); foreach (string property in shared) { if (!BatchEditing.TryGetHasProperty(this, property, out var src)) continue; var prop = src.GetValue(this); if (prop is not (byte[] or null) && BatchEditing.TryGetHasProperty(Destination, property, out var pi)) ReflectUtil.SetValue(pi, Destination, prop); } // set shared properties for the Gen1/2 base class if (Destination is GBPKM l) l.ImportFromFuture(this); } /// <summary> /// Checks if the <see cref="PKM"/> has the <see cref="move"/> in its current move list. /// </summary> public bool HasMove(int move) => Move1 == move || Move2 == move || Move3 == move || Move4 == move; public int GetMoveIndex(int move) => Move1 == move ? 0 : Move2 == move ? 1 : Move3 == move ? 2 : Move4 == move ? 3 : -1; public int GetMove(int index) => index switch { 0 => Move1, 1 => Move2, 2 => Move3, 3 => Move4, _ => throw new IndexOutOfRangeException(nameof(index)), }; public int SetMove(int index, int value) => index switch { 0 => Move1 = value, 1 => Move2 = value, 2 => Move3 = value, 3 => Move4 = value, _ => throw new IndexOutOfRangeException(nameof(index)), }; /// <summary> /// Clears moves that a <see cref="PKM"/> may have, possibly from a future generation. /// </summary> public void ClearInvalidMoves() { uint invalid = 0; var moves = Moves; for (var i = 0; i < moves.Length; i++) { if (moves[i] <= MaxMoveID) continue; invalid++; moves[i] = 0; } if (invalid == 0) return; if (invalid == 4) // no moves remain { moves[0] = 1; // Pound Move1_PP = GetMovePP(1, Move1_PPUps); } Moves = moves; FixMoves(); } /// <summary> /// Gets one of the <see cref="EVs"/> based on its index within the array. /// </summary> /// <param name="index">Index to get</param> public int GetEV(int index) => index switch { 0 => EV_HP, 1 => EV_ATK, 2 => EV_DEF, 3 => EV_SPE, 4 => EV_SPA, 5 => EV_SPD, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; /// <summary> /// Gets one of the <see cref="IVs"/> based on its index within the array. /// </summary> /// <param name="index">Index to get</param> public int GetIV(int index) => index switch { 0 => IV_HP, 1 => IV_ATK, 2 => IV_DEF, 3 => IV_SPE, 4 => IV_SPA, 5 => IV_SPD, _ => throw new ArgumentOutOfRangeException(nameof(index)), }; } }
javierhimura/PKHeX
PKHeX.Core/PKM/PKM.cs
C#
gpl-3.0
42,596
'use strict'; const expect = require('chai').expect; const Board = require('../src/board'); const Search = require('../src/search'); describe('search', () => { var board; var search; var timePerMove; // ms var maxDepth = 64; beforeEach(() => { board = new Board(); search = new Search(); }); describe('tactics', () => { beforeEach(() => { timePerMove = 200; }); it('should find white checkmate', () => { board.fen = '8/8/8/5K1k/8/8/8/6R1 w - - 0 1'; var correctMove = board.moveStringToMove('g1h1'); var move = search.iterativeDeepening(board, timePerMove, maxDepth); expect(move).to.equal(correctMove); }); it('should find black checkmate', () => { board.fen = '8/8/8/5k1K/8/8/8/6r1 b - - 0 1'; var correctMove = board.moveStringToMove('g1h1'); var move = search.iterativeDeepening(board, timePerMove, maxDepth); expect(move).to.equal(correctMove); }); }); });
joeyrobert/ceruleanjs
test/search.test.js
JavaScript
gpl-3.0
1,071
/* * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/b2Distance.h> #include <Box2D/Dynamics/b2Island.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Common/b2StackAllocator.h> #include <Box2D/Common/b2Timer.h> /* Position Correction Notes ========================= I tried the several algorithms for position correction of the 2D revolute joint. I looked at these systems: - simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. - suspension bridge with 30 1m long planks of length 1m. - multi-link chain with 30 1m long links. Here are the algorithms: Baumgarte - A fraction of the position error is added to the velocity error. There is no separate position solver. Pseudo Velocities - After the velocity solver and position integration, the position error, Jacobian, and effective mass are recomputed. Then the velocity constraints are solved with pseudo velocities and a fraction of the position error is added to the pseudo velocity error. The pseudo velocities are initialized to zero and there is no warm-starting. After the position solver, the pseudo velocities are added to the positions. This is also called the First Order World method or the Position LCP method. Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the position error is re-computed for each constraint and the positions are updated after the constraint is solved. The radius vectors (aka Jacobians) are re-computed too (otherwise the algorithm has horrible instability). The pseudo velocity states are not needed because they are effectively zero at the beginning of each iteration. Since we have the current position error, we allow the iterations to terminate early if the error becomes smaller than b2_linearSlop. Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed each time a constraint is solved. Here are the results: Baumgarte - this is the cheapest algorithm but it has some stability problems, especially with the bridge. The chain links separate easily close to the root and they jitter as they struggle to pull together. This is one of the most common methods in the field. The big drawback is that the position correction artificially affects the momentum, thus leading to instabilities and false bounce. I used a bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller factor makes joints and contacts more spongy. Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is stable. However, joints still separate with large angular velocities. Drag the simple pendulum in a circle quickly and the joint will separate. The chain separates easily and does not recover. I used a bias factor of 0.2. A larger value lead to the bridge collapsing when a heavy cube drops on it. Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo Velocities, but in other ways it is worse. The bridge and chain are much more stable, but the simple pendulum goes unstable at high angular velocities. Full NGS - stable in all tests. The joints display good stiffness. The bridge still sags, but this is better than infinite forces. Recommendations Pseudo Velocities are not really worthwhile because the bridge and chain cannot recover from joint separation. In other cases the benefit over Baumgarte is small. Modified NGS is not a robust method for the revolute joint due to the violent instability seen in the simple pendulum. Perhaps it is viable with other constraint types, especially scalar constraints where the effective mass is a scalar. This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities and is very fast. I don't think we can escape Baumgarte, especially in highly demanding cases where high constraint fidelity is not needed. Full NGS is robust and easy on the eyes. I recommend this as an option for higher fidelity simulation and certainly for suspension bridges and long chains. Full NGS might be a good choice for ragdolls, especially motorized ragdolls where joint separation can be problematic. The number of NGS iterations can be reduced for better performance without harming robustness much. Each joint in a can be handled differently in the position solver. So I recommend a system where the user can select the algorithm on a per joint basis. I would probably default to the slower Full NGS and let the user select the faster Baumgarte method in performance critical scenarios. */ /* Cache Performance The Box2D solvers are dominated by cache misses. Data structures are designed to increase the number of cache hits. Much of misses are due to random access to body data. The constraint structures are iterated over linearly, which leads to few cache misses. The bodies are not accessed during iteration. Instead read only data, such as the mass values are stored with the constraints. The mutable data are the constraint impulses and the bodies velocities/positions. The impulses are held inside the constraint structures. The body velocities/positions are held in compact, temporary arrays to increase the number of cache hits. Linear and angular velocity are stored in a single array since multiple arrays lead to multiple misses. */ /* 2D Rotation R = [cos(theta) -sin(theta)] [sin(theta) cos(theta) ] thetaDot = omega Let q1 = cos(theta), q2 = sin(theta). R = [q1 -q2] [q2 q1] q1Dot = -thetaDot * q2 q2Dot = thetaDot * q1 q1_new = q1_old - dt * w * q2 q2_new = q2_old + dt * w * q1 then normalize. This might be faster than computing sin+cos. However, we can compute sin+cos of the same angle fast. */ b2Island::b2Island( int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, b2StackAllocator* allocator, b2ContactListener* listener) { m_bodyCapacity = bodyCapacity; m_contactCapacity = contactCapacity; m_jointCapacity = jointCapacity; m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_allocator = allocator; m_listener = listener; #ifdef __CHEERP__ /* m_bodies = new b2Body* [bodyCapacity]; m_contacts = new b2Contact* [contactCapacity]; m_joints = new b2Joint* [jointCapacity]; m_velocities = new b2Velocity [m_bodyCapacity]; m_positions = new b2Position [m_bodyCapacity]; */ m_bodies = m_allocator->Allocate_pb2Body(bodyCapacity); m_contacts = m_allocator->Allocate_pb2Contact(contactCapacity); m_joints = m_allocator->Allocate_pb2Joint(jointCapacity); m_velocities = m_allocator->Allocate_b2Velocity(m_bodyCapacity); m_positions = m_allocator->Allocate_b2Position(m_bodyCapacity); #else m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); #endif } b2Island::~b2Island() { #ifdef __CHEERP__ /* delete [] m_positions; delete [] m_velocities; delete [] m_joints; delete [] m_contacts; delete [] m_bodies; */ m_allocator->Free_b2Position(m_positions); m_allocator->Free_b2Velocity(m_velocities); m_allocator->Free_pb2Joint(m_joints); m_allocator->Free_pb2Contact(m_contacts); m_allocator->Free_pb2Body(m_bodies); #else // Warning: the order should reverse the constructor order. m_allocator->Free(m_positions); m_allocator->Free(m_velocities); m_allocator->Free(m_joints); m_allocator->Free(m_contacts); m_allocator->Free(m_bodies); #endif } void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) { b2Timer timer; float32 h = step.dt; // Integrate velocities and apply damping. Initialize the body state. for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; b2Vec2 c = b->m_sweep.c; float32 a = b->m_sweep.a; b2Vec2 v = b->m_linearVelocity; float32 w = b->m_angularVelocity; // Store positions for continuous collision. b->m_sweep.c0 = b->m_sweep.c; b->m_sweep.a0 = b->m_sweep.a; if (b->m_type == b2_dynamicBody) { // Integrate velocities. v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); w += h * b->m_invI * b->m_torque; // Apply damping. // ODE: dv/dt + c * v = 0 // Solution: v(t) = v0 * exp(-c * t) // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) // v2 = exp(-c * dt) * v1 // Taylor expansion: // v2 = (1.0f - c * dt) * v1 v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f); w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f); } m_positions[i].c = c; m_positions[i].a = a; m_velocities[i].v = v; m_velocities[i].w = w; } timer.Reset(); // Solver data b2SolverData solverData; solverData.step = step; solverData.positions = m_positions; solverData.velocities = m_velocities; // Initialize velocity constraints. b2ContactSolverDef contactSolverDef; contactSolverDef.step = step; contactSolverDef.contacts = m_contacts; contactSolverDef.count = m_contactCount; contactSolverDef.positions = m_positions; contactSolverDef.velocities = m_velocities; contactSolverDef.allocator = m_allocator; b2ContactSolver contactSolver(&contactSolverDef); contactSolver.InitializeVelocityConstraints(); if (step.warmStarting) { contactSolver.WarmStart(); } for (int32 i = 0; i < m_jointCount; ++i) { m_joints[i]->InitVelocityConstraints(solverData); } profile->solveInit = timer.GetMilliseconds(); // Solve velocity constraints timer.Reset(); for (int32 i = 0; i < step.velocityIterations; ++i) { for (int32 j = 0; j < m_jointCount; ++j) { m_joints[j]->SolveVelocityConstraints(solverData); } contactSolver.SolveVelocityConstraints(); } // Store impulses for warm starting contactSolver.StoreImpulses(); profile->solveVelocity = timer.GetMilliseconds(); // Integrate positions for (int32 i = 0; i < m_bodyCount; ++i) { b2Vec2 c = m_positions[i].c; float32 a = m_positions[i].a; b2Vec2 v = m_velocities[i].v; float32 w = m_velocities[i].w; // Check for large velocities b2Vec2 translation = h * v; if (b2Dot(translation, translation) > b2_maxTranslationSquared) { float32 ratio = b2_maxTranslation / translation.Length(); v *= ratio; } float32 rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { float32 ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } // Integrate c += h * v; a += h * w; m_positions[i].c = c; m_positions[i].a = a; m_velocities[i].v = v; m_velocities[i].w = w; } // Solve position constraints timer.Reset(); bool positionSolved = false; for (int32 i = 0; i < step.positionIterations; ++i) { bool contactsOkay = contactSolver.SolvePositionConstraints(); bool jointsOkay = true; for (int32 i = 0; i < m_jointCount; ++i) { bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { // Exit early if the position errors are small. positionSolved = true; break; } } // Copy state buffers back to the bodies for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* body = m_bodies[i]; body->m_sweep.c = m_positions[i].c; body->m_sweep.a = m_positions[i].a; body->m_linearVelocity = m_velocities[i].v; body->m_angularVelocity = m_velocities[i].w; body->SynchronizeTransform(); } profile->solvePosition = timer.GetMilliseconds(); Report(contactSolver.m_velocityConstraints); if (allowSleep) { float32 minSleepTime = b2_maxFloat; const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; if (b->GetType() == b2_staticBody) { continue; } if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || b->m_angularVelocity * b->m_angularVelocity > angTolSqr || b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) { b->m_sleepTime = 0.0f; minSleepTime = 0.0f; } else { b->m_sleepTime += h; minSleepTime = b2Min(minSleepTime, b->m_sleepTime); } } if (minSleepTime >= b2_timeToSleep && positionSolved) { for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; b->SetAwake(false); } } } } void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) { b2Assert(toiIndexA < m_bodyCount); b2Assert(toiIndexB < m_bodyCount); // Initialize the body state. for (int32 i = 0; i < m_bodyCount; ++i) { b2Body* b = m_bodies[i]; m_positions[i].c = b->m_sweep.c; m_positions[i].a = b->m_sweep.a; m_velocities[i].v = b->m_linearVelocity; m_velocities[i].w = b->m_angularVelocity; } b2ContactSolverDef contactSolverDef; contactSolverDef.contacts = m_contacts; contactSolverDef.count = m_contactCount; contactSolverDef.allocator = m_allocator; contactSolverDef.step = subStep; contactSolverDef.positions = m_positions; contactSolverDef.velocities = m_velocities; b2ContactSolver contactSolver(&contactSolverDef); // Solve position constraints. for (int32 i = 0; i < subStep.positionIterations; ++i) { bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); if (contactsOkay) { break; } } #if 0 // Is the new position really safe? for (int32 i = 0; i < m_contactCount; ++i) { b2Contact* c = m_contacts[i]; b2Fixture* fA = c->GetFixtureA(); b2Fixture* fB = c->GetFixtureB(); b2Body* bA = fA->GetBody(); b2Body* bB = fB->GetBody(); int32 indexA = c->GetChildIndexA(); int32 indexB = c->GetChildIndexB(); b2DistanceInput input; input.proxyA.Set(fA->GetShape(), indexA); input.proxyB.Set(fB->GetShape(), indexB); input.transformA = bA->GetTransform(); input.transformB = bB->GetTransform(); input.useRadii = false; b2DistanceOutput output; b2SimplexCache cache; cache.count = 0; b2Distance(&output, &cache, &input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } #endif // Leap of faith to new safe state. m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; // No warm starting is needed for TOI events because warm // starting impulses were applied in the discrete solver. contactSolver.InitializeVelocityConstraints(); // Solve velocity constraints. for (int32 i = 0; i < subStep.velocityIterations; ++i) { contactSolver.SolveVelocityConstraints(); } // Don't store the TOI contact forces for warm starting // because they can be quite large. float32 h = subStep.dt; // Integrate positions for (int32 i = 0; i < m_bodyCount; ++i) { b2Vec2 c = m_positions[i].c; float32 a = m_positions[i].a; b2Vec2 v = m_velocities[i].v; float32 w = m_velocities[i].w; // Check for large velocities b2Vec2 translation = h * v; if (b2Dot(translation, translation) > b2_maxTranslationSquared) { float32 ratio = b2_maxTranslation / translation.Length(); v *= ratio; } float32 rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { float32 ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } // Integrate c += h * v; a += h * w; m_positions[i].c = c; m_positions[i].a = a; m_velocities[i].v = v; m_velocities[i].w = w; // Sync bodies b2Body* body = m_bodies[i]; body->m_sweep.c = c; body->m_sweep.a = a; body->m_linearVelocity = v; body->m_angularVelocity = w; body->SynchronizeTransform(); } Report(contactSolver.m_velocityConstraints); } void b2Island::Report(const b2ContactVelocityConstraint* constraints) { if (m_listener == NULL) { return; } for (int32 i = 0; i < m_contactCount; ++i) { b2Contact* c = m_contacts[i]; const b2ContactVelocityConstraint* vc = constraints + i; b2ContactImpulse impulse; impulse.count = vc->pointCount; for (int32 j = 0; j < vc->pointCount; ++j) { impulse.normalImpulses[j] = vc->points[j].normalImpulse; impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; } m_listener->PostSolve(c, &impulse); } }
ddiproietto/nontetris
srclib/Box2D/Box2D/Dynamics/b2Island.cpp
C++
gpl-3.0
18,136
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-13 20:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Artist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=80, unique=True)), ], ), migrations.CreateModel( name='Song', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('order', models.IntegerField()), ('name', models.CharField(max_length=100)), ('duration', models.IntegerField()), ('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='songs', to='songs.Album')), ], options={ 'ordering': ['order'], }, ), migrations.AddField( model_name='album', name='artist', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='albums', to='songs.Artist'), ), ]
migglu/song-streamer
songstreamer/songs/migrations/0001_initial.py
Python
gpl-3.0
1,687
<?php /** * Command Console * * Common Commands. * * Console script for Battlefield Play4Free MH Clan. * Interprets in-game chat messages to commands. * * @category BFP4F * @package cmdcon * @author piqus <ovirendo@gmail.com> * @license RESTRICTED. * @version 0.1 * @link http://piqus.pl/ */ class CommonCommands extends Commands { public function sendMsg($message='') { $output = self::enchanceMessage($message); if (empty($output)) { $output = $message; } self::$rcc->send($output); return true; } public function showPing() { foreach (self::$players as $id => $player) { if (self::$msg->origin == $player->name) { $output = str_replace("%ping%", $player->ping, self::$config['msg.ping.message']); $output = str_replace("%player%", $player->name, $output); self::$rcc->send($output); return true; } } return false; } public function report($soldier_name, $issue='') { var_dump(func_get_args()); $author = null; // Get author of report foreach (self::$players as $id => $player) { if (self::$msg->origin == $player->name) { $author = $player; break; } } if (empty($author)) { self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.report.not_sent']); return false; } // Check if it player report or just issue report if (isset($soldier_name) && !empty($soldier_name) && $reported = self::findPlayer($soldier_name)) { // PlayerReport if (DB::reportPlayer(self::$config['db.table_reports'], $author->name, $reported->name, $issue, $author->nucleusId, $author->cdKeyHash, $reported->nucleusId, $reported->cdKeyHash)) { self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.player_report.sent']); return true; } else { self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.player_report.not_sent']); return false; } } elseif (isset($soldier_name) && !empty($soldier_name)) { $issue = $soldier_name . " " . $issue; if (DB::reportIssue(self::$config['db.table_reports'], $author->name, $issue, $author->nucleusId, $author->cdKeyHash)) { self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.issue_report.sent']); return true; } else { self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.issue_report.not_sent']); return false; } } else { // Problem with report self::$rcc->sendPlayer(self::$msg->index, self::$config['msg.report.not_sent']); return false; } } public function kickPlayer($soldier_name, $reason = null) { if (($player = self::findPlayer($soldier_name))!==false) { self::$rcp->kick($player->index, $reason); return true; } else { return false; } } public function banPlayer($soldier_name, $time = "perm", $reason = null) { if (($player = self::findPlayer($soldier_name))!==false) { self::$rcp->ban($player->index, $time, $reason); return true; } else { return false; } } public function timeKickPlayer($soldier_name, $time, $reason = null) { $time = self::convertTime($time); if (($player = self::findPlayer($soldier_name))!==false) { $output = self::enchanceMessage($reason); DB::addMisbehavingPlayer(self::$config['db.table_kicklog'], $player->name, $time, $reason, $player->profileId, $player->cdKeyHash); self::$rcp->kick($player->index, $reason); return true; } else { return false; } } public function warnPlayer($soldier_name, $reason = null) { if (($player = self::findPlayer($soldier_name))!==false) { $output = self::enchanceMessage($reason); self::$rcc->send($output); return true; } else { return false; } } public function sendPM($recipient, $message='') { if (($player = self::findPlayer($recipient))!==false) { $output = self::enchanceMessage($message); if (empty($output)) { $output = $message; } self::$rcc->sendPlayer($player->index, $output); return true; } else { return false; } } public function switchAutobalance($status = "1") { switch ($status) { case '1': case 'on': self::$rcp->switchAutobalance("1"); self::$rcc->send(self::$config['msg.ab.status_on']); return true; break; case '0': case 'off': self::$rcp->switchAutobalance("0"); self::$rcc->send(self::$config['msg.ab.status_off']); return true; break; default: self::$rcc->sendPlayer(self::$msg->origin, self::$config['msg.ab.wrong_param']); return false; break; } } public function restart() { self::$srv->restartMap(); if (isset(self::$config['msg.restart']) && !empty(self::$config['msg.restart']) && self::$config['msg.restart'] != false) { self::$rcc->send(self::$config['msg.restart']); } return true; } public function nextMap() { self::$srv->skip(); return true; } public function pause() { if (isset(self::$config['msg.pause']) && !empty(self::$config['msg.pause']) && self::$config['msg.pause'] != false) { self::$rcc->send(self::$config['msg.pause']); } self::$srv->pause(); return true; } public function unpause() { if (isset(self::$config['msg.unpause']) && !empty(self::$config['msg.unpause']) && self::$config['msg.unpause'] != false) { self::$rcc->send(self::$config['msg.unpause']); } self::$srv->unpause(); return true; } public function togglePause() { if (isset(self::$config['msg.toggle_pause']) && !empty(self::$config['msg.toggle_pause']) && self::$config['msg.toggle_pause'] != false) { self::$rcc->send(self::$config['msg.toggle_pause']); } self::$srv->togglePause(); return true; } public function changeMap($type, $map) { $game_type = null; switch (true) { case strcasecmp($type, "gpm_cq") != true: case strcasecmp($type, "cq") != true: case strcasecmp($type, "gpm_nv") != true: case strcasecmp($type, "nv") != true: case strcasecmp($type, "conquest") != true: $game_type = "gpm_cq"; break; case strcasecmp($type, "gpm_ti") != true: case strcasecmp($type, "ti") != true: case strcasecmp($type, "titan") != true: $game_type = "gpm_ti"; break; case strcasecmp($type, "gpm_coop") != true: case strcasecmp($type, "coop") != true: $game_type = "gpm_coop"; break; case strcasecmp($type, "gpm_ca") != true: case strcasecmp($type, "ca") != true: case strcasecmp($type, "conqassault") != true: case strcasecmp($type, "conquestassault") != true: case strcasecmp($type, "conquest_assault") != true: $game_type = "gpm_ca"; break; case strcasecmp($type, "gpm_hoth") != true: case strcasecmp($type, "hoth") != true: case strcasecmp($type, "v2") != true: case strcasecmp($type, "vengence") != true: $game_type = "gpm_hoth"; break; case strcasecmp($type, "assault") != true: case strcasecmp($type, "as") != true: case strcasecmp($type, "sa") != true: case strcasecmp($type, "ass") != true: case strcasecmp($type, "assa") != true: case strcasecmp($type, "gpm_sa") != true: $game_type = "gpm_sa"; break; case strcasecmp($type, "gpm_rush") != true: case strcasecmp($type, "rush") != true: $game_type = "gpm_rush"; break; case strcasecmp($type, "gpm_tdm") != true: case strcasecmp($type, "deathmatch") != true: case strcasecmp($type, "teamdeathmatch") != true: case strcasecmp($type, "team_deathmatch") != true: $game_type = "gpm_tdm"; break; default: self::$rcc->sendPrivate(self::$msg->index, self::$config['msg.no_such_game_type']); $game_type = "gpm_sa"; break; } $change_map = null; switch (true) { case strcasecmp($map, "karkand") != true: case strcasecmp($map, "strike_at_karkand") != true: case strcasecmp($map, "strike at karkand") != true: case strcasecmp($map, "karkand_assault") != true: case strcasecmp($map, "karkand-assault") != true: case strcasecmp($map, "karkand assault") != true: $change_map = "strike_at_karkand"; $change_map = "kar"; $change_map = "kark"; $type = "gm_sa"; break; case strcasecmp($map, "oman") != true: case strcasecmp($map, "gulf_of_oman") != true: case strcasecmp($map, "gulf of oman") != true: $change_map = "gulf_of_oman"; break; case strcasecmp($map, "sharqi") != true: $change_map = "sharqi"; break; case strcasecmp($map, "Dalian_plant") != true: case strcasecmp($map, "Dalian plant") != true: case strcasecmp($map, "dalian") != true: case strcasecmp($map, "delian") != true: case strcasecmp($map, "daliant") != true: case strcasecmp($map, "dal") != true: case strcasecmp($map, "dali") != true: $change_map = "dalian_plant"; break; case strcasecmp($map, "Downtown") != true: case strcasecmp($map, "Basra") != true: case strcasecmp($map, "Basrah") != true: case strcasecmp($map, "Bas") != true: case strcasecmp($map, "Basr") != true: $change_map = "downtown"; break; case strcasecmp($map, "Dragon_Valley") != true: case strcasecmp($map, "Dragon Valley") != true: case strcasecmp($map, "Dragon-Valley") != true: case strcasecmp($map, "Dragon") != true: case strcasecmp($map, "DV") != true: case strcasecmp($map, "Drag") != true: case strcasecmp($map, "Dra") != true: $change_map = "dragon_valley"; break; case strcasecmp($map, "karkand_rush") != true: case strcasecmp($map, "karkand rush") != true: case strcasecmp($map, "karkrush") != true: $change_map = "karkand_rush"; break; case strcasecmp($map, "Mashtuur_City") != true: case strcasecmp($map, "Mashtuur City") != true: case strcasecmp($map, "Mashtuur-City") != true: case strcasecmp($map, "Mashtuur") != true: case strcasecmp($map, "Mashtur") != true: case strcasecmp($map, "Mash") != true: case strcasecmp($map, "Mas") != true: $change_map = "mashtuur_city"; break; case strcasecmp($map, "Trail") != true: case strcasecmp($map, "Myanmar") != true: case strcasecmp($map, "Burma") != true: case strcasecmp($map, "Birma") != true: case strcasecmp($map, "Myan") != true: $change_map = "trail"; break; default: self::$rcc->sendPrivate(self::$msg->index, self::$config['msg.no_such_map']); return false; break; } if (isset(self::$config['msg.change_map']) && !empty(self::$config['msg.change_map']) && self::$config['msg.change_map'] != false) { self::$rcc->send(self::$config['msg.change_map']); } self::$srv->changeMap($change_map); return true; } public function listAvailableCommands($type = null) { if (isset($type) && $type == "owner") { $results = DB::getCommandsByLevel(self::$config['db.table_user_commands'], 200); } elseif(isset($type) && $type == "admin") { $results = DB::getCommandsByLevel(self::$config['db.table_user_commands'], 100); } elseif (isset($type) && $type = "mod") { $results = DB::getCommandsByLevel(self::$config['db.table_user_commands'], 50); } else { $results = DB::getCommandsByLevel(self::$config['db.table_user_commands'], 0); } $commands = implode(", ", $results); $output = str_replace("%commands%", $commands, self::$config['msg.commands']); self::$rcc->send($output); return true; } public function listAdmins($type = "online") { if (isset($type) && $type == "list") { $results = DB::getAllAdmins(); if (count($results) > 0) { $output = str_replace("%admins%", implode(", ", $results), self::$config['msg.admins.all']); self::$rcc->send($output); return true; } else { self::$rcc->send(self::$config['msg.admin_search.no_admins_found']); return true; } } else { $profileIds = array(); $soldierIds = array(); foreach (self::$players as $iter => $player) { $profileIds[] = $player->nucleusId; $soldierIds[] = $player->cdKeyHash; } $results = DB::getOnlineAdmins($profileIds, $soldierIds); if (count($results) > 0) { $output = str_replace("%admins%", implode(", ", $results), self::$config['msg.admins.online']); self::$rcc->send($output); return true; } else { self::$rcc->send(self::$config['msg.admin_online.no_admins_found']); return true; } $online = implode(", ", $admins); $adminString = implode(", ", $admins); $output = str_replace("%admins%", $adminString, self::$config['msg.admins.online']); self::$rcc->send($output); return true; } } public function searchAdmin($player) { $results = DB::getSpecifiedAdmins($player); if (is_array($results)) { if (count($results) > 0) { $output = str_replace("%admins%", implode(", ", $results), self::$config['msg.admin_search.results']); self::$rcc->send($output); return true; } else { self::$rcc->send(self::$config['msg.admin_search.no_admins_found']); return true; } } else { self::$rcc->send(self::$config['msg.admin_search.problem']); return false; } } public function switch($soldier_name) { $soldier_name = trim($soldier_name); if (($player = self::findPlayer($soldier_name))!==false) { $output = self::enchanceMessage($config['msg.switch_player'], $player); self::$rcc->send($output); self::$rcp->switchPlayer($player->index); return true; } else { return false; } } } ?>
piqus/bfp4f-console
src/console/CommonCommands.php
PHP
gpl-3.0
13,376
from calfbox._cbox2 import * from io import BytesIO import struct import sys import traceback import calfbox.metadata as metadata #local file metadata.py type_wrapper_debug = False is_python3 = not sys.version.startswith("2") ############################################################################### # Ugly internals. Please skip this section for your own sanity. ############################################################################### class GetUUID: """An object that calls a C layer command, receives a /uuid callback from it and stores the passed UUID in its uuid attribute. Example use: GetUUID('/command', arg1, arg2...).uuid """ def __init__(self, cmd, *cmd_args): def callback(cmd, fb, args): if cmd == "/uuid" and len(args) == 1: self.uuid = args[0] else: raise ValueException("Unexpected callback: %s" % cmd) self.callback = callback self.uuid = None do_cmd(cmd, self, list(cmd_args)) def __call__(self, *args): self.callback(*args) class GetThings: """A generic callback object that receives various forms of information from C layer and converts then into object's Python attributes. This is an obsolete interface, to be replaced by GetUUID or metaclass based type-safe autoconverter. However, there are still some cases that aren't (yet) handled by either. """ @staticmethod def by_uuid(uuid, cmd, anames, args): return GetThings(Document.uuid_cmd(uuid, cmd), anames, args) def __init__(self, cmd, anames, args): for i in anames: if i.startswith("*"): setattr(self, i[1:], []) elif i.startswith("%"): setattr(self, i[1:], {}) else: setattr(self, i, None) anames = set(anames) self.seq = [] def update_callback(cmd, fb, args): self.seq.append((cmd, fb, args)) cmd = cmd[1:] if cmd in anames: if len(args) == 1: setattr(self, cmd, args[0]) else: setattr(self, cmd, args) elif "*" + cmd in anames: if len(args) == 1: getattr(self, cmd).append(args[0]) else: getattr(self, cmd).append(args) elif "%" + cmd in anames: if len(args) == 2: getattr(self, cmd)[args[0]] = args[1] else: getattr(self, cmd)[args[0]] = args[1:] elif "?" + cmd in anames: setattr(self, cmd, bool(args[0])) elif len(args) == 1: setattr(self, cmd, args[0]) do_cmd(cmd, update_callback, args) def __str__(self): return str(self.seq) class PropertyDecorator(object): """Abstract property decorator.""" def __init__(self, base): self.base = base def get_base(self): return self.base def map_cmd(self, cmd): return cmd class AltPropName(PropertyDecorator): """Command-name-changing property decorator. Binds a property to the specified /path, different from the default one, which based on property name, with -s and -es suffix removed for lists and dicts.""" def __init__(self, alt_name, base): PropertyDecorator.__init__(self, base) self.alt_name = alt_name def map_cmd(self, cmd): return self.alt_name def execute(self, property, proptype, klass): pass class SettableProperty(PropertyDecorator): """Decorator that creates a setter method for the property.""" def execute(self, property, proptype, klass): if type(proptype) is dict: setattr(klass, 'set_' + property, lambda self, key, value: self.cmd('/' + property, None, key, value)) elif type(proptype) is bool: setattr(klass, 'set_' + property, lambda self, value: self.cmd('/' + property, None, 1 if value else 0)) elif issubclass(proptype, DocObj): setattr(klass, 'set_' + property, lambda self, value: self.cmd('/' + property, None, value.uuid)) else: setattr(klass, 'set_' + property, lambda self, value: self.cmd('/' + property, None, proptype(value))) def new_get_things(obj, cmd, settermap, args): """Call C command with arguments 'args', populating a return object obj using settermap to interpret callback commands and initialise the return object.""" def update_callback(cmd2, fb, args2): try: if cmd2 in settermap: settermap[cmd2](obj, args2) elif cmd2 != '/uuid': # Ignore UUID as it's usually safe to do so print ("Unexpected command: %s" % cmd2) except Exception as error: traceback.print_exc() raise # Set initial values for the properties (None or empty dict/list) for setterobj in settermap.values(): setattr(obj, setterobj.property, setterobj.init_value()) # Call command and apply callback commands via setters to the object do_cmd(cmd, update_callback, args) return obj def _error_arg_mismatch(required, passed): raise ValueError("Types required: %s, values passed: %s" % (repr(required), repr(passed))) def _handle_object_wrapping(t): if issubclass(t, DocObj): return lambda uuid: Document.map_uuid_and_check(uuid, t) return t def _make_args_to_type_lambda(t): t = _handle_object_wrapping(t) return lambda args: t(*args) def _make_args_to_tuple_of_types_lambda(ts): ts = list(map(_handle_object_wrapping, ts)) return lambda args: tuple([ts[i](args[i]) for i in range(max(len(ts), len(args)))]) if len(ts) == len(args) else _error_arg_mismatch(ts, args) def _make_args_decoder(t): if type(t) is tuple: return _make_args_to_tuple_of_types_lambda(t) else: return _make_args_to_type_lambda(t) def get_thing(cmd, fieldcmd, datatype, *args): pull = False if type(datatype) is list: assert (len(datatype) == 1) decoder = _make_args_decoder(datatype[0]) value = [] def adder(data): value.append(decoder(data)) elif type(datatype) is dict: assert (len(datatype) == 1) key_type, value_type = list(datatype.items())[0] key_decoder = _make_args_decoder(key_type) value_decoder = _make_args_decoder(value_type) value = {} def adder(data): value[key_decoder([data[0]])] = value_decoder(data[1:]) else: decoder = _make_args_decoder(datatype) def adder(data): value[0] = decoder(data) value = [None] pull = True def callback(cmd2, fb, args2): if cmd2 == fieldcmd: adder(args2) else: print ("Unexpected command %s" % cmd2) do_cmd(cmd, callback, list(args)) if pull: return value[0] else: return value class SetterWithConversion: """A setter object class that sets a specific property to a typed value or a tuple of typed value.""" def __init__(self, property, extractor): self.property = property self.extractor = extractor def init_value(self): return None def __call__(self, obj, args): # print ("Setting attr %s on object %s" % (self.property, obj)) setattr(obj, self.property, self.extractor(args)) class ListAdderWithConversion: """A setter object class that adds a tuple filled with type-converted arguments of the callback to a list. E.g. ListAdderWithConversion('foo', (int, int))(obj, [1,2]) adds a tuple: (int(1), int(2)) to the list obj.foo""" def __init__(self, property, extractor): self.property = property self.extractor = extractor def init_value(self): return [] def __call__(self, obj, args): getattr(obj, self.property).append(self.extractor(args)) class DictAdderWithConversion: """A setter object class that adds a tuple filled with type-converted arguments of the callback to a dictionary under a key passed as first argument i.e. DictAdderWithConversion('foo', str, (int, int))(obj, ['bar',1,2]) adds a tuple: (int(1), int(2)) under key 'bar' to obj.foo""" def __init__(self, property, keytype, valueextractor): self.property = property self.keytype = keytype self.valueextractor = valueextractor def init_value(self): return {} def __call__(self, obj, args): getattr(obj, self.property)[self.keytype(args[0])] = self.valueextractor(args[1:]) def _type_properties(base_type): return {prop: getattr(base_type, prop) for prop in dir(base_type) if not prop.startswith("__")} def _create_setter(prop, t): if type(t) in [type, tuple] or issubclass(type(t), DocObj): if type_wrapper_debug: print ("%s is type %s" % (prop, repr(t))) return SetterWithConversion(prop, _make_args_decoder(t)) elif type(t) is dict: assert(len(t) == 1) tkey, tvalue = list(t.items())[0] if type_wrapper_debug: print ("%s is type: %s -> %s" % (prop, repr(tkey), repr(tvalue))) return DictAdderWithConversion(prop, tkey, _make_args_decoder(tvalue)) elif type(t) is list: assert(len(t) == 1) if type_wrapper_debug: print ("%s is array of %s" % (prop, repr(t[0]))) return ListAdderWithConversion(prop, _make_args_decoder(t[0])) else: raise ValueError("Don't know what to do with property '%s' of type %s" % (prop, repr(t))) def _create_unmarshaller(name, base_type, object_wrapper = False, property_grabber = _type_properties): all_decorators = {} prop_types = {} settermap = {} if type_wrapper_debug: print ("Wrapping type: %s" % name) print ("-----") for prop, proptype in property_grabber(base_type).items(): decorators = [] propcmd = '/' + prop if type(proptype) in [list, dict]: if propcmd.endswith('s'): if propcmd.endswith('es'): propcmd = propcmd[:-2] else: propcmd = propcmd[:-1] while isinstance(proptype, PropertyDecorator): decorators.append(proptype) propcmd = proptype.map_cmd(propcmd) proptype = proptype.get_base() settermap[propcmd] = _create_setter(prop, proptype) all_decorators[prop] = decorators prop_types[prop] = proptype base_type.__str__ = lambda self: (str(name) + ":" + " ".join(["%s=%s" % (v.property, str(getattr(self, v.property))) for v in settermap.values()])) if type_wrapper_debug: print ("") def exec_cmds(o): for propname, decorators in all_decorators.items(): for decorator in decorators: decorator.execute(propname, prop_types[propname], o) if object_wrapper: return exec_cmds, lambda cmd: (lambda self, *args: new_get_things(base_type(), self.path + cmd, settermap, list(args))) else: return lambda cmd, *args: new_get_things(base_type(), cmd, settermap, list(args)) class NonDocObj(object): """Root class for all wrapper classes that wrap objects that don't have their own identity/UUID. This covers various singletons and inner objects (e.g. engine in instruments).""" class Status: pass def __init__(self, path): self.path = path def __new__(classObj, *args, **kwargs): if is_python3: result = object.__new__(classObj) result.__init__(*args, **kwargs) else: result = object.__new__(classObj, *args, **kwargs) name = classObj.__name__ if getattr(classObj, 'wrapped_class', None) != name: classfinaliser, cmdwrapper = _create_unmarshaller(name, classObj.Status, object_wrapper = True) classfinaliser(classObj) classObj.status = cmdwrapper('/status') classObj.wrapped_class = name return result def cmd(self, cmd, fb = None, *args): do_cmd(self.path + cmd, fb, list(args)) def cmd_makeobj(self, cmd, *args): return Document.map_uuid(GetUUID(self.path + cmd, *args).uuid) def get_things(self, cmd, fields, *args): return GetThings(self.path + cmd, fields, list(args)) def get_thing(self, cmd, fieldcmd, type, *args): return get_thing(self.path + cmd, fieldcmd, type, *args) def make_path(self, path): return self.path + path def __str__(self): return "%s<%s>" % (self.__class__.__name__, self.path) class DocObj(NonDocObj): """Root class for all wrapper classes that wrap first-class document objects.""" class Status: pass def __init__(self, uuid): NonDocObj.__init__(self, Document.uuid_cmd(uuid, '')) self.uuid = uuid def delete(self): self.cmd("/delete") def __str__(self): return "%s<%s>" % (self.__class__.__name__, self.uuid) class VarPath: def __init__(self, path, args = []): self.path = path self.args = args def plus(self, subpath, *args): return VarPath(self.path if subpath is None else self.path + "/" + subpath, self.args + list(args)) def set(self, *values): do_cmd(self.path, None, self.args + list(values)) ############################################################################### # And those are the proper user-accessible objects. ############################################################################### class Config: class KeysUnmarshaller: keys = [str] keys_unmarshaller = _create_unmarshaller('Config.keys()', KeysUnmarshaller) """INI file manipulation class.""" @staticmethod def sections(prefix = ""): """Return a list of configuration sections.""" return [CfgSection(name) for name in get_thing('/config/sections', '/section', [str], prefix)] @staticmethod def keys(section, prefix = ""): """Return a list of configuration keys in a section, with optional prefix filtering.""" return Config.keys_unmarshaller('/config/keys', str(section), str(prefix)).keys @staticmethod def get(section, key): """Return a string value of a given key.""" return get_thing('/config/get', '/value', str, str(section), str(key)) @staticmethod def set(section, key, value): """Set a string value for a given key.""" do_cmd('/config/set', None, [str(section), str(key), str(value)]) @staticmethod def delete(section, key): """Delete a given key.""" do_cmd('/config/delete', None, [str(section), str(key)]) @staticmethod def save(filename = None): """Save config, either into current INI file or some other file.""" if filename is None: do_cmd('/config/save', None, []) else: do_cmd('/config/save', None, [str(filename)]) @staticmethod def add_section(section, content): """Populate a config section based on a string with key=value lists. This is a toy/debug function, it doesn't handle any edge cases.""" for line in content.splitlines(): line = line.strip() if line == '' or line.startswith('#'): continue try: key, value = line.split("=", 2) except ValueError as err: raise ValueError("Cannot parse config line '%s'" % line) Config.set(section, key.strip(), value.strip()) class Transport: @staticmethod def seek_ppqn(ppqn): do_cmd('/master/seek_ppqn', None, [int(ppqn)]) @staticmethod def seek_samples(samples): do_cmd('/master/seek_samples', None, [int(samples)]) @staticmethod def set_tempo(tempo): do_cmd('/master/set_tempo', None, [float(tempo)]) @staticmethod def set_timesig(nom, denom): do_cmd('/master/set_timesig', None, [int(nom), int(denom)]) @staticmethod def set_ppqn_factor(factor): do_cmd('/master/set_ppqn_factor', None, [int(factor)]) @staticmethod def play(): do_cmd('/master/play', None, []) @staticmethod def stop(): do_cmd('/master/stop', None, []) @staticmethod def panic(): do_cmd('/master/panic', None, []) @staticmethod def status(): return GetThings("/master/status", ['pos', 'pos_ppqn', 'tempo', 'timesig', 'sample_rate', 'playing', 'ppqn_factor'], []) @staticmethod def tell(): return GetThings("/master/tell", ['pos', 'pos_ppqn', 'playing'], []) @staticmethod def ppqn_to_samples(pos_ppqn): return get_thing("/master/ppqn_to_samples", '/value', int, pos_ppqn) @staticmethod def samples_to_ppqn(pos_samples): return get_thing("/master/samples_to_ppqn", '/value', int, pos_samples) # Currently responsible for both JACK and USB I/O - not all functionality is # supported by both. class JackIO: AUDIO_TYPE = "32 bit float mono audio" MIDI_TYPE = "8 bit raw midi" PORT_IS_SINK = 0x1 PORT_IS_SOURCE = 0x2 PORT_IS_PHYSICAL = 0x4 PORT_CAN_MONITOR = 0x8 PORT_IS_TERMINAL = 0x10 metadata.get_thing = get_thing #avoid circular dependency and redundant code Metadata = metadata.Metadata #use with cbox.JackIO.Metadata.get_all_properties() @staticmethod def status(): # Some of these only make sense for JACK return GetThings("/io/status", ['client_type', 'client_name', 'audio_inputs', 'audio_outputs', 'buffer_size', '*midi_output', '*midi_input', 'sample_rate', 'output_resolution', '*usb_midi_input', '*usb_midi_output', '?external_tempo'], []) @staticmethod def jack_transport_position(): # Some of these only make sense for JACK return GetThings("/io/jack_transport_position", ['state', 'unique_lo', 'unique_hi', 'usecs_lo', 'usecs_hi', 'frame_rate', 'frame', 'bar', 'beat', 'tick', 'bar_start_tick', 'bbt_frame_offset', 'beats_per_bar', 'beat_type', 'ticks_per_beat', 'beats_per_minute', 'is_master'], []) @staticmethod def jack_transport_locate(pos): do_cmd("/io/jack_transport_locate", None, [pos]) @staticmethod def transport_mode(master = True, conditional = False): if master: do_cmd("/io/transport_mode", None, [1 if conditional else 2]) else: do_cmd("/io/transport_mode", None, [0]) @staticmethod def create_midi_input(name, autoconnect_spec = None): uuid = GetUUID("/io/create_midi_input", name).uuid if autoconnect_spec is not None and autoconnect_spec != '': JackIO.autoconnect(uuid, autoconnect_spec) return uuid @staticmethod def create_midi_output(name, autoconnect_spec = None): uuid = GetUUID("/io/create_midi_output", name).uuid if autoconnect_spec is not None and autoconnect_spec != '': JackIO.autoconnect(uuid, autoconnect_spec) return uuid @staticmethod def autoconnect(uuid, autoconnect_spec = None): if autoconnect_spec is not None: do_cmd("/io/autoconnect", None, [uuid, autoconnect_spec]) else: do_cmd("/io/autoconnect", None, [uuid, '']) autoconnect_midi_input = autoconnect autoconnect_midi_output = autoconnect autoconnect_audio_output = autoconnect @staticmethod def rename_midi_output(uuid, new_name): do_cmd("/io/rename_midi_port", None, [uuid, new_name]) rename_midi_input = rename_midi_output @staticmethod def disconnect_midi_port(uuid): do_cmd("/io/disconnect_midi_port", None, [uuid]) @staticmethod def disconnect_midi_output(uuid): do_cmd("/io/disconnect_midi_output", None, [uuid]) @staticmethod def disconnect_midi_input(uuid): do_cmd("/io/disconnect_midi_input", None, [uuid]) @staticmethod def delete_midi_input(uuid): do_cmd("/io/delete_midi_input", None, [uuid]) @staticmethod def delete_midi_output(uuid): do_cmd("/io/delete_midi_output", None, [uuid]) @staticmethod def route_midi_input(input_uuid, scene_uuid): do_cmd("/io/route_midi_input", None, [input_uuid, scene_uuid]) @staticmethod def set_appsink_for_midi_input(input_uuid, enabled): do_cmd("/io/set_appsink_for_midi_input", None, [input_uuid, 1 if enabled else 0]) @staticmethod def get_new_events(input_uuid): seq = [] do_cmd("/io/get_new_events", (lambda cmd, fb, args: seq.append((cmd, fb, args))), [input_uuid]) return seq @staticmethod def create_audio_output(name, autoconnect_spec = None): uuid = GetUUID("/io/create_audio_output", name).uuid if autoconnect_spec is not None and autoconnect_spec != '': JackIO.autoconnect(uuid, autoconnect_spec) return uuid @staticmethod def create_audio_output_router(uuid_left, uuid_right): return get_thing("/io/create_audio_output_router", "/uuid", DocRecorder, uuid_left, uuid_right) @staticmethod def delete_audio_output(uuid): do_cmd("/io/delete_audio_output", None, [uuid]) @staticmethod def rename_audio_output(uuid, new_name): do_cmd("/io/rename_audio_port", None, [uuid, new_name]) @staticmethod def disconnect_audio_output(uuid): do_cmd("/io/disconnect_audio_output", None, [uuid]) @staticmethod def port_connect(pfrom, pto): do_cmd("/io/port_connect", None, [pfrom, pto]) @staticmethod def port_disconnect(pfrom, pto): do_cmd("/io/port_disconnect", None, [pfrom, pto]) @staticmethod def get_ports(name_mask = ".*", type_mask = ".*", flag_mask = 0): return get_thing("/io/get_ports", '/port', [str], name_mask, type_mask, int(flag_mask)) @staticmethod def get_connected_ports(port): return get_thing("/io/get_connected_ports", '/port', [str], port) @staticmethod def external_tempo(enable): """Enable reacting to JACK transport tempo""" do_cmd('/io/external_tempo', None, [1 if enable else 0]) def call_on_idle(callback = None): do_cmd("/on_idle", callback, []) def get_new_events(): seq = [] do_cmd("/on_idle", (lambda cmd, fb, args: seq.append((cmd, fb, args))), []) return seq def send_midi_event(*data, **kwargs): output = kwargs.get('output', None) do_cmd('/send_event_to', None, [output if output is not None else ''] + list(data)) def send_sysex(data, output = None): do_cmd('/send_sysex_to', None, [output if output is not None else '', bytearray(data)]) def flush_rt(): do_cmd('/rt/flush', None, []) class CfgSection: def __init__(self, name): self.name = name def __getitem__(self, key): return Config.get(self.name, key) def __setitem__(self, key, value): Config.set(self.name, key, value) def __delitem__(self, key): Config.delete(self.name, key) def keys(self, prefix = ""): return Config.keys(self.name, prefix) class Pattern: @staticmethod def get_pattern(): pat_data = get_thing("/get_pattern", '/pattern', (bytes, int)) if pat_data is not None: pat_blob, length = pat_data pat_data = [] ofs = 0 while ofs < len(pat_blob): data = list(struct.unpack_from("iBBbb", pat_blob, ofs)) data[1:2] = [] pat_data.append(tuple(data)) ofs += 8 return pat_data, length return None @staticmethod def serialize_event(time, *data): if len(data) >= 1 and len(data) <= 3: return struct.pack("iBBbb"[0:2 + len(data)], int(time), len(data), *[int(v) for v in data]) raise ValueError("Invalid length of an event (%d)" % len(data)) class Document: """Document singleton.""" classmap = {} objmap = {} @staticmethod def dump(): """Print all objects in the documents to stdout. Only used for debugging.""" do_cmd("/doc/dump", None, []) @staticmethod def uuid_cmd(uuid, cmd): """Internal: execute a given request on an object with specific UUID.""" return "/doc/uuid/%s%s" % (uuid, cmd) @staticmethod def get_uuid(path): """Internal: retrieve an UUID of an object that has specified path.""" return GetUUID('%s/get_uuid' % path).uuid @staticmethod def map_path(path, *args): """Internal: return an object corresponding to a path""" return Document.map_uuid(Document.get_uuid(path)) @staticmethod def cmd_makeobj(cmd, *args): """Internal: create an object from the UUID result of a command""" return Document.map_uuid(GetUUID(cmd, *args).uuid) @staticmethod def get_obj_class(uuid): """Internal: retrieve an internal class type of an object that has specified path.""" return get_thing(Document.uuid_cmd(uuid, "/get_class_name"), '/class_name', str) @staticmethod def get_song(): """Retrieve the current song object of a given document. Each document can only have one current song.""" return Document.map_path("/song") @staticmethod def get_scene(): """Retrieve the first scene object of a default engine. This function is considered obsolete-ish, because of multiple scene support.""" return Document.map_path("/scene") @staticmethod def get_engine(): """Retrieve the current RT engine object of a given document. Each document can only have one current RT engine.""" return Document.map_path("/rt/engine") @staticmethod def get_rt(): """Retrieve the RT singleton. RT is an object used to communicate between realtime and user thread, and is currently also used to access the audio engine.""" return Document.map_path("/rt") @staticmethod def new_engine(srate, bufsize): """Create a new off-line engine object. This new engine object cannot be used for audio playback - that's only allowed for default engine.""" return Document.cmd_makeobj('/new_engine', int(srate), int(bufsize)) @staticmethod def map_uuid(uuid): """Create or retrieve a Python-side accessor proxy for a C-side object.""" if uuid is None: return None if uuid in Document.objmap: return Document.objmap[uuid] try: oclass = Document.get_obj_class(uuid) except Exception as e: print ("Note: Cannot get class for " + uuid) Document.dump() raise o = Document.classmap[oclass](uuid) Document.objmap[uuid] = o if hasattr(o, 'init_object'): o.init_object() return o @staticmethod def map_uuid_and_check(uuid, t): o = Document.map_uuid(uuid) if not isinstance(o, t): raise TypeError("UUID %s is of type %s, expected %s" % (uuid, o.__class__, t)) return o class DocPattern(DocObj): class Status: event_count = int loop_end = int name = str def __init__(self, uuid): DocObj.__init__(self, uuid) def set_name(self, name): self.cmd("/name", None, name) Document.classmap['cbox_midi_pattern'] = DocPattern class ClipItem: def __init__(self, pos, offset, length, pattern, clip): self.pos = pos self.offset = offset self.length = length self.pattern = Document.map_uuid(pattern) self.clip = Document.map_uuid(clip) def __str__(self): return "pos=%d offset=%d length=%d pattern=%s clip=%s" % (self.pos, self.offset, self.length, self.pattern.uuid, self.clip.uuid) def __eq__(self, other): return str(self) == str(other) class DocTrackClip(DocObj): class Status: pos = SettableProperty(int) offset = SettableProperty(int) length = SettableProperty(int) pattern = SettableProperty(DocPattern) def __init__(self, uuid): DocObj.__init__(self, uuid) Document.classmap['cbox_track_item'] = DocTrackClip class DocTrack(DocObj): class Status: clips = [ClipItem] name = SettableProperty(str) external_output = SettableProperty(str) mute = SettableProperty(int) def add_clip(self, pos, offset, length, pattern): return self.cmd_makeobj("/add_clip", int(pos), int(offset), int(length), pattern.uuid) def clear_clips(self): return self.cmd_makeobj("/clear_clips") Document.classmap['cbox_track'] = DocTrack class TrackItem: def __init__(self, name, count, track): self.name = name self.count = count self.track = Document.map_uuid(track) class PatternItem: def __init__(self, name, length, pattern): self.name = name self.length = length self.pattern = Document.map_uuid(pattern) class MtiItem: def __init__(self, pos, tempo, timesig_num, timesig_denom): self.pos = pos self.tempo = tempo # Original misspelling self.timesig_num = timesig_num self.timesig_denom = timesig_denom def __getattr__(self, name): if name == 'timesig_nom': return self.timesig_num raise AttributeError(name) def __setattr__(self, name, value): if name == 'timesig_nom': self.timesig_num = value else: self.__dict__[name] = value def __eq__(self, o): return self.pos == o.pos and self.tempo == o.tempo and self.timesig_num == o.timesig_num and self.timesig_denom == o.timesig_denom def __repr__(self): return ("pos: {}, bpm: {}, timesig: {}/{}".format(self.pos, self.tempo, self.timesig_num, self.timesig_denom)) class DocSongStatus: tracks = None patterns = None class DocSong(DocObj): class Status: tracks = [TrackItem] patterns = [PatternItem] mtis = [MtiItem] loop_start = int loop_end = int def clear(self): return self.cmd("/clear", None) def set_loop(self, ls, le): return self.cmd("/set_loop", None, int(ls), int(le)) def set_mti(self, pos, tempo = None, timesig_num = None, timesig_denom = None, timesig_nom = None): if timesig_nom is not None: timesig_num = timesig_nom self.cmd("/set_mti", None, int(pos), float(tempo) if tempo is not None else -1.0, int(timesig_num) if timesig_num is not None else -1, int(timesig_denom) if timesig_denom else -1) def delete_mti(self, pos): """Deleting works only if we set everything to exactly 0. Not None, not -1""" self.set_mti(pos, tempo = 0, timesig_num = 0, timesig_denom = 0, timesig_nom = 0) def add_track(self): return self.cmd_makeobj("/add_track") def load_drum_pattern(self, name): return self.cmd_makeobj("/load_pattern", name, 1) def load_drum_track(self, name): return self.cmd_makeobj("/load_track", name, 1) def pattern_from_blob(self, blob, length): return self.cmd_makeobj("/load_blob", bytearray(blob), int(length)) def loop_single_pattern(self, loader): self.clear() track = self.add_track() pat = loader() length = pat.status().loop_end track.add_clip(0, 0, length, pat) self.set_loop(0, length) self.update_playback() def update_playback(self): # XXXKF Maybe make it a song-level API instead of global do_cmd("/update_playback", None, []) Document.classmap['cbox_song'] = DocSong class UnknownModule(NonDocObj): class Status: pass class DocRecorder(DocObj): class Status: filename = str gain = SettableProperty(float) Document.classmap['cbox_recorder'] = DocRecorder class RecSource(NonDocObj): class Status: handler = [DocRecorder] def attach(self, recorder): self.cmd('/attach', None, recorder.uuid) def detach(self, recorder): self.cmd('/detach', None, recorder.uuid) class EffectSlot(NonDocObj): class Status: insert_preset = SettableProperty(str) insert_engine = SettableProperty(str) bypass = SettableProperty(bool) def init_object(self): # XXXKF add wrapper classes for effect engines self.engine = UnknownModule(self.path + "/engine") class InstrumentOutput(EffectSlot): class Status(EffectSlot.Status): gain_linear = float gain = float output = SettableProperty(int) def init_object(self): EffectSlot.init_object(self) self.rec_dry = RecSource(self.make_path('/rec_dry')) self.rec_wet = RecSource(self.make_path('/rec_wet')) class DocInstrument(DocObj): class Status: name = str outputs = int aux_offset = int engine = str def init_object(self): s = self.status() engine = s.engine if engine in engine_classes: self.engine = engine_classes[engine]("/doc/uuid/" + self.uuid + "/engine") else: raise ValueError("Unknown engine %s" % engine) self.output_slots = [] for i in range(s.outputs): io = InstrumentOutput(self.make_path('/output/%d' % (i + 1))) io.init_object() self.output_slots.append(io) def move_to(self, target_scene, pos = 0): return self.cmd_makeobj("/move_to", target_scene.uuid, pos + 1) def get_output_slot(self, slot): return self.output_slots[slot] Document.classmap['cbox_instrument'] = DocInstrument class DocLayer(DocObj): class Status: name = str instrument_name = str instrument = AltPropName('/instrument_uuid', DocInstrument) enable = SettableProperty(bool) low_note = SettableProperty(int) high_note = SettableProperty(int) fixed_note = SettableProperty(int) in_channel = SettableProperty(int) out_channel = SettableProperty(int) disable_aftertouch = SettableProperty(bool) invert_sustain = SettableProperty(bool) consume = SettableProperty(bool) ignore_scene_transpose = SettableProperty(bool) ignore_program_changes = SettableProperty(bool) transpose = SettableProperty(int) external_output = SettableProperty(str) def get_instrument(self): return self.status().instrument Document.classmap['cbox_layer'] = DocLayer class SamplerEngine(NonDocObj): class Status(object): """Maximum number of voices playing at the same time.""" polyphony = int """Current number of voices playing.""" active_voices = int """Current number of delayed-startup voices waiting to be played.""" active_prevoices = int """Current number of disk streams.""" active_pipes = int """GM volume (14-bit) per MIDI channel.""" volume = {int:int} """GM pan (14-bit) per MIDI channel.""" pan = {int:int} """Output offset per MIDI channel.""" output = {int:int} """Current number of voices playing per MIDI channel.""" channel_voices = AltPropName('/channel_voices', {int:int}) """Current number of voices waiting to be played per MIDI channel.""" channel_prevoices = AltPropName('/channel_prevoices', {int:int}) """MIDI channel -> (program number, program name)""" patches = {int:(int, str)} def load_patch_from_cfg(self, patch_no, cfg_section, display_name): """Load a sampler program from an 'spgm:' config section.""" return self.cmd_makeobj("/load_patch", int(patch_no), cfg_section, display_name) def load_patch_from_string(self, patch_no, sample_dir, sfz_data, display_name): """Load a sampler program from a string, using given filesystem path for sample directory.""" return self.cmd_makeobj("/load_patch_from_string", int(patch_no), sample_dir, sfz_data, display_name) def load_patch_from_file(self, patch_no, sfz_name, display_name): """Load a sampler program from a filesystem file.""" return self.cmd_makeobj("/load_patch_from_file", int(patch_no), sfz_name, display_name) def load_patch_from_tar(self, patch_no, tar_name, sfz_name, display_name): """Load a sampler program from a tar file.""" return self.cmd_makeobj("/load_patch_from_file", int(patch_no), "sbtar:%s;%s" % (tar_name, sfz_name), display_name) def set_patch(self, channel, patch_no): """Select patch identified by patch_no in a specified MIDI channel.""" self.cmd("/set_patch", None, int(channel), int(patch_no)) def set_output(self, channel, output): """Set output offset value in a specified MIDI channel.""" self.cmd("/set_output", None, int(channel), int(output)) def get_unused_program(self): """Returns first program number that has no program associated with it.""" return self.get_thing("/get_unused_program", '/program_no', int) def set_polyphony(self, polyphony): """Set a maximum number of voices that can be played at a given time.""" self.cmd("/polyphony", None, int(polyphony)) def get_patches(self): """Return a map of program identifiers to program objects.""" return self.get_thing("/patches", '/patch', {int : (str, SamplerProgram, int)}) def get_keyswitch_state(self, channel, group): """Return a map of program identifiers to program objects.""" return self.get_thing("/keyswitch_state", '/last_key', int, channel, group) class FluidsynthEngine(NonDocObj): class Status: polyphony = int soundfont = str patch = {int: (int, str)} def load_soundfont(self, filename): return self.cmd_makeobj("/load_soundfont", filename) def set_patch(self, channel, patch_no): self.cmd("/set_patch", None, int(channel), int(patch_no)) def set_polyphony(self, polyphony): self.cmd("/polyphony", None, int(polyphony)) def get_patches(self): return self.get_thing("/patches", '/patch', {int: str}) class StreamPlayerEngine(NonDocObj): class Status: filename = str pos = int length = int playing = int def play(self): self.cmd('/play') def stop(self): self.cmd('/stop') def seek(self, place): self.cmd('/seek', None, int(place)) def load(self, filename, loop_start = -1): self.cmd('/load', None, filename, int(loop_start)) def unload(self): self.cmd('/unload') class TonewheelOrganEngine(NonDocObj): class Status: upper_drawbar = SettableProperty({int: int}) lower_drawbar = SettableProperty({int: int}) pedal_drawbar = SettableProperty({int: int}) upper_vibrato = SettableProperty(bool) lower_vibrato = SettableProperty(bool) vibrato_mode = SettableProperty(int) vibrato_chorus = SettableProperty(int) percussion_enable = SettableProperty(bool) percussion_3rd = SettableProperty(bool) class JackInputEngine(NonDocObj): class Status: inputs = (int, int) engine_classes = { 'sampler' : SamplerEngine, 'fluidsynth' : FluidsynthEngine, 'stream_player' : StreamPlayerEngine, 'tonewheel_organ' : TonewheelOrganEngine, 'jack_input' : JackInputEngine, } class DocAuxBus(DocObj): class Status: name = str def init_object(self): self.slot = EffectSlot("/doc/uuid/" + self.uuid + "/slot") self.slot.init_object() Document.classmap['cbox_aux_bus'] = DocAuxBus class DocScene(DocObj): class Status: name = str title = str transpose = int layers = [DocLayer] instruments = {str: (str, DocInstrument)} auxes = {str: DocAuxBus} enable_default_song_input = SettableProperty(bool) enable_default_external_input = SettableProperty(bool) def clear(self): self.cmd("/clear", None) def load(self, name): self.cmd("/load", None, name) def load_aux(self, aux): return self.cmd_makeobj("/load_aux", aux) def delete_aux(self, aux): return self.cmd("/delete_aux", None, aux) def delete_layer(self, pos): self.cmd("/delete_layer", None, int(1 + pos)) def move_layer(self, old_pos, new_pos): self.cmd("/move_layer", None, int(old_pos + 1), int(new_pos + 1)) #Layer positions are 0 for "append" and other positions are 1...n which need to be unique def add_layer(self, aux, pos = None): if pos is None: return self.cmd_makeobj("/add_layer", 0, aux) else: # Note: The positions in high-level API are zero-based. return self.cmd_makeobj("/add_layer", int(1 + pos), aux) def add_instrument_layer(self, name, pos = None): if pos is None: return self.cmd_makeobj("/add_instrument_layer", 0, name) else: return self.cmd_makeobj("/add_instrument_layer", int(1 + pos), name) def add_new_instrument_layer(self, name, engine, pos = None): if pos is None: return self.cmd_makeobj("/add_new_instrument_layer", 0, name, engine) else: return self.cmd_makeobj("/add_new_instrument_layer", int(1 + pos), name, engine) def add_new_midi_layer(self, ext_output_uuid, pos = None): if pos is None: return self.cmd_makeobj("/add_midi_layer", 0, ext_output_uuid) else: return self.cmd_makeobj("/add_midi_layer", int(1 + pos), ext_output_uuid) def send_midi_event(self, *data): self.cmd('/send_event', None, *data) def play_pattern(self, pattern, tempo, id = 0): self.cmd('/play_pattern', None, pattern.uuid, float(tempo), int(id)) Document.classmap['cbox_scene'] = DocScene class DocRt(DocObj): class Status: audio_channels = (int, int) state = (int, str) Document.classmap['cbox_rt'] = DocRt class DocModule(DocObj): class Status: pass Document.classmap['cbox_module'] = DocModule class DocEngine(DocObj): class Status: scenes = AltPropName('/scene', [DocScene]) def init_object(self): self.master_effect = EffectSlot(self.path + "/master_effect") self.master_effect.init_object() def new_scene(self): return self.cmd_makeobj('/new_scene') def new_recorder(self, filename): return self.cmd_makeobj("/new_recorder", filename) def render_stereo(self, samples): return self.get_thing("/render_stereo", '/data', bytes, samples) Document.classmap['cbox_engine'] = DocEngine class SamplerProgram(DocObj): class Status: name = str sample_dir = str source_file = str program_no = int in_use = int def get_regions(self): return self.get_thing("/regions", '/region', [SamplerLayer]) def get_global(self): return self.cmd_makeobj("/global") def get_hierarchy(self): """see SamplerLayer.get_hierarchy""" return {self.get_global() : self.get_global().get_hierarchy()} def get_control_inits(self): return self.get_thing("/control_inits", '/control_init', [(int, int)]) def get_control_labels(self): return self.get_thing("/control_labels", '/control_label', {int : str}) def get_key_labels(self): return self.get_thing("/key_labels", '/key_label', {int : str}) def get_keyswitch_groups(self): return self.get_thing("/keyswitch_groups", '/key_range', [(int, int)]) def new_group(self): # Obsolete return self.cmd_makeobj("/new_group") def add_control_init(self, controller, value): return self.cmd("/add_control_init", None, controller, value) def add_control_label(self, controller, label): return self.cmd("/add_control_label", None, controller, label) # which = -1 -> remove all controllers with that number from the list def delete_control_init(self, controller, which = 0): return self.cmd("/delete_control_init", None, controller, which) def load_file(self, filename, max_size = -1): """Return an in-memory file corresponding to a given file inside sfbank. This can be used for things like scripts, images, descriptions etc.""" data = self.get_thing("/load_file", '/data', bytes, filename, max_size) if data is None: return data return BytesIO(data) def clone_to(self, dest_module, prog_index): return self.cmd_makeobj('/clone_to', dest_module.uuid, int(prog_index)) Document.classmap['sampler_program'] = SamplerProgram class SamplerLayer(DocObj): class Status: parent_program = SamplerProgram parent = DocObj level = str def get_children(self): """Return all children SamplerLayer. The hierarchy is always global-master-group-region Will be empty if this is an sfz <region>, which has no further children. """ return self.get_thing("/get_children", '/child', [SamplerLayer]) def get_hierarchy(self): """Returns either a level of hierarchy, e.g. <global> or <group> or None, if this is a childless layer, such as a <region>. The hierarchy is always global-master-group-region. Regions alre always on the fourth level. But not all levels might have regions. Hint: Print with pprint during development.""" children = self.get_children() if children: result = {} for childLayer in children: result[childLayer] = childLayer.get_hierarchy() else: result = None return result def as_dict(self): """Returns a dictionary of parameters set at this level of the layer hierarchy.""" return self.get_thing("/as_list", '/value', {str: str}) def as_dict_full(self): """Returns a dictionary of parameters set either at this level of the layer hierarchy or at one of the ancestors.""" return self.get_thing("/as_list_full", '/value', {str: str}) def as_string(self): """A space separated string of all sampler values at this level in the hierarchy, for example ampeg_decay. This only includes non-default values, e.g. from the sfz file""" return self.get_thing("/as_string", '/value', str) def as_string_full(self): """A space separated string of all sampler values at this level in the hierarchy, for example ampeg_decay. This includes all default values. To access the values as dict with number data types use get_params_full(). '_oncc1' will be converted to '_cc1' """ return self.get_thing("/as_string_full", '/value', str) def set_param(self, key, value): self.cmd("/set_param", None, key, str(value)) def unset_param(self, key): self.cmd("/unset_param", None, key) def new_child(self): return self.cmd_makeobj("/new_child") Document.classmap['sampler_layer'] = SamplerLayer
kfoltman/calfbox
py/cbox.py
Python
gpl-3.0
47,278
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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/>. */ import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {GanttChartModeTextPipe} from './gantt-chart-mode-text.pipe'; import {GanttChartPropertyItemsPipe} from './gantt-chart-property-items.pipe'; import {GanttChartBarPlaceholderPipe} from './gantt-chart-bar-placeholder.pipe'; import {GanttChartBarEmptyValuePipe} from './gantt-chart-bar-empty-value.pipe'; import {TasksInvalidRangeInfoPipe} from './tasks-invalid-range-info.pipe'; import {GanttChartSelectItemsPipe} from './gantt-chart-select-items.pipe'; import {GanttChartSelectedItemWithConstraintPipe} from './gantt-chart-selected-item-with-constraint.pipe'; @NgModule({ imports: [CommonModule], declarations: [ GanttChartModeTextPipe, GanttChartPropertyItemsPipe, GanttChartBarPlaceholderPipe, GanttChartBarEmptyValuePipe, TasksInvalidRangeInfoPipe, GanttChartSelectItemsPipe, GanttChartSelectedItemWithConstraintPipe, ], exports: [ GanttChartModeTextPipe, GanttChartPropertyItemsPipe, GanttChartBarPlaceholderPipe, GanttChartBarEmptyValuePipe, TasksInvalidRangeInfoPipe, GanttChartSelectItemsPipe, GanttChartSelectedItemWithConstraintPipe, ], }) export class GanttChartPipesModule {}
livthomas/Lumeer-web-ui
src/app/view/perspectives/gantt-chart/pipes/gantt-chart-pipes.module.ts
TypeScript
gpl-3.0
2,033
// #define BOOST_TEST_MODULE "SimulationBasisTests" #include "boost\test\unit_test.hpp" BOOST_AUTO_TEST_SUITE(test_ModelCustomer) BOOST_AUTO_TEST_CASE(test_case2a) { BOOST_CHECK(true); } BOOST_AUTO_TEST_SUITE_END()
JWidder/SimulationBasis
Simulation/test/testModelCustomer.cpp
C++
gpl-3.0
217
# (c) Copyright 2014, University of Manchester # # This file is part of Pynsim. # # Pynsim 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. # # Pynsim 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 Pynsim. If not, see <http://www.gnu.org/licenses/>. from pynsim import Engine from PyModel import OptimisationModel from pyomo.environ import * class PyomoAllocation(Engine): name = """A pyomo-based engine which allocates water throughout a whole network in a single time-step.""" target = None storage = {} def run(self): """ Calling Pyomo model """ print "========================= Timestep: %s =======================" % self.target.current_timestep allocation = "_____________ Flows _____________" storage = "_____________ Storage _____________" alpha = "_____________ Demand satisfaction ratio _____________" for n in self.target.nodes: if n.type == 'agricultural' or n.type == 'urban': print "%s target demand is %s" % (n.name, n.target_demand) print "======== calling Pyomo ==============" optimisation = OptimisationModel(self.target) results = optimisation.run() for var in results.active_components(Var): if var == "S": s_var = getattr(results, var) for vv in s_var: name = ''.join(map(str, vv)) self.storage[name] = s_var[vv].value storage += '\n' + name + ": " + str(s_var[vv].value) elif var == "X": x_var = getattr(results, var) for xx in x_var: name = "(" + ', '.join(map(str, xx)) + ")" allocation += '\n' + name + ": " + str(x_var[xx].value) elif var == "alpha": alpha_var = getattr(results, var) for aa in alpha_var: name = ''.join(map(str, aa)) alpha += '\n' + name + ": " + str(alpha_var[aa].value) print allocation print storage print alpha self.target.set_initial_storage(self.storage)
UMWRG/demos
WaterAllocationDemo/model/pynsim/engines/allocation.py
Python
gpl-3.0
2,662
(function () { define( ['i18next', 'appevents', 'uihandler', 'database', './receivemoney.html!text'], function (i18next, appevents, uihandle, database, template) { function MyReceiveMoney(params) { var viewModel = { // Fields message: ko.observable(), amount: ko.observable(), label: ko.observable(), addressPanel: ko.observable(false), transactions: ko.observableArray([]), address: null, // Errors errMessage: ko.observable(false), errTxtMessage: ko.observable(''), errAmount: ko.observable(false), errTxtAmount: ko.observable(''), errLabel: ko.observable(false), errTxtLabel: ko.observable(''), // QRCode element qrcode_element: '#addr-qrcode', addressClass: '.payment-to', // Validation validateForm: function () { var message = this.message(), amount = this.amount(), label = this.label(); if (message && message.length && !/^[a-z0-9 ,\._!\?#%&\(\)\+\-]{2,100}$/im.test(message)) { this.errMessage(true); this.errTxtMessage(i18next.t('errmsg-wallet-receive-message')); } else { this.errMessage(false); this.errTxtMessage(''); } if (amount && amount.length && (isNaN(+amount) || +amount <= 0)) { this.errAmount(true); this.errTxtAmount(i18next.t('errmsg-wallet-send-amount')); } else { this.errAmount(false); this.errTxtAmount(''); } if (label && label.length && !/^[a-z0-9 _\-]{2,40}$/im.test(label)) { this.errLabel(true); this.errTxtLabel(i18next.t('errmsg-wallet-receive-label')); } else { this.errLabel(false); this.errTxtLabel(''); } if (this.errMessage() === true || this.errAmount() === true || this.errLabel() === true) { return false; } return true; }, clear: function () { this.message(''); this.amount(''); this.label(''); this.errMessage(false); this.errTxtMessage(''); this.errAmount(false); this.errTxtAmount(''); this.errLabel(false); this.errTxtLabel(''); }, closePanel: function () { this.addressPanel(false); $(viewModel.addressClass).text(''); $(viewModel.qrcode_element).html(''); this.clear(); }, copyUri: function () { return this.ctrlc(`streambit:${this.address}`); }, copyAddress: function () { return this.ctrlc(this.address); }, ctrlc: function (txt) { if (!this.address) { return; } uihandle.copyToClipboard(txt); }, saveImg: function () { if (!this.address) { return; } var qrCodeBlock = $('#addr-qrcode'); uihandle.saveImgFromCanvas(qrCodeBlock, this.address); }, generateAddress: function () { if (this.validateForm()) { appevents.dispatch("on-payment-request", {}, this.requestPaymentCallback); } }, updateIndexDB: function (data, callback) { database.update(database.BCPAYMENTREQUESTS, data).then( () => callback(null, data), err => callback(err) ) }, requestPaymentCallback: function(err, address) { if (err) { return streembit.notify.error(err); } if (viewModel.validateForm()) { // protect on direct access viewModel.address = address; var data = { key: address, time: +new Date(), // ms amount: viewModel.amount(), label: viewModel.label(), message: viewModel.message() }; // Async DB update viewModel.updateIndexDB(data, viewModel.reportUpdateDB); // and show modal unrelated(?) to result of DB saving uihandle.qrGenerate(viewModel.qrcode_element, address); $(viewModel.addressClass).text(address); viewModel.addressPanel(true); } }, reportUpdateDB: function (err, data) { if (err) { return streembit.notify.error(err); } viewModel.transactions([ ...viewModel.transactions(), data ]); streembit.notify.success('Address successfully saved in DB'); }, init: function () { // get payment request collections database.getall(database.BCPAYMENTREQUESTS, (err, result) => { if (err) { return streembit.notify.error(err); } this.transactions(result); }); } }; viewModel.init(); return viewModel; } return { viewModel: MyReceiveMoney, template: template }; }); }());
streembit/streembitui
lib/app/views/wallet/receivemoney/receivemoney.js
JavaScript
gpl-3.0
7,037
// From the software distribution accompanying the textbook // "A Practical Introduction to Data Structures and Algorithm Analysis, // Third Edition (C++)" by Clifford A. Shaffer. // Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. // Mergesort implementation and timing test driver // Mergesort implementation optimized to reverse the 2nd half, // so that there is no need to test for exhausted sublists. // Also, sublists of length <= THRESHOLD are sorted with insertion sort. #include "book.h" // Include comparator functions #include "compare.h" // Standard insertion sort implementation template <typename E, typename Comp> void inssort(E A[], int n) { // Insertion Sort for (int i=1; i<n; i++) // Insert i'th record for (int j=i; (j>0) && (Comp::prior(A[j], A[j-1])); j--) swap(A, j, j-1); } extern int THRESHOLD; //Optimized mergesort implementation template <typename E, typename Comp> void mergesort(E A[], E temp[], int left, int right) { if ((right-left) <= THRESHOLD) { // Small list inssort<E,Comp>(&A[left], right-left+1); return; } int i, j, k, mid = (left+right)/2; mergesort<E,Comp>(A, temp, left, mid); mergesort<E,Comp>(A, temp, mid+1, right); // Do the merge operation. First, copy 2 halves to temp. for (i=mid; i>=left; i--) temp[i] = A[i]; for (j=1; j<=right-mid; j++) temp[right-j+1] = A[j+mid]; // Merge sublists back to A for (i=left,j=right,k=left; k<=right; k++) if (Comp::prior(temp[i], temp[j])) A[k] = temp[i++]; else A[k] = temp[j--]; } template <typename E, typename Comp> void sort(E* array, int n) { static E* temp = NULL; if (temp == NULL) temp = new E[n]; // Declare temp array mergesort<E,Comp>(array, temp, 0, n-1); } #include "sortmain.cpp" int main(int argc, char** argv) { return sortmain<minintCompare>(argc, argv); }
wsricardo/mcestudos
ebooks/distrib/mrgsort3.cpp
C++
gpl-3.0
1,844
/* * Copyright (C) 2000 - 2008 TagServlet Ltd * * This file is part of Open BlueDragon (OpenBD) CFML Server Engine. * * OpenBD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Free Software Foundation,version 3. * * OpenBD 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 OpenBD. If not, see http://www.gnu.org/licenses/ * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining * it with any of the JARS listed in the README.txt (or a modified version of * (that library), containing parts covered by the terms of that JAR, the * licensors of this Program grant you additional permission to convey the * resulting work. * README.txt @ http://www.openbluedragon.org/license/README.txt * * http://www.openbluedragon.org/ */ /* * Returns back a date formatted for the use in HTTP requests. * * If no date is passed in then the current time is used */ package com.naryx.tagfusion.expression.function; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import com.naryx.tagfusion.cfm.engine.cfArgStructData; import com.naryx.tagfusion.cfm.engine.cfData; import com.naryx.tagfusion.cfm.engine.cfSession; import com.naryx.tagfusion.cfm.engine.cfStringData; import com.naryx.tagfusion.cfm.engine.cfmRunTimeException; public class getHttpTimeString extends functionBase { private static final long serialVersionUID = 1L; public getHttpTimeString() { min = 0; max = 1; setNamedParams( new String[]{ "date" } ); } public String[] getParamInfo(){ return new String[]{ "date1" }; } public java.util.Map getInfo(){ return makeInfo( "date", "Returns back the time given (or the current time) in the format of the HTTP header", ReturnType.STRING ); } public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException { long date; cfData p = getNamedParam(argStruct, "date"); if ( p == null ){ date = System.currentTimeMillis(); }else{ date = p.getDateData().getLong(); } // The following code is the fix for bug #2578 // Get the time Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(new Date(date)); // Convert to GMT TimeZone zone = cal.getTimeZone(); int offset = zone.getOffset(cal.get(Calendar.ERA), cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.DAY_OF_WEEK), cal.get(Calendar.MILLISECOND)); cal.add(Calendar.MILLISECOND, -offset); return new cfStringData(com.nary.util.Date.formatDate(cal.getTime().getTime(), "EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)); } }
OpenBD/openbd-core
src/com/naryx/tagfusion/expression/function/getHttpTimeString.java
Java
gpl-3.0
3,072