code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php // Esercizio: un numero che si dimezza sempre header('Content-Type: text/plain'); ini_set('display_errors', true); // MAI in produzione!!! ini_set('html_errors', 0); /** * Questa classe continua a dividere * il suo stato interno per un valore dato. */ class invert { /** * Il valore corrente * @var integer */ public $val = 1; /** * Il divisore * @var integer */ protected $_divisor = 3; /** * Esegue la divisione e restituisce il risultato * @return integer */ public function div() { $this->val = $this->val / $this->_divisor; return $this->val; } /** * Imposta il valore del divisore * @param integer $divisor * @return void */ public function setDivisor($divisor) { if ($divisor) { $this->_divisor = $divisor; } else { // Prendo dei provvedimenti } } } $sempreMeno = new invert; while ($sempreMeno->val > 1e-5) { echo $sempreMeno->div(), PHP_EOL; } // Tento di impostare un nuovo divisore... $sempreMeno->_divisor = 2; // ...ma devo usare la funzione $sempreMeno->setDivisor(2); echo $sempreMeno->div(), PHP_EOL;
hujuice/oopphp
public/esercizi/divide.php
PHP
gpl-3.0
1,214
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Open Software License version 3.0 * * This source file is subject to the Open Software License (OSL 3.0) that is * bundled with this package in the files license.txt / license.rst. It is * also available through the world wide web at this URL: * http://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * [email protected] so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * @link http://codeigniter.com * @since Version 1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Database Utility Class * * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ abstract class CI_DB_utility { /** * Database object * * @var object */ protected $db; // -------------------------------------------------------------------- /** * List databases statement * * @var string */ protected $_list_databases = FALSE; /** * OPTIMIZE TABLE statement * * @var string */ protected $_optimize_table = FALSE; /** * REPAIR TABLE statement * * @var string */ protected $_repair_table = FALSE; // -------------------------------------------------------------------- /** * Class constructor * * @param object &$db Database object * @return void */ public function __construct(&$db) { $this->db =& $db; log_message('debug', 'Database Utility Class Initialized'); } // -------------------------------------------------------------------- /** * List databases * * @return array */ public function list_databases() { // Is there a cached result? if (isset($this->db->data_cache['db_names'])) { return $this->db->data_cache['db_names']; } elseif ($this->_list_databases === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $this->db->data_cache['db_names'] = array(); $query = $this->db->query($this->_list_databases); if ($query === FALSE) { return $this->db->data_cache['db_names']; } for ($i = 0, $query = $query->result_array(), $c = count($query); $i < $c; $i++) { $this->db->data_cache['db_names'][] = current($query[$i]); } return $this->db->data_cache['db_names']; } // -------------------------------------------------------------------- /** * Determine if a particular database exists * * @param string $database_name * @return bool */ public function database_exists($database_name) { return in_array($database_name, $this->list_databases()); } // -------------------------------------------------------------------- /** * Optimize Table * * @param string $table_name * @return mixed */ public function optimize_table($table_name) { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if ($query !== FALSE) { $query = $query->result_array(); return current($query); } return FALSE; } // -------------------------------------------------------------------- /** * Optimize Database * * @return mixed */ public function optimize_database() { if ($this->_optimize_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $result = array(); foreach ($this->db->list_tables() as $table_name) { $res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name))); if (is_bool($res)) { return $res; } // Build the result array... $res = $res->result_array(); $res = current($res); $key = str_replace($this->db->database.'.', '', current($res)); $keys = array_keys($res); unset($res[$keys[0]]); $result[$key] = $res; } return $result; } // -------------------------------------------------------------------- /** * Repair Table * * @param string $table_name * @return mixed */ public function repair_table($table_name) { if ($this->_repair_table === FALSE) { return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE; } $query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name))); if (is_bool($query)) { return $query; } $query = $query->result_array(); return current($query); } // -------------------------------------------------------------------- /** * Generate CSV from a query result object * * @param object $query Query result object * @param string $delim Delimiter (default: ,) * @param string $newline Newline character (default: \n) * @param string $enclosure Enclosure (default: ") * @return string */ public function csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"') { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } $out = ''; // First generate the headings from the table column names foreach ($query->list_fields() as $name) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim; } $out = substr(rtrim($out), 0, -strlen($delim)).$newline; // Next blast through the result array and build out the rows while ($row = $query->unbuffered_row('array')) { foreach ($row as $item) { $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim; } $out = substr(rtrim($out), 0, -strlen($delim)).$newline; } return $out; } // -------------------------------------------------------------------- /** * Generate XML data from a query result object * * @param object $query Query result object * @param array $params Any preferences * @return string */ public function xml_from_result($query, $params = array()) { if ( ! is_object($query) OR ! method_exists($query, 'list_fields')) { show_error('You must submit a valid result object'); } // Set our default values foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val) { if ( ! isset($params[$key])) { $params[$key] = $val; } } // Create variables for convenience extract($params); // Load the xml helper get_instance()->load->helper('xml'); // Generate the result $xml = '<'.$root.'>'.$newline; while ($row = $query->unbuffered_row()) { $xml .= $tab.'<'.$element.'>'.$newline; foreach ($row as $key => $val) { $xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).'</'.$key.'>'.$newline; } $xml .= $tab.'</'.$element.'>'.$newline; } return $xml.'</'.$root.'>'.$newline; } // -------------------------------------------------------------------- /** * Database Backup * * @param array $params * @return void */ public function backup($params = array()) { // If the parameters have not been submitted as an // array then we know that it is simply the table // name, which is a valid short cut. if (is_string($params)) { $params = array('tables' => $params); } // Set up our default preferences $prefs = array( 'tables' => array(), 'ignore' => array(), 'filename' => '', 'format' => 'gzip', // gzip, zip, txt 'add_drop' => TRUE, 'add_insert' => TRUE, 'newline' => "\n", 'foreign_key_checks' => TRUE ); // Did the user submit any preferences? If so set them.... if (count($params) > 0) { foreach ($prefs as $key => $val) { if (isset($params[$key])) { $prefs[$key] = $params[$key]; } } } // Are we backing up a complete database or individual tables? // If no table names were submitted we'll fetch the entire table list if (count($prefs['tables']) === 0) { $prefs['tables'] = $this->db->list_tables(); } // Validate the format if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE)) { $prefs['format'] = 'txt'; } // Is the encoder supported? If not, we'll either issue an // error or use plain text depending on the debug settings if (($prefs['format'] === 'gzip' && ! @function_exists('gzencode')) OR ($prefs['format'] === 'zip' && ! @function_exists('gzcompress'))) { if ($this->db->db_debug) { return $this->db->display_error('db_unsupported_compression'); } $prefs['format'] = 'txt'; } // Was a Zip file requested? if ($prefs['format'] === 'zip') { // Set the filename if not provided (only needed with Zip files) if ($prefs['filename'] === '') { $prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database) .date('Y-m-d_H-i', time()).'.sql'; } else { // If they included the .zip file extension we'll remove it if (preg_match('|.+?\.zip$|', $prefs['filename'])) { $prefs['filename'] = str_replace('.zip', '', $prefs['filename']); } // Tack on the ".sql" file extension if needed if ( ! preg_match('|.+?\.sql$|', $prefs['filename'])) { $prefs['filename'] .= '.sql'; } } // Load the Zip class and output it $CI =& get_instance(); $CI->load->library('zip'); $CI->zip->add_data($prefs['filename'], $this->_backup($prefs)); return $CI->zip->get_zip(); } elseif ($prefs['format'] === 'txt') // Was a text file requested? { return $this->_backup($prefs); } elseif ($prefs['format'] === 'gzip') // Was a Gzip file requested? { return gzencode($this->_backup($prefs)); } return; } } /* End of file DB_utility.php */ /* Location: ./system/database/DB_utility.php */
ngoaho91/sharif-judge
system/database/DB_utility.php
PHP
gpl-3.0
10,617
from mercurial import cmdutil _hgignore_content = """\ syntax: glob *~ *.pyc *.pyo *.bak cache/* databases/* sessions/* errors/* """ def commit(): app = request.args[0] path = apath(app, r=request) uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config("ui", "username"): os.environ['HGUSER'] = 'web2py@localhost' try: r = hg.repository(ui=uio, path=path) except: r = hg.repository(ui=uio, path=path, create=True) hgignore = os.path.join(path, '.hgignore') if not os.path.exists(hgignore): open(hgignore, 'w').write(_hgignore_content) form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()), INPUT(_type='submit',_value='Commit')) if form.accepts(request.vars,session): oldid = r[r.lookup('.')] cmdutil.addremove(r) r.commit(text=form.vars.comment) if r[r.lookup('.')] == oldid: response.flash = 'no changes' files = r[r.lookup('.')].files() return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
henkelis/sonospy
web2py/applications/admin/controllers/mercurial.py
Python
gpl-3.0
1,107
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on Population. Contact : [email protected] .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Rizky Maulana Nugraha' from safe.common.utilities import OrderedDict from safe.defaults import ( default_minimum_needs, default_gender_postprocessor, age_postprocessor, minimum_needs_selector) from safe.impact_functions.impact_function_metadata import \ ImpactFunctionMetadata from safe.utilities.i18n import tr from safe.definitions import ( layer_mode_continuous, layer_geometry_raster, hazard_flood, hazard_category_single_event, unit_metres, unit_feet, count_exposure_unit, exposure_population ) class FloodEvacuationRasterHazardMetadata(ImpactFunctionMetadata): """Metadata for FloodEvacuationFunction. .. versionadded:: 2.1 We only need to re-implement as_dict(), all other behaviours are inherited from the abstract base class. """ @staticmethod def as_dict(): """Return metadata as a dictionary. This is a static method. You can use it to get the metadata in dictionary format for an impact function. :returns: A dictionary representing all the metadata for the concrete impact function. :rtype: dict """ dict_meta = { 'id': 'FloodEvacuationRasterHazardFunction', 'name': tr('Raster flood on population'), 'impact': tr('Need evacuation'), 'title': tr('Need evacuation'), 'function_type': 'old-style', 'author': 'AIFDR', 'date_implemented': 'N/A', 'overview': tr( 'To assess the impacts of flood inundation in raster ' 'format on population.'), 'detailed_description': tr( 'The population subject to inundation exceeding a ' 'threshold (default 1m) is calculated and returned as a ' 'raster layer. In addition the total number of affected ' 'people and the required needs based on the user ' 'defined minimum needs are reported. The threshold can be ' 'changed and even contain multiple numbers in which case ' 'evacuation and needs are calculated using the largest number ' 'with population breakdowns provided for the smaller numbers. ' 'The population raster is resampled to the resolution of the ' 'hazard raster and is rescaled so that the resampled ' 'population counts reflect estimates of population count ' 'per resampled cell. The resulting impact layer has the ' 'same resolution and reflects population count per cell ' 'which are affected by inundation.'), 'hazard_input': tr( 'A hazard raster layer where each cell represents flood ' 'depth (in meters).'), 'exposure_input': tr( 'An exposure raster layer where each cell represent ' 'population count.'), 'output': tr( 'Raster layer contains people affected and the minimum ' 'needs based on the people affected.'), 'actions': tr( 'Provide details about how many people would likely need ' 'to be evacuated, where they are located and what ' 'resources would be required to support them.'), 'limitations': [ tr('The default threshold of 1 meter was selected based ' 'on consensus, not hard evidence.') ], 'citations': [], 'layer_requirements': { 'hazard': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'hazard_categories': [hazard_category_single_event], 'hazard_types': [hazard_flood], 'continuous_hazard_units': [unit_feet, unit_metres], 'vector_hazard_classifications': [], 'raster_hazard_classifications': [], 'additional_keywords': [] }, 'exposure': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'exposure_types': [exposure_population], 'exposure_units': [count_exposure_unit], 'exposure_class_fields': [], 'additional_keywords': [] } }, 'parameters': OrderedDict([ ('thresholds [m]', [1.0]), ('postprocessors', OrderedDict([ ('Gender', default_gender_postprocessor()), ('Age', age_postprocessor()), ('MinimumNeeds', minimum_needs_selector()), ])), ('minimum needs', default_minimum_needs()) ]) } return dict_meta
wonder-sk/inasafe
safe/impact_functions/inundation/flood_raster_population/metadata_definitions.py
Python
gpl-3.0
5,408
/** * */ package cz.geokuk.core.napoveda; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import cz.geokuk.core.program.FConst; import cz.geokuk.framework.Action0; import cz.geokuk.util.process.BrowserOpener; /** * @author Martin Veverka * */ public class ZadatProblemAction extends Action0 { private static final long serialVersionUID = -2882817111560336824L; /** * @param aBoard */ public ZadatProblemAction() { super("Zadat problém ..."); putValue(SHORT_DESCRIPTION, "Zobrazí stránku na code.google.com, která umožní zadat chybu v Geokuku nebo požadavek na novou funkcionalitu."); putValue(MNEMONIC_KEY, KeyEvent.VK_P); } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent aE) { try { BrowserOpener.displayURL(new URL(FConst.POST_PROBLEM_URL)); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } }
marvertin/geokuk
src/main/java/cz/geokuk/core/napoveda/ZadatProblemAction.java
Java
gpl-3.0
1,073
/** * Copyright 2013, 2014 Ioana Ileana @ Telecom ParisTech * 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 instance; import java.util.ArrayList; public class Parser { private ArrayList<ArrayList<String>> m_relationals; private ArrayList<String[]> m_equalities; int m_pos; public Parser() { m_relationals = new ArrayList<ArrayList<String>>(); m_equalities = new ArrayList<String[]>(); m_pos=0; } public void flush() { m_pos = 0; m_relationals.clear(); m_equalities.clear(); } public boolean charIsValidForRelation(char c) { return ((c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_')); } public boolean charIsValidForTerm(char c) { return ((c>='a' && c<='z') || (c>='0' && c<='9') || (c=='_') || (c=='.') ); } public ArrayList<String> parseAtom(String line) { ArrayList<String> list = new ArrayList<String>(); String relation=""; while (m_pos<line.length()) { if (charIsValidForRelation(line.charAt(m_pos))) { relation+=line.charAt(m_pos); m_pos++; } else if (line.charAt(m_pos)=='(') { m_pos++; list.add(relation); parseTerms(line, list); return list; } else { m_pos++; } } return null; } public void parseTerms(String line, ArrayList<String> list) { while (m_pos<line.length()) { if (line.charAt(m_pos) == ')') { m_pos++; return; } else if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else { String term=parseSingleTerm(line); list.add(term); } } } public String parseSingleTerm(String line) { String term=""; while (m_pos<line.length() && charIsValidForTerm(line.charAt(m_pos))) { term+=line.charAt(m_pos); m_pos++; } return term; } public void parseRelationals(String line) { m_pos = 0; while (m_pos<line.length()) { if (line.charAt(m_pos)<'A' || line.charAt(m_pos)>'Z') m_pos++; else { ArrayList<String> relStr = parseAtom(line); m_relationals.add(relStr); } } } public void parseEqualities(String line) { m_pos = 0; while (m_pos<line.length()) { if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else parseEquality(line); } } public void parseEquality(String line) { String[] terms=new String[2]; terms[0] = parseSingleTerm(line); while (m_pos<line.length() && !charIsValidForTerm(line.charAt(m_pos))) m_pos++; terms[1] = parseSingleTerm(line); m_equalities.add(terms); } public ArrayList<String[]> getEqualities() { return m_equalities; } public ArrayList<ArrayList<String>> getRelationals() { return m_relationals; } public ArrayList<String> parseProvenance(String line) { ArrayList<String> provList = new ArrayList<String>(); while (m_pos < line.length()) { while (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; String term = parseSingleTerm(line); if (!(term.equals(""))) { provList.add(term); } } return provList; } }
IoanaIleana/ProvCB
src/instance/Parser.java
Java
gpl-3.0
3,628
(function() { 'use strict'; angular .module('app.grid') .service('GridDemoModelSerivce', GridDemoModelSerivce) .service('GridUtils',GridUtils) .factory('GridFactory',GridFactory) ; GridFactory.$inject = ['modelNode','$q','$filter']; function GridFactory(modelNode,$q,$filter) { return { buildGrid: function (option) { return new Grid(option,modelNode,$q,$filter); } } } function Grid(option,modelNode,$q,$filter) { var self = this; this.page = angular.extend({size: 9, no: 1}, option.page); this.sort = { column: option.sortColumn || '_id', direction: option.sortDirection ||-1, toggle: function (column) { if (column.sortable) { if (this.column === column.name) { this.direction = -this.direction || -1; } else { this.column = column.name; this.direction = -1; } self.paging(); } } }; this.searchForm = option.searchForm; this.rows = []; this.rawData = []; this.modelling = false; //必须有的 this.model = option.model; if (angular.isString(this.model)) { this.model = modelNode.services[this.model]; } if (!this.model) this.model = angular.noop; var promise; if (angular.isFunction(this.model)) { this.model = this.model(); } promise = $q.when(this.model).then(function (ret) { if (angular.isArray(ret)) { self.rawData = ret; } else { self.modelling = true; } self.setData = setData; self.query = query; self.paging = paging; return self; }); return promise; function setData(data) { self.rawData = data; } function query(param) { var queryParam = angular.extend({}, self.searchForm, param); if (self.modelling) { self.rows = self.model.page(self.page, queryParam, null, (self.sort.direction > 0 ? '' : '-') + self.sort.column); //服务端totals在查询数据时计算 self.model.totals(queryParam).$promise.then(function (ret) { self.page.totals = ret.totals; }); } else { if (self.rawData) self.rows = $filter('filter')(self.rawData, queryParam); } } function paging() { if (this.modelling) { this.query(); } } } GridDemoModelSerivce.$inject = ['Utils']; function GridDemoModelSerivce(Utils) { this.query = query; this.find = find; this.one = one; this.save = save; this.update = update; this.remove = remove; this._demoData_ = []; function query(refresh) { refresh = this._demoData_.length == 0 || refresh; if (refresh) { this._demoData_.length = 0; var MAX_NUM = 10 * 50; for (var i = 0; i < MAX_NUM; ++i) { var id = Utils.rand(0, MAX_NUM); this._demoData_.push({ id: i + 1, name: 'Name' + id, // 字符串类型 followers: Utils.rand(0, 100 * 1000 * 1000), // 数字类型 birthday: moment().subtract(Utils.rand(365, 365 * 50), 'day').toDate(), // 日期类型 summary: '这是一个测试' + i, income: Utils.rand(1000, 100000) // 金额类型 }); } } return this._demoData_; } function one(properties) { return _.findWhere(this._demoData_, properties); } function find(id) { return _.find(this._demoData_, function (item) { return item.id == id; }); } ///为了保证何$resource中的save功能一样此方法用于添加 function save(data) { //添加 this._demoData_.push(_.defaults(data, {})); //if (id != 'new') { // //修改 // var dest = _.bind(find, this, id); // _.extend(dest, data); //} //else { // //} } function update(id,data){ var dest = _.bind(find, this, id); _.extend(dest, data); } function remove(ids) { console.log(this._demoData_.length); this._demoData_ = _.reject(this._demoData_, function (item) { return _.contains(ids, item.id); }); console.log(this._demoData_.length); } } GridUtils.$inject = ['$filter','ViewUtils']; function GridUtils($filter,ViewUtils) { return { paging: paging, totals: totals, hide: hide, width: width, toggleOrderClass: toggleOrderClass, noResultsColspan: noResultsColspan, revertNumber: revertNumber, calcAge: calcAge, formatter: formatter, populateFilter: populateFilter, boolFilter: boolFilter, diFilter: diFilter, repeatInfoCombo: repeatInfoCombo, orFilter: orFilter }; function paging(items, vm) { if (!items) return []; if(vm.serverPaging){ //服务端分页 vm.paged = items; } else{ //客户端分页 var offset = (vm.page.no - 1) * vm.page.size; vm.paged = items.slice(offset, offset + vm.page.size); ////客户端totals在分页数据时计算 vm.page.totals = items.length;//客户端分页是立即触发结果 } return vm.paged; } function totals(items,filter,vm) { if (!items) return 0; if (vm.serverPaging) { //服务端分页 return vm.page.totals; } else { //客户端分页 return items.length || 0 } } function hide(column) { if (!column) return true; return column.hidden === true; } function width(column) { if (!column) return 0; return column.width || 100; } function toggleOrderClass(direction) { if (direction === -1) return "glyphicon-chevron-down"; else return "glyphicon-chevron-up"; } function noResultsColspan(vm) { if (!vm || !vm.columns) return 1; return 1 + vm.columns.length - _.where(vm.columns, {hidden: true}).length; } function revertNumber(num,notConvert) { if (num && !notConvert) { return -num; } return num; } function calcAge(rowValue) { return ViewUtils.age(rowValue) } function formatter(rowValue, columnName, columns) { var one = _.findWhere(columns, {name: columnName}); if(one && !one.hidden) { if (one.formatterData) { if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ return one.formatterData[o]; }); } else{ return one.formatterData[rowValue]; } } } return rowValue; } function populateFilter(rowValue, key) { key = key || 'name'; if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ console.log(o); return ViewUtils.getPropery(o, key); }); } else{ return ViewUtils.getPropery(o, key); } return rowValue; } function boolFilter(rowValue){ return {"1": "是", "0": "否", "true": "是", "false": "否"}[rowValue]; } function diFilter(rowValue,di) { if (_.isArray(rowValue)) { return _.map(rowValue, function (o) { return di[o] || (_.findWhere(di, {value: rowValue}) || {}).name; }); } else { return di[rowValue] || (_.findWhere(di, {value: rowValue}) || {}).name; } } function repeatInfoCombo(repeatValues, repeat_start) { if (_.isArray(repeatValues) && repeatValues.length > 0) { return _.map(repeatValues, function (r) { return r + repeat_start; }).join('\r\n'); } else { return repeat_start; } } /** * AngularJS default filter with the following expression: * "person in people | filter: {name: $select.search, age: $select.search}" * performs a AND between 'name: $select.search' and 'age: $select.search'. * We want to perform a OR. */ function orFilter(items, props) { var out = []; if (_.isArray(items)) { _.each(items,function (item) { var itemMatches = false; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; } })();
zppro/4gtour
src/vendor-1.x/js/modules/grid/grid.service.js
JavaScript
gpl-3.0
11,119
ForceTool ======= Allows administrators to force tool usage based on how they want it.
AlmuraDev/ForceTools
README.md
Markdown
gpl-3.0
87
package com.test.ipetrov.start; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @SpringBootApplication @EnableWebMvc @ComponentScan(basePackages = {"com.test.ipetrov.configuration", "com.test.ipetrov.portal"}) @EnableJpaRepositories(basePackages = "com.test.ipetrov") public class Application { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); } }
081krieger/rps
src/main/java/com/test/ipetrov/start/Application.java
Java
gpl-3.0
804
import { Pipeline, Step } from '@ephox/agar'; import { Arr } from '@ephox/katamari'; import { LegacyUnit } from '@ephox/mcagar'; import Serializer from 'tinymce/core/api/dom/Serializer'; import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; import TrimHtml from 'tinymce/core/dom/TrimHtml'; import ViewBlock from '../../module/test/ViewBlock'; import Zwsp from 'tinymce/core/text/Zwsp'; import { UnitTest } from '@ephox/bedrock'; declare const escape: any; UnitTest.asynctest('browser.tinymce.core.dom.SerializerTest', function () { const success = arguments[arguments.length - 2]; const failure = arguments[arguments.length - 1]; const suite = LegacyUnit.createSuite(); const DOM = DOMUtils.DOM; const viewBlock = ViewBlock(); const teardown = function () { viewBlock.update(''); }; const addTeardown = function (steps) { return Arr.bind(steps, function (step) { return [step, Step.sync(teardown)]; }); }; suite.test('Schema rules', function () { let ser = Serializer({ fix_list_elements : true }); ser.setRules('@[id|title|class|style],div,img[src|alt|-style|border],span,hr'); DOM.setHTML('test', '<img title="test" src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="test" ' + 'border="0" style="border: 1px solid red" class="test" /><span id="test2">test</span><hr />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img title="test" class="test" src="tinymce/ui/img/raster.gif" ' + 'alt="test" border="0" /><span id="test2">test</span><hr />', 'Global rule' ); ser.setRules('*a[*],em/i[*],strong/b[*i*]'); DOM.setHTML('test', '<a href="test" data-mce-href="test">test</a><strong title="test" class="test">test2</strong><em title="test">test3</em>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<a href="test">test</a><strong title="test">test2</strong><em title="test">' + 'test3</em>', 'Wildcard rules'); ser.setRules('br,hr,input[type|name|value],div[id],span[id],strong/b,a,em/i,a[!href|!name],img[src|border=0|title={$uid}]'); DOM.setHTML('test', '<br /><hr /><input type="text" name="test" value="val" class="no" />' + '<span id="test2" class="no"><b class="no">abc</b><em class="no">123</em></span>123<a href="file.html" ' + 'data-mce-href="file.html">link</a><a name="anchor"></a><a>no</a><img src="tinymce/ui/img/raster.gif" ' + 'data-mce-src="tinymce/ui/img/raster.gif" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<div id="test"><br /><hr /><input type="text" name="test" value="val" />' + '<span id="test2"><strong>abc</strong><em>123</em></span>123<a href="file.html">link</a>' + '<a name="anchor"></a>no<img src="tinymce/ui/img/raster.gif" border="0" title="mce_0" /></div>', 'Output name and attribute rules'); ser.setRules('img[src|border=0|alt=]'); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" border="0" alt="" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<img src="tinymce/ui/img/raster.gif" border="0" alt="" />', 'Default attribute with empty value'); ser.setRules('img[src|border=0|alt=],div[style|id],*[*]'); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img src="tinymce/ui/img/raster.gif" border="0" alt="" /><hr />' ); ser = Serializer({ valid_elements : 'img[src|border=0|alt=]', extended_valid_elements : 'div[id],img[src|alt=]' }); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" alt="" />'); LegacyUnit.equal( ser.serialize(DOM.get('test')), '<div id="test"><img src="tinymce/ui/img/raster.gif" alt="" /></div>' ); ser = Serializer({ invalid_elements : 'hr,br' }); DOM.setHTML('test', '<img src="tinymce/ui/img/raster.gif" data-mce-src="tinymce/ui/img/raster.gif" /><hr /><br />'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<img src="tinymce/ui/img/raster.gif" />' ); }); suite.test('allow_unsafe_link_target (default)', function () { const ser = Serializer({ }); DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="noopener">a</a><a href="b" target="_blank" rel="noopener">b</a>' ); DOM.setHTML('test', '<a href="a" rel="lightbox" target="_blank">a</a><a href="b" rel="lightbox" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="lightbox noopener">a</a><a href="b" target="_blank" rel="lightbox noopener">b</a>' ); DOM.setHTML('test', '<a href="a" rel="lightbox x" target="_blank">a</a><a href="b" rel="lightbox x" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="lightbox noopener x">a</a><a href="b" target="_blank" rel="lightbox noopener x">b</a>' ); DOM.setHTML('test', '<a href="a" rel="noopener a" target="_blank">a</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="noopener a">a</a>' ); DOM.setHTML('test', '<a href="a" rel="a noopener b" target="_blank">a</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank" rel="a noopener b">a</a>' ); }); suite.test('allow_unsafe_link_target (disabled)', function () { const ser = Serializer({ allow_unsafe_link_target: true }); DOM.setHTML('test', '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<a href="a" target="_blank">a</a><a href="b" target="_blank">b</a>' ); }); suite.test('format tree', function () { const ser = Serializer({ }); DOM.setHTML('test', 'a'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { format: 'tree' }).name, 'body' ); }); suite.test('Entity encoding', function () { let ser; ser = Serializer({ entity_encoding : 'numeric' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&#160;&#229;&#228;&#246;'); ser = Serializer({ entity_encoding : 'named' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&nbsp;&aring;&auml;&ouml;'); ser = Serializer({ entity_encoding : 'named+numeric', entities : '160,nbsp,34,quot,38,amp,60,lt,62,gt' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"&nbsp;&#229;&#228;&#246;'); ser = Serializer({ entity_encoding : 'raw' }); DOM.setHTML('test', '&lt;&gt;&amp;&quot;&nbsp;&aring;&auml;&ouml;'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '&lt;&gt;&amp;"\u00a0\u00e5\u00e4\u00f6'); }); suite.test('Form elements (general)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules( 'form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],' + 'option[value|selected],textarea[name|disabled|readonly]' ); DOM.setHTML('test', '<input type="text" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" />'); DOM.setHTML('test', '<input type="text" value="text" length="128" maxlength="129" />'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="text" value="text" length="128" maxlength="129" />'); DOM.setHTML('test', '<form method="post"><input type="hidden" name="method" value="get" /></form>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<form method="post"><input type="hidden" name="method" value="get" /></form>'); DOM.setHTML('test', '<label for="test">label</label>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<label for="test">label</label>'); DOM.setHTML('test', '<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>'); // Edge will add an empty input value so remove that to normalize test since it doesn't break anything LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/ value=""/g, ''), '<input type="checkbox" value="test" /><input type="button" /><textarea></textarea>' ); }); suite.test('Form elements (checkbox)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]'); DOM.setHTML('test', '<input type="checkbox" value="1">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked disabled readonly>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked="1" disabled="1" readonly="1">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); DOM.setHTML('test', '<input type="checkbox" value="1" checked="true" disabled="true" readonly="true">'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<input type="checkbox" value="1" checked="checked" disabled="disabled" readonly="readonly" />'); }); suite.test('Form elements (select)', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('form[method],label[for],input[type|name|value|checked|disabled|readonly|length|maxlength],select[multiple],option[value|selected]'); DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected>test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select><option value="1">test1</option><option selected="1" value="2">test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select><option value="1">test1</option><option value="2" selected="true">test2</option></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select><option value="1">test1</option><option value="2" selected="selected">test2</option></select>'); DOM.setHTML('test', '<select multiple></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select multiple="multiple"></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select multiple="1"></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select multiple="multiple"></select>'); DOM.setHTML('test', '<select></select>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<select></select>'); }); suite.test('List elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('ul[compact],ol,li'); DOM.setHTML('test', '<ul compact></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul compact="compact"></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul compact="1"></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul compact="compact"></ul>'); DOM.setHTML('test', '<ul></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul></ul>'); DOM.setHTML('test', '<ol><li>a</li><ol><li>b</li><li>c</li></ol><li>e</li></ol>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ol><li>a<ol><li>b</li><li>c</li></ol></li><li>e</li></ol>'); }); suite.test('Tables', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('table,tr,td[nowrap]'); DOM.setHTML('test', '<table><tr><td></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap="nowrap"></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); DOM.setHTML('test', '<table><tr><td nowrap="1"></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<table><tr><td nowrap="nowrap"></td></tr></table>'); }); suite.test('Styles', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); DOM.setHTML('test', '<span style="border: 1px solid red" data-mce-style="border: 1px solid red;">test</span>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<span style="border: 1px solid red;">test</span>'); }); suite.test('Comments', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); DOM.setHTML('test', '<!-- abc -->'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), '<!-- abc -->'); }); suite.test('Non HTML elements and attributes', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('*[*]'); ser.schema.addValidChildren('+div[prefix:test]'); DOM.setHTML('test', '<div test:attr="test">test</div>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner : true }), '<div test:attr="test">test</div>'); DOM.setHTML('test', 'test1<prefix:test>Test</prefix:test>test2'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: true }), 'test1<prefix:test>Test</prefix:test>test2'); }); suite.test('Padd empty elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('#p'); DOM.setHTML('test', '<p>test</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p><p>&nbsp;</p>'); }); suite.test('Padd empty elements with BR', function () { const ser = Serializer({ padd_empty_with_br: true }); ser.setRules('#p,table,tr,#td,br'); DOM.setHTML('test', '<p>a</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><p><br /></p>'); DOM.setHTML('test', '<p>a</p><table><tr><td><br></td></tr></table>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p><table><tr><td><br /></td></tr></table>'); }); suite.test('Do not padd empty elements with padded children', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('#p,#span,b'); DOM.setHTML('test', '<p><span></span></p><p><b><span></span></b></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p><span>&nbsp;</span></p><p><b><span>&nbsp;</span></b></p>'); }); suite.test('Remove empty elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('-p'); DOM.setHTML('test', '<p>test</p><p></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>test</p>'); }); suite.test('Script with non JS type attribute', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="mylanguage"></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript type="mylanguage"></s' + 'cript>'); }); suite.test('Script with tags inside a comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n// <img src="test"><a href="#"></a>\n// ]]></s' + 'cript>' ); }); suite.test('Script with tags inside a comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <img src="test"><a href="#"></a></s' + 'cript>' ); }); suite.test('Script with less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript>1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>1 < 2;</s' + 'cript>'); }); suite.test('Script with type attrib and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type="text/javascript">// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with type attrib and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<s' + 'cript type="text/javascript">1 < 2;</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script type=\"text/javascript\">1 < 2;</script>'); }); suite.test('Script with whitespace in beginning/end with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n// ]]></s' + 'cript>' ); }); suite.test('Script with whitespace in beginning/end', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</s' + 'cript>'); LegacyUnit.equal( ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\t1 < 2;\n\t if (2 < 1)\n\t\talert(1);\n</script>' ); }); suite.test('Script with a HTML comment and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with a HTML comment and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- 1 < 2; // --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><!-- 1 < 2; // --></script>'); }); suite.test('Script with white space in beginning, comment and less than with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with white space in beginning, comment and less than', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<!-- 1 < 2;\n\n--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<!-- 1 < 2;\n\n--></script>'); }); suite.test('Script with comments and cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with comments and cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <![CDATA[1 < 2; // ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>// <![CDATA[1 < 2; // ]]></script>'); }); suite.test('Script with cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script with cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><![CDATA[1 < 2; ]]></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script><![CDATA[1 < 2; ]]></script>'); }); suite.test('Script whitespace in beginning/end and cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<s' + 'cript>// <![CDATA[\n1 < 2;\n// ]]></s' + 'cript>'); }); suite.test('Script whitespace in beginning/end and cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<script>\n\n<![CDATA[\n\n1 < 2;\n\n]]>\n\n</script>'); }); suite.test('Whitespace preserve in pre', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('pre'); DOM.setHTML('test', '<pre> </pre>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<pre> </pre>'); }); suite.test('Script with src attr', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script src="test.js" data-mce-src="test.js"></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<s' + 'cript src="test.js"></s' + 'cript>'); }); suite.test('Script with HTML comment, comment and CDATA with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with HTML comment, comment and CDATA', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!--// <![CDATA[var hi = "hello";// ]]>--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!--// <![CDATA[var hi = \"hello\";// ]]>--></script>'); }); suite.test('Script with block comment around cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with block comment around cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <![CDATA[ */\nvar hi = "hello";\n/* ]]> */</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>/* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]> */</script>'); }); suite.test('Script with html comment and block comment around cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with html comment and block comment around cdata', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script><!-- /* <![CDATA[ */\nvar hi = "hello";\n/* ]]>*/--></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script><!-- /* <![CDATA[ */\nvar hi = \"hello\";\n/* ]]>*/--></script>'); }); suite.test('Script with line comment and html comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with line comment and html comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>// <!--\nvar hi = "hello";\n// --></s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <!--\nvar hi = \"hello\";\n// --></script>'); }); suite.test('Script with block comment around html comment with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, element_format: 'xhtml' }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <!-- */\nvar hi = "hello";\n/*-->*/</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>// <![CDATA[\nvar hi = \"hello\";\n// ]]></s' + 'cript>'); }); suite.test('Script with block comment around html comment', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('script[type|language|src]'); DOM.setHTML('test', '<script>/* <!-- */\nvar hi = "hello";\n/*-->*/</s' + 'cript>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<script>/* <!-- */\nvar hi = \"hello\";\n/*-->*/</script>'); }); suite.test('Protected blocks', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('noscript[test]'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript test="test"><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript test="test"><br></noscript>'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><br></noscript>'); DOM.setHTML('test', '<!--mce:protected ' + escape('<noscript><!-- text --><br></noscript>') + '-->'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<noscript><!-- text --><br></noscript>'); }); suite.test('Style with whitespace at beginning with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' }); ser.setRules('style'); DOM.setHTML('test', '<style> body { background:#fff }</style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\n body { background:#fff }\n--></style>'); }); suite.test('Style with whitespace at beginning', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' }); ser.setRules('style'); DOM.setHTML('test', '<style> body { background:#fff }</style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style> body { background:#fff }</style>'); }); suite.test('Style with cdata with element_format: xhtml', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]', element_format: 'xhtml' }); ser.setRules('style'); DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style><!--\nbody { background:#fff }\n--></style>'); }); suite.test('Style with cdata', function () { const ser = Serializer({ fix_list_elements : true, valid_children: '+body[style]' }); ser.setRules('style'); DOM.setHTML('test', '<style>\r\n<![CDATA[\r\n body { background:#fff }]]></style>'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '<style>\n<![CDATA[\n body { background:#fff }]]></style>'); }); suite.test('CDATA', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('span'); DOM.setHTML('test', '123<!--[CDATA[<test>]]-->abc'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '123<![CDATA[<test>]]>abc'); DOM.setHTML('test', '123<!--[CDATA[<te\n\nst>]]-->abc'); LegacyUnit.equal(ser.serialize(DOM.get('test')).replace(/\r/g, ''), '123<![CDATA[<te\n\nst>]]>abc'); }); suite.test('BR at end of blocks', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('ul,li,br'); DOM.setHTML('test', '<ul><li>test<br /></li><li>test<br /></li><li>test<br /></li></ul>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<ul><li>test</li><li>test</li><li>test</li></ul>'); }); suite.test('Map elements', function () { const ser = Serializer({ fix_list_elements : true }); ser.setRules('map[id|name],area[shape|coords|href|target|alt]'); DOM.setHTML( 'test', '<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" data-mce-href="sun.htm" target="_blank" alt="sun" /></map>' ); LegacyUnit.equal( ser.serialize(DOM.get('test')).toLowerCase(), '<map id="planetmap" name="planetmap"><area shape="rect" coords="0,0,82,126" href="sun.htm" target="_blank" alt="sun" /></map>' ); }); suite.test('Custom elements', function () { const ser = Serializer({ custom_elements: 'custom1,~custom2', valid_elements: 'custom1,custom2' }); document.createElement('custom1'); document.createElement('custom2'); DOM.setHTML('test', '<p><custom1>c1</custom1><custom2>c2</custom2></p>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<custom1>c1</custom1><custom2>c2</custom2>'); }); suite.test('Remove internal classes', function () { const ser = Serializer({ valid_elements: 'span[class]' }); DOM.setHTML('test', '<span class="a mce-item-X mce-item-selected b"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a b"></span>'); DOM.setHTML('test', '<span class="a mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="a"></span>'); DOM.setHTML('test', '<span class="mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span></span>'); DOM.setHTML('test', '<span class="mce-item-X b"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class=" b"></span>'); DOM.setHTML('test', '<span class="b mce-item-X"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span class="b"></span>'); }); suite.test('Restore tabindex', function () { const ser = Serializer({ valid_elements: 'span[tabindex]' }); DOM.setHTML('test', '<span data-mce-tabindex="42"></span>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<span tabindex="42"></span>'); }); suite.test('Trailing BR (IE11)', function () { const ser = Serializer({ valid_elements: 'p,br' }); DOM.setHTML('test', '<p>a</p><br><br>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), '<p>a</p>'); DOM.setHTML('test', 'a<br><br>'); LegacyUnit.equal(ser.serialize(DOM.get('test')), 'a'); }); suite.test('addTempAttr', function () { const ser = Serializer({}); ser.addTempAttr('data-x'); ser.addTempAttr('data-y'); DOM.setHTML('test', '<p data-x="1" data-y="2" data-z="3">a</p>'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser, '<p data-x="1" data-y="2" data-z="3">a</p>'), '<p data-z="3">a</p>'); }); suite.test('addTempAttr same attr twice', function () { const ser1 = Serializer({}); const ser2 = Serializer({}); ser1.addTempAttr('data-x'); ser2.addTempAttr('data-x'); DOM.setHTML('test', '<p data-x="1" data-z="3">a</p>'); LegacyUnit.equal(ser1.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser1, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>'); LegacyUnit.equal(ser2.serialize(DOM.get('test'), { getInner: 1 }), '<p data-z="3">a</p>'); LegacyUnit.equal(TrimHtml.trimExternal(ser2, '<p data-x="1" data-z="3">a</p>'), '<p data-z="3">a</p>'); }); suite.test('trim data-mce-bougs="all"', function () { const ser = Serializer({}); DOM.setHTML('test', 'a<p data-mce-bogus="all">b</p>c'); LegacyUnit.equal(ser.serialize(DOM.get('test'), { getInner: 1 }), 'ac'); LegacyUnit.equal(TrimHtml.trimExternal(ser, 'a<p data-mce-bogus="all">b</p>c'), 'ac'); }); suite.test('zwsp should not be treated as contents', function () { const ser = Serializer({ }); DOM.setHTML('test', '<p>' + Zwsp.ZWSP + '</p>'); LegacyUnit.equal( ser.serialize(DOM.get('test'), { getInner: true }), '<p>&nbsp;</p>' ); }); viewBlock.attach(); viewBlock.get().id = 'test'; Pipeline.async({}, addTeardown(suite.toSteps({})), function () { viewBlock.detach(); success(); }, failure); });
jabber-at/hp
hp/core/static/lib/tinymce/src/core/test/ts/browser/dom/SerializerTest.ts
TypeScript
gpl-3.0
36,451
<?php /** * Core Class To Style RAD Builder Components * @author Abhin Sharma * @dependency none * @since IOA Framework V1 */ if(!class_exists('RADStyler')) { class RADStyler { function registerbgColor($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Background Color','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Background Color",'ioa') , "name" => $key."_bg_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "background-color" ) )); return $code.'</div>'; } function registerBorder($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Border','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Top Border Color",'ioa') , "name" => $key."_tbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-top-color" ) )); $code .= getIOAInput(array( "label" => __("Top Border Size(ex : 1px)",'ioa') , "name" => $key."_tbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-top-width" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Color",'ioa') , "name" => $key."_bbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-bottom-color" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Size(ex : 1px)",'ioa') , "name" => $key."_bbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-bottom-width" ) )); return $code.'</div>'; } function registerbgImage($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Image','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Add Background Image",'ioa') , "name" => $key."_bg_image" , "default" => "" , "type" => "upload", "description" => "" , "length" => 'small' , "title" => __("Use as Background Image",'ioa'), "std" => "", "button" => __("Add Image",'ioa'), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Background Position",'ioa') , "name" => $key."_bgposition" , "default" => "top left" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("top left","top right","bottom left","bottom right","center top","center center","center bottom","center left","center right"), "data" => array( "target" => $target , "property" => "background-position" ) ) ); $code .= getIOAInput(array( "label" => __("Background Cover",'ioa') , "name" => $key."_bgcover" , "default" => "auto" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("auto","contain","cover"), "data" => array( "target" => $target , "property" => "background-size" ) ) ); $code .= getIOAInput(array( "label" => __("Background Repeat",'ioa') , "name" => $key."_bgrepeat" , "default" => "repeat" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("repeat","repeat-x","repeat-y","no-repeat"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-repeat" ) ) ); $code .= getIOAInput(array( "label" => __("Background Scroll",'ioa') , "name" => $key."_bgscroll" , "default" => "" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("scroll","fixed"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-attachment" ) ) ); return $code.'</div>'; } function registerbgGradient($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Gradient','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix"><a class="set-rad-gradient button-default" href="">'.__('Apply','ioa').'</a> '; $code .= getIOAInput(array( "label" => __("Use Background Gradient",'ioa') , "name" => $key."_gradient_dir" , "default" => "no" , "type" => "select", "description" => "" , "length" => 'small' , "options" => array("horizontal" => __("Horizontal",'ioa'),"vertical"=> __("Vertical",'ioa'),"diagonaltl" => __("Diagonal Top Left",'ioa'),"diagonalbr" => __("Diagonal Bottom Right",'ioa') ), "class" => ' hasGradient dir ', "data" => array( "target" => $target , "property" => "removable" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grstart" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grstart no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grend" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grend no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); return $code.'</div>'; } } }
lithqube/sedesgroup
IT/wp-content/themes/limitless/backend/rad_builder/class_radstyler.php
PHP
gpl-3.0
7,651
--- title: '1º Aberto Gaúcho de Super Smash Bros. - Wii U Singles, Doubles e Crews! (22/07 e 23/07)' date: 2016-04-21 18:17:00 author: 'DASH|Vinikun' image: 'http://i.imgur.com/7w6udGs.jpg' ---
smashrs/smash-rs
_drafts/2017-02-08-1º Aberto Gaúcho de Super Smash Bros.md
Markdown
gpl-3.0
197
#if defined (_MSC_VER) && !defined (_WIN64) #pragma warning(disable:4244) // boost::number_distance::distance() // converts 64 to 32 bits integers #endif #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/IO/read_xyz_points.h> #include <CGAL/Point_with_normal_3.h> #include <CGAL/property_map.h> #include <CGAL/Shape_detection_3.h> #include <CGAL/Timer.h> #include <iostream> #include <fstream> // Type declarations typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal; typedef std::vector<Point_with_normal> Pwn_vector; typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map; typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map; // In Shape_detection_traits the basic types, i.e., Point and Vector types // as well as iterator type and property maps, are defined. typedef CGAL::Shape_detection_3::Shape_detection_traits <Kernel, Pwn_vector, Point_map, Normal_map> Traits; typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac; typedef CGAL::Shape_detection_3::Region_growing<Traits> Region_growing; typedef CGAL::Shape_detection_3::Plane<Traits> Plane; struct Timeout_callback { mutable int nb; mutable CGAL::Timer timer; const double limit; Timeout_callback(double limit) : nb(0), limit(limit) { timer.start(); } bool operator()(double advancement) const { // Avoid calling time() at every single iteration, which could // impact performances very badly ++ nb; if (nb % 1000 != 0) return true; // If the limit is reach, interrupt the algorithm if (timer.time() > limit) { std::cerr << "Algorithm takes too long, exiting (" << 100. * advancement << "% done)" << std::endl; return false; } return true; } }; // This program both works for RANSAC and Region Growing template <typename ShapeDetection> int run(const char* filename) { Pwn_vector points; std::ifstream stream(filename); if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()). normal_map(Normal_map()))) { std::cerr << "Error: cannot read file cube.pwn" << std::endl; return EXIT_FAILURE; } ShapeDetection shape_detection; shape_detection.set_input(points); shape_detection.template add_shape_factory<Plane>(); // Create callback that interrupts the algorithm if it takes more than half a second Timeout_callback timeout_callback(0.5); // Detects registered shapes with default parameters. shape_detection.detect(typename ShapeDetection::Parameters(), timeout_callback); return EXIT_SUCCESS; } int main (int argc, char** argv) { if (argc > 1 && std::string(argv[1]) == "-r") { std::cout << "Efficient RANSAC" << std::endl; return run<Efficient_ransac> ((argc > 2) ? argv[2] : "data/cube.pwn"); } std::cout << "Region Growing" << std::endl; return run<Region_growing> ((argc > 1) ? argv[1] : "data/cube.pwn"); }
FEniCS/mshr
3rdparty/CGAL/examples/Point_set_shape_detection_3/shape_detection_with_callback.cpp
C++
gpl-3.0
3,227
public class Rectangulo { public int Base; public int Altura; //Ejercicio realizado con ayuda de esta pagina:http://diagramas-de-flujo.blogspot.com/2013/02/calcular-perimetro-rectangulo-Java.html //aqui llamamos las dos variables que utilizaremos. Rectangulo(int Base, int Altura) { this.Base = Base; this.Altura = Altura; } //COmo pueden observar aqui se obtiene la base y se asigna el valor de la base. int getBase () { return Base; } //aqui devolvemos ese valor void setBase (int Base) { this.Base = Base; } //aqui de igual forma se obtiene la altura y se le asigna el valor int getAltura () { return Altura; } //aqui devuelve el valor de la altura void setAltura (int Altura) { this.Altura = Altura; } //aqui con una formula matematica se obtiene el perimetro hacemos una suma y una multiplicacion int getPerimetro() { return 2*(Base+Altura); } //aqui solo se hace un calculo matematico como la multiplicacion int getArea() { return Base*Altura; } }
IvethS/Tarea2
src/Rectangulo.java
Java
gpl-3.0
1,004
/* * This file is part of "U Turismu" project. * * U Turismu is an enterprise application in support of calabrian tour operators. * This system aims to promote tourist services provided by the operators * and to develop and improve tourism in Calabria. * * Copyright (C) 2012 "LagrecaSpaccarotella" team. * * 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 uturismu.dao; import uturismu.dto.Booking; /** * @author "LagrecaSpaccarotella" team. * */ public interface BookingDao extends GenericDao<Booking> { }
spa-simone/u-turismu
src/main/java/uturismu/dao/BookingDao.java
Java
gpl-3.0
1,133
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , mongo = require('mongodb') , format = require('util').format; var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } var server = new mongo.Server("localhost", 27017, {auto_reconnect: true}); var dbManager = new mongo.Db("applique-web", server, {safe:true}); dbManager.open(function(err, db) { require('./routes/index')(app, db); app.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); });
jkamga/INM5151-payGoStore
app.js
JavaScript
gpl-3.0
991
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2016 Cppcheck team. * * 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 "cmdlineparser.h" #include "cppcheck.h" #include "cppcheckexecutor.h" #include "filelister.h" #include "path.h" #include "settings.h" #include "timer.h" #include "check.h" #include "threadexecutor.h" // Threading model #include <algorithm> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <cstring> #include <cstdlib> // EXIT_FAILURE #ifdef HAVE_RULES // xml is used for rules #include <tinyxml2.h> #endif static void AddFilesToList(const std::string& FileList, std::vector<std::string>& PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::istream *Files; std::ifstream Infile; if (FileList.compare("-") == 0) { // read from stdin Files = &std::cin; } else { Infile.open(FileList.c_str()); Files = &Infile; } if (Files && *Files) { std::string FileName; while (std::getline(*Files, FileName)) { // next line if (!FileName.empty()) { PathNames.push_back(FileName); } } } } static void AddInclPathsToList(const std::string& FileList, std::list<std::string>* PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::ifstream Files(FileList.c_str()); if (Files) { std::string PathName; while (std::getline(Files, PathName)) { // next line if (!PathName.empty()) { PathName = Path::removeQuotationMarks(PathName); PathName = Path::fromNativeSeparators(PathName); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (PathName.back() != '/') #else if (PathName[PathName.size() - 1] != '/') #endif PathName += '/'; PathNames->push_back(PathName); } } } } static void AddPathsToSet(const std::string& FileName, std::set<std::string>* set) { std::list<std::string> templist; AddInclPathsToList(FileName, &templist); set->insert(templist.begin(), templist.end()); } CmdLineParser::CmdLineParser(Settings *settings) : _settings(settings) , _showHelp(false) , _showVersion(false) , _showErrorMessages(false) , _exitAfterPrint(false) { } void CmdLineParser::PrintMessage(const std::string &message) { std::cout << message << std::endl; } void CmdLineParser::PrintMessage(const char* message) { std::cout << message << std::endl; } bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) { bool def = false; bool maxconfigs = false; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (std::strcmp(argv[i], "--version") == 0) { _showVersion = true; _exitAfterPrint = true; return true; } // Flag used for various purposes during debugging else if (std::strcmp(argv[i], "--debug") == 0) _settings->debug = _settings->debugwarnings = true; // Show --debug output after the first simplifications else if (std::strcmp(argv[i], "--debug-normal") == 0) _settings->debugnormal = true; // Show debug warnings else if (std::strcmp(argv[i], "--debug-warnings") == 0) _settings->debugwarnings = true; // dump cppcheck data else if (std::strcmp(argv[i], "--dump") == 0) _settings->dump = true; // (Experimental) exception handling inside cppcheck client else if (std::strcmp(argv[i], "--exception-handling") == 0) _settings->exceptionHandling = true; else if (std::strncmp(argv[i], "--exception-handling=", 21) == 0) { _settings->exceptionHandling = true; const std::string exceptionOutfilename = &(argv[i][21]); CppCheckExecutor::setExceptionOutput((exceptionOutfilename=="stderr") ? stderr : stdout); } // Inconclusive checking else if (std::strcmp(argv[i], "--inconclusive") == 0) _settings->inconclusive = true; // Enforce language (--language=, -x) else if (std::strncmp(argv[i], "--language=", 11) == 0 || std::strcmp(argv[i], "-x") == 0) { std::string str; if (argv[i][2]) { str = argv[i]+11; } else { i++; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: No language given to '-x' option."); return false; } str = argv[i]; } if (str == "c") _settings->enforcedLang = Settings::C; else if (str == "c++") _settings->enforcedLang = Settings::CPP; else { PrintMessage("cppcheck: Unknown language '" + str + "' enforced."); return false; } } // Filter errors else if (std::strncmp(argv[i], "--exitcode-suppressions=", 24) == 0) { // exitcode-suppressions=filename.txt std::string filename = 24 + argv[i]; std::ifstream f(filename.c_str()); if (!f.is_open()) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } const std::string errmsg(_settings->nofail.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Filter errors else if (std::strncmp(argv[i], "--suppressions-list=", 20) == 0) { std::string filename = argv[i]+20; std::ifstream f(filename.c_str()); if (!f.is_open()) { std::string message("cppcheck: Couldn't open the file: \""); message += filename; message += "\"."; if (std::count(filename.begin(), filename.end(), ',') > 0 || std::count(filename.begin(), filename.end(), '.') > 1) { // If user tried to pass multiple files (we can only guess that) // e.g. like this: --suppressions-list=a.txt,b.txt // print more detailed error message to tell user how he can solve the problem message += "\nIf you want to pass two files, you can do it e.g. like this:"; message += "\n cppcheck --suppressions-list=a.txt --suppressions-list=b.txt file.cpp"; } PrintMessage(message); return false; } const std::string errmsg(_settings->nomsg.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } else if (std::strncmp(argv[i], "--suppress=", 11) == 0) { std::string suppression = argv[i]+11; const std::string errmsg(_settings->nomsg.addSuppressionLine(suppression)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Enables inline suppressions. else if (std::strcmp(argv[i], "--inline-suppr") == 0) _settings->inlineSuppressions = true; // Verbose error messages (configuration info) else if (std::strcmp(argv[i], "-v") == 0 || std::strcmp(argv[i], "--verbose") == 0) _settings->verbose = true; // Force checking of files that have "too many" configurations else if (std::strcmp(argv[i], "-f") == 0 || std::strcmp(argv[i], "--force") == 0) _settings->force = true; // Output relative paths else if (std::strcmp(argv[i], "-rp") == 0 || std::strcmp(argv[i], "--relative-paths") == 0) _settings->relativePaths = true; else if (std::strncmp(argv[i], "-rp=", 4) == 0 || std::strncmp(argv[i], "--relative-paths=", 17) == 0) { _settings->relativePaths = true; if (argv[i][argv[i][3]=='='?4:17] != 0) { std::string paths = argv[i]+(argv[i][3]=='='?4:17); for (;;) { std::string::size_type pos = paths.find(';'); if (pos == std::string::npos) { _settings->basePaths.push_back(Path::fromNativeSeparators(paths)); break; } else { _settings->basePaths.push_back(Path::fromNativeSeparators(paths.substr(0, pos))); paths.erase(0, pos + 1); } } } else { PrintMessage("cppcheck: No paths specified for the '" + std::string(argv[i]) + "' option."); return false; } } // Write results in results.xml else if (std::strcmp(argv[i], "--xml") == 0) _settings->xml = true; // Define the XML file version (and enable XML output) else if (std::strncmp(argv[i], "--xml-version=", 14) == 0) { std::string numberString(argv[i]+14); std::istringstream iss(numberString); if (!(iss >> _settings->xml_version)) { PrintMessage("cppcheck: argument to '--xml-version' is not a number."); return false; } if (_settings->xml_version < 0 || _settings->xml_version > 2) { // We only have xml versions 1 and 2 PrintMessage("cppcheck: '--xml-version' can only be 1 or 2."); return false; } // Enable also XML if version is set _settings->xml = true; } // Only print something when there are errors else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0) _settings->quiet = true; // Append user-defined code to checked source code else if (std::strncmp(argv[i], "--append=", 9) == 0) { const std::string filename = 9 + argv[i]; if (!_settings->append(filename)) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } } // Check configuration else if (std::strcmp(argv[i], "--check-config") == 0) { _settings->checkConfiguration = true; } // Check library definitions else if (std::strcmp(argv[i], "--check-library") == 0) { _settings->checkLibrary = true; } else if (std::strncmp(argv[i], "--enable=", 9) == 0) { const std::string errmsg = _settings->addEnabled(argv[i] + 9); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } // when "style" is enabled, also enable "warning", "performance" and "portability" if (_settings->isEnabled("style")) { _settings->addEnabled("warning"); _settings->addEnabled("performance"); _settings->addEnabled("portability"); } } // --error-exitcode=1 else if (std::strncmp(argv[i], "--error-exitcode=", 17) == 0) { std::string temp = argv[i]+17; std::istringstream iss(temp); if (!(iss >> _settings->exitCode)) { _settings->exitCode = 0; PrintMessage("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'."); return false; } } // User define else if (std::strncmp(argv[i], "-D", 2) == 0) { std::string define; // "-D define" if (std::strcmp(argv[i], "-D") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-D' is missing."); return false; } define = argv[i]; } // "-Ddefine" else { define = 2 + argv[i]; } // No "=", append a "=1" if (define.find('=') == std::string::npos) define += "=1"; if (!_settings->userDefines.empty()) _settings->userDefines += ";"; _settings->userDefines += define; def = true; } // User undef else if (std::strncmp(argv[i], "-U", 2) == 0) { std::string undef; // "-U undef" if (std::strcmp(argv[i], "-U") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-U' is missing."); return false; } undef = argv[i]; } // "-Uundef" else { undef = 2 + argv[i]; } _settings->userUndefs.insert(undef); } // -E else if (std::strcmp(argv[i], "-E") == 0) { _settings->preprocessOnly = true; } // Include paths else if (std::strncmp(argv[i], "-I", 2) == 0) { std::string path; // "-I path/" if (std::strcmp(argv[i], "-I") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-I' is missing."); return false; } path = argv[i]; } // "-Ipath/" else { path = 2 + argv[i]; } path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; _settings->includePaths.push_back(path); } else if (std::strncmp(argv[i], "--include=", 10) == 0) { std::string path = argv[i] + 10; path = Path::fromNativeSeparators(path); _settings->userIncludes.push_back(path); } else if (std::strncmp(argv[i], "--includes-file=", 16) == 0) { // open this file and read every input file (1 file name per line) AddInclPathsToList(16 + argv[i], &_settings->includePaths); } else if (std::strncmp(argv[i], "--config-exclude=",17) ==0) { std::string path = argv[i] + 17; path = Path::fromNativeSeparators(path); _settings->configExcludePaths.insert(path); } else if (std::strncmp(argv[i], "--config-excludes-file=", 23) == 0) { // open this file and read every input file (1 file name per line) AddPathsToSet(23 + argv[i], &_settings->configExcludePaths); } // file list specified else if (std::strncmp(argv[i], "--file-list=", 12) == 0) { // open this file and read every input file (1 file name per line) AddFilesToList(12 + argv[i], _pathnames); } // Ignored paths else if (std::strncmp(argv[i], "-i", 2) == 0) { std::string path; // "-i path/" if (std::strcmp(argv[i], "-i") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-i' is missing."); return false; } path = argv[i]; } // "-ipath/" else { path = 2 + argv[i]; } if (!path.empty()) { path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); path = Path::simplifyPath(path); if (FileLister::isDirectory(path)) { // If directory name doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; } _ignoredPaths.push_back(path); } } // --library else if (std::strncmp(argv[i], "--library=", 10) == 0) { if (!CppCheckExecutor::tryLoadLibrary(_settings->library, argv[0], argv[i]+10)) return false; } // Report progress else if (std::strcmp(argv[i], "--report-progress") == 0) { _settings->reportProgress = true; } // --std else if (std::strcmp(argv[i], "--std=posix") == 0) { _settings->standards.posix = true; } else if (std::strcmp(argv[i], "--std=c89") == 0) { _settings->standards.c = Standards::C89; } else if (std::strcmp(argv[i], "--std=c99") == 0) { _settings->standards.c = Standards::C99; } else if (std::strcmp(argv[i], "--std=c11") == 0) { _settings->standards.c = Standards::C11; } else if (std::strcmp(argv[i], "--std=c++03") == 0) { _settings->standards.cpp = Standards::CPP03; } else if (std::strcmp(argv[i], "--std=c++11") == 0) { _settings->standards.cpp = Standards::CPP11; } // Output formatter else if (std::strcmp(argv[i], "--template") == 0 || std::strncmp(argv[i], "--template=", 11) == 0) { // "--template path/" if (argv[i][10] == '=') _settings->outputFormat = argv[i] + 11; else if ((i+1) < argc && argv[i+1][0] != '-') { ++i; _settings->outputFormat = argv[i]; } else { PrintMessage("cppcheck: argument to '--template' is missing."); return false; } if (_settings->outputFormat == "gcc") _settings->outputFormat = "{file}:{line}: {severity}: {message}"; else if (_settings->outputFormat == "vs") _settings->outputFormat = "{file}({line}): {severity}: {message}"; else if (_settings->outputFormat == "edit") _settings->outputFormat = "{file} +{line}: {severity}: {message}"; } // Checking threads else if (std::strncmp(argv[i], "-j", 2) == 0) { std::string numberString; // "-j 3" if (std::strcmp(argv[i], "-j") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-j' is missing."); return false; } numberString = argv[i]; } // "-j3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->jobs)) { PrintMessage("cppcheck: argument to '-j' is not a number."); return false; } if (_settings->jobs > 10000) { // This limit is here just to catch typos. If someone has // need for more jobs, this value should be increased. PrintMessage("cppcheck: argument for '-j' is allowed to be 10000 at max."); return false; } } else if (std::strncmp(argv[i], "-l", 2) == 0) { std::string numberString; // "-l 3" if (std::strcmp(argv[i], "-l") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-l' is missing."); return false; } numberString = argv[i]; } // "-l3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->loadAverage)) { PrintMessage("cppcheck: argument to '-l' is not a number."); return false; } } // print all possible error messages.. else if (std::strcmp(argv[i], "--errorlist") == 0) { _showErrorMessages = true; _settings->xml = true; _exitAfterPrint = true; } // documentation.. else if (std::strcmp(argv[i], "--doc") == 0) { std::ostringstream doc; // Get documentation.. for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { const std::string& name((*it)->name()); const std::string info((*it)->classInfo()); if (!name.empty() && !info.empty()) doc << "## " << name << " ##\n" << info << "\n"; } std::cout << doc.str(); _exitAfterPrint = true; return true; } // show timing information.. else if (std::strncmp(argv[i], "--showtime=", 11) == 0) { const std::string showtimeMode = argv[i] + 11; if (showtimeMode == "file") _settings->showtime = SHOWTIME_FILE; else if (showtimeMode == "summary") _settings->showtime = SHOWTIME_SUMMARY; else if (showtimeMode == "top5") _settings->showtime = SHOWTIME_TOP5; else if (showtimeMode.empty()) _settings->showtime = SHOWTIME_NONE; else { std::string message("cppcheck: error: unrecognized showtime mode: \""); message += showtimeMode; message += "\". Supported modes: file, summary, top5."; PrintMessage(message); return false; } } #ifdef HAVE_RULES // Rule given at command line else if (std::strncmp(argv[i], "--rule=", 7) == 0) { Settings::Rule rule; rule.pattern = 7 + argv[i]; _settings->rules.push_back(rule); } // Rule file else if (std::strncmp(argv[i], "--rule-file=", 12) == 0) { tinyxml2::XMLDocument doc; if (doc.LoadFile(12+argv[i]) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement *node = doc.FirstChildElement(); for (; node && strcmp(node->Value(), "rule") == 0; node = node->NextSiblingElement()) { Settings::Rule rule; tinyxml2::XMLElement *tokenlist = node->FirstChildElement("tokenlist"); if (tokenlist) rule.tokenlist = tokenlist->GetText(); tinyxml2::XMLElement *pattern = node->FirstChildElement("pattern"); if (pattern) { rule.pattern = pattern->GetText(); } tinyxml2::XMLElement *message = node->FirstChildElement("message"); if (message) { tinyxml2::XMLElement *severity = message->FirstChildElement("severity"); if (severity) rule.severity = Severity::fromString(severity->GetText()); tinyxml2::XMLElement *id = message->FirstChildElement("id"); if (id) rule.id = id->GetText(); tinyxml2::XMLElement *summary = message->FirstChildElement("summary"); if (summary) rule.summary = summary->GetText() ? summary->GetText() : ""; } if (!rule.pattern.empty()) _settings->rules.push_back(rule); } } } #endif // Specify platform else if (std::strncmp(argv[i], "--platform=", 11) == 0) { std::string platform(11+argv[i]); if (platform == "win32A") _settings->platform(Settings::Win32A); else if (platform == "win32W") _settings->platform(Settings::Win32W); else if (platform == "win64") _settings->platform(Settings::Win64); else if (platform == "unix32") _settings->platform(Settings::Unix32); else if (platform == "unix64") _settings->platform(Settings::Unix64); else if (platform == "native") _settings->platform(Settings::Unspecified); else if (!_settings->platformFile(platform)) { std::string message("cppcheck: error: unrecognized platform: \""); message += platform; message += "\"."; PrintMessage(message); return false; } } // Set maximum number of #ifdef configurations to check else if (std::strncmp(argv[i], "--max-configs=", 14) == 0) { _settings->force = false; std::istringstream iss(14+argv[i]); if (!(iss >> _settings->maxConfigs)) { PrintMessage("cppcheck: argument to '--max-configs=' is not a number."); return false; } if (_settings->maxConfigs < 1) { PrintMessage("cppcheck: argument to '--max-configs=' must be greater than 0."); return false; } maxconfigs = true; } // Print help else if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) { _pathnames.clear(); _showHelp = true; _exitAfterPrint = true; break; } else { std::string message("cppcheck: error: unrecognized command line option: \""); message += argv[i]; message += "\"."; PrintMessage(message); return false; } } else { std::string path = Path::removeQuotationMarks(argv[i]); path = Path::fromNativeSeparators(path); _pathnames.push_back(path); } } if (_settings->force) _settings->maxConfigs = ~0U; else if ((def || _settings->preprocessOnly) && !maxconfigs) _settings->maxConfigs = 1U; if (_settings->isEnabled("unusedFunction") && _settings->jobs > 1) { PrintMessage("cppcheck: unusedFunction check can't be used with '-j' option. Disabling unusedFunction check."); } if (_settings->inconclusive && _settings->xml && _settings->xml_version == 1U) { PrintMessage("cppcheck: inconclusive messages will not be shown, because the old xml format is not compatible. It's recommended to use the new xml format (use --xml-version=2)."); } if (argc <= 1) { _showHelp = true; _exitAfterPrint = true; } if (_showHelp) { PrintHelp(); return true; } // Print error only if we have "real" command and expect files if (!_exitAfterPrint && _pathnames.empty()) { PrintMessage("cppcheck: No C or C++ source files found."); return false; } // Use paths _pathnames if no base paths for relative path output are given if (_settings->basePaths.empty() && _settings->relativePaths) _settings->basePaths = _pathnames; return true; } void CmdLineParser::PrintHelp() { std::cout << "Cppcheck - A tool for static C/C++ code analysis\n" "\n" "Syntax:\n" " cppcheck [OPTIONS] [files or paths]\n" "\n" "If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n" "*.tpp, and *.txx files are checked recursively from the given directory.\n\n" "Options:\n" " --append=<file> This allows you to provide information about functions\n" " by providing an implementation for them.\n" " --check-config Check cppcheck configuration. The normal code\n" " analysis is disabled by this flag.\n" " --check-library Show information messages when library files have\n" " incomplete info.\n" " --config-exclude=<dir>\n" " Path (prefix) to be excluded from configuration\n" " checking. Preprocessor configurations defined in\n" " headers (but not sources) matching the prefix will not\n" " be considered for evaluation.\n" " --config-excludes-file=<file>\n" " A file that contains a list of config-excludes\n" " --dump Dump xml data for each translation unit. The dump\n" " files have the extension .dump and contain ast,\n" " tokenlist, symboldatabase, valueflow.\n" " -D<ID> Define preprocessor symbol. Unless --max-configs or\n" " --force is used, Cppcheck will only check the given\n" " configuration when -D is used.\n" " Example: '-DDEBUG=1 -D__cplusplus'.\n" " -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n" " hide certain #ifdef <ID> code paths from checking.\n" " Example: '-UDEBUG'\n" " -E Print preprocessor output on stdout and don't do any\n" " further processing.\n" " --enable=<id> Enable additional checks. The available ids are:\n" " * all\n" " Enable all checks. It is recommended to only\n" " use --enable=all when the whole program is\n" " scanned, because this enables unusedFunction.\n" " * warning\n" " Enable warning messages\n" " * style\n" " Enable all coding style checks. All messages\n" " with the severities 'style', 'performance' and\n" " 'portability' are enabled.\n" " * performance\n" " Enable performance messages\n" " * portability\n" " Enable portability messages\n" " * information\n" " Enable information messages\n" " * unusedFunction\n" " Check for unused functions. It is recommend\n" " to only enable this when the whole program is\n" " scanned.\n" " * missingInclude\n" " Warn if there are missing includes. For\n" " detailed information, use '--check-config'.\n" " Several ids can be given if you separate them with\n" " commas. See also --std\n" " --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n" " the default '0'. '" << EXIT_FAILURE << "' is returned\n" " if arguments are not valid or if no input files are\n" " provided. Note that your operating system can modify\n" " this value, e.g. '256' can become '0'.\n" " --errorlist Print a list of all the error messages in XML format.\n" " --exitcode-suppressions=<file>\n" " Used when certain messages should be displayed but\n" " should not cause a non-zero exitcode.\n" " --file-list=<file> Specify the files to check in a text file. Add one\n" " filename per line. When file is '-,' the file list will\n" " be read from standard input.\n" " -f, --force Force checking of all configurations in files. If used\n" " together with '--max-configs=', the last option is the\n" " one that is effective.\n" " -h, --help Print this help.\n" " -I <dir> Give path to search for include files. Give several -I\n" " parameters to give several paths. First given path is\n" " searched for contained header files first. If paths are\n" " relative to source files, this is not needed.\n" " --includes-file=<file>\n" " Specify directory paths to search for included header\n" " files in a text file. Add one include path per line.\n" " First given path is searched for contained header\n" " files first. If paths are relative to source files,\n" " this is not needed.\n" " --include=<file>\n" " Force inclusion of a file before the checked file. Can\n" " be used for example when checking the Linux kernel,\n" " where autoconf.h needs to be included for every file\n" " compiled. Works the same way as the GCC -include\n" " option.\n" " -i <dir or file> Give a source file or source file directory to exclude\n" " from the check. This applies only to source files so\n" " header files included by source files are not matched.\n" " Directory name is matched to all parts of the path.\n" " --inconclusive Allow that Cppcheck reports even though the analysis is\n" " inconclusive.\n" " There are false positives with this option. Each result\n" " must be carefully investigated before you know if it is\n" " good or bad.\n" " --inline-suppr Enable inline suppressions. Use them by placing one or\n" " more comments, like: '// cppcheck-suppress warningId'\n" " on the lines before the warning to suppress.\n" " -j <jobs> Start <jobs> threads to do the checking simultaneously.\n" #ifdef THREADING_MODEL_FORK " -l <load> Specifies that no new threads should be started if\n" " there are other threads running and the load average is\n" " at least <load>.\n" #endif " --language=<language>, -x <language>\n" " Forces cppcheck to check all files as the given\n" " language. Valid values are: c, c++\n" " --library=<cfg>\n" " Load file <cfg> that contains information about types\n" " and functions. With such information Cppcheck\n" " understands your your code better and therefore you\n" " get better results. The std.cfg file that is\n" " distributed with Cppcheck is loaded automatically.\n" " For more information about library files, read the\n" " manual.\n" " --max-configs=<limit>\n" " Maximum number of configurations to check in a file\n" " before skipping it. Default is '12'. If used together\n" " with '--force', the last option is the one that is\n" " effective.\n" " --platform=<type>, --platform=<file>\n" " Specifies platform specific types and sizes. The\n" " available builtin platforms are:\n" " * unix32\n" " 32 bit unix variant\n" " * unix64\n" " 64 bit unix variant\n" " * win32A\n" " 32 bit Windows ASCII character encoding\n" " * win32W\n" " 32 bit Windows UNICODE character encoding\n" " * win64\n" " 64 bit Windows\n" " * native\n" " Unspecified platform. Type sizes of host system\n" " are assumed, but no further assumptions.\n" " -q, --quiet Do not show progress reports.\n" " -rp, --relative-paths\n" " -rp=<paths>, --relative-paths=<paths>\n" " Use relative paths in output. When given, <paths> are\n" " used as base. You can separate multiple paths by ';'.\n" " Otherwise path where source files are searched is used.\n" " We use string comparison to create relative paths, so\n" " using e.g. ~ for home folder does not work. It is\n" " currently only possible to apply the base paths to\n" " files that are on a lower level in the directory tree.\n" " --report-progress Report progress messages while checking a file.\n" #ifdef HAVE_RULES " --rule=<rule> Match regular expression.\n" " --rule-file=<file> Use given rule file. For more information, see: \n" " http://sourceforge.net/projects/cppcheck/files/Articles/\n" #endif " --std=<id> Set standard.\n" " The available options are:\n" " * posix\n" " POSIX compatible code\n" " * c89\n" " C code is C89 compatible\n" " * c99\n" " C code is C99 compatible\n" " * c11\n" " C code is C11 compatible (default)\n" " * c++03\n" " C++ code is C++03 compatible\n" " * c++11\n" " C++ code is C++11 compatible (default)\n" " More than one --std can be used:\n" " 'cppcheck --std=c99 --std=posix file.c'\n" " --suppress=<spec> Suppress warnings that match <spec>. The format of\n" " <spec> is:\n" " [error id]:[filename]:[line]\n" " The [filename] and [line] are optional. If [error id]\n" " is a wildcard '*', all error ids match.\n" " --suppressions-list=<file>\n" " Suppress warnings listed in the file. Each suppression\n" " is in the same format as <spec> above.\n" " --template='<text>' Format the error messages. E.g.\n" " '{file}:{line},{severity},{id},{message}' or\n" " '{file}({line}):({severity}) {message}' or\n" " '{callstack} {message}'\n" " Pre-defined templates: gcc, vs, edit.\n" " -v, --verbose Output more detailed error information.\n" " --version Print out version number.\n" " --xml Write results in xml format to error stream (stderr).\n" " --xml-version=<version>\n" " Select the XML file version. Currently versions 1 and\n" " 2 are available. The default version is 1." "\n" "Example usage:\n" " # Recursively check the current folder. Print the progress on the screen and\n" " # write errors to a file:\n" " cppcheck . 2> err.txt\n" "\n" " # Recursively check ../myproject/ and don't print progress:\n" " cppcheck --quiet ../myproject/\n" "\n" " # Check test.cpp, enable all checks:\n" " cppcheck --enable=all --inconclusive --std=posix test.cpp\n" "\n" " # Check f.cpp and search include files from inc1/ and inc2/:\n" " cppcheck -I inc1/ -I inc2/ f.cpp\n" "\n" "For more information:\n" " http://cppcheck.net/manual.pdf\n"; }
Nicobubu/cppcheck
cli/cmdlineparser.cpp
C++
gpl-3.0
46,169
### Relevant Articles: - [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode)
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/apache-geode/README.md
Markdown
gpl-3.0
98
/* dx2vtk: OpenDX to VTK file format converter * Copyright (C) 2015 David J. Warne * * 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/>. */ /** * @file vtkFileWriter.h * @brief Writes a vtk data file using the legacy format * * @details This library implements a light weight legacy vtk * format writer. This is intended to be used as a part of the * dx2vtk program. * * @author David J. Warne ([email protected]) * @author High Performance Computing and Research Support * @author Queensland University of Technology * */ #ifndef __VTKFILEWRITER_H #define __VTKFILEWRITER_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <endian.h> /*data types*/ #define VTK_ASCII 0 #define VTK_BINARY 1 #define H2BE32(buf,size) \ { \ int iii; \ uint32_t * buf32; \ buf32 = (uint32_t *)(buf); \ for(iii=0;iii<(size);iii++) \ { \ buf32[iii] = htobe32(buf32[iii]); \ } \ } \ #define BE2H32(buf,size) \ { \ int iii; \ uint32_t * buf32; \ buf32 = (uint32_t *)(buf); \ for(iii=0;iii<(size);iii++) \ { \ buf32[iii] = be32toh(buf32[iii]); \ } \ } \ /*geometry*/ #define VTK_STRUCTURED_POINTS 0 #define VTK_STRUCTURED_GRID 1 #define VTK_UNSTRUCTURED_GRID 2 #define VTK_POLYDATA 3 #define VTK_RECTILINEAR_GRID 4 #define VTK_FIELD 5 #define VTK_VERTEX 1 #define VTK_POLY_VERTEX 2 #define VTK_LINE 3 #define VTK_POLY_LINE 4 #define VTK_TRIANGLE 5 #define VTK_TRIANGLE_STRIP 6 #define VTK_POLYGON 7 #define VTK_PIXEL 8 #define VTK_QUAD 9 #define VTK_TETRA 10 #define VTK_VOXEL 11 #define VTK_HEXAHEDRON 12 #define VTK_WEDGE 13 #define VTK_PYRAMID 14 #define VTK_QUADRATIC_EDGE 21 #define VTK_QUADRATIC_TRIANGLE 22 #define VTK_QUADRATIC_QUAD 23 #define VTK_QUADRATIC_TETRA 24 #define VTK_QUADRATIC_HEXAHEDRON 25 #define VTK_VERSION "4.2" #define VTK_TITLE_LENGTH 256 #define VTK_DIM 3 #define VTK_INT 0 #define VTK_FLOAT 1 #define VTK_SUCCESS 1 #define VTK_MEMORY_ERROR 0 #define VTK_FILE_NOT_FOUND_ERROR -1 #define VTK_INVALID_FILE_ERROR -2 #define VTK_NOT_SUPPORTED_ERROR -3 #define VTK_INVALID_USAGE_ERROR -4 #define VTK_NOT_IMPLEMENTED_YET_ERROR -5 #define VTK_FILE_ERROR -6 #ifndef VTK_TYPE_DEFAULT #define VTK_TYPE_DEFAULT VTK_ASCII #endif typedef struct vtkDataFile_struct vtkDataFile; typedef struct unstructuredGrid_struct unstructuredGrid; typedef struct structuredPoints_struct structuredPoints; typedef struct polydata_struct polydata; typedef struct vtkData_struct vtkData; typedef struct scalar_struct scalar; typedef struct vector_struct vector; struct scalar_struct { char name[32]; int type; void * data; }; struct vector_struct { char name[32]; int type; void *data; }; struct vtkData_struct { int numScalars; int numColorScalars; int numLookupTables; int numVectors; int numNormals; int numTextureCoords; int numTensors; int numFields; int size; /** @todo for now only support scalars and vectors */ scalar *scalar_data; vector *vector_data; }; struct vtkDataFile_struct { FILE *fp; char vtkVersion[4]; /*header version*/ char title[VTK_TITLE_LENGTH]; /**/ unsigned char dataType; unsigned char geometry; void * dataset; vtkData * pointdata; vtkData * celldata; }; struct structuredPoints_struct { int dimensions[VTK_DIM]; float origin[VTK_DIM]; float spacing[VTK_DIM]; }; struct structuredGrid_struct { int dimensions[VTK_DIM]; int numPoints; float *points; // numpoints*3; }; struct polydata_struct{ int numPoints; float * points; int numPolygons; int *numVerts; int *polygons; }; struct rectilinearGrid_struct{ int dimensions[VTK_DIM]; int numX; int numY; int numZ; float *X_coordinates; float *Y_coordinates; float *Z_coordinates; }; struct unstructuredGrid_struct{ int numPoints; float * points; int numCells; int cellSize; int *cells; int *numVerts; int *cellTypes; }; /*function prototypes */ int VTK_Open(vtkDataFile *file, char * filename); int VTK_Write(vtkDataFile *file); int VTK_WriteUnstructuredGrid(FILE *fp,unstructuredGrid *ug,char type); int VTK_WritePolydata(FILE *fp,polydata *pd,char type); int VTK_WriteStructuredPoints(FILE *fp,structuredPoints *sp,char type); int VTK_WriteData(FILE *fp,vtkData *data,char type); int VTK_Close(vtkDataFile*file); #endif
davidwarne/dx2vtk
vtkFileWriter.h
C
gpl-3.0
5,534
/* * Copyright (C) ST-Ericsson SA 2010 * * License Terms: GNU General Public License v2 * Author: Naveen Kumar Gaddipati <[email protected]> * * ux500 Scroll key and Keypad Encoder (SKE) header */ #ifndef __SKE_H #define __SKE_H #include <linux/input/matrix_keypad.h> /* register definitions for SKE peripheral */ #define SKE_CR 0x00 #define SKE_VAL0 0x04 #define SKE_VAL1 0x08 #define SKE_DBCR 0x0C #define SKE_IMSC 0x10 #define SKE_RIS 0x14 #define SKE_MIS 0x18 #define SKE_ICR 0x1C /* * Keypad module */ /** * struct keypad_platform_data - structure for platform specific data * @init: pointer to keypad init function * @exit: pointer to keypad deinitialisation function * @keymap_data: matrix scan code table for keycodes * @krow: maximum number of rows * @kcol: maximum number of columns * @debounce_ms: platform specific debounce time * @no_autorepeat: flag for auto repetition * @wakeup_enable: allow waking up the system */ struct ske_keypad_platform_data { int (*init)(void); int (*exit)(void); const struct matrix_keymap_data *keymap_data; u8 krow; u8 kcol; u8 debounce_ms; bool no_autorepeat; bool wakeup_enable; }; #endif /*__SKE_KPD_H*/
williamfdevine/PrettyLinux
include/linux/platform_data/keypad-nomadik-ske.h
C
gpl-3.0
1,200
<?php /** * Created by PhpStorm. * User: Ermin Islamagić - https://ermin.islamagic.com * Date: 22.8.2016 * Time: 09:37 */ // Check if root path is defined if (!defined("ROOT_PATH")) { // Show 403 if root path not defined header("HTTP/1.1 403 Forbidden"); exit; } /** * Class LocaleAppController */ class LocaleAppController extends Plugin { /** * LocaleAppController constructor. */ public function __construct() { $this->setLayout('ActionAdmin'); } /** * @param $const * @return null */ public static function getConst($const) { $registry = Registry::getInstance(); $store = $registry->get('Locale'); return isset($store[$const]) ? $store[$const] : NULL; } /** * @return array */ public function ActionCheckInstall() { $this->setLayout('ActionEmpty'); $result = array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded', 'info' => array()); $folders = array(UPLOAD_PATH . 'locale'); foreach ($folders as $dir) { if (!is_writable($dir)) { $result['status'] = 'ERR'; $result['code'] = 101; $result['text'] = 'Permission requirement'; $result['info'][] = sprintf('Folder \'<span class="bold">%1$s</span>\' is not writable. You need to set write permissions (chmod 777) to directory located at \'<span class="bold">%1$s</span>\'', $dir); } } return $result; } }
clientmarketing/food-factory
source/app/plugins/Locale/controllers/LocaleAppController.controller.php
PHP
gpl-3.0
1,402
// // MSGRTickConnection.h // wehuibao // // Created by Ke Zeng on 13-6-20. // Copyright (c) 2013年 Zeng Ke. All rights reserved. // #import <Foundation/Foundation.h> typedef enum { MSGRTickConnectionStateNotConnected=0, MSGRTickConnectionStateConnecting, MSGRTickConnectionStateConnected, MSGRTickConnectionStateClosed, MSGRTickConnectionStateError } MSGRTickConnectionState; @class MSGRTickConnection; @protocol MSGRTickConnectionDelegate <NSObject> @optional - (void)connectionLost:(MSGRTickConnection *)connection; - (void)connection:(MSGRTickConnection *)connection error:(NSError *)error; @required - (void)connectionEstablished:(MSGRTickConnection *)connection; - (void)connection:(MSGRTickConnection *)connection receivedPacket:(id)packet withDirective:(NSString *)directive; @end @interface MSGRTickConnection: NSObject<NSStreamDelegate> @property (nonatomic) MSGRTickConnectionState state; @property (nonatomic) BOOL loginOK; @property (nonatomic, weak) id<MSGRTickConnectionDelegate> delegate; - (void)connect; - (void)close; - (void)sendPacket:(id)packet directive:(NSString *)directive; @end
superisaac/msgr
iOS/MSGR/MSGRTickConnection.h
C
gpl-3.0
1,139
/*************************************************************************** begin : Thu Apr 24 15:54:58 CEST 2003 copyright : (C) 2003 by Giuseppe Lipari email : [email protected] ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <algorithm> #include <string> #include <simul.hpp> #include <server.hpp> #include <jtrace.hpp> #include <task.hpp> #include <task.hpp> #include <waitinstr.hpp> namespace RTSim { using namespace std; using namespace MetaSim; // Init globals JavaTrace::TRACE_ENDIANESS JavaTrace::endianess = TRACE_UNKNOWN_ENDIAN; string JavaTrace::version = "1.2"; JavaTrace::JavaTrace(const char *name, bool tof, unsigned long int limit) :Trace(name, Trace::BINARY, tof), taskList(10) { if (endianess == TRACE_UNKNOWN_ENDIAN) probeEndianess(); const char cver[] = "version 1.2"; if (toFile) _os.write(cver, sizeof(cver)); filenum = 0; fileLimit = limit; } JavaTrace::~JavaTrace() { // WARNING: the data vector is cleared but its content isn't. It // must be deleted manually (close). if (toFile) Trace::close(); else data.clear(); } void JavaTrace::probeEndianess(void) { // Used for endianess check (Big/Little!) static char const big_endian[] = { static_cast<char const>(0xff), static_cast<char const>(0), static_cast<char const>(0xff), static_cast<char const>(0)}; static int const probe = 0xff00ff00; int *probePtr = (int *)(big_endian); if (*probePtr == probe) endianess = TRACE_BIG_ENDIAN; else endianess = TRACE_LITTLE_ENDIAN; //DBGFORCE("Endianess: " << (endianess == TRACE_LITTLE_ENDIAN ? "Little\n" : "Big\n")); } void JavaTrace::close() { if (toFile) Trace::close(); else { for (unsigned int i = 0; i < data.size(); i++) delete data[i]; data.clear(); } } void JavaTrace::record(Event* e) { DBGENTER(_JTRACE_DBG_LEV); TaskEvt* ee = dynamic_cast<TaskEvt*>(e); if (ee == NULL) { DBGPRINT("The event is not a TaskEvt"); return; } Task* task = ee->getTask(); if (task != NULL) { vector<int>::const_iterator p = find(taskList.begin(), taskList.end(), task->getID()); if (p == taskList.end()) { TraceNameEvent* a = new TraceNameEvent(ee->getLastTime(), task->getID(), task->getName()); if (toFile) a->write(_os); else data.push_back(a); taskList.push_back(task->getID()); } } // at this point we have to see what kind of event it is... if (dynamic_cast<ArrEvt*>(e) != NULL) { DBGPRINT("ArrEvt"); ArrEvt* tae = dynamic_cast<ArrEvt*>(e); TraceArrEvent* a = new TraceArrEvent(e->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); Task* rttask = dynamic_cast<Task*>(task); if (rttask) { TraceDlineSetEvent* b = new TraceDlineSetEvent(tae->getLastTime(), rttask->getID(), rttask->getDeadline()); if (toFile) b->write(_os); else data.push_back(b); } } else if (dynamic_cast<EndEvt*>(e) != NULL) { DBGPRINT("EndEvt"); EndEvt* tee = dynamic_cast<EndEvt*>(e); TraceEndEvent* a = new TraceEndEvent(tee->getLastTime(), task->getID(), tee->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<DeschedEvt*>(e) != NULL) { DBGPRINT("DeschedEvt"); DeschedEvt *tde = dynamic_cast<DeschedEvt *>(e); TraceDeschedEvent* a = new TraceDeschedEvent(tde->getLastTime(), task->getID(), tde->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<WaitEvt*>(e) != NULL) { DBGPRINT("WaitEvt"); WaitEvt* we = dynamic_cast<WaitEvt*>(e); //WaitInstr* instr = dynamic_cast<WaitInstr*>(we->getInstr()); WaitInstr* instr = we->getInstr(); string res = instr->getResource(); TraceWaitEvent* a = new TraceWaitEvent(we->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SignalEvt*>(e) != NULL) { DBGPRINT("SignalEvt"); SignalEvt* se = dynamic_cast<SignalEvt*>(e); //SignalInstr* instr = dynamic_cast<SignalInstr*>(se->getInstr()); SignalInstr* instr = se->getInstr(); string res = instr->getResource(); TraceSignalEvent* a = new TraceSignalEvent(se->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SchedEvt*>(e) != NULL) { DBGPRINT("SchedEvt"); SchedEvt* tse = dynamic_cast<SchedEvt*>(e); TraceSchedEvent* a = new TraceSchedEvent(tse->getLastTime(), task->getID(), tse->getCPU()); if (toFile) a->write(_os); else data.push_back(a); // } else if (dynamic_cast<DlinePostEvt*>(e) != NULL) { // DBGPRINT("DlinePostEvt"); // DlinePostEvt* dpe = dynamic_cast<DlinePostEvt*>(e); // TraceDlinePostEvent* a = new TraceDlinePostEvent(dpe->getLastTime(), // task->getID(), // dpe->getPrevDline(), // dpe->getPostDline()); // if (toFile) a->write(_os); // else data.push_back(a); } else if (dynamic_cast<DeadEvt*>(e) != NULL) { DBGPRINT("DlineMissEvt"); DeadEvt* de = dynamic_cast<DeadEvt*>(e); TraceDlineMissEvent* a = new TraceDlineMissEvent(de->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); } if (toFile) _os.flush(); } }
glipari/rtlib
src/jtrace.cpp
C++
gpl-3.0
6,330
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required def centres(request): #Python练习项目管理中心Center return render(request, 'centres/centres.html') def upload(request): #文件上传 return render(request, 'centres/upload.html') def uploadfile(request): import os if request.method == "POST": # 请求方法为POST时,进行处理 myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None if not myFile: #return HttpResponse("no files for upload!") return render(request, 'centres/upload.html',{'what':'no file for upload!'}) upfile = open(os.path.join("D:\\xHome\\data\\upload",myFile.name),'wb+') # 打开特定的文件进行二进制的写操作 for chunk in myFile.chunks(): # 分块写入文件 upfile.write(chunk) upfile.close() #return HttpResponse("upload over!") return render(request, 'centres/upload.html', {'what':'upload over!'})
xBoye/xHome
centres/views.py
Python
gpl-3.0
1,162
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>Super Martin: Globals</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Super Martin </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="globals.html#index_a"><span>a</span></a></li> <li><a href="globals_b.html#index_b"><span>b</span></a></li> <li><a href="globals_c.html#index_c"><span>c</span></a></li> <li><a href="globals_d.html#index_d"><span>d</span></a></li> <li><a href="globals_e.html#index_e"><span>e</span></a></li> <li><a href="globals_f.html#index_f"><span>f</span></a></li> <li><a href="globals_g.html#index_g"><span>g</span></a></li> <li><a href="globals_i.html#index_i"><span>i</span></a></li> <li><a href="globals_j.html#index_j"><span>j</span></a></li> <li><a href="globals_k.html#index_k"><span>k</span></a></li> <li><a href="globals_l.html#index_l"><span>l</span></a></li> <li><a href="globals_m.html#index_m"><span>m</span></a></li> <li><a href="globals_n.html#index_n"><span>n</span></a></li> <li class="current"><a href="globals_o.html#index_o"><span>o</span></a></li> <li><a href="globals_p.html#index_p"><span>p</span></a></li> <li><a href="globals_r.html#index_r"><span>r</span></a></li> <li><a href="globals_s.html#index_s"><span>s</span></a></li> <li><a href="globals_t.html#index_t"><span>t</span></a></li> <li><a href="globals_u.html#index_u"><span>u</span></a></li> <li><a href="globals_w.html#index_w"><span>w</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Macros</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:</div> <h3><a class="anchor" id="index_o"></a>- o -</h3><ul> <li>openFile() : <a class="el" href="file_8c.html#ab763060cbdd57fdb704871d896fc492a">file.c</a> , <a class="el" href="file_8h.html#a279d2082dd2ddcdbbce81da176f135b4">file.h</a> </li> <li>openLevel() : <a class="el" href="file__level_8h.html#a05b04a7e24539a2ae826cfb87ea4d859">file_level.h</a> , <a class="el" href="file__level_8c.html#a8464887031ce16d797b564fc7a9e661f">file_level.c</a> </li> <li>optionMenu() : <a class="el" href="menu__option_8c.html#a6f370e66ea56a5fdf95dfa2abfac5baa">menu_option.c</a> , <a class="el" href="menu__option_8h.html#a6f370e66ea56a5fdf95dfa2abfac5baa">menu_option.h</a> </li> <li>outOfList() : <a class="el" href="enemies_8h.html#a7774be61944dce2ae021e0e4442b4515">enemies.h</a> , <a class="el" href="enemies_8c.html#a7774be61944dce2ae021e0e4442b4515">enemies.c</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 2 2014 17:19:18 for Super Martin by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
Dalan94/Super_Martin
Super_Martin/doc/html/globals_o.html
HTML
gpl-3.0
7,049
import cv2 import numpy as np np.set_printoptions(threshold=np.nan) import util as util import edge_detect import lineseg import drawedgelist # img = cv2.imread("img/Slide2.jpg", 0) img = cv2.imread("unsorted/Unit Tests/lambda.png", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow("newcanny", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) res.append(current) # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, "res") """ for x in range(len(res)): for y in range(lan ): """ drawedgelist.drawedgelist(res, img) """ seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """ #print(seglist, "seglist") #print(len(seglist), "seglist len") #print(seglist.shape, "seglistshape") #drawedgelist.drawedgelist(seglist) """ # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size) #print(Line_new, "line new") print(len(Line_new), "len line new") util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)"""
Jordan-Zhu/RoboVision
scratch/testingColorImg.py
Python
gpl-3.0
2,023
"use strict"; module.exports = function registerDefaultRoutes( baseUrl, app, opts ){ var controller = opts.controller; var listRouter = app.route( baseUrl ); if( opts.all ){ listRouter = listRouter.all( opts.all ); } if( opts.list ){ listRouter.get( opts.list ); } if( opts.create ){ listRouter.post( opts.create ); } listRouter.get( controller.list ) .post( controller.create ); var resourceRouter = app.route( baseUrl + "/:_id" ); if( opts.all ){ resourceRouter.all( opts.all ); } if( opts.retrieve ){ resourceRouter.get(opts.retrieve); } if(opts.update){ resourceRouter.patch(opts.update); } if(opts.remove){ resourceRouter.delete(opts.remove); } resourceRouter.get( controller.retrieve ) .patch( controller.update ) .delete( controller.remove ); return { list: listRouter, resources: resourceRouter }; };
beni55/d-pac.cms
app/routes/api/helpers/registerDefaultRoutes.js
JavaScript
gpl-3.0
999
package it.ads.activitiesmanager.model.dao; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; //Segnala che si tratta di una classe DAO (o Repository) @Repository //Significa che tutti i metodi della classe sono definiti come @Transactional @Transactional public abstract class AbstractDao<T extends Serializable> { private Class<T> c; @PersistenceContext EntityManager em; public final void setClass(Class<T> c){ this.c = c; } public T find(Integer id) { return em.find(c,id); } public List<T> findAll(){ String SELECT = "SELECT * FROM " + c.getName(); Query query = em.createQuery(SELECT); return query.getResultList(); } public void save(T entity){ em.persist(entity); } public void update(T entity){ em.merge(entity); } public void delete(T entity){ em.remove(entity); } public void deleteById(Integer id){ T entity = find(id); delete(entity); } }
paoloap/activitiesmanager
activitiesmanager-model/src/main/java/it/ads/activitiesmanager/model/dao/AbstractDao.java
Java
gpl-3.0
1,147
----------------------------------- -- Area: Windurst Woods -- NPC: Amimi -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(10004,price,gil,level); else player:startEvent(10007); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 10004 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(dsp.effects.MOUNTED,dsp.effects.MOUNTED,0,0,duration,true); else player:addStatusEffectEx(dsp.effects.MOUNTED,dsp.effects.MOUNTED,0,0,900,true); end player:setPos(-122,-4,-520,0,0x74); end end end;
Cloudef/darkstar
scripts/zones/Windurst_Woods/npcs/Amimi.lua
Lua
gpl-3.0
1,661
#include "VRConstructionKit.h" #include "selection/VRSelector.h" #include "core/objects/geometry/VRGeometry.h" #include "core/objects/material/VRMaterial.h" #include "core/utils/toString.h" #include "core/utils/VRFunction.h" #include "core/setup/devices/VRDevice.h" #include "core/setup/devices/VRSignal.h" using namespace OSG; VRConstructionKit::VRConstructionKit() { snapping = VRSnappingEngine::create(); selector = VRSelector::create(); onSnap = VRSnappingEngine::VRSnapCb::create("on_snap_callback", bind(&VRConstructionKit::on_snap, this, placeholders::_1)); snapping->getSignalSnap()->add(onSnap); } VRConstructionKit::~VRConstructionKit() {} VRConstructionKitPtr VRConstructionKit::create() { return VRConstructionKitPtr(new VRConstructionKit()); } void VRConstructionKit::clear() { objects.clear(); selector->clear(); snapping->clear(); } VRSnappingEnginePtr VRConstructionKit::getSnappingEngine() { return snapping; } VRSelectorPtr VRConstructionKit::getSelector() { return selector; } vector<VRObjectPtr> VRConstructionKit::getObjects() { vector<VRObjectPtr> res; for (auto m : objects) res.push_back(m.second); return res; } bool VRConstructionKit::on_snap(VRSnappingEngine::EventSnapWeakPtr we) { if (!doConstruction) return true; auto e = we.lock(); if (!e) return true; if (!e->snap) { breakup(e->o1); return true; } if (!e->o1 || !e->o2) return true; VRObjectPtr p1 = e->o1->getDragParent(); VRObjectPtr p2 = e->o2->getParent(); if (p1 == 0 || p2 == 0) return true; if (p1 == p2) if (p1->hasTag("kit_group")) return true; if (p2->hasTag("kit_group")) { e->o1->rebaseDrag(p2); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); return true; } VRTransformPtr group = VRTransform::create("kit_group"); group->setPersistency(0); group->setPickable(true); group->addAttachment("kit_group", 0); p2->addChild(group); e->o1->rebaseDrag(group); Matrix4d m = e->o2->getWorldMatrix(); e->o2->switchParent(group); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); e->o2->setWorldMatrix(m); return true; } int VRConstructionKit::ID() { static int i = 0; i++; return i; } void VRConstructionKit::breakup(VRTransformPtr obj) { if (!doConstruction) return; if (obj == 0) return; auto p = obj->getParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->switchParent( p->getParent() ); obj->setPickable(true); return; } p = obj->getDragParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->rebaseDrag( p->getParent() ); obj->setPickable(true); } } int VRConstructionKit::addAnchorType(float size, Color3f color) { auto g = VRGeometry::create("anchor"); string bs = toString(size); g->setPrimitive("Box " + bs + " " + bs + " " + bs + " 1 1 1"); auto m = VRMaterial::create("anchor"); m->setDiffuse(color); g->setMaterial(m); int id = ID(); anchors[id] = g; return id; } void VRConstructionKit::toggleConstruction(bool active) { doConstruction = active; } void VRConstructionKit::addObject(VRTransformPtr t) { objects[t.get()] = t; snapping->addObject(t); } void VRConstructionKit::remObject(VRTransformPtr t) { objects.erase(t.get()); snapping->remObject(t); } VRGeometryPtr VRConstructionKit::addObjectAnchor(VRTransformPtr t, int a, Vec3d pos, float radius) { if (!anchors.count(a)) return 0; Vec3d d(0,1,0); Vec3d u(1,0,0); VRGeometryPtr anc = static_pointer_cast<VRGeometry>(anchors[a]->duplicate()); anc->setTransform(pos, d, u); anc->show(); anc->switchParent(t); snapping->addObjectAnchor(t, anc); snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), d, u), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), Vec3d(1,0,0), Vec3d(0,1,0)), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(), radius, 0, t ); return anc; }
Victor-Haefner/polyvr
src/core/tools/VRConstructionKit.cpp
C++
gpl-3.0
4,295
## A Vim plugin offers Nginx/Openresty syntax highlight and directives completion ![example](./example.png) This little plugin offers: 1. syntax highlight for Nginx configuration, with addition OpenResty enhancement. 1. syntax highlight for LuaJIT source file, with adddition OpenResty API highlight. 1. syntax-based directives completion. #### Support version This plugin supports OpenResty v1.21.4. #### How to use First of all, install this plugin with your favorite plugin manager. The syntax highlight is enabled once your file is detected as Nginx configuration. If Vim doesn't recognize the file type, you could add this to your `.vimrc`: ``` autocmd BufRead,BufNewFile pattern_matched_your_file(s) set filetype=nginx ``` For example, `autocmd BufRead,BufNewFile nginx_*.conf.tpl set filetype=nginx`. To complete the directives, type part of the word and then type `Ctrl+x Ctrl+o` to trigger it. If you are using [YouCompleteMe](https://github.com/Valloric/YouCompleteMe), set `let g:ycm_seed_identifiers_with_syntax = 1` in your `.vimrc`. #### Known issue There is a limit to render Lua snippet inside `_by_lua_block` directives. You need to close the block with `}` in separate line, and `}` should have the same indent with the `{`. It is a hack to distinguish from `}` of the inner Lua snippet. Anyway, if your configuration is in good format, the highlight should work smoothly.
spacewander/openresty-vim
README.md
Markdown
gpl-3.0
1,403
/* _ /_\ _ _ ___ ___ / _ \| '_/ -_|_-< /_/ \_\_| \___/__/ */ #include "Ares.h" /* Description: Function that is called when the library is loaded, use this as an entry point. */ int __attribute__((constructor)) Ares() { SDL2::SetupSwapWindow(); return 0; }
gitaphu/Ares
Source/Ares.cpp
C++
gpl-3.0
277
#!/usr/bin/env python # setup of the grid parameters # default queue used for training training_queue = { 'queue':'q1dm', 'memfree':'16G', 'pe_opt':'pe_mth 2', 'hvmem':'8G', 'io_big':True } # the queue that is used solely for the final ISV training step isv_training_queue = { 'queue':'q1wm', 'memfree':'32G', 'pe_opt':'pe_mth 4', 'hvmem':'8G' } # number of audio files that one job should preprocess number_of_audio_files_per_job = 1000 preprocessing_queue = {} # number of features that one job should extract number_of_features_per_job = 600 extraction_queue = { 'queue':'q1d', 'memfree':'8G' } # number of features that one job should project number_of_projections_per_job = 600 projection_queue = { 'queue':'q1d', 'hvmem':'8G', 'memfree':'8G' } # number of models that one job should enroll number_of_models_per_enrol_job = 20 enrol_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } # number of models that one score job should process number_of_models_per_score_job = 20 score_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } grid_type = 'local' # on Idiap grid
guker/spear
config/grid/para_training_local.py
Python
gpl-3.0
1,092
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Module: Ronin::Model::HasLicense::InstanceMethods &mdash; Ronin Documentation </title> <link rel="stylesheet" href="../../../css/style.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="../../../css/common.css" type="text/css" media="screen" charset="utf-8" /> <script type="text/javascript" charset="utf-8"> hasFrames = window.top.frames.main ? true : false; relpath = '../../../'; framesUrl = "../../../frames.html#!" + escape(window.location.href); </script> <script type="text/javascript" charset="utf-8" src="../../../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../../../js/app.js"></script> </head> <body> <div id="header"> <div id="menu"> <a href="../../../_index.html">Index (I)</a> &raquo; <span class='title'><span class='object_link'><a href="../../../Ronin.html" title="Ronin (module)">Ronin</a></span></span> &raquo; <span class='title'><span class='object_link'><a href="../../Model.html" title="Ronin::Model (module)">Model</a></span></span> &raquo; <span class='title'><span class='object_link'><a href="../HasLicense.html" title="Ronin::Model::HasLicense (module)">HasLicense</a></span></span> &raquo; <span class="title">InstanceMethods</span> <div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div> </div> <div id="search"> <a class="full_list_link" id="class_list_link" href="../../../class_list.html"> Class List </a> <a class="full_list_link" id="method_list_link" href="../../../method_list.html"> Method List </a> <a class="full_list_link" id="file_list_link" href="../../../file_list.html"> File List </a> </div> <div class="clear"></div> </div> <iframe id="search_frame"></iframe> <div id="content"><h1>Module: Ronin::Model::HasLicense::InstanceMethods </h1> <dl class="box"> <dt class="r1 last">Defined in:</dt> <dd class="r1 last">lib/ronin/model/has_license.rb</dd> </dl> <div class="clear"></div> <h2>Overview</h2><div class="docstring"> <div class="discussion"> <p>Instance methods that are added when <span class='object_link'><a href="../HasLicense.html" title="Ronin::Model::HasLicense (module)">Ronin::Model::HasLicense</a></span> is included into a model.</p> </div> </div> <div class="tags"> </div> <h2> Instance Method Summary <small>(<a href="#" class="summary_toggle">collapse</a>)</small> </h2> <ul class="summary"> <li class="public deprecated"> <span class="summary_signature"> <a href="#license%21-instance_method" title="#license! (instance method)">- (Object) <strong>license!</strong>(name) </a> </span> <span class="deprecated note title">deprecated</span> <span class="summary_desc"><strong>Deprecated.</strong> <div class='inline'><p><code>license!</code> was deprecated in favor of <span class='object_link'><a href="#licensed_under-instance_method" title="Ronin::Model::HasLicense::InstanceMethods#licensed_under (method)">#licensed_under</a></span>.</p> </div></span> </li> <li class="public "> <span class="summary_signature"> <a href="#licensed_under-instance_method" title="#licensed_under (instance method)">- (License) <strong>licensed_under</strong>(name) </a> </span> <span class="summary_desc"><div class='inline'><p>Sets the license of the model.</p> </div></span> </li> </ul> <div id="instance_method_details" class="method_details_list"> <h2>Instance Method Details</h2> <div class="method_details first"> <h3 class="signature first" id="license!-instance_method"> - (<tt>Object</tt>) <strong>license!</strong>(name) </h3><div class="docstring"> <div class="discussion"> <div class="note deprecated"><strong>Deprecated.</strong> <div class='inline'><p><code>license!</code> was deprecated in favor of <span class='object_link'><a href="#licensed_under-instance_method" title="Ronin::Model::HasLicense::InstanceMethods#licensed_under (method)">#licensed_under</a></span>.</p> </div></div> </div> </div> <div class="tags"> <p class="tag_title">Since:</p> <ul class="since"> <li> <div class='inline'><p>1.0.0</p> </div> </li> </ul> </div><table class="source_code"> <tr> <td> <pre class="lines"> 123 124 125</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/ronin/model/has_license.rb', line 123</span> <span class='kw'>def</span> <span class='id identifier rubyid_license!'>license!</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='id identifier rubyid_licensed_under'>licensed_under</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> <div class="method_details "> <h3 class="signature " id="licensed_under-instance_method"> - (<tt><span class='object_link'><a href="../../License.html" title="Ronin::License (class)">License</a></span></tt>) <strong>licensed_under</strong>(name) </h3><div class="docstring"> <div class="discussion"> <p>Sets the license of the model.</p> </div> </div> <div class="tags"> <div class="examples"> <p class="tag_title">Examples:</p> <pre class="example code"><span class='id identifier rubyid_licensed_under'>licensed_under</span> <span class='symbol'>:mit</span></pre> </div> <p class="tag_title">Parameters:</p> <ul class="param"> <li> <span class='name'>name</span> <span class='type'>(<tt>Symbol</tt>, <tt>String</tt>)</span> &mdash; <div class='inline'><p>The name of the license to use.</p> </div> </li> </ul> <p class="tag_title">Returns:</p> <ul class="return"> <li> <span class='type'>(<tt><span class='object_link'><a href="../../License.html" title="Ronin::License (class)">License</a></span></tt>)</span> &mdash; <div class='inline'><p>The new license of the model.</p> </div> </li> </ul> <p class="tag_title">Since:</p> <ul class="since"> <li> <div class='inline'><p>1.3.0</p> </div> </li> </ul> </div><table class="source_code"> <tr> <td> <pre class="lines"> 114 115 116</pre> </td> <td> <pre class="code"><span class="info file"># File 'lib/ronin/model/has_license.rb', line 114</span> <span class='kw'>def</span> <span class='id identifier rubyid_licensed_under'>licensed_under</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>self</span><span class='period'>.</span><span class='id identifier rubyid_license'>license</span> <span class='op'>=</span> <span class='const'>Ronin</span><span class='op'>::</span><span class='const'>License</span><span class='period'>.</span><span class='id identifier rubyid_predefined_resource'>predefined_resource</span><span class='lparen'>(</span><span class='id identifier rubyid_name'>name</span><span class='rparen'>)</span> <span class='kw'>end</span></pre> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated on Sat Jun 16 20:51:28 2012 by <a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a> 0.8.2.1 (ruby-1.9.3). </div> </body> </html>
ilsec/ilsec.github.io
docs/ronin/Ronin/Model/HasLicense/InstanceMethods.html
HTML
gpl-3.0
8,248
package ca.six.tomato.util; import org.json.JSONArray; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowEnvironment; import java.io.File; import ca.six.tomato.BuildConfig; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; /** * Created by songzhw on 2016-10-03 */ @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class DataUtilsTest { @Test public void testFile() { File dstFile = ShadowEnvironment.getExternalStorageDirectory(); assertTrue(dstFile.exists()); System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true System.out.println("szw isExisting = " + dstFile.exists()); //=> true System.out.println("szw path = " + dstFile.getPath()); //=> C:\Users\***\AppData\Local\Temp\android-tmp-robolectric7195966122073188215 } @Test public void testWriteString(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; DataUtilKt.write("abc", path); String ret = DataUtilKt.read(path, false); assertEquals("abc", ret); } @Test public void testWriteJSON(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}"; DataUtilKt.write(content, path); JSONArray ret = DataUtilKt.read(path); System.out.println("szw, ret = "+ret.toString()); assertNotNull(ret); } }
SixCan/SixTomato
app/src/test/java/ca/six/tomato/util/DataUtilsTest.java
Java
gpl-3.0
2,002
/* * The basic test codes to check the AnglogIn. */ #include "mbed.h" static AnalogIn ain_x(A6); // connect joistics' x axis to A6 pin of mbed static AnalogIn ain_y(A5); // connect joistics' y axis to A5 pin of mbed static void printAnalogInput(AnalogIn *xin, AnalogIn *yin) { uint8_t point[2] = { 0 }; point[0] = (uint8_t)(xin->read()*100.0f + 0.5); point[1] = (uint8_t)(yin->read()*100.0f + 0.5); printf("x: %d, y: %d\n", point[0], point[1]); } int main() { while(1) { printAnalogInput(&ain_x, &ain_y); wait(0.2f); } }
Darkblue38/mbedTrust
MiniProjects/AnalogInOut/Joistick/TestAnalogInUsingJoistick.cpp
C++
gpl-3.0
563
/*** * Copyright (c) 2013 John Krauss. * * This file is part of Crashmapper. * * Crashmapper 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. * * Crashmapper 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 Crashmapper. If not, see <http://www.gnu.org/licenses/>. * ***/ /*jslint browser: true, nomen: true, sloppy: true*/ /*globals Backbone, Crashmapper */ /** * @param {Object} options * @constructor * @extends Backbone.View */ Crashmapper.AppView = Backbone.View.extend({ id: 'app', /** * @this {Crashmapper.AppView} */ initialize: function () { this.about = new Crashmapper.AboutView({}).render(); this.about.$el.appendTo(this.$el).hide(); this.map = new Crashmapper.MapView({}); this.map.$el.appendTo(this.$el); }, /** * @this {Crashmapper.AppView} */ render: function () { return this; } });
talos/nypd-crash-data-bandaid
map/src/views/app.js
JavaScript
gpl-3.0
1,396
FROM golang:alpine AS builder RUN apk add --update git && go get github.com/fffaraz/microdns FROM alpine:latest COPY --from=builder /go/bin/microdns /usr/local/bin ENTRYPOINT ["microdns"]
fffaraz/microdns
Dockerfile
Dockerfile
gpl-3.0
189
/* **************************************************************************** * * Copyright Saab AB, 2005-2013 (http://safirsdkcore.com) * * Created by: Lars Hagström / stlrha * ******************************************************************************* * * This file is part of Safir SDK Core. * * Safir SDK Core is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Safir SDK Core 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 Safir SDK Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace Safir.Dob.Typesystem { /// <summary> /// Base class for all Containers. /// <para/> ///This class contains common functionality for all Containers. /// Basically this amounts to the interface for nullability and /// the change flag. /// </summary> abstract public class ContainerBase { /// <summary> /// Default Constructor. /// <para/> /// Construct a container that is not changed. /// </summary> public ContainerBase() { m_bIsChanged = false; } /// <summary> /// Is the container set to null? /// </summary> /// <returns>True if the container is set to null.</returns> abstract public bool IsNull(); /// <summary> /// Set the container to null. /// </summary> abstract public void SetNull(); /// <summary> /// Is the change flag set on the container? /// <para/> /// The change flag gets updated every time the contained value changes. /// <para/> /// Note: If this is a container containing objects this call will recursively /// check change flags in the contained objects. /// </summary> /// <returns> True if the containers change flag is set.</returns> virtual public bool IsChanged() { return m_bIsChanged; } /// <summary> /// Set the containers change flag. /// <para/> /// It should be fairly unusual for an application to have to use this /// operation. There is nothing dangerous about it, but are you sure this /// is the operation you were after? /// <para/> /// The change flag is how receivers of objects can work out what the /// sender really wanted done on the object. /// <para/> /// Note: If this is a container containing one or more objects this call /// will recursively set all the change flags in the contained objects. /// </summary> /// <param name="changed">The value to set the change flag(s) to.</param> virtual public void SetChanged(bool changed) { m_bIsChanged = changed; } #region Cloning /// <summary> /// Create a copy of the Container. /// <para> /// This method is deprecated. /// </para> /// </summary> public dynamic Clone() { return this.DeepClone(); } /// <summary> /// Copy. /// </summary> /// <param name="other">Other ContainerBase.</param> virtual public void Copy(ContainerBase other) { ShallowCopy(other); } #endregion /// <summary> /// Flag accessible from subclasses. /// </summary> protected internal bool m_bIsChanged; virtual internal void ShallowCopy(ContainerBase other) { if (this.GetType() != other.GetType()) { throw new SoftwareViolationException("Invalid call to Copy, containers are not of same type"); } m_bIsChanged = other.m_bIsChanged; } } }
SafirSDK/safir-sdk-core
src/dots/dots_dotnet.ss/src/ContainerBase.cs
C#
gpl-3.0
4,296
#!/usr/bin/python2 # -*- coding: utf-8 -*- # coding=utf-8 import unittest from datetime import datetime from lib.escala import Escala import dirs dirs.DEFAULT_DIR = dirs.TestDir() class FrameTest(unittest.TestCase): def setUp(self): self.escala = Escala('fixtures/escala.xml') self.dir = dirs.TestDir() self.maxDiff = None def tearDown(self): pass def test_attributos_voo_1(self): p_voo = self.escala.escalas[0] self.assertEqual(p_voo.activity_date, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4148') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'GYN') self.assertEqual(p_voo.actype, 'E95') self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 3, 1, 10, 36)) self.assertEqual(p_voo.std, datetime(2013, 3, 1, 13, 13)) self.assertEqual(p_voo.sta, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.activity_info, 'AD4148') self.assertFalse(p_voo.duty_design) def test_attributos_voo_17(self): p_voo = self.escala.escalas[17] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, None) self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'VCP') self.assertEqual(p_voo.activity_info, 'P04') self.assertEqual(p_voo.actype, None) self.assertEqual(p_voo.sta, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.std, datetime(2013, 10, 28, 15, 0)) self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertFalse(p_voo.duty_design) def test_attributos_voo_18(self): p_voo = self.escala.escalas[18] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4050') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'FLN') self.assertEqual(p_voo.activity_info, 'AD4050') self.assertEqual(p_voo.actype, 'E95') self.assertEqual(p_voo.sta, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.std, datetime(2013, 10, 29, 6, 15)) self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 10, 29, 5, 8)) self.assertFalse(p_voo.duty_design) self.assertEqual(p_voo.horas_de_voo, '1:17') def test_attributos_quarto_voo(self): p_voo = self.escala.escalas[25] self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertEqual(p_voo.flight_no, '2872') self.assertEqual(p_voo.activity_info, 'AD2872') def test_calculo_horas_voadas(self): s_horas = { 'h_diurno': '6:40', 'h_noturno': '6:47', 'h_total_voo': '13:27', 'h_faixa2': '0:00', 'h_sobreaviso': '40:00', 'h_reserva': '29:13' } self.assertEqual(self.escala.soma_horas(), s_horas) def test_ics(self): """ Check ICS output """ escala = Escala('fixtures/escala_ics.xml') f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics') self.assertEqual(escala.ics(), f_result.read()) f_result.close() def test_csv(self): """ Check CSV output """ f_result = open(self.dir.get_data_dir() + 'fixtures/escala.csv') self.assertEqual(self.escala.csv(), f_result.read()) f_result.close() def main(): unittest.main() if __name__ == '__main__': main()
camponez/importescala
test/test_escala.py
Python
gpl-3.0
3,876
package net.thevpc.upa.impl; import net.thevpc.upa.*; import net.thevpc.upa.impl.transform.IdentityDataTypeTransform; import net.thevpc.upa.impl.util.NamingStrategy; import net.thevpc.upa.impl.util.NamingStrategyHelper; import net.thevpc.upa.impl.util.PlatformUtils; import net.thevpc.upa.types.*; import net.thevpc.upa.exceptions.UPAException; import net.thevpc.upa.filters.FieldFilter; import net.thevpc.upa.types.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public abstract class AbstractField extends AbstractUPAObject implements Field, Comparable<Object> { protected Entity entity; protected EntityItem parent; protected DataType dataType; protected Formula persistFormula; protected int persistFormulaOrder; protected Formula updateFormula; protected int updateFormulaOrder; protected Formula queryFormula; protected Object defaultObject; protected SearchOperator searchOperator = SearchOperator.DEFAULT; protected DataTypeTransform typeTransform; protected HashMap<String, Object> properties; protected FlagSet<UserFieldModifier> userModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<UserFieldModifier> userExcludeModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<FieldModifier> effectiveModifiers = FlagSets.noneOf(FieldModifier.class); protected boolean closed; protected Object unspecifiedValue = UnspecifiedValue.DEFAULT; private AccessLevel persistAccessLevel = AccessLevel.READ_WRITE; private AccessLevel updateAccessLevel = AccessLevel.READ_WRITE; private AccessLevel readAccessLevel = AccessLevel.READ_WRITE; private ProtectionLevel persistProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel updateProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel readProtectionLevel = ProtectionLevel.PUBLIC; private FieldPersister fieldPersister; private PropertyAccessType accessType; private List<Relationship> manyToOneRelationships; private List<Relationship> oneToOneRelationships; private boolean _customDefaultObject = false; private Object _typeDefaultObject = false; protected AbstractField() { } @Override public String getAbsoluteName() { return (getEntity() == null ? "?" : getEntity().getName()) + "." + getName(); } public EntityItem getParent() { return parent; } public void setParent(EntityItem item) { EntityItem old = this.parent; EntityItem recent = item; beforePropertyChangeSupport.firePropertyChange("parent", old, recent); this.parent = item; afterPropertyChangeSupport.firePropertyChange("parent", old, recent); } @Override public void commitModelChanges() { manyToOneRelationships = getManyToOneRelationshipsImpl(); oneToOneRelationships = getOneToOneRelationshipsImpl(); } public boolean is(FieldFilter filter) throws UPAException { return filter.accept(this); } public boolean isId() throws UPAException { return getModifiers().contains(FieldModifier.ID); } @Override public boolean isGeneratedId() throws UPAException { if (!isId()) { return false; } Formula persistFormula = getPersistFormula(); return (persistFormula != null); } public boolean isMain() throws UPAException { return getModifiers().contains(FieldModifier.MAIN); } @Override public boolean isSystem() { return getModifiers().contains(FieldModifier.SYSTEM); } public boolean isSummary() throws UPAException { return getModifiers().contains(FieldModifier.SUMMARY); } public List<Relationship> getManyToOneRelationships() { return manyToOneRelationships; } public List<Relationship> getOneToOneRelationships() { return oneToOneRelationships; } protected List<Relationship> getManyToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } protected List<Relationship> getOneToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } public void setFormula(Formula formula) { setPersistFormula(formula); setUpdateFormula(formula); } @Override public void setFormula(String formula) { setFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setPersistFormula(Formula formula) { this.persistFormula = formula; } public void setUpdateFormula(Formula formula) { this.updateFormula = formula; } @Override public void setFormulaOrder(int order) { setPersistFormulaOrder(order); setUpdateFormulaOrder(order); } public int getUpdateFormulaOrder() { return updateFormulaOrder; } @Override public void setUpdateFormulaOrder(int order) { this.updateFormulaOrder = order; } public int getPersistFormulaOrder() { return persistFormulaOrder; } @Override public void setPersistFormulaOrder(int order) { this.persistFormulaOrder = order; } public Formula getUpdateFormula() { return updateFormula; } @Override public void setUpdateFormula(String formula) { setUpdateFormula(formula == null ? null : new ExpressionFormula(formula)); } public Formula getSelectFormula() { return queryFormula; } @Override public void setSelectFormula(String formula) { setSelectFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setSelectFormula(Formula queryFormula) { this.queryFormula = queryFormula; } // public boolean isRequired() throws UPAException { // return (!isReadOnlyOnPersist() || !isReadOnlyOnUpdate()) && !getDataType().isNullable(); // } public String getPath() { EntityItem parent = getParent(); return parent == null ? ("/" + getName()) : (parent.getPath() + "/" + getName()); } @Override public PersistenceUnit getPersistenceUnit() { return entity.getPersistenceUnit(); } public Formula getPersistFormula() { return persistFormula; } @Override public void setPersistFormula(String formula) { setPersistFormula(formula == null ? null : new ExpressionFormula(formula)); } public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public DataType getDataType() { return dataType; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param datatype datatype */ @Override public void setDataType(DataType datatype) { this.dataType = datatype; if (!getDataType().isNullable()) { _typeDefaultObject = getDataType().getDefaultValue(); } else { _typeDefaultObject = null; } } public Object getDefaultValue() { if (_customDefaultObject) { Object o = ((CustomDefaultObject) defaultObject).getObject(); if (o == null) { o = _typeDefaultObject; } return o; } else { Object o = defaultObject; if (o == null) { o = _typeDefaultObject; } return o; } } public Object getDefaultObject() { return defaultObject; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param o default value witch may be san ObjectHandler */ public void setDefaultObject(Object o) { defaultObject = o; if (o instanceof CustomDefaultObject) { _customDefaultObject = true; } } public FlagSet<FieldModifier> getModifiers() { return effectiveModifiers; } public void setEffectiveModifiers(FlagSet<FieldModifier> effectiveModifiers) { this.effectiveModifiers = effectiveModifiers; } // public void addModifiers(long modifiers) { // setModifiers(getModifiers() | modifiers); // } // // public void removeModifiers(long modifiers) { // setModifiers(getModifiers() & ~modifiers); // } // public Expression getExpression() { // return formula == null ? null : formula.getExpression(); // } @Override public boolean equals(Object other) { return !(other == null || !(other instanceof Field)) && compareTo(other) == 0; } public int compareTo(Object other) { if (other == this) { return 0; } if (other == null) { return 1; } Field f = (Field) other; NamingStrategy comp = NamingStrategyHelper.getNamingStrategy(getEntity().getPersistenceUnit().isCaseSensitiveIdentifiers()); String s1 = entity != null ? comp.getUniformValue(entity.getName()) : ""; String s2 = f.getName() != null ? comp.getUniformValue(f.getEntity().getName()) : ""; int i = s1.compareTo(s2); if (i != 0) { return i; } else { String s3 = getName() != null ? comp.getUniformValue(getName()) : ""; String s4 = f.getName() != null ? comp.getUniformValue(f.getName()) : ""; i = s3.compareTo(s4); return i; } } @Override public FlagSet<UserFieldModifier> getUserModifiers() { return userModifiers; } // public void resetModifiers() { // modifiers = 0; // } public void setUserModifiers(FlagSet<UserFieldModifier> modifiers) { this.userModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public FlagSet<UserFieldModifier> getUserExcludeModifiers() { return userExcludeModifiers; } public void setUserExcludeModifiers(FlagSet<UserFieldModifier> modifiers) { this.userExcludeModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public String toString() { return getAbsoluteName(); } @Override public void close() throws UPAException { this.closed = true; } public boolean isClosed() { return closed; } @Override public Object getUnspecifiedValue() { return unspecifiedValue; } @Override public void setUnspecifiedValue(Object o) { this.unspecifiedValue = o; } public Object getUnspecifiedValueDecoded() { final Object fuv = getUnspecifiedValue(); if (UnspecifiedValue.DEFAULT.equals(fuv)) { return getDataType().getDefaultUnspecifiedValue(); } else { return fuv; } } public boolean isUnspecifiedValue(Object value) { Object v = getUnspecifiedValueDecoded(); return (v == value || (v != null && v.equals(value))); } public AccessLevel getPersistAccessLevel() { return persistAccessLevel; } public void setPersistAccessLevel(AccessLevel persistAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, persistAccessLevel)) { persistAccessLevel = AccessLevel.READ_WRITE; } this.persistAccessLevel = persistAccessLevel; } public AccessLevel getUpdateAccessLevel() { return updateAccessLevel; } public void setUpdateAccessLevel(AccessLevel updateAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, updateAccessLevel)) { updateAccessLevel = AccessLevel.READ_WRITE; } this.updateAccessLevel = updateAccessLevel; } public AccessLevel getReadAccessLevel() { return readAccessLevel; } public void setReadAccessLevel(AccessLevel readAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, readAccessLevel)) { readAccessLevel = AccessLevel.READ_ONLY; } if (readAccessLevel == AccessLevel.READ_WRITE) { readAccessLevel = AccessLevel.READ_ONLY; } this.readAccessLevel = readAccessLevel; } public void setAccessLevel(AccessLevel accessLevel) { setPersistAccessLevel(accessLevel); setUpdateAccessLevel(accessLevel); setReadAccessLevel(accessLevel); } public ProtectionLevel getPersistProtectionLevel() { return persistProtectionLevel; } public void setPersistProtectionLevel(ProtectionLevel persistProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, persistProtectionLevel)) { persistProtectionLevel = ProtectionLevel.PUBLIC; } this.persistProtectionLevel = persistProtectionLevel; } public ProtectionLevel getUpdateProtectionLevel() { return updateProtectionLevel; } public void setUpdateProtectionLevel(ProtectionLevel updateProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, updateProtectionLevel)) { updateProtectionLevel = ProtectionLevel.PUBLIC; } this.updateProtectionLevel = updateProtectionLevel; } public ProtectionLevel getReadProtectionLevel() { return readProtectionLevel; } public void setReadProtectionLevel(ProtectionLevel readProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, readProtectionLevel)) { readProtectionLevel = ProtectionLevel.PUBLIC; } this.readProtectionLevel = readProtectionLevel; } public void setProtectionLevel(ProtectionLevel persistLevel) { setPersistProtectionLevel(persistLevel); setUpdateProtectionLevel(persistLevel); setReadProtectionLevel(persistLevel); } public SearchOperator getSearchOperator() { return searchOperator; } public void setSearchOperator(SearchOperator searchOperator) { this.searchOperator = searchOperator; } public FieldPersister getFieldPersister() { return fieldPersister; } public void setFieldPersister(FieldPersister fieldPersister) { this.fieldPersister = fieldPersister; } public DataTypeTransform getTypeTransform() { return typeTransform; } @Override public DataTypeTransform getEffectiveTypeTransform() { DataTypeTransform t = getTypeTransform(); if (t == null) { DataType d = getDataType(); if (d != null) { t = new IdentityDataTypeTransform(d); } } return t; } public void setTypeTransform(DataTypeTransform transform) { this.typeTransform = transform; } public PropertyAccessType getPropertyAccessType() { return accessType; } public void setPropertyAccessType(PropertyAccessType accessType) { this.accessType = accessType; } @Override public Object getMainValue(Object instance) { Object v = getValue(instance); if (v != null) { Relationship manyToOneRelationship = getManyToOneRelationship(); if (manyToOneRelationship != null) { v = manyToOneRelationship.getTargetEntity().getBuilder().getMainValue(v); } } return v; } @Override public Object getValue(Object instance) { if (instance instanceof Document) { return ((Document) instance).getObject(getName()); } return getEntity().getBuilder().getProperty(instance, getName()); } @Override public void setValue(Object instance, Object value) { getEntity().getBuilder().setProperty(instance, getName(), value); } @Override public void check(Object value) { getDataType().check(value, getName(), null); } @Override public boolean isManyToOne() { return getDataType() instanceof ManyToOneType; } @Override public boolean isOneToOne() { return getDataType() instanceof OneToOneType; } @Override public ManyToOneRelationship getManyToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof ManyToOneType) { return (ManyToOneRelationship) ((ManyToOneType) dataType).getRelationship(); } return null; } @Override public OneToOneRelationship getOneToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof OneToOneType) { return (OneToOneRelationship) ((OneToOneType) dataType).getRelationship(); } return null; } protected void fillFieldInfo(FieldInfo i) { Field f = this; fillObjectInfo(i); DataTypeInfo dataType = f.getDataType() == null ? null : f.getDataType().getInfo(); if (dataType != null) { UPAI18n d = getPersistenceGroup().getI18nOrDefault(); if (f.getDataType() instanceof EnumType) { List<Object> values = ((EnumType) f.getDataType()).getValues(); StringBuilder v = new StringBuilder(); for (Object o : values) { if (v.length() > 0) { v.append(","); } v.append(d.getEnum(o)); } dataType.getProperties().put("titles", String.valueOf(v)); } } i.setDataType(dataType); i.setId(f.isId()); i.setGeneratedId(f.isGeneratedId()); i.setModifiers(f.getModifiers().toArray()); i.setPersistAccessLevel(f.getPersistAccessLevel()); i.setUpdateAccessLevel(f.getUpdateAccessLevel()); i.setReadAccessLevel(f.getReadAccessLevel()); i.setPersistProtectionLevel(f.getPersistProtectionLevel()); i.setUpdateProtectionLevel(f.getUpdateProtectionLevel()); i.setReadProtectionLevel(f.getReadProtectionLevel()); i.setEffectivePersistAccessLevel(f.getEffectivePersistAccessLevel()); i.setEffectiveUpdateAccessLevel(f.getEffectiveUpdateAccessLevel()); i.setEffectiveReadAccessLevel(f.getEffectiveReadAccessLevel()); i.setMain(f.isMain()); i.setSystem(f.getModifiers().contains(FieldModifier.SYSTEM)); i.setSummary(f.isSummary()); i.setManyToOne(f.isManyToOne()); i.setPropertyAccessType(f.getPropertyAccessType()); Relationship r = f.getManyToOneRelationship(); i.setManyToOneRelationship(r == null ? null : r.getName()); } @Override public AccessLevel getEffectiveAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getEffectiveReadAccessLevel(); case PERSIST: return getEffectivePersistAccessLevel(); case UPDATE: return getEffectiveUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public AccessLevel getAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadAccessLevel(); case PERSIST: return getPersistAccessLevel(); case UPDATE: return getUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public ProtectionLevel getProtectionLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadProtectionLevel(); case PERSIST: return getPersistProtectionLevel(); case UPDATE: return getUpdateProtectionLevel(); } } return ProtectionLevel.PRIVATE; } public AccessLevel getEffectivePersistAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getPersistAccessLevel(); ProtectionLevel pl = getPersistProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getPersistFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } break; } case PUBLIC: { break; } } break; } } if (al != AccessLevel.INACCESSIBLE) { if (isGeneratedId()) { al = AccessLevel.INACCESSIBLE; } if (!getModifiers().contains(FieldModifier.PERSIST_DEFAULT)) { al = AccessLevel.INACCESSIBLE; } } return al; } public AccessLevel getEffectiveUpdateAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getUpdateAccessLevel(); ProtectionLevel pl = getUpdateProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getUpdateFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } if (isId() && al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (getModifiers().contains(FieldModifier.UPDATE_DEFAULT)) { // } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } return al; } public AccessLevel getEffectiveReadAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getReadAccessLevel(); ProtectionLevel pl = getReadProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (al == AccessLevel.READ_ONLY) { if (!getModifiers().contains(FieldModifier.SELECT)) { al = AccessLevel.INACCESSIBLE; } } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } return al; } }
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/AbstractField.java
Java
gpl-3.0
27,988
#include "../../VM/Handler/Opcode8030Handler.h" #include "../../VM/Script.h" namespace Falltergeist { namespace VM { namespace Handler { Opcode8030::Opcode8030(VM::Script *script, std::shared_ptr<ILogger> logger) : OpcodeHandler(script) { this->logger = std::move(logger); } void Opcode8030::_run() { logger->debug() << "[8030] [*] op_while(address, condition)" << std::endl; auto condition = _script->dataStack()->popLogical(); if (!condition) { _script->setProgramCounter(_script->dataStack()->popInteger()); } } } } }
falltergeist/falltergeist
src/VM/Handler/Opcode8030Handler.cpp
C++
gpl-3.0
731
MT19937AR_OBJ = mt19937ar.o MT19937AR_H = mt19937ar.h ##################################################################### .PHONY : all clean help all: $(MT19937AR_OBJ) clean: @echo " CLEAN mt19937ar" @rm -rf *.o help: @echo "possible targets are 'all' 'clean' 'help'" @echo "'all' - builds $(MT19937AR_OBJ)" @echo "'clean' - deletes $(MT19937AR_OBJ)" @echo "'help' - outputs this message" ##################################################################### %.o: %.c $(MT19937AR_H) @echo " CC $<" @gcc -flto -fuse-linker-plugin -ffat-lto-objects -flto -fuse-linker-plugin -g -O2 -pipe -ffast-math -Wall -Wno-maybe-uninitialized -Wno-clobbered -Wempty-body -Wno-switch -Wno-missing-field-initializers -Wshadow -fno-strict-aliasing -DMAXCONN=16384 -I../common -DHAS_TLS -DHAVE_SETRLIMIT -DHAVE_STRNLEN -I/usr/include -DHAVE_MONOTONIC_CLOCK -c $(OUTPUT_OPTION) $<
Daniel4rt/mkAthena
3rdparty/mt19937ar/Makefile
Makefile
gpl-3.0
890
----------------------------------- -- Area: Windurst Woods -- NPC: Matata -- Type: Standard NPC -- Involved in quest: In a Stew -- !pos 131 -5 -109 241 ----------------------------------- require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local IAS = player:getQuestStatus(WINDURST, IN_A_STEW) local IASvar = player:getVar("IASvar") local CB = player:getQuestStatus(WINDURST, CHOCOBILIOUS) -- IN A STEW if IAS == QUEST_ACCEPTED and IASvar == 1 then player:startEvent(233, 0, 0, 4545) -- In a Stew in progress elseif IAS == QUEST_ACCEPTED and IASvar == 2 then player:startEvent(237) -- In a Stew reminder elseif IAS == QUEST_COMPLETED then player:startEvent(241) -- new dialog after In a Stew -- CHOCOBILIOUS elseif CB == QUEST_COMPLETED then player:startEvent(226) -- Chocobilious complete -- STANDARD DIALOG else player:startEvent(223) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) -- IN A STEW if csid == 233 then player:setVar("IASvar", 2) end end
m3rlin87/darkstar
scripts/zones/Windurst_Woods/npcs/Matata.lua
Lua
gpl-3.0
1,209
#include "report_mib_feature.h" #include "mib_feature_definition.h" #include "report_manager.h" #include "protocol.h" #include "bus_slave.h" #include "momo_config.h" #include "report_log.h" #include "report_comm_stream.h" #include "system_log.h" #include <string.h> #define BASE64_REPORT_MAX_LENGTH 160 //( 4 * ( ( RAW_REPORT_MAX_LENGTH + 2 ) / 3) ) extern char base64_report_buffer[BASE64_REPORT_MAX_LENGTH+1]; static void start_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, true ); start_report_scheduling(); } static void stop_scheduled_reporting(void) { set_momo_state_flag( kStateFlagReportingEnabled, false ); stop_report_scheduling(); } static void get_scheduled_reporting(void) { bus_slave_return_int16( get_momo_state_flag( kStateFlagReportingEnabled ) ); } static void send_report(void) { taskloop_add( post_report, NULL ); } static void set_reporting_interval(void) { set_report_scheduling_interval( plist_get_int16(0) ); } static void get_reporting_interval(void) { bus_slave_return_int16( current_momo_state.report_config.report_interval ); } static void set_reporting_route(void) { update_report_route( (plist_get_int16(0) >> 8) & 0xFF , plist_get_int16(0) & 0xFF , (const char*)plist_get_buffer(1) , plist_get_buffer_length() ); } static void get_reporting_route(void) { const char* route = get_report_route( ( plist_get_int16(0) >> 8 ) & 0xFF ); if ( !route ) { bus_slave_seterror( kUnknownError ); return; } uint8 start = plist_get_int16(0) & 0xFF; uint8 len = strlen( route ) - start; if ( len < 0 ) { bus_slave_seterror( kCallbackError ); return; } if ( len > kBusMaxMessageSize ) len = kBusMaxMessageSize; bus_slave_return_buffer( route + start, len ); } static void set_reporting_apn(void) { set_gprs_apn( (const char*)plist_get_buffer(0), plist_get_buffer_length() ); } static void get_reporting_apn(void) { bus_slave_return_buffer( current_momo_state.report_config.gprs_apn, strlen(current_momo_state.report_config.gprs_apn) ); } static void set_reporting_flags(void) { current_momo_state.report_config.report_flags = plist_get_int16(0); } static void get_reporting_flags(void) { bus_slave_return_int16( current_momo_state.report_config.report_flags ); } static void set_reporting_aggregates(void) { current_momo_state.report_config.bulk_aggregates = plist_get_int16(0); current_momo_state.report_config.interval_aggregates = plist_get_int16(1); } static void get_reporting_aggregates(void) { plist_set_int16( 0, current_momo_state.report_config.bulk_aggregates ); plist_set_int16( 1, current_momo_state.report_config.interval_aggregates ); bus_slave_setreturn( pack_return_status( kNoMIBError, 4 ) ); } static void build_report() { construct_report(); } static void get_report() { uint16 offset = plist_get_int16(0); memcpy(plist_get_buffer(0), base64_report_buffer+offset, 20); bus_slave_setreturn( pack_return_status(kNoMIBError, 20 )); } static void get_reporting_sequence(void) { bus_slave_return_int16( current_momo_state.report_config.transmit_sequence ); } static BYTE report_buffer[RAW_REPORT_MAX_LENGTH]; static void read_report_log_mib(void) { uint16 index = plist_get_int16(0); uint16 offset = plist_get_int16(1); if ( offset >= RAW_REPORT_MAX_LENGTH ) { bus_slave_seterror( kCallbackError ); return; } uint8 length = RAW_REPORT_MAX_LENGTH - offset; if ( length > kBusMaxMessageSize ) length = kBusMaxMessageSize; if ( report_log_read( index, (void*)&report_buffer, 1 ) == 0 ) { // No more entries bus_slave_seterror( kCallbackError ); return; } bus_slave_return_buffer( report_buffer+offset, length ); } static void count_report_log_mib(void) { bus_slave_return_int16( report_log_count() ); } static void clear_report_log_mib(void) { report_log_clear(); } static void handle_report_stream_success(void) { notify_report_success(); } static void handle_report_stream_failure(void) { notify_report_failure(); } DEFINE_MIB_FEATURE_COMMANDS(reporting) { { 0x00, send_report, plist_spec_empty() }, { 0x01, start_scheduled_reporting, plist_spec_empty() }, { 0x02, stop_scheduled_reporting, plist_spec_empty() }, { 0x03, set_reporting_interval, plist_spec(1, false) }, { 0x04, get_reporting_interval, plist_spec_empty() }, { 0x05, set_reporting_route, plist_spec(1, true) }, { 0x06, get_reporting_route, plist_spec(1, false) }, { 0x07, set_reporting_flags, plist_spec(1, false) }, { 0x08, get_reporting_flags, plist_spec_empty() }, { 0x09, set_reporting_aggregates, plist_spec(2, false) }, { 0x0A, get_reporting_aggregates, plist_spec_empty() }, { 0x0B, get_reporting_sequence, plist_spec_empty() }, { 0x0C, build_report, plist_spec_empty() }, { 0x0D, get_report, plist_spec(1, false) }, { 0x0E, get_scheduled_reporting, plist_spec_empty() }, { 0x0F, read_report_log_mib, plist_spec(2, false) }, { 0x10, count_report_log_mib, plist_spec_empty() }, { 0x11, clear_report_log_mib, plist_spec_empty() }, { 0x12, init_report_config, plist_spec_empty() }, { 0x13, set_reporting_apn, plist_spec(0,true) }, { 0x14, get_reporting_apn, plist_spec_empty() }, { 0xF0, handle_report_stream_success, plist_spec_empty() }, { 0xF1, handle_report_stream_failure, plist_spec_empty() } }; DEFINE_MIB_FEATURE(reporting);
WellDone/MoMo-Firmware
momo_modules/mainboard/src/mib/commands/report_mib_feature.c
C
gpl-3.0
5,340
<?php /** * Fired during plugin activation. * * This class defines all code necessary to run during the plugin's activation. * * @link https://wordpress.org/plugins/woocommerce-role-based-price/ * @package Role Based Price For WooCommerce * @subpackage Role Based Price For WooCommerce/core * @since 3.0 */ class WooCommerce_Role_Based_Price_Activator { public function __construct() { } /** * Short Description. (use period) * * Long Description. * * @since 1.0.0 */ public static function activate() { require_once( WC_RBP_INC . 'helpers/class-version-check.php' ); require_once( WC_RBP_INC . 'helpers/class-dependencies.php' ); if( WooCommerce_Role_Based_Price_Dependencies(WC_RBP_DEPEN) ) { WooCommerce_Role_Based_Price_Version_Check::activation_check('3.7'); $message = '<h3> <center> ' . __("Thank you for installing <strong>Role Based Price For WooCommerce</strong> : <strong>Version 3.0 </strong>", WC_RBP_TXT) . '</center> </h3>'; $message .= '<p>' . __("We have worked entire 1 year to improve our plugin to best of our ability and we hope you will enjoy working with it. We are always open for your sugestions and feature requests", WC_RBP_TXT) . '</p>'; $message .= '</hr>'; $message .= '<p>' . __("If you have installed <strong>WPRB</strong> for the 1st time or upgrading from <strong> Version 2.8.7</strong> then you will need to update its' settings once again or this plugin will not function properly. ", WC_RBP_TXT); $url = admin_url('admin.php?page=woocommerce-role-based-price-settings'); $message .= '<a href="' . $url . '" class="button button-primary">' . __("Click Here to update the settings", WC_RBP_TXT) . '</a> </p>'; wc_rbp_admin_update($message, 1, 'activate_message', array(), array( 'wraper' => FALSE, 'times' => 1 )); set_transient('_welcome_redirect_wcrbp', TRUE, 60); } else { if( is_plugin_active(WC_RBP_FILE) ) { deactivate_plugins(WC_RBP_FILE); } wp_die(wc_rbp_dependency_message()); } } }
technofreaky/WooCommerce-Role-Based-Price
includes/helpers/class-activator.php
PHP
gpl-3.0
2,218
[![Build Status](https://api.travis-ci.org/felixarntz/screen-reader-check.png?branch=master)](https://travis-ci.org/felixarntz/screen-reader-check) # Screen Reader Check A tool to help developers to make their HTML code accessible for screen reader users. This is a project I'm working on as part of my Bachelor thesis at Ruhr-Universität Bochum, Germany.
felixarntz/screen-reader-check
README.md
Markdown
gpl-3.0
360
Au terme de ce chapitre, vous en savez désormais plus quant aux retours et aux phases de bêta et de validation. Nous allons maintenant voir comme faire un retour, ce qui peut aussi vous aider à développer votre œil critique si vous êtes rédacteur.
firm1/zest-writer
src/test/resources/com/zds/zw/fixtures/le-guide-du-contributeur/828_contribuer-au-contenu/les-phases-de-correction-et-de-validation/conclusion.md
Markdown
gpl-3.0
256
<!-- jQuery --> <script src="<?php echo base_url('assets/frontend/js/jquery.js') ?>"></script> <!-- Bootstrap Core JavaScript --> <script src="<?php echo base_url('assets/frontend/js/bootstrap.min.js') ?>"></script> <!-- Contact Form JavaScript --> <!-- Do not edit these files! In order to set the email address and subject line for the contact form go to the bin/contact_me.php file. --> <script src="<?php echo base_url('assets/frontend/js/jqBootstrapValidation.js') ?>"></script> <script src="<?php echo base_url('assets/frontend/js/contact_me.js') ?>"></script> <script> $('.carousel').carousel({ interval: 5000 //changes the speed }) </script> <!-- DATA TABLE SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/dataTables/jquery.dataTables.js') ?>"></script> <script src="<?php echo base_url('assets/backend/js/dataTables/dataTables.bootstrap.js') ?>"></script> <script> $(document).ready(function () { $('#dataTables-example').dataTable(); }); </script> <script type="text/javascript"> CKEDITOR.replace( 'editor1', { on: { instanceReady: function( ev ) { // Output paragraphs as <p>Text</p>. this.dataProcessor.writer.setRules( 'p', { indent: false, breakBeforeOpen: true, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: true }); } } });</script>
SisteminformasisekolahMANCibadak/Sistem-informasi-sekolah-menggunakan-framewok-codeigniter-dengan-sub-modul-akademik
aplikasi/SIA_mancib/application/views/portalv/js.php
PHP
gpl-3.0
1,548
<?php /* * bla-tinymce * Copyright (C) 2017 bestlife AG * info: [email protected] * * 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/> * * Marat Bedoev */ class blaTinyMceOxViewConfig extends blaTinyMceOxViewConfig_parent { public function loadTinyMce() { $cfg = oxRegistry::getConfig(); $blEnabled = in_array($this->getActiveClassName(), $cfg->getConfigParam("aTinyMCE_classes")); $blPlainCms = in_array($cfg->getActiveView()->getViewDataElement("edit")->oxcontents__oxloadid->value, $cfg->getConfigParam("aTinyMCE_plaincms")); $blFilemanager = $cfg->getConfigParam("blTinyMCE_filemanager"); if (!$blEnabled) return false; if ($blPlainCms) return oxRegistry::getLang()->translateString("BLA_TINYMCE_PLAINCMS"); // processing editor config & other stuff $sLang = oxRegistry::getLang()->getLanguageAbbr(oxRegistry::getLang()->getTplLanguage()); // array to assign shops lang abbreviations to lang file names of tinymce: shopLangAbbreviation => fileName (without .js ) $aLang = array( "cs" => "cs", "da" => "da", "de" => "de", "fr" => "fr_FR", "it" => "it", "nl" => "nl", "ru" => "ru" ); // default config $aDefaultConfig = array( 'force_br_newlines' => 'false', 'force_p_newlines' => 'false', 'forced_root_block' => '""', 'selector' => '"textarea:not(.mceNoEditor)"', 'language' => '"' . ( in_array($sLang, $aLang) ? $aLang[$sLang] : 'en' ) . '"', //'spellchecker_language' => '"' . (in_array($sLang, $aLang) ? $aLang[$sLang] : 'en') . '"', 'nowrap' => 'false', 'entity_encoding' => '"raw"', // http://www.tinymce.com/wiki.php/Configuration:entity_encoding 'height' => 300, 'menubar' => 'false', 'document_base_url' => '"' . $this->getBaseDir() . '"', // http://www.tinymce.com/wiki.php/Configuration:document_base_url 'relative_urls' => 'false', // http://www.tinymce.com/wiki.php/Configuration:relative_urls 'plugin_preview_width' => 'window.innerWidth', 'plugin_preview_height' => 'window.innerHeight-90', 'code_dialog_width' => 'window.innerWidth-50', 'code_dialog_height' => 'window.innerHeight-130', 'image_advtab' => 'true', 'imagetools_toolbar' => '"rotateleft rotateright | flipv fliph | editimage imageoptions"', 'moxiemanager_fullscreen' => 'true', 'insertdatetime_formats' => '[ "%d.%m.%Y", "%H:%M" ]', 'nonbreaking_force_tab' => 'true', // http://www.tinymce.com/wiki.php/Plugin:nonbreaking 'autoresize_max_height' => '400', 'urlconverter_callback' => '"urlconverter"', 'filemanager_access_key' => '"' . md5($_SERVER['DOCUMENT_ROOT']) . '"', 'tinymcehelper' => '"' . $this->getSelfActionLink() . 'renderPartial=1"' ); if ($blFilemanager) { $aDefaultConfig['external_filemanager_path'] = '"../modules/bla/bla-tinymce/fileman/"'; $aDefaultConfig['filemanager_access_key'] = '"' . md5($_SERVER['HTTP_HOST']) . '"'; $oUS = oxRegistry::get("oxUtilsServer"); $oUS->setOxCookie("filemanagerkey", md5($_SERVER['DOCUMENT_ROOT'] . $oUS->getOxCookie("admin_sid"))); } //merging with onfig override $aConfig = ( $aOverrideConfig = $this->_getTinyCustConfig() ) ? array_merge($aDefaultConfig, $aOverrideConfig) : $aDefaultConfig; // default plugins and their buttons $aDefaultPlugins = array( 'advlist' => '', // '' = plugin has no buttons 'anchor' => 'anchor', 'autolink' => '', 'autoresize' => '', 'charmap' => 'charmap', 'code' => 'code', 'colorpicker' => '', 'hr' => 'hr', 'image' => 'image', 'imagetools' => '', 'insertdatetime' => 'insertdatetime', 'link' => 'link unlink', 'lists' => '', 'media' => 'media', 'nonbreaking' => 'nonbreaking', 'pagebreak' => 'pagebreak', 'paste' => 'pastetext', 'preview' => 'preview', 'searchreplace' => 'searchreplace', 'table' => 'table', 'textcolor' => 'forecolor backcolor', 'visualblocks' => '', //'visualchars' => 'visualchars', 'wordcount' => '', 'oxfullscreen' => 'fullscreen', //custom fullscreen plugin //'oxwidget' => 'widget' //'oxgetseourl' => 'yolo' //custom seo url plugin // wip ); // plugins for newsletter emails if ($this->getActiveClassName() == "newsletter_main") { $aDefaultPlugins["legacyoutput"] = "false"; $aDefaultPlugins["fullpage"] = "fullpage"; } // override for active plugins $aOverridePlugins = $cfg->getConfigParam("aTinyMCE_plugins"); $aPlugins = ( empty( $aOverridePlugins ) || !is_array($aOverridePlugins) ) ? $aDefaultPlugins : array_merge($aDefaultPlugins, $aOverridePlugins); $aPlugins = array_filter($aPlugins, function ( $value ) { return $value !== "false"; }); // array keys von $aPlugins enthalten aktive plugins $aConfig['plugins'] = '"' . implode(' ', array_keys($aPlugins)) . '"'; // external plugins $aConfig['external_plugins'] = '{ "oxfullscreen":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxfullscreen/plugin.js') . '" '; //$aConfig['external_plugins'] .= ', "oxwidget":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxwidget/plugin.js') . '" '; if ($blFilemanager) $aConfig['external_plugins'] .= ',"roxy":"' . $this->getModuleUrl('bla-tinymce', 'plugins/roxy/plugin.js') . '" '; //$aConfig['external_plugins'] .= ',"oxgetseourl":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxgetseourl/plugin.js') . '" '; if ($aExtPlugins = $this->_getTinyExtPlugins()) { foreach ($aExtPlugins AS $plugin => $file) { $aConfig['external_plugins'] .= ', "' . $plugin . '": "' . $file . '" '; } } $aConfig['external_plugins'] .= ' }'; // default toolbar buttons $aDefaultButtons = array( "undo redo", "cut copy paste", "bold italic underline strikethrough", "alignleft aligncenter alignright alignjustify", "bullist numlist", "outdent indent", "blockquote", "subscript", "superscript", "formatselect", "removeformat", "fontselect", "fontsizeselect" ); $aOverrideButtons = oxRegistry::getConfig()->getConfigParam("aTinyMCE_buttons"); $aButtons = ( empty( $aOverrideButtons ) || !is_array($aOverrideButtons) ) ? $aDefaultButtons : $aOverrideButtons; // plugin buttons $aPluginButtons = array_filter($aPlugins); // zusätzliche buttons $aCustomButtons = $this->_getTinyToolbarControls(); $aButtons = array_merge(array_filter($aButtons), array_filter($aPluginButtons), array_filter($aCustomButtons)); $aConfig['toolbar'] = '"' . implode(" | ", $aButtons) . '"'; // compile the whole config stuff $sConfig = ''; foreach ($aConfig AS $param => $value) { $sConfig .= "$param: $value, "; } // add init script $sInit = 'tinymce.init({ ' . $sConfig . ' });'; $sCopyLongDescFromTinyMCE = 'function copyLongDescFromTinyMCE(sIdent) { var editor = tinymce.get("editor_"+sIdent); var content = (editor && !editor.isHidden()) ? editor.getContent() : document.getElementById("editor_"+sIdent).value; document.getElementsByName("editval[" + sIdent + "]").item(0).value = content.replace(/\[{([^\]]*?)}\]/g, function(m) { return m.replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&") }); return true; } var origCopyLongDesc = copyLongDesc; copyLongDesc = function(sIdent) { if ( copyLongDescFromTinyMCE( sIdent ) ) return; console.log("tinymce disabled, copy content from regular textarea"); origCopyLongDesc( sIdent ); }'; $sUrlConverter = 'function urlconverter(url, node, on_save) { console.log(tinyMCE.activeEditor); if(url.indexOf("[{") == 0) return url; return (tinyMCE.activeEditor.settings.relative_urls) ? tinyMCE.activeEditor.documentBaseURI.toRelative(url) : tinyMCE.activeEditor.documentBaseURI.toAbsolute(url); }'; // adding scripts to template $smarty = oxRegistry::get("oxUtilsView")->getSmarty(); $sSufix = ( $smarty->_tpl_vars["__oxid_include_dynamic"] ) ? '_dynamic' : ''; $aScript = (array)$cfg->getGlobalParameter('scripts' . $sSufix); $aScript[] = $sCopyLongDescFromTinyMCE; $aScript[] = $sUrlConverter; $aScript[] = $sInit; $cfg->setGlobalParameter('scripts' . $sSufix, $aScript); $aInclude = (array)$cfg->getGlobalParameter('includes' . $sSufix); $aExtjs = $cfg->getConfigParam('aTinyMCE_extjs'); if (!empty( $aExtjs ) && is_array($aExtjs)) foreach ($aExtjs as $key => $js) $aInclude[3][] = $js; $aInclude[3][] = $this->getModuleUrl('bla-tinymce', 'tinymce/tinymce.min.js'); $cfg->setGlobalParameter('includes' . $sSufix, $aInclude); return '<li style="margin-left: 50px;"><button style="border: 1px solid #0089EE; color: #0089EE;padding: 3px 10px; margin-top: -10px; background: white;" ' . 'onclick="tinymce.each(tinymce.editors, function(editor) { if(editor.isHidden()) { editor.show(); } else { editor.hide(); } });"><span>' . oxRegistry::getLang()->translateString('BLA_TINYMCE_TOGGLE') . '</span></button></li>'; // javascript:tinymce.execCommand(\'mceToggleEditor\',false,\'editor1\'); } protected function _getTinyToolbarControls() { $aControls = ( method_exists(get_parent_class(__CLASS__), __FUNCTION__) ) ? parent::_getTinyToolbarControls() : array(); return $aControls; } protected function _getTinyExtPlugins() { $aPlugins = oxRegistry::getConfig()->getConfigParam("aTinyMCE_external_plugins"); if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) { $aPlugins = array_merge(parent::_getTinyExtPlugins(), $aPlugins); } return $aPlugins; } protected function _getTinyCustConfig() { $aConfig = oxRegistry::getConfig()->getConfigParam("aTinyMCE_config"); if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) { $aConfig = array_merge(parent::_getTinyCustConfig(), $aConfig); } return $aConfig; } }
vanilla-thunder/bla-tinymce
copy_this/modules/bla/bla-tinymce/application/core/blatinymceoxviewconfig.php
PHP
gpl-3.0
11,435
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Nerdz.Messenger.Controller; using Nerdz.Messages; using Nerdz; namespace Tests.Controller { public class DummyUI : IMessengerView { private Credentials credentials; private IMessengerController controller; public IMessengerController Controller { set { controller = value; } get { return controller; } } public void UpdateConversations(System.Collections.Generic.List<Nerdz.Messages.IConversation> conversations) { Console.WriteLine("Conversations: "); foreach (IConversation c in conversations) { Console.WriteLine(c); } } public void UpdateMessages(System.Collections.Generic.List<Nerdz.Messages.IMessage> messages) { Console.WriteLine("Messages: "); foreach (IMessage m in messages) { Console.WriteLine(m); } } public void ShowLogin() { Console.WriteLine("Username: "); string username = "new user input from textbox"; Console.WriteLine("Password: "); string password = "password input from textbox"; credentials = new Credentials(username, password); } public void ClearConversations() { Console.WriteLine("\n\n\nConversations list cleaned\n\n"); } public void ClearConversation() { Console.WriteLine("\n\nConversation cleaned\n\n"); } public void DisplayError(string error) { Console.Error.WriteLine("[!] " + error); } public void DisplayCriticalError(string error) { Console.Error.WriteLine("CRITICAL: " + error); } public int ConversationDisplayed() { return 0; } } [TestClass] public class MessengerControllerTests { static private IMessengerView view; static private IMessengerController controller; [TestMethod] public void NewController() { Credentials c = new Credentials(0, "wrongpass"); view = new DummyUI(); try { controller = new MessengerController(view, c); } catch (LoginException) { Console.WriteLine("Wrong username and password (OK!)"); } c = new Credentials("admin", "adminadmin"); controller = new MessengerController(view, c); } [TestMethod] public void TestGetConversations() { controller.Conversations(); } [TestMethod] public void TestGetConversationOK() { controller.Conversation(0); // exists, no exception expected } [ExpectedException(typeof(CriticalException))] [TestMethod] public void TestGetConversationFAIL() { controller.Conversation(110); } [TestMethod] public void TestSendOK() { controller.Send("Gaben", "great app :>"); // user nessuno exists, no exception expected } [ExpectedException(typeof(BadStatusException))] [TestMethod] public void TestSendFAIL() { controller.Send("94949494", "great app :>"); // numeric username can't exists, so this test shoudl fail } [TestMethod] public void TestLogout() { controller.Logout(); } } }
nerdzeu/nm.net
Tests/Controller/MessengerControllerTestMethods.cs
C#
gpl-3.0
3,786
/* * Copyright (C) 2016 Stuart Howarth <[email protected]> * * 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/>. */ #include "independentfeedrequest.h" #include "independentarticlerequest.h" #include <QNetworkAccessManager> #include <QNetworkReply> #ifdef INDEPENDENT_DEBUG #include <QDebug> #endif const int IndependentFeedRequest::MAX_REDIRECTS = 8; const QString IndependentFeedRequest::BASE_URL("http://www.independent.co.uk"); const QString IndependentFeedRequest::ICON_URL("http://www.independent.co.uk/sites/all/themes/ines_themes/independent_theme/img/apple-icon-72x72.png"); const QByteArray IndependentFeedRequest::USER_AGENT("Wget/1.13.4 (linux-gnu)"); IndependentFeedRequest::IndependentFeedRequest(QObject *parent) : FeedRequest(parent), m_request(0), m_nam(0), m_status(Idle), m_results(0), m_redirects(0) { } QString IndependentFeedRequest::errorString() const { return m_errorString; } void IndependentFeedRequest::setErrorString(const QString &e) { m_errorString = e; #ifdef INDEPENDENT_DEBUG if (!e.isEmpty()) { qDebug() << "IndependentFeedRequest::error." << e; } #endif } QByteArray IndependentFeedRequest::result() const { return m_buffer.data(); } void IndependentFeedRequest::setResult(const QByteArray &r) { m_buffer.open(QBuffer::WriteOnly); m_buffer.write(r); m_buffer.close(); } FeedRequest::Status IndependentFeedRequest::status() const { return m_status; } void IndependentFeedRequest::setStatus(FeedRequest::Status s) { if (s != status()) { m_status = s; emit statusChanged(s); } } bool IndependentFeedRequest::cancel() { if (status() == Active) { if ((m_request) && (m_request->status() == ArticleRequest::Active)) { m_request->cancel(); } else { setStatus(Canceled); emit finished(this); } } return true; } bool IndependentFeedRequest::getFeed(const QVariantMap &settings) { if (status() == Active) { return false; } setStatus(Active); setResult(QByteArray()); setErrorString(QString()); m_settings = settings; m_results = 0; m_redirects = 0; QString url(BASE_URL); const QString section = m_settings.value("section").toString(); if (!section.isEmpty()) { url.append("/"); url.append(section); } url.append("/rss"); #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::getFeed(). URL:" << url; #endif QNetworkRequest request(url); request.setRawHeader("User-Agent", USER_AGENT); QNetworkReply *reply = networkAccessManager()->get(request); connect(reply, SIGNAL(finished()), this, SLOT(checkFeed())); connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater())); return true; } void IndependentFeedRequest::checkFeed() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) { setErrorString(tr("Network error")); setStatus(Error); emit finished(this); return; } const QString redirect = getRedirect(reply); if (!redirect.isEmpty()) { if (m_redirects < MAX_REDIRECTS) { reply->deleteLater(); followRedirect(redirect, SLOT(checkFeed())); } else { setErrorString(tr("Maximum redirects reached")); setStatus(Error); emit finished(this); } return; } switch (reply->error()) { case QNetworkReply::NoError: break; case QNetworkReply::OperationCanceledError: setStatus(Canceled); emit finished(this); return; default: setErrorString(reply->errorString()); setStatus(Error); emit finished(this); return; } m_parser.setContent(reply->readAll()); if (m_parser.readChannel()) { writeStartFeed(); writeFeedTitle(m_parser.title()); writeFeedUrl(m_parser.url()); const bool fetchFullArticle = m_settings.value("fetchFullArticle", true).toBool(); const QDateTime lastUpdated = m_settings.value("lastUpdated").toDateTime(); if (fetchFullArticle) { if (m_parser.readNextArticle()) { if (m_parser.date() > lastUpdated) { reply->deleteLater(); getArticle(m_parser.url()); } else { writeEndFeed(); setStatus(Ready); emit finished(this); } return; } writeEndFeed(); } else { const int max = m_settings.value("maxResults", 20).toInt(); while((m_results < max) && (m_parser.readNextArticle()) && (m_parser.date() > lastUpdated)) { ++m_results; writeStartItem(); writeItemAuthor(m_parser.author()); writeItemBody(m_parser.description()); writeItemCategories(m_parser.categories()); writeItemDate(m_parser.date()); writeItemEnclosures(m_parser.enclosures()); writeItemTitle(m_parser.title()); writeItemUrl(m_parser.url()); writeEndItem(); } writeEndFeed(); setStatus(Ready); emit finished(this); return; } } setErrorString(m_parser.errorString()); setStatus(Error); emit finished(this); } void IndependentFeedRequest::getArticle(const QString &url) { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::getArticle(). URL:" << url; #endif articleRequest()->getArticle(url, m_settings); } void IndependentFeedRequest::checkArticle(ArticleRequest *request) { if (request->status() == ArticleRequest::Canceled) { setStatus(Canceled); emit finished(this); return; } ++m_results; if (request->status() == ArticleRequest::Ready) { const ArticleResult article = request->result(); writeStartItem(); writeItemAuthor(article.author.isEmpty() ? m_parser.author() : article.author); writeItemBody(article.body.isEmpty() ? m_parser.description() : article.body); writeItemCategories(article.categories.isEmpty() ? m_parser.categories() : article.categories); writeItemDate(article.date.isNull() ? m_parser.date() : article.date); writeItemEnclosures(article.enclosures.isEmpty() ? m_parser.enclosures() : article.enclosures); writeItemTitle(article.title.isEmpty() ? m_parser.title() : article.title); writeItemUrl(article.url.isEmpty() ? m_parser.url() : article.url); writeEndItem(); } #ifdef INDEPENDENT_DEBUG else { qDebug() << "IndependentFeedRequest::checkArticle(). Error:" << request->errorString(); } #endif if ((m_results < m_settings.value("maxResults", 20).toInt()) && (m_parser.readNextArticle()) && (m_parser.date() > m_settings.value("lastUpdated").toDateTime())) { getArticle(m_parser.url()); return; } #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::checkArticle(). No more new articles"; #endif writeEndFeed(); setStatus(Ready); emit finished(this); } void IndependentFeedRequest::followRedirect(const QString &url, const char *slot) { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::followRedirect(). URL:" << url; #endif ++m_redirects; QNetworkRequest request(url); request.setRawHeader("User-Agent", USER_AGENT); QNetworkReply *reply = networkAccessManager()->get(request); connect(reply, SIGNAL(finished()), this, slot); connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater())); } QString IndependentFeedRequest::getRedirect(const QNetworkReply *reply) { QString redirect = QString::fromUtf8(reply->rawHeader("Location")); if ((!redirect.isEmpty()) && (!redirect.startsWith("http"))) { const QUrl url = reply->url(); if (redirect.startsWith("/")) { redirect.prepend(url.scheme() + "://" + url.authority()); } else { redirect.prepend(url.scheme() + "://" + url.authority() + "/"); } } return redirect; } void IndependentFeedRequest::writeStartFeed() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeStartFeed()"; #endif m_buffer.open(QBuffer::WriteOnly); m_writer.setDevice(&m_buffer); m_writer.writeStartDocument(); m_writer.writeStartElement("rss"); m_writer.writeAttribute("version", "2.0"); m_writer.writeAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/"); m_writer.writeAttribute("xmlns:content", "http://purl.org/rss/1.0/modules/content/"); m_writer.writeStartElement("channel"); m_writer.writeTextElement("description", tr("News articles from The Independent")); m_writer.writeStartElement("image"); m_writer.writeTextElement("url", ICON_URL); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeEndFeed() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeEndFeed()"; #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeEndElement(); m_writer.writeEndElement(); m_writer.writeEndDocument(); m_buffer.close(); } void IndependentFeedRequest::writeFeedTitle(const QString &title) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("title"); m_writer.writeCDATA(title); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeFeedUrl(const QString &url) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("link", url); m_buffer.close(); } void IndependentFeedRequest::writeStartItem() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeStartItem(). Item" << m_results << "of" << m_settings.value("maxResults", 20).toInt(); #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("item"); m_buffer.close(); } void IndependentFeedRequest::writeEndItem() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeEndItem(). Item" << m_results << "of" << m_settings.value("maxResults", 20).toInt(); #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemAuthor(const QString &author) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("dc:creator", author); m_buffer.close(); } void IndependentFeedRequest::writeItemBody(const QString &body) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("content:encoded"); m_writer.writeCDATA(body); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemCategories(const QStringList &categories) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); foreach (const QString &category, categories) { m_writer.writeTextElement("category", category); } m_buffer.close(); } void IndependentFeedRequest::writeItemDate(const QDateTime &date) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("dc:date", date.toString(Qt::ISODate)); m_buffer.close(); } void IndependentFeedRequest::writeItemEnclosures(const QVariantList &enclosures) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); foreach (const QVariant &e, enclosures) { const QVariantMap enclosure = e.toMap(); m_writer.writeStartElement("enclosure"); m_writer.writeAttribute("url", enclosure.value("url").toString()); m_writer.writeAttribute("type", enclosure.value("type").toString()); m_writer.writeEndElement(); } m_buffer.close(); } void IndependentFeedRequest::writeItemTitle(const QString &title) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("title"); m_writer.writeCDATA(title); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemUrl(const QString &url) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("link", url); m_buffer.close(); } IndependentArticleRequest* IndependentFeedRequest::articleRequest() { if (!m_request) { m_request = new IndependentArticleRequest(this); connect(m_request, SIGNAL(finished(ArticleRequest*)), this, SLOT(checkArticle(ArticleRequest*))); } return m_request; } QNetworkAccessManager* IndependentFeedRequest::networkAccessManager() { if (!m_nam) { m_nam = new QNetworkAccessManager(this); } return m_nam; }
marxoft/cutenews
plugins/independent/independentfeedrequest.cpp
C++
gpl-3.0
13,483
{% if unique_login_provider %} <form id="signin-form" method="post" action="{{ settings.LOGIN_URL }}"> {{ macros.csrf_middleware_token(csrf_token) }} {{ login_form.next }} {{ login_form.persona_assertion }} <input type='hidden' name='login_provider_name' value='{{ unique_login_provider.name }}' /> <input name="{{ unique_login_provider.name }}" type="submit" class="{{ unique_login_provider.type }}" value="{% trans login_name=unique_login_provider.name|capitalize %}Sign in via {{ login_name }}{% endtrans %}" /> </form> {% else %} <a href="{{ settings.LOGIN_URL }}?next={{ request.path|clean_login_url|escape }}" >{% trans %}Hi there! Please sign in{% endtrans %}</a> {% endif %}
divio/askbot-devel
askbot/templates/widgets/login_link.html
HTML
gpl-3.0
832
--- title: 通天仙路 第四百八十四章 改朝换代? date: 2017-05-20 01:00:05 categories: 通天仙路 tags: [Duke, Hannb] --- “方前辈,您有什么事情么?”欧阳明转身,冷下了脸,连客套也没有,就开门见山地说道。? ? ? 以他和方家的交情,本不应该如此势利。但是,惊扰到老匠头就非他所愿了。 方朝阳苦着脸道:“欧大师,老夫确实是有要事相商。”他顿了顿,低声道:“若是可以的话,景深兄也会来此的。” 欧阳明讶然望去,心中第一次正视起来。 这里是倪家府邸,倪景深不直接登门,却派方朝阳迂回求见,确实让人难以理解。他沉吟片刻,道:“也好,请随我来。”提着鸟笼子,回到了房间之中,欧阳明轻轻地将笼子放下。 大黄鬼头鬼脑地张望了过来,欧阳明好笑道:“进来吧。” 大黄兴奋地叫了一声,双足用力一跳,顿时进入其中,只是它依旧不敢朝着小鸟儿的方向张望。 虽然它并不知道小鸟儿凤族强者的身份,但血脉传承中对于危险的警惕,却让它做出了最佳选择。 欧阳明沉声道:“方前辈,倪老应该到了,你们有什么事情,请直说吧。” “呵呵,欧小友竟然听出老夫的声音,真是让老夫汗颜啊。”随着一道轻笑声,倪景深身形闪动,已经是无声无息地进入其中。 欧阳明一看他的模样顿时明白,他是瞒着下人偷偷潜入的。只是,让这位极道老祖如此谨慎的,又会是什么事情呢? “欧小友。”倪景深满脸笑容地道:“老夫冒昧前来,你可不要见怪啊。” 欧阳明微微一笑,坦然道:“前辈多虑了,有英姐在这儿,我可不敢放肆呢。” 倪景深老怀大慰,道:“英鸿能够得到小友垂怜,真是她的幸运啊。” 欧阳明脸色一正,道:“倪老错了。” “啊,什么?”倪景深讶然问道,那声音中竟然透着一丝紧张的感觉。 欧阳明正容道:“能够认识英姐,并且得到她的青睐,是我的幸运。” 倪景深愣了半晌,不由得苦笑连连,不过心中却是愈的笃定了。既然欧阳明对英鸿如此牵挂,那么就算他所说的事情惹恼了欧阳明,他也不至于翻脸不认人吧。 “倪老,方前辈,两位联袂来此,不知有何要事,请说。”欧阳明肃然说道,他已经三番五次提及,若是这两位再打哈哈,欧阳明也没有多少耐心了。 倪景深和方朝阳对望了一眼,他们微微点头。 “咳咳,欧小友,你如今已经降服了走兽族和飞禽族的两位灵兽,不知下一步有何打算呢?”倪景深沉声问道。 欧阳明毫不犹豫地道:“如果不出意外,我想要到沧海郡走一遭。”他淡淡地道:“据说那儿的海族已经开始肆虐,既然如此,早点平息了省得麻烦。” 人族八郡,如今唯一还在遭受劫难的,就唯有沧海平海两郡了。不过相比之下,沧海郡才是水族攻击的方向,如果欧阳明要平乱,自然要走沧海郡了。 倪景深和方朝阳面面相觑,两个人的眼眸中都有着一种诡异之色。 八郡劫难,那可是人族大劫啊,每一次大劫兴起,都会给人族带来巨大的伤亡。哪怕各郡都有着杀手锏存在,但也必须付出足够的代价才能够将劫难消弭无形。 可是,听听欧阳明的那番话,似乎人族大劫根本就没有放在他的眼中,仿佛只要他过去了,举手投足间便能安定天下,剿灭水族。 如果其他人这么说,这两位极道老祖绝对是立即翻脸。 可是,他们的目光在大黄的身上一瞥,再想想门外的那只苍鹰,以及远方尚未回来的多臂金刚之时,竟然是由衷地泛起了一种深深的无力感。 是啊,在不知不觉中,欧阳明已经掌握了那么强大的实力,这水族大劫,似乎真的不用被他放在眼中了。 而事实上,这两位并不知道,此刻欧阳明本身的实力已经足以平定这场大劫了。而且,那笼子中的小红鸟儿才是欧阳明最大的底牌呢。 凤族,虽然并不是水族之王,但想要叼一条小鱼尝尝鲜,也绝不是什么难事。 欧阳明眉头略皱,道:“两位莫非有什么高见么?” 倪景深如梦惊醒般的道:“高见不敢当,哎,就是有一些话请欧小友考虑一二。” 欧阳明微笑着道:“倪老请讲。” 倪景深双目中陡然闪过了一道凌厉之色,道:“欧小友,如今你手头上的实力,已经强大得可以与皇室抗衡了吧。” 欧阳明心中微动,暗道,何止是抗衡啊,若是真的与皇室生冲突,哪怕是杀入皇室秘境,也能够将他们全部灭杀了吧。 皇室的实力虽然极为强大,但真正能够越极道境界的强者,却仅有待在秘境之中,不敢轻易离开的武元伟而已。而以欧阳明此刻所拥有的实力,哪怕不动用小红鸟儿这张底牌,也足以将皇族灭绝了。 不过,他并没有直接回答,而是道:“皇室有着人族第一强者坐镇,还有着秘境加成,而在下根基浅薄,未必就能胜得了皇室。” 他这句话虽然不尽不实,但是在倪景深两人耳中听来,却是相当的诚恳。 皇室之强大,可是有着千年的积累,欧阳明虽然崛起迅,但要说他能够轻易碾压皇室,却也无人可信。 倪景深微微地点着头,道:“欧小友所言极是,就算你能够灭杀皇族第一人,他们也会请动上界强者降临,那时候就不免大祸临头了。” “噗……”小鸟儿突地在鸟笼中出了一道古怪的声音。 倪景深和方朝阳不约而同地看了过去,都是一脸的惊讶之色。 欧阳明用警告的眼神瞥了眼小鸟儿,连忙道:“是啊,皇族的实力深不可测。不过,在下想不出,他们就算有着强大的实力,与我又有什么关系?” 倪景深的眼眸顿时亮了起来,他低声道:“欧小友,难道你就没有一点想法么?” 欧阳明瞪着他的眼睛,慢慢地道:“什么想法?” 倪景深犹豫片刻,终于是忍耐不住,道:“改朝换代啊!” 他先前一直遮遮掩掩,直到此刻一口气说出来,那悬着的心才真正放下。而且,既然已经说出了这句话,就等于是射出的箭,再也没有回头和转圜的余地了。 方朝阳在一旁也是重重地一点头,道:“武家坐镇天下,已经有千余年了,也是时候换一家了。” 欧阳明虽然早就有所猜测,但是当他真的听到这两位的提议之后,不由得也是脸色微变。 目光炯炯的看着这两位,欧阳明沉声道:“两位,你们不是开玩笑吧?” 倪景深哑然失笑,道:“欧小友,你以为在这件事情上,我们会开玩笑么?” 欧阳明的眉头略皱,看着他们两人眼眸中那期待的眼神,不由得心中嘀咕,他们在搞什么鬼。 仿佛是看出了欧阳明的顾虑,倪景深肃然道:“欧小友,你尽管放心,只要我们能够击败皇室,他们上界的援军就肯定不会到来!” 欧阳明微怔,讶然问道:“什么?” 方朝阳神神秘秘地道:“皇室有上界靠山,我们也有啊!” 欧阳明的眼神一凝,望着他们半晌,叹道:“两位,如今人族大劫尚未过去,你们突然提及此事,不觉得有些过分么?” 倪景深脸上闪过了一抹红晕,但立即道:“欧小友,如果是往日,我等绝不会如此行事。但是这一次情况不同了……”他瞅了眼大黄,道:“欧小友你横空出世,不仅仅降服了两头灵兽,而且还击杀了虫族灵兽,只要再往沧海郡走一遭,人族大劫就将平复。呵呵,历代以来,我们人族应付大劫之时,都是损兵折将。但这一次却是平淡而过,令人喜不自禁啊。” 欧阳明苦笑一声,道:“倪老,城中伤亡之人众多,怎么能说是平淡而过?” 倪景深面不改色,道:“若是与以往相比,确实称得上了。” 方朝阳也是在一旁推波助澜,道:“欧大师,人无伤虎之心,虎有伤人之意啊。就算你没有取代皇室的念头,但你在这一次立下了赫赫战功,并且降服了两头灵兽。嘿嘿,您以为,皇室还会放心么?” “不错,就算他们忌惮你所拥有的实力,不敢正面抗衡,但肯定会设局针对。”倪景深肃然道:“若是他们请你进入秘境,并且在秘境中请到上界强者降临,那么就算你有着两只灵兽相助,怕也是难以抵抗了。” 欧阳明心中微动,尚未回答,就听到小鸟儿再度出了讥讽嘲弄之音。 区区上界之人,又有什么了不起,只要老子在此,来一个杀一个,来两个杀一双! 不过,它的话除了欧阳明之外,倪景深两人却是一无所知。 欧阳明无奈地长叹一声,他突然现,在谈论这些事情的时候,让小鸟儿在一旁,绝对是一个天大的错误。 这小家伙,在这种场合中只会给自己添麻烦。 只是,欧阳明虽然没有颠覆皇室之心,但被这两位提及之后,心中多多少少都有着一份警惕了。 (三七中文 www.37zw.net
1xuanyuan1/noval
source/_posts/通天仙路 第四百八十四章 改朝换代?.md
Markdown
gpl-3.0
9,366
package com.dmtools.webapp.config; import com.dmtools.webapp.config.locale.AngularCookieLocaleResolver; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocaleConfiguration extends WebMvcConfigurerAdapter implements EnvironmentAware { @SuppressWarnings("unused") private RelaxedPropertyResolver propertyResolver; @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messages."); } @Bean(name = "localeResolver") public LocaleResolver localeResolver() { AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); } }
jero-rodriguez/dmtools
src/main/java/com/dmtools/webapp/config/LocaleConfiguration.java
Java
gpl-3.0
1,616
/** * This class is generated by jOOQ */ package com.aviafix.db.generated.tables.pojos; import java.io.Serializable; import java.time.LocalDate; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class PAYBYCREDITCARDPROJECTION implements Serializable { private static final long serialVersionUID = 1444342293; private Integer ETID; private Integer CREDITCARDNUM; private LocalDate EXPDATE; private Integer CODE; private String CARDHOLDERNAME; private Double AMOUNT; public PAYBYCREDITCARDPROJECTION() {} public PAYBYCREDITCARDPROJECTION(PAYBYCREDITCARDPROJECTION value) { this.ETID = value.ETID; this.CREDITCARDNUM = value.CREDITCARDNUM; this.EXPDATE = value.EXPDATE; this.CODE = value.CODE; this.CARDHOLDERNAME = value.CARDHOLDERNAME; this.AMOUNT = value.AMOUNT; } public PAYBYCREDITCARDPROJECTION( Integer ETID, Integer CREDITCARDNUM, LocalDate EXPDATE, Integer CODE, String CARDHOLDERNAME, Double AMOUNT ) { this.ETID = ETID; this.CREDITCARDNUM = CREDITCARDNUM; this.EXPDATE = EXPDATE; this.CODE = CODE; this.CARDHOLDERNAME = CARDHOLDERNAME; this.AMOUNT = AMOUNT; } public Integer ETID() { return this.ETID; } public void ETID(Integer ETID) { this.ETID = ETID; } public Integer CREDITCARDNUM() { return this.CREDITCARDNUM; } public void CREDITCARDNUM(Integer CREDITCARDNUM) { this.CREDITCARDNUM = CREDITCARDNUM; } public LocalDate EXPDATE() { return this.EXPDATE; } public void EXPDATE(LocalDate EXPDATE) { this.EXPDATE = EXPDATE; } public Integer CODE() { return this.CODE; } public void CODE(Integer CODE) { this.CODE = CODE; } public String CARDHOLDERNAME() { return this.CARDHOLDERNAME; } public void CARDHOLDERNAME(String CARDHOLDERNAME) { this.CARDHOLDERNAME = CARDHOLDERNAME; } public Double AMOUNT() { return this.AMOUNT; } public void AMOUNT(Double AMOUNT) { this.AMOUNT = AMOUNT; } @Override public String toString() { StringBuilder sb = new StringBuilder("PAYBYCREDITCARDPROJECTION ("); sb.append(ETID); sb.append(", ").append(CREDITCARDNUM); sb.append(", ").append(EXPDATE); sb.append(", ").append(CODE); sb.append(", ").append(CARDHOLDERNAME); sb.append(", ").append(AMOUNT); sb.append(")"); return sb.toString(); } }
purple-sky/avia-fixers
app/src/main/java/com/aviafix/db/generated/tables/pojos/PAYBYCREDITCARDPROJECTION.java
Java
gpl-3.0
2,891
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>src\fork\box2d\collision\b2Manifold.js - Box2D Port Fork API</title> <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css"> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="stylesheet" href="../assets/css/main.css" id="site_styles"> <link rel="shortcut icon" type="image/png" href="../assets/favicon.png"> <script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script> </head> <body class="yui3-skin-sam"> <div id="doc"> <div id="hd" class="yui3-g header"> <div class="yui3-u-3-4"> <h1><img src="../assets/css/logo.png" title="Box2D Port Fork API"></h1> </div> <div class="yui3-u-1-4 version"> <em>API Docs for: 1.0.0</em> </div> </div> <div id="bd" class="yui3-g"> <div class="yui3-u-1-4"> <div id="docs-sidebar" class="sidebar apidocs"> <div id="api-list"> <h2 class="off-left">APIs</h2> <div id="api-tabview" class="tabview"> <ul class="tabs"> <li><a href="#api-classes">Classes</a></li> <li><a href="#api-modules">Modules</a></li> </ul> <div id="api-tabview-filter"> <input type="search" id="api-filter" placeholder="Type to filter APIs"> </div> <div id="api-tabview-panel"> <ul id="api-classes" class="apis classes"> <li><a href="../classes/b2AABB.html">b2AABB</a></li> <li><a href="../classes/b2Body.html">b2Body</a></li> <li><a href="../classes/b2BodyDef.html">b2BodyDef</a></li> <li><a href="../classes/b2Bound.html">b2Bound</a></li> <li><a href="../classes/b2BoundValues.html">b2BoundValues</a></li> <li><a href="../classes/b2BoxDef.html">b2BoxDef</a></li> <li><a href="../classes/b2BufferedPair.html">b2BufferedPair</a></li> <li><a href="../classes/b2CircleContact.html">b2CircleContact</a></li> <li><a href="../classes/b2CircleDef.html">b2CircleDef</a></li> <li><a href="../classes/b2CircleShape.html">b2CircleShape</a></li> <li><a href="../classes/b2Collision.html">b2Collision</a></li> <li><a href="../classes/b2CollisionFilter.html">b2CollisionFilter</a></li> <li><a href="../classes/b2Conservative.html">b2Conservative</a></li> <li><a href="../classes/b2Contact.html">b2Contact</a></li> <li><a href="../classes/b2ContactConstraint.html">b2ContactConstraint</a></li> <li><a href="../classes/b2ContactConstraintPoint.html">b2ContactConstraintPoint</a></li> <li><a href="../classes/b2ContactID.html">b2ContactID</a></li> <li><a href="../classes/b2ContactManager.html">b2ContactManager</a></li> <li><a href="../classes/b2ContactNode.html">b2ContactNode</a></li> <li><a href="../classes/b2ContactPoint.html">b2ContactPoint</a></li> <li><a href="../classes/b2ContactRegister.html">b2ContactRegister</a></li> <li><a href="../classes/b2ContactSolver.html">b2ContactSolver</a></li> <li><a href="../classes/b2Distance.html">b2Distance</a></li> <li><a href="../classes/b2DistanceJoint.html">b2DistanceJoint</a></li> <li><a href="../classes/b2DistanceJointDef.html">b2DistanceJointDef</a></li> <li><a href="../classes/b2GearJoint.html">b2GearJoint</a></li> <li><a href="../classes/b2GearJointDef.html">b2GearJointDef</a></li> <li><a href="../classes/b2Island.html">b2Island</a></li> <li><a href="../classes/b2Jacobian.html">b2Jacobian</a></li> <li><a href="../classes/b2Joint.html">b2Joint</a></li> <li><a href="../classes/b2JointDef.html">b2JointDef</a></li> <li><a href="../classes/b2JointNode.html">b2JointNode</a></li> <li><a href="../classes/b2Manifold.html">b2Manifold</a></li> <li><a href="../classes/b2MassData.html">b2MassData</a></li> <li><a href="../classes/b2Mat22.html">b2Mat22</a></li> <li><a href="../classes/b2Math.html">b2Math</a></li> <li><a href="../classes/b2MouseJoint.html">b2MouseJoint</a></li> <li><a href="../classes/b2MouseJointDef.html">b2MouseJointDef</a></li> <li><a href="../classes/b2NullContact.html">b2NullContact</a></li> <li><a href="../classes/b2OBB.html">b2OBB</a></li> <li><a href="../classes/b2Pair.html">b2Pair</a></li> <li><a href="../classes/b2PairCallback.html">b2PairCallback</a></li> <li><a href="../classes/b2PairManager.html">b2PairManager</a></li> <li><a href="../classes/b2PolyAndCircleContact.html">b2PolyAndCircleContact</a></li> <li><a href="../classes/b2PolyContact.html">b2PolyContact</a></li> <li><a href="../classes/b2PolyDef.html">b2PolyDef</a></li> <li><a href="../classes/b2PolyShape.html">b2PolyShape</a></li> <li><a href="../classes/b2PrismaticJoint.html">b2PrismaticJoint</a></li> <li><a href="../classes/b2PrismaticJointDef.html">b2PrismaticJointDef</a></li> <li><a href="../classes/b2Proxy.html">b2Proxy</a></li> <li><a href="../classes/b2PulleyJoint.html">b2PulleyJoint</a></li> <li><a href="../classes/b2PulleyJointDef.html">b2PulleyJointDef</a></li> <li><a href="../classes/b2RevoluteJoint.html">b2RevoluteJoint</a></li> <li><a href="../classes/b2RevoluteJointDef.html">b2RevoluteJointDef</a></li> <li><a href="../classes/b2Settings.html">b2Settings</a></li> <li><a href="../classes/b2Shape.html">b2Shape</a></li> <li><a href="../classes/b2ShapeDef.html">b2ShapeDef</a></li> <li><a href="../classes/b2TimeStep.html">b2TimeStep</a></li> <li><a href="../classes/b2Vec2.html">b2Vec2</a></li> <li><a href="../classes/b2World.html">b2World</a></li> <li><a href="../classes/b2WorldListener.html">b2WorldListener</a></li> <li><a href="../classes/ClipVertex.html">ClipVertex</a></li> <li><a href="../classes/Features.html">Features</a></li> </ul> <ul id="api-modules" class="apis modules"> </ul> </div> </div> </div> </div> </div> <div class="yui3-u-3-4"> <div id="api-options"> Show: <label for="api-show-inherited"> <input type="checkbox" id="api-show-inherited" checked> Inherited </label> <label for="api-show-protected"> <input type="checkbox" id="api-show-protected"> Protected </label> <label for="api-show-private"> <input type="checkbox" id="api-show-private"> Private </label> <label for="api-show-deprecated"> <input type="checkbox" id="api-show-deprecated"> Deprecated </label> </div> <div class="apidocs"> <div id="docs-main"> <div class="content"> <h1 class="file-heading">File: src\fork\box2d\collision\b2Manifold.js</h1> <div class="file"> <pre class="code prettyprint linenums"> /* * Copyright (c) 2006-2007 Erin Catto http: * * This software is provided &#x27;as-is&#x27;, 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, and must not be * misrepresented the original software. * 3. This notice may not be removed or altered from any source distribution. */ /** * A manifold for two touching convex shapes. * * @class b2Manifold * @constructor */ var b2Manifold = function () { this.points = new Array(b2Settings.b2_maxManifoldPoints); for (var i = 0; i &lt; b2Settings.b2_maxManifoldPoints; i++){ this.points[i] = new b2ContactPoint(); } this.normal = new b2Vec2(); }; b2Manifold.prototype = { points: null, normal: null, pointCount: 0 }; </pre> </div> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> <script src="../assets/js/yui-prettify.js"></script> <script src="../assets/../api.js"></script> <script src="../assets/js/api-filter.js"></script> <script src="../assets/js/api-list.js"></script> <script src="../assets/js/api-search.js"></script> <script src="../assets/js/apidocs.js"></script> </body> </html>
PixxxeL/box2d-js-port-fork
docs/files/src_fork_box2d_collision_b2Manifold.js.html
HTML
gpl-3.0
10,434
from test_support import * # this test calls a prover which is correctly configured but whose execution # gives an error (here: the prover executable doesn't exist). The intent is to # test the output of gnatprove in this specific case prove_all(prover=["plop"], opt=["--why3-conf=test.conf"])
ptroja/spark2014
testsuite/gnatprove/tests/N804-036__bad_prover/test.py
Python
gpl-3.0
296
import altConnect from 'higher-order-components/altConnect'; import { STATUS_OK } from 'app-constants'; import ItemStore from 'stores/ItemStore'; import ProgressBar from '../components/ProgressBar'; const mapStateToProps = ({ itemState }) => ({ progress: itemState.readingPercentage, hidden: itemState.status !== STATUS_OK, }); mapStateToProps.stores = { ItemStore }; export default altConnect(mapStateToProps)(ProgressBar); // WEBPACK FOOTER // // ./src/js/app/modules/item/containers/ProgressBarContainer.js
BramscoChill/BlendleParser
information/blendle-frontend-react-source/app/modules/item/containers/ProgressBarContainer.js
JavaScript
gpl-3.0
518
/* * Author: Bob Limnor ([email protected]) * Project: Limnor Studio * Item: Visual Programming Language Implement * License: GNU General Public License v3.0 */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using VPL; namespace LimnorDesigner { /// <summary> /// load primary types and Type into the treeview for selection for creating Attribute /// </summary> public partial class TypeSelector : UserControl { public Type SelectedType; IWindowsFormsEditorService _svc; public TypeSelector() { InitializeComponent(); } public void LoadAttributeParameterTypes(IWindowsFormsEditorService service, EnumWebRunAt runAt, Type initSelection) { _svc = service; treeView1.LoadAttributeParameterTypes(runAt, initSelection); treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); treeView1.Click += new EventHandler(treeView1_Click); treeView1.KeyPress += new KeyPressEventHandler(treeView1_KeyPress); } void treeView1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { if (_svc != null) { _svc.CloseDropDown(); } } } void treeView1_Click(object sender, EventArgs e) { if (_svc != null) { _svc.CloseDropDown(); } } void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { TreeNodeClassType tnct = e.Node as TreeNodeClassType; if (tnct != null) { SelectedType = tnct.OwnerDataType; } } public static Bitmap GetTypeImageByName(string name) { if (string.CompareOrdinal("Number", name) == 0) { return Resources._decimal; } if (string.CompareOrdinal("String", name) == 0) { return Resources.abc; } if (string.CompareOrdinal("Array", name) == 0) { return Resources._array.ToBitmap(); } if (string.CompareOrdinal("DateTime", name) == 0) { return Resources.date; } if (string.CompareOrdinal("TimeSpan", name) == 0) { return Resources.date; } return Resources._decimal; } public static TypeSelector GetAttributeParameterDialogue(IWindowsFormsEditorService service, EnumWebRunAt runAt, Type initSelection) { TypeSelector dlg = new TypeSelector(); dlg.LoadAttributeParameterTypes(service, runAt, initSelection); return dlg; } } }
Limnor/Limnor-Studio-Source-Code
Source/LimnorDesigner/TypeSelector.cs
C#
gpl-3.0
2,549
/* ComJail - A jail plugin for Minecraft servers Copyright (C) 2015 comdude2 (Matt Armer) 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/>. Contact: [email protected] */ package net.mcviral.dev.plugins.comjail.events; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; import net.mcviral.dev.plugins.comjail.main.JailController; public class TeleportEvent implements Listener{ @SuppressWarnings("unused") private Plugin plugin; private JailController jailcontroller; public TeleportEvent(Plugin mplugin, JailController mjailcontroller){ plugin = mplugin; jailcontroller = mjailcontroller; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerTeleport(PlayerTeleportEvent event){ if (jailcontroller.isJailed(event.getPlayer().getUniqueId())){ if (!event.getPlayer().hasPermission("jail.override")){ event.setCancelled(true); event.getPlayer().sendMessage("[" + ChatColor.BLUE + "GUARD" + ChatColor.WHITE + "] " + ChatColor.RED + "You are jailed, you may not teleport."); } } } }
comdude2/ComJail
src/net/mcviral/dev/plugins/comjail/events/TeleportEvent.java
Java
gpl-3.0
1,828
package se.solit.timeit.resources; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpSession; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class BaseResource { protected WebApplicationException redirect(String destination) throws URISyntaxException { URI uri = new URI(destination); Response response = Response.seeOther(uri).build(); return new WebApplicationException(response); } /** * Set message to show the message in the next shown View. * * @param session * @param message */ protected void setMessage(HttpSession session, String message) { session.setAttribute("message", message); } }
Hoglet/TimeIT-Server
src/main/java/se/solit/timeit/resources/BaseResource.java
Java
gpl-3.0
703
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.3/15.3.2/15.3.2.1/15.3.2.1-11-8-s.js * @description Strict Mode - SyntaxError is not thrown if a function is created using a Function constructor that has two identical parameters, which are separated by a unique parameter name and there is no explicit 'use strict' in the function constructor's body * @onlyStrict */ function testcase() { "use strict"; var foo = new Function("baz", "qux", "baz", "return 0;"); return true; } runTestCase(testcase);
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.3/15.3.2/15.3.2.1/15.3.2.1-11-8-s.js
JavaScript
gpl-3.0
881
/* * This file is part of rasdaman community. * * Rasdaman community 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. * * Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <[email protected]>. */ package petascope.wcs2.handlers; import static petascope.wcs2.extensions.FormatExtension.MIME_XML; /** * Bean holding the response from executing a request operation. * * @author <a href="mailto:[email protected]">Dimitar Misev</a> */ public class Response { private final byte[] data; private final String xml; private final String mimeType; private final int exit_code; private static final int DEFAULT_CODE = 200; // constructrs public Response(byte[] data) { this(data, null, null, DEFAULT_CODE); } public Response(byte[] data, int code) { this(data, null, null, code); } public Response(String xml) { this(null, xml, null); //FormatExtension.MIME_GML); } public Response(String xml, int code) { this(null, xml, MIME_XML, code); } public Response(byte[] data, String xml, String mimeType) { this(data, xml, mimeType, DEFAULT_CODE); } public Response(byte[] data, String xml, String mimeType, int code) { this.data = data; this.xml = xml; this.mimeType = mimeType; this.exit_code = code; } // interface public byte[] getData() { return data; } public String getMimeType() { return mimeType; } public String getXml() { return xml; } public int getExitCode() { return exit_code; } }
miracee/rasdaman
applications/petascope/src/main/java/petascope/wcs2/handlers/Response.java
Java
gpl-3.0
2,322
function createCategorySlider(selector) { $(document).ready(function(){ var checkforloadedcats = []; var firstImage = $(selector).find('img').filter(':first'); if(firstImage.length > 0){ checkforloadedcats[selector] = setInterval(function() { var image = firstImage.get(0); if (image.complete || image.readyState == 'complete' || image.readyState == 4) { clearInterval(checkforloadedcats[selector]); $(selector).flexslider({ namespace: "", animation: "slide", easing: "easeInQuart", slideshow: false, animationLoop: false, animationSpeed: 700, pauseOnHover: true, controlNav: false, itemWidth: 238, minItems: flexmin, maxItems: flexmax, move: 0 }); } }, 20); } $(window).resize(function() { try { $(selector).flexslider(0); if($('#center_column').width()<=280){ $(selector).data('flexslider').setOpts({minItems: 1, maxItems: 1}); } else if($('#center_column').width()<=440){ $(selector).data('flexslider').setOpts({minItems: grid_size_ms, maxItems: grid_size_ms});} else if($('#center_column').width()<963){ $(selector).data('flexslider').setOpts({minItems: grid_size_sm, maxItems: grid_size_sm});} else if($('#center_column').width()>=1240){ $(selector).data('flexslider').setOpts({minItems: grid_size_lg, maxItems: grid_size_lg});} else if($('#center_column').width()>=963){ $(selector).data('flexslider').setOpts({minItems: grid_size_md, maxItems: grid_size_md});} } catch(e) { // handle all your exceptions here } }); }); }
desarrollosimagos/puroextremo.com.ve
modules/categoryslider/categoryslider.js
JavaScript
gpl-3.0
1,648
<?php /** * Skeleton subclass for performing query and update operations on the 'transaction' table. * * * * This class was autogenerated by Propel 1.4.2 on: * * Sun Jul 17 20:02:37 2011 * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package lib.model.basic */ class TransactionPeer extends BaseTransactionPeer { } // TransactionPeer
joseortega/finance
lib/model/basic/TransactionPeer.php
PHP
gpl-3.0
505
from itertools import combinations def is_good(n): return 1 + ((int(n) - 1) % 9) == 9 def generate_subsequences(n): subsequences = [] combinations_list = [] index = 4 #Generate all combinations while index > 0: combinations_list.append(list(combinations(str(n), index))) index -= 1 #Formatting combinations for index in combinations_list: for combination in index: subsequences.append(''.join(combination)) return subsequences if __name__ == '__main__': #The modulo modulo = ((10 ** 9) + 7) #Get number of cases cases = int(raw_input()) while cases > 0: value = raw_input() good_subsequences = 0 for sub in generate_subsequences(value): if is_good(sub): good_subsequences += 1 print (good_subsequences % modulo)-1 cases -= 1
Dawny33/Code
HackerEarth/BeCoder 2/nine.py
Python
gpl-3.0
882
<!-- This is a more advanced example of using the each function in jQuery. The idea here is that the handling function can choose to return false in which case the 'each' loop is stopped and no further DOM elements are processed. You can use this in order to find a specific element, process only a prefix of the elements and more. Mark Veltzer <[email protected]> --> <html> <head> <script src='/jquery.js'></script> <script> $(document).ready(function() { $('#mybutton').click(function() { $('li').each(function(index,element) { if(element!=this) { throw new String('what ?!?'); } $(this).text($(this).text()+'-'+index); if(Math.random()<0.2) { return false; } else { return true; } }); }); }); </script> </head> <body> <ul> <li>a</li> <li>b</li> <li>c</li> <li>d</li> <li>e</li> <li>f</li> <li>g</li> <li>h</li> <li>i</li> </ul> <button id='mybutton'>Push me to process <b>some</b> of the elements!</button> </body> </html>
veltzer/demos-javascript
src/jquery/examples/each2.html
HTML
gpl-3.0
1,063
#coding=utf-8 import unittest import HTMLTestRunner import time from config import globalparam from public.common import sendmail def run(): test_dir = './testcase' suite = unittest.defaultTestLoader.discover(start_dir=test_dir,pattern='test*.py') now = time.strftime('%Y-%m-%d_%H_%M_%S') reportname = globalparam.report_path + '\\' + 'TestResult' + now + '.html' with open(reportname,'wb') as f: runner = HTMLTestRunner.HTMLTestRunner( stream=f, title='测试报告', description='Test the import testcase' ) runner.run(suite) time.sleep(3) # 发送邮件 mail = sendmail.SendMail() mail.send() if __name__=='__main__': run()
lsp84ch83/PyText
UItestframework/run.py
Python
gpl-3.0
730
package com.hacks.collegebarter.fragments; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hacks.collegebarter.R; import com.hacks.collegebarter.navdrawer.MainAppActivity; public class TradeboardFragment extends Fragment{ public static final String ARG_SECTION_NUMBER = "section_number"; // Following constructor public TradeboardFragment() { Bundle bundle = new Bundle(); bundle.putInt(ARG_SECTION_NUMBER, 0); this.setArguments(bundle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tradeboard_fragment, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainAppActivity) activity).onSectionAttached(getArguments().getInt( ARG_SECTION_NUMBER)); } }
ReggieSackey/CollegeBarter
CollegeBarter/src/com/hacks/collegebarter/fragments/TradeboardFragment.java
Java
gpl-3.0
1,009
/* -*- c++ -*- */ /* * Copyright 2014 Felix Wunsch, Communications Engineering Lab (CEL) / Karlsruhe Institute of Technology (KIT). * * This 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, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DRM_GENERATE_FAC_VB_IMPL_H #define INCLUDED_DRM_GENERATE_FAC_VB_IMPL_H #include <drm/generate_fac_vb.h> #include "drm_util.h" namespace gr { namespace drm { class generate_fac_vb_impl : public generate_fac_vb { private: transm_params* d_tp; unsigned short d_tf_ctr; // transmission frame counter public: generate_fac_vb_impl(transm_params* tp); ~generate_fac_vb_impl(); void init_data(unsigned char* data); // set FAC bitstream according to config parameters (see DRM standard chapter 6.3) void increment_tf_ctr(); // increments tf_ctr and takes account of wraparound; // Where all the action really happens int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace drm } // namespace gr #endif /* INCLUDED_DRM_GENERATE_FAC_VB_IMPL_H */
marcusmueller/gr-drm
gr-drm/lib/generate_fac_vb_impl.h
C
gpl-3.0
1,753
# -*- coding: utf-8 -*- from pyload.plugin.internal.DeadCrypter import DeadCrypter class FiredriveCom(DeadCrypter): __name = "FiredriveCom" __type = "crypter" __version = "0.03" __pattern = r'https?://(?:www\.)?(firedrive|putlocker)\.com/share/.+' __config = [] #@TODO: Remove in 0.4.10 __description = """Firedrive.com folder decrypter plugin""" __license = "GPLv3" __authors = [("Walter Purcaro", "[email protected]")]
ardi69/pyload-0.4.10
pyload/plugin/crypter/FiredriveCom.py
Python
gpl-3.0
474
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Portal.BLL.Concrete.Multimedia.AdjusterParam; using Portal.BLL.Concrete.Multimedia.Adjusters; using Portal.BLL.Concrete.Multimedia.Builder; using Portal.Domain.BackendContext.Entity; namespace Portal.BLL.Tests.MultimediaTests { [TestClass] public class ProcessedScreenshotBuilderTest { [TestMethod] public void BuildProcessedScreenshotTest() { //Arrange const string imageFormat = "imageFormat"; const string contentType = "contentType"; var screenshotAdjuster = new Mock<IScreenshotAdjuster>(); var builder = new ProcessdScreenshotBuilder(screenshotAdjuster.Object); var screenshotAdjusterParam = new ScreenshotAdjusterParam(); var screenshotParm = new ScreenshotParam(); screenshotAdjuster.Setup(m => m.AdjustScreenshotParam(screenshotAdjusterParam)).Returns(screenshotParm); //Act var processedScreenshot = builder.BuildProcessedScreenshot(screenshotAdjusterParam, imageFormat, contentType); //Assert Assert.AreEqual(screenshotParm,processedScreenshot.ScreenshotParam); Assert.AreEqual(imageFormat, processedScreenshot.ImageFormat); Assert.AreEqual(contentType,processedScreenshot.ContentType); } } }
clickberry/video-portal
Tests/Portal.BLL.Tests/MultimediaTests/ProcessedScreenshotBuilderTest.cs
C#
gpl-3.0
1,410
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>GNU Radio 3.6.4.2 C++ API: gr_file_descriptor_source Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">GNU Radio 3.6.4.2 C++ API </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> </div> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> initNavTree('classgr__file__descriptor__source.html',''); </script> <div id="doc-content"> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pro-methods">Protected Member Functions</a> &#124; <a href="#friends">Friends</a> </div> <div class="headertitle"> <div class="title">gr_file_descriptor_source Class Reference<div class="ingroups"><a class="el" href="group__source__blk.html">Signal Sources</a></div></div> </div> </div><!--header--> <div class="contents"> <!-- doxytag: class="gr_file_descriptor_source" --><!-- doxytag: inherits="gr_sync_block" --> <p>Read stream from file descriptor. <a href="classgr__file__descriptor__source.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="gr__file__descriptor__source_8h_source.html">gr_file_descriptor_source.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for gr_file_descriptor_source:</div> <div class="dyncontent"> <div class="center"> <img src="classgr__file__descriptor__source.png" usemap="#gr_file_descriptor_source_map" alt=""/> <map id="gr_file_descriptor_source_map" name="gr_file_descriptor_source_map"> <area href="structgr__sync__block.html" alt="gr_sync_block" shape="rect" coords="0,56,158,80"/> <area href="structgr__block.html" alt="gr_block" shape="rect" coords="0,0,158,24"/> </map> </div></div> <p><a href="classgr__file__descriptor__source-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#a8553a2b7f53a6ffe8754860177c6a714">~gr_file_descriptor_source</a> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#a28a7c20d750296c73c14c1391605ab19">work</a> (int noutput_items, gr_vector_const_void_star &amp;input_items, gr_vector_void_star &amp;output_items)</td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">just like <a class="el" href="structgr__block.html#adf59080d10f322e3816b7ac8f7cb2a7c" title="compute output items from input items">gr_block::general_work</a>, only this arranges to call consume_each for you <a href="#a28a7c20d750296c73c14c1391605ab19"></a><br/></td></tr> <tr><td colspan="2"><h2><a name="pro-methods"></a> Protected Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#a18569b6c876227223e861d66c726218d">gr_file_descriptor_source</a> (size_t itemsize, int fd, <a class="el" href="stdbool_8h.html#a97a80ca1602ebf2303258971a2c938e2">bool</a> repeat)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#a19ace13388bd5037196b9ee4dce0543a">read_items</a> (char *buf, int nitems)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#af0f9a847bf3cb06905b587e47368340e">handle_residue</a> (char *buf, int nbytes_read)</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="volk_8tmpl_8h.html#a2b104da38b6f0a28d721ed74346ef298">void</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#a11599f25e05597bdda4f7e003435fecb">flush_residue</a> ()</td></tr> <tr><td colspan="2"><h2><a name="friends"></a> Friends</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <br class="typebreak"/> <a class="el" href="classboost_1_1shared__ptr.html">gr_file_descriptor_source_sptr</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__file__descriptor__source.html#ad2c64a0018c82cc0f6944632600fc6d4">gr_make_file_descriptor_source</a> (size_t itemsize, int fd, <a class="el" href="stdbool_8h.html#a97a80ca1602ebf2303258971a2c938e2">bool</a> repeat)</td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>Read stream from file descriptor. </p> </div><hr/><h2>Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="a18569b6c876227223e861d66c726218d"></a><!-- doxytag: member="gr_file_descriptor_source::gr_file_descriptor_source" ref="a18569b6c876227223e861d66c726218d" args="(size_t itemsize, int fd, bool repeat)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="classgr__file__descriptor__source.html#a18569b6c876227223e861d66c726218d">gr_file_descriptor_source::gr_file_descriptor_source</a> </td> <td>(</td> <td class="paramtype">size_t&#160;</td> <td class="paramname"><em>itemsize</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>fd</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="stdbool_8h.html#a97a80ca1602ebf2303258971a2c938e2">bool</a>&#160;</td> <td class="paramname"><em>repeat</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [protected]</code></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="a8553a2b7f53a6ffe8754860177c6a714"></a><!-- doxytag: member="gr_file_descriptor_source::~gr_file_descriptor_source" ref="a8553a2b7f53a6ffe8754860177c6a714" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="classgr__file__descriptor__source.html#a8553a2b7f53a6ffe8754860177c6a714">gr_file_descriptor_source::~gr_file_descriptor_source</a> </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <hr/><h2>Member Function Documentation</h2> <a class="anchor" id="a11599f25e05597bdda4f7e003435fecb"></a><!-- doxytag: member="gr_file_descriptor_source::flush_residue" ref="a11599f25e05597bdda4f7e003435fecb" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="volk_8tmpl_8h.html#a2b104da38b6f0a28d721ed74346ef298">void</a> <a class="el" href="classgr__file__descriptor__source.html#a11599f25e05597bdda4f7e003435fecb">gr_file_descriptor_source::flush_residue</a> </td> <td>(</td> <td class="paramname"></td><td>)</td> <td><code> [inline, protected]</code></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="af0f9a847bf3cb06905b587e47368340e"></a><!-- doxytag: member="gr_file_descriptor_source::handle_residue" ref="af0f9a847bf3cb06905b587e47368340e" args="(char *buf, int nbytes_read)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int <a class="el" href="classgr__file__descriptor__source.html#af0f9a847bf3cb06905b587e47368340e">gr_file_descriptor_source::handle_residue</a> </td> <td>(</td> <td class="paramtype">char *&#160;</td> <td class="paramname"><em>buf</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>nbytes_read</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [protected]</code></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="a19ace13388bd5037196b9ee4dce0543a"></a><!-- doxytag: member="gr_file_descriptor_source::read_items" ref="a19ace13388bd5037196b9ee4dce0543a" args="(char *buf, int nitems)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int <a class="el" href="classgr__file__descriptor__source.html#a19ace13388bd5037196b9ee4dce0543a">gr_file_descriptor_source::read_items</a> </td> <td>(</td> <td class="paramtype">char *&#160;</td> <td class="paramname"><em>buf</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>nitems</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [protected]</code></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <a class="anchor" id="a28a7c20d750296c73c14c1391605ab19"></a><!-- doxytag: member="gr_file_descriptor_source::work" ref="a28a7c20d750296c73c14c1391605ab19" args="(int noutput_items, gr_vector_const_void_star &amp;input_items, gr_vector_void_star &amp;output_items)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int <a class="el" href="classgr__file__descriptor__source.html#a28a7c20d750296c73c14c1391605ab19">gr_file_descriptor_source::work</a> </td> <td>(</td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>noutput_items</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">gr_vector_const_void_star &amp;&#160;</td> <td class="paramname"><em>input_items</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">gr_vector_void_star &amp;&#160;</td> <td class="paramname"><em>output_items</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p>just like <a class="el" href="structgr__block.html#adf59080d10f322e3816b7ac8f7cb2a7c" title="compute output items from input items">gr_block::general_work</a>, only this arranges to call consume_each for you </p> <p>The user must override work to define the signal processing code </p> <p>Reimplemented from <a class="el" href="structgr__sync__block.html#aa8c8060e41ba213e038eb7a4eec8f723">gr_sync_block</a>.</p> </div> </div> <hr/><h2>Friends And Related Function Documentation</h2> <a class="anchor" id="ad2c64a0018c82cc0f6944632600fc6d4"></a><!-- doxytag: member="gr_file_descriptor_source::gr_make_file_descriptor_source" ref="ad2c64a0018c82cc0f6944632600fc6d4" args="(size_t itemsize, int fd, bool repeat)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="el" href="classboost_1_1shared__ptr.html">gr_file_descriptor_source_sptr</a> <a class="el" href="classgr__file__descriptor__source.html#ad2c64a0018c82cc0f6944632600fc6d4">gr_make_file_descriptor_source</a> </td> <td>(</td> <td class="paramtype">size_t&#160;</td> <td class="paramname"><em>itemsize</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&#160;</td> <td class="paramname"><em>fd</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="stdbool_8h.html#a97a80ca1602ebf2303258971a2c938e2">bool</a>&#160;</td> <td class="paramname"><em>repeat</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [friend]</code></td> </tr> </table> </div> <div class="memdoc"> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li><a class="el" href="gr__file__descriptor__source_8h_source.html">gr_file_descriptor_source.h</a></li> </ul> </div><!-- contents --> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="classgr__file__descriptor__source.html">gr_file_descriptor_source</a> </li> <li class="footer">Generated on Mon Oct 14 2013 11:58:16 for GNU Radio 3.6.4.2 C++ API by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li> </ul> </div> </body> </html>
aviralchandra/Sandhi
build/gr36/docs/doxygen/html/classgr__file__descriptor__source.html
HTML
gpl-3.0
14,536
package visualk.gallery.db; import java.awt.Color; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import visualk.db.MysqlLayer; import visualk.gallery.objects.Artist; import visualk.gallery.objects.Work; public class DbGallery extends MysqlLayer{ public DbGallery(String user, String pass, String db) { super(user, pass, db); } public void addObra(Work obra, Artist author) { if (this != null) { try { /*mySQL.executeDB("insert into hrzns (" + "nameHrz," + "dt," + "topHrz," + "topHrzColor," + "bottomHrzColor," + "canvasWidth," + "canvasHeigth," + "authorHrz," + "xPal," + "yPal," + "hPalx," + "hPaly," + "alcada," + "colPal," + "horizontal," + "aureaProp," + "superX," + "superY," + "textura," + "version) values ('" + hrz.getNameHrz() + "', " + "NOW()" + ", '" + hrz.getTopHrz() + "', '" + hrz.getTopHrzColor().getRGB() + "', '" + hrz.getBottomHrzColor().getRGB() + "', '" + hrz.getCanvasWidth() + "', '" + hrz.getCanvasHeigth() + "', '" + authorName + "', '" + hrz.getxPal() + "', '" + hrz.getyPal() + "', '" + hrz.gethPalx() + "', '" + hrz.gethPaly() + "', '" + hrz.getAlçada() + "', '" + hrz.getColPal().getRGB() + "', '" + hrz.isHorizontal() + "', '" + hrz.isAureaProp() + "', '" + hrz.getSuperX() + "', '" + hrz.getSuperY() + "', '" + hrz.isTextura() + "', '" + hrz.getVersion() + "')");*/ } catch (Exception e) { } finally { disconnect(); } } } public ResultSet listHrzns() { ResultSet myResult = null; try { myResult = queryDB("SELECT * FROM hrzns WHERE namehrz<>'wellcome' order by dt desc;"); } catch (SQLException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } return (myResult); } /* public Horizon getHrznBD(String name) { Horizon temp = new Horizon(name); ResultSet myResult; myResult = mySQL.queryDB("SELECT * FROM hrzns where nameHrz='" + name + "'"); temp.makeRandom(100, 300); if (myResult != null) { try { while (myResult.next()) { String nameHrz = ""; String topHrz = ""; String topHrzColor = ""; String bottomHrzColor = ""; String canvasWidth = ""; String canvasHeigth = ""; String authorHrz = ""; String xPal = ""; String yPal = ""; String hPalx = ""; String hPaly = ""; String alcada = ""; String horizontal = ""; String aureaProp = ""; String colPal = ""; String superX = ""; String superY = ""; String textura = ""; String version = ""; try { nameHrz = myResult.getString("nameHrz"); topHrz = myResult.getString("topHrz"); topHrzColor = myResult.getString("topHrzColor"); bottomHrzColor = myResult.getString("bottomHrzColor"); canvasWidth = myResult.getString("canvasWidth"); canvasHeigth = myResult.getString("canvasHeigth"); authorHrz = myResult.getString("authorHrz"); xPal = myResult.getString("xPal"); yPal = myResult.getString("yPal"); hPalx = myResult.getString("hPalx"); hPaly = myResult.getString("hPaly"); alcada = myResult.getString("alcada"); colPal = myResult.getString("colPal"); horizontal = myResult.getString("horizontal"); aureaProp = myResult.getString("aureaProp"); superX = myResult.getString("superX"); superY = myResult.getString("superY"); textura = myResult.getString("textura"); version = myResult.getString("version"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp.setNameHrz(nameHrz); temp.setTopHrz(Integer.parseInt(topHrz)); temp.setTopHrzColor(new Color(Integer.parseInt(topHrzColor))); temp.setBottomHrzColor(new Color(Integer.parseInt(bottomHrzColor))); temp.setCanvasWidth(Integer.parseInt(canvasWidth)); temp.setCanvasHeigth(Integer.parseInt(canvasHeigth)); temp.setAuthorHrz(authorHrz); temp.setxPal(Integer.parseInt(xPal)); temp.setyPal(Integer.parseInt(yPal)); temp.sethPalx(Integer.parseInt(hPalx)); temp.sethPaly(Integer.parseInt(hPaly)); temp.setAlcada(Integer.parseInt(alcada)); temp.setColPal(new Color(Integer.parseInt(colPal))); temp.setHorizontal(horizontal.equals("true")); temp.setAureaProp(aureaProp.equals("true")); temp.setSuperX(Integer.parseInt(superX)); temp.setSuperY(Integer.parseInt(superY)); temp.setTextura(textura.equals("true")); temp.setVersion(version); } myResult.close(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return (temp); } */ }
lamaken/visualk
src/java/visualk/gallery/db/DbGallery.java
Java
gpl-3.0
7,208
/** * Java Settlers - An online multiplayer version of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas <[email protected]> * Portions of this file Copyright (C) 2014,2017,2020 Jeremy D Monin <[email protected]> * * 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/>. * * The maintainer of this program can be reached at [email protected] **/ package soc.message; /** * This reply from server means this client currently isn't allowed to connect. * * @author Robert S Thomas */ public class SOCRejectConnection extends SOCMessage { private static final long serialVersionUID = 100L; // last structural change v1.0.0 or earlier /** * Text message */ private String text; /** * Create a RejectConnection message. * * @param message the text message */ public SOCRejectConnection(String message) { messageType = REJECTCONNECTION; text = message; } /** * @return the text message */ public String getText() { return text; } /** * REJECTCONNECTION sep text * * @return the command String */ public String toCmd() { return toCmd(text); } /** * REJECTCONNECTION sep text * * @param tm the text message * @return the command string */ public static String toCmd(String tm) { return REJECTCONNECTION + sep + tm; } /** * Parse the command String into a RejectConnection message * * @param s the String to parse; will be directly used as {@link #getText()} without any parsing * @return a RejectConnection message */ public static SOCRejectConnection parseDataStr(String s) { return new SOCRejectConnection(s); } /** * @return a human readable form of the message */ public String toString() { return "SOCRejectConnection:" + text; } }
jdmonin/JSettlers2
src/main/java/soc/message/SOCRejectConnection.java
Java
gpl-3.0
2,564
(function (angular) { 'use strict'; var config = { githubApiUrl: 'https://api.github.com/', }; angular.module('myGithubApp').constant('config', config); })(angular);
PetrusStarken/MyGit
app/scripts/app-config.js
JavaScript
gpl-3.0
180
<html> <style> body { font-family: Helvetica, Arial; color: #2B332E; } .errorlist li { margin: 0; color: red; } a { text-decoration: none; color: #2B332E; } p.button { font-size: 0.875em; font-weight: bold; float: left; border: 1px solid #C0CCC4; background-color: #ebf2ee; padding: 0.25em 8px; -webkit-border-radius: 5px; -webkit-box-shadow: 0 1px #FFF; } </style> <body> <h1>Opt-In/Opt-Out</h1> <form method="POST" action=""> <p> <label>Email Address</label> {{ form.email }} {% if form.email.errors %}{{ form.email.errors }}{% endif %} </p> <p> <label>Subscribe</label> {{ form.subscribed }} </p> <p class="button"><a href="javascript:document.forms[0].submit()">Submit</a></p> </form> </body> </html>
pielgrzym/django-minishop
newsletter/templates/newsletter/subscribe.html
HTML
gpl-3.0
772
/* Copyright 2013-2017 Matt Tytel * * helm 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. * * helm 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 helm. If not, see <http://www.gnu.org/licenses/>. */ #include "fonts.h" Fonts::Fonts() { proportional_regular_ = Font(Typeface::createSystemTypefaceFor( BinaryData::RobotoRegular_ttf, BinaryData::RobotoRegular_ttfSize)); proportional_light_ = Font(Typeface::createSystemTypefaceFor( BinaryData::RobotoLight_ttf, BinaryData::RobotoLight_ttfSize)); monospace_ = Font(Typeface::createSystemTypefaceFor( BinaryData::DroidSansMono_ttf, BinaryData::DroidSansMono_ttfSize)); }
mtytel/helm
src/look_and_feel/fonts.cpp
C++
gpl-3.0
1,106
manual.html: manual.md Makefile pandoc --to=html5 --standalone --css=manual.css --table-of-contents --variable=lang:en --mathjax $< > $@
axch/probscheme
doc/Makefile
Makefile
gpl-3.0
138
package org.codefx.jwos.file; import org.codefx.jwos.analysis.AnalysisPersistence; import org.codefx.jwos.artifact.AnalyzedArtifact; import org.codefx.jwos.artifact.CompletedArtifact; import org.codefx.jwos.artifact.DownloadedArtifact; import org.codefx.jwos.artifact.FailedArtifact; import org.codefx.jwos.artifact.FailedProject; import org.codefx.jwos.artifact.IdentifiesArtifact; import org.codefx.jwos.artifact.IdentifiesProject; import org.codefx.jwos.artifact.ProjectCoordinates; import org.codefx.jwos.artifact.ResolvedArtifact; import org.codefx.jwos.artifact.ResolvedProject; import org.codefx.jwos.file.persistence.PersistentAnalysis; import org.codefx.jwos.file.persistence.PersistentAnalyzedArtifact; import org.codefx.jwos.file.persistence.PersistentCompletedArtifact; import org.codefx.jwos.file.persistence.PersistentDownloadedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedProject; import org.codefx.jwos.file.persistence.PersistentProjectCoordinates; import org.codefx.jwos.file.persistence.PersistentResolvedArtifact; import org.codefx.jwos.file.persistence.PersistentResolvedProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Collection; import java.util.SortedSet; import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.Function; import static java.util.Collections.unmodifiableSet; import static org.codefx.jwos.Util.transformToList; /** * An {@link AnalysisPersistence} that uses YAML to store results. * <p> * This implementation is not thread-safe. */ public class YamlAnalysisPersistence implements AnalysisPersistence { private static final Logger LOGGER = LoggerFactory.getLogger("Persistence"); private static final YamlPersister PERSISTER = new YamlPersister(); private final SortedSet<ProjectCoordinates> projects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<ResolvedProject> resolvedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<FailedProject> resolutionFailedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<DownloadedArtifact> downloadedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> downloadFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<AnalyzedArtifact> analyzedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> analysisFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<ResolvedArtifact> resolvedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> resolutionFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<CompletedArtifact> completedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); // CREATION & PERSISTENCE private YamlAnalysisPersistence() { // private constructor to enforce use of static factory methods } public static YamlAnalysisPersistence empty() { return new YamlAnalysisPersistence(); } public static YamlAnalysisPersistence fromString(String yamlString) { if (yamlString.isEmpty()) return empty(); PersistentAnalysis persistent = PERSISTER.read(yamlString, PersistentAnalysis.class); return from(persistent); } public static YamlAnalysisPersistence fromStream(InputStream yamlStream) { LOGGER.debug("Parsing result file..."); PersistentAnalysis persistent = PERSISTER.read(yamlStream, PersistentAnalysis.class); if (persistent == null) return new YamlAnalysisPersistence(); else return from(persistent); } private static YamlAnalysisPersistence from(PersistentAnalysis persistent) { YamlAnalysisPersistence yaml = new YamlAnalysisPersistence(); addTo(persistent.step_1_projects, PersistentProjectCoordinates::toProject, yaml.projects); addTo(persistent.step_2_resolvedProjects, PersistentResolvedProject::toProject, yaml.resolvedProjects); addTo(persistent.step_2_resolutionFailedProjects, PersistentFailedProject::toProject, yaml.resolutionFailedProjects); addTo(persistent.step_3_downloadedArtifacts, PersistentDownloadedArtifact::toArtifact, yaml.downloadedArtifacts); addTo(persistent.step_3_downloadFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.downloadFailedArtifacts); addTo(persistent.step_4_analyzedArtifacts, PersistentAnalyzedArtifact::toArtifact, yaml.analyzedArtifacts); addTo(persistent.step_4_analysisFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.analysisFailedArtifacts); addTo(persistent.step_5_resolvedArtifacts, PersistentResolvedArtifact::toArtifact, yaml.resolvedArtifacts); addTo(persistent.step_5_resolutionFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.resolutionFailedArtifacts); PersistentCompletedArtifact .toArtifacts(persistent.step_6_completedArtifacts.stream()) .forEach(yaml.completedArtifacts::add); return yaml; } private static <P, T> void addTo(Collection<P> source, Function<P, T> transform, Collection<T> target) { source.stream() .map(transform) .forEach(target::add); } public String toYaml() { PersistentAnalysis persistent = toPersistentAnalysis(); return PERSISTER.write(persistent); } private PersistentAnalysis toPersistentAnalysis() { PersistentAnalysis persistent = new PersistentAnalysis(); persistent.step_1_projects = transformToList(projects, PersistentProjectCoordinates::from); persistent.step_2_resolvedProjects = transformToList(resolvedProjects, PersistentResolvedProject::from); persistent.step_2_resolutionFailedProjects = transformToList(resolutionFailedProjects, PersistentFailedProject::from); persistent.step_3_downloadedArtifacts = transformToList(downloadedArtifacts, PersistentDownloadedArtifact::from); persistent.step_3_downloadFailedArtifacts = transformToList(downloadFailedArtifacts, PersistentFailedArtifact::from); persistent.step_4_analyzedArtifacts = transformToList(analyzedArtifacts, PersistentAnalyzedArtifact::from); persistent.step_4_analysisFailedArtifacts = transformToList(analysisFailedArtifacts, PersistentFailedArtifact::from); persistent.step_5_resolvedArtifacts = transformToList(resolvedArtifacts, PersistentResolvedArtifact::from); persistent.step_5_resolutionFailedArtifacts = transformToList(resolutionFailedArtifacts, PersistentFailedArtifact::from); persistent.step_6_completedArtifacts = transformToList(completedArtifacts, PersistentCompletedArtifact::from); return persistent; } // IMPLEMENTATION OF 'AnalysisPersistence' @Override public Collection<ProjectCoordinates> projectsUnmodifiable() { return unmodifiableSet(projects); } @Override public Collection<ResolvedProject> resolvedProjectsUnmodifiable() { return unmodifiableSet(resolvedProjects); } @Override public Collection<FailedProject> projectResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedProjects); } @Override public Collection<DownloadedArtifact> downloadedArtifactsUnmodifiable() { return unmodifiableSet(downloadedArtifacts); } @Override public Collection<FailedArtifact> artifactDownloadErrorsUnmodifiable() { return unmodifiableSet(downloadFailedArtifacts); } @Override public Collection<AnalyzedArtifact> analyzedArtifactsUnmodifiable() { return unmodifiableSet(analyzedArtifacts); } @Override public Collection<FailedArtifact> artifactAnalysisErrorsUnmodifiable() { return unmodifiableSet(analysisFailedArtifacts); } @Override public Collection<ResolvedArtifact> resolvedArtifactsUnmodifiable() { return unmodifiableSet(resolvedArtifacts); } @Override public Collection<FailedArtifact> artifactResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedArtifacts); } @Override public void addProject(ProjectCoordinates project) { projects.add(project); } @Override public void addResolvedProject(ResolvedProject project) { resolvedProjects.add(project); } @Override public void addProjectResolutionError(FailedProject project) { resolutionFailedProjects.add(project); } @Override public void addDownloadedArtifact(DownloadedArtifact artifact) { downloadedArtifacts.add(artifact); } @Override public void addDownloadError(FailedArtifact artifact) { downloadFailedArtifacts.add(artifact); } @Override public void addAnalyzedArtifact(AnalyzedArtifact artifact) { analyzedArtifacts.add(artifact); } @Override public void addAnalysisError(FailedArtifact artifact) { analysisFailedArtifacts.add(artifact); } @Override public void addResolvedArtifact(ResolvedArtifact artifact) { resolvedArtifacts.add(artifact); } @Override public void addArtifactResolutionError(FailedArtifact artifact) { resolutionFailedArtifacts.add(artifact); } @Override public void addResult(CompletedArtifact artifact) { completedArtifacts.add(artifact); } }
CodeFX-org/jdeps-wall-of-shame
src/main/java/org/codefx/jwos/file/YamlAnalysisPersistence.java
Java
gpl-3.0
9,278
package Calibradores; import java.io.File; import Metricas.MultiescalaConBorde; import Modelo.UrbanizandoFrenos; public class TanteadorTopilejo extends Tanteador { UrbanizandoFrenos CA; public TanteadorTopilejo() { // int[] unConjuntoDeParametros = {1, 1, 1, 333, 333, 333, 1, 1, 444, 400, 400, 555}; // puntoDeTanteo = new PuntoDeBusqueda(unConjuntoDeParametros); // puntoDelRecuerdo = new PuntoDeBusqueda(unConjuntoDeParametros); CA = new UrbanizandoFrenos(72, 56, 11, 4); CA.setInitialGrid(new File ("Topilejo/topi1995.txt")); CA.setBosque(new File ("Topilejo/bosqueb.txt")); CA.setDistVias(new File ("Topilejo/distancia1.txt")); CA.setPendiente(new File ("Topilejo/pendiente.txt")); CA.setGoalGrid(new File ("Topilejo/topi1999.txt")); infoADN = CA.infoADN; MultiescalaConBorde metrica = new MultiescalaConBorde(CA.gridMeta, CA.numeroDeCeldasX, CA.numeroDeCeldasY ); metrica.normalizateConEste(new File ("Topilejo/topi1995.txt")); CA.setMetric(metrica); CA.setIteraciones(4); puntoDeTanteo = new PuntoDeBusqueda(infoADN.size); puntoDelRecuerdo = new PuntoDeBusqueda(infoADN.size); vuelo = new PuntoDeBusqueda(infoADN.size); bajando = new Ventana("Guardar Acercamiento", "Caminante Siego Estocastico"); bajando.setVisible(true); bajando.graf.setLocation(850, 715); bajando.setQueTantoLocation(865, 650); //solo para correr los 3 calibradores al mismo tiempo // ventana = new Ventana("Guardar Todo", "Todos"); // ventana.setVisible(true); pintaGrid1 = new PintaGrid(new File("Topilejo/topi1999.txt"), "Grrid Meta", 4); pintaGrid2 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Mejor Aproximacion", 5); pintaGrid3 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Grid de Salida", 4); pintaGrid2.setLocation(865, 370); } public double mide(int[] parametros) { return CA.mide(parametros, 100); } public static void main(String[] args) { TanteadorTopilejo topo = new TanteadorTopilejo(); topo.busca(); } @Override public int[][] unOutputPara(int[] parametros) { // TODO Auto-generated method stub return CA.unOutputPara(parametros); } }
sostenibilidad-unam/crecimiento-urbano
Calibradores/TanteadorTopilejo.java
Java
gpl-3.0
2,250
#!/bin/bash #Coded by:FadyHazem/V2.0 Support:LinuxMint-Ubuntu-Debian. #You can recodeing this script but yo must typing the own of this script(FadyHazem). echo "Welcome i will help you to update your system." sleep 4 echo "This script support:LinuxMint-Ubuntu-Debian" sleep 2 read -p "What's your distro name?:" DISTRO echo "Now updateing $DISTRO" sleep 3 echo "Now loading..." sleep 4 sudo apt-get update && sudo apt-get upgrade
FadyHazem/Linux-Sytem-Update
system_updating.sh
Shell
gpl-3.0
430
/* * Copyright (C) 2017 phantombot.tv * * 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 me.mast3rplan.phantombot.event.ytplayer; import me.mast3rplan.phantombot.twitchwsirc.Channel; import me.mast3rplan.phantombot.ytplayer.YTPlayerState; public class YTPlayerStateEvent extends YTPlayerEvent { private final YTPlayerState state; public YTPlayerStateEvent(YTPlayerState state) { this.state = state; } public YTPlayerStateEvent(YTPlayerState state, Channel channel) { super(channel); this.state = state; } public YTPlayerState getState() { return state; } public int getStateId() { return state.i; } }
MrAdder/PhantomBot
source/me/mast3rplan/phantombot/event/ytplayer/YTPlayerStateEvent.java
Java
gpl-3.0
1,295
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_102) on Tue Feb 21 18:04:04 GMT 2017 --> <title>gate.chineseSeg (${plugin.name} JavaDoc)</title> <meta name="date" content="2017-02-21"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../gate/chineseSeg/package-summary.html" target="classFrame">gate.chineseSeg</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ChineseSegMain.html" title="class in gate.chineseSeg" target="classFrame">ChineseSegMain</a></li> <li><a href="ConstantParameters.html" title="class in gate.chineseSeg" target="classFrame">ConstantParameters</a></li> <li><a href="TestChineseSegMain.html" title="class in gate.chineseSeg" target="classFrame">TestChineseSegMain</a></li> </ul> <h2 title="Enums">Enums</h2> <ul title="Enums"> <li><a href="RunMode.html" title="enum in gate.chineseSeg" target="classFrame">RunMode</a></li> </ul> </div> </body> </html>
masterucm1617/botzzaroni
BotzzaroniDev/GATE_Developer_8.4/plugins/Lang_Chinese/doc/javadoc/gate/chineseSeg/package-frame.html
HTML
gpl-3.0
1,199
package com.plasmablazer.tutorialmod.proxy; public interface IProxy { }
PlasmaBlazer/TutorialMod
src/main/java/com/plasmablazer/tutorialmod/proxy/IProxy.java
Java
gpl-3.0
74
using System; namespace org.btg.Star.Rhapsody { public struct SkeletalPoint { public int x { get; set; } public int y { get; set; } public int z { get; set; } public SkeletalPointType type { get; set; } } }
chrisatkin/star
Rhapsody/SkeletalPoint.cs
C#
gpl-3.0
447
GPG Suite 2015.09 ================= September 24th, 2015 GPGMail 2.6b2 ------------- ### Pre-release version info * This beta will be disabled, once the next stable version of GPGMail is released. If you want to continue using GPGMail after that, you will have to acquire a valid license. ### Adds support for OS X 10.11 El Capitan * GPGMail has been updated to support the latest OS from Apple. Enjoy! ### Bugfixes * Greatly improves reliability * Fixes the appearance of the security indicator to look better as a toolbar item * Properly displays error messages when a gpg operation fails as the user attemtps to send a message. * The signature detail view is now properly displayed again. * Fixes an issue where the sign and encrypt status were not properly saved in the draft and hence couldn't be properly restored when continuing editing a draft. GPGMail 2.5.2 ------------- ### Smooth upgrade to El Capitan * Instead of seeing the "incompatible Bundle"-message, when you launch Mail with GPGMail installed after upgrading to El Capitan, you will have the option to install our newest beta for El Capitan or disable GPGMail ### Bugfixes * GPGMail handles binary pgp messages as expected again. The regression was introduced in GPG Suite 2015.08. [#843] * Adds better support for variants of inline PGP in HTML messages. Libmacgpg 0.6.1 --------------- ### Bugfixes * The most common crash in GPG suite 2015.08 was a crash in Libmacgpg when parsing PGP messages. [#150]
GPGTools/GPGTools_Installer
Release Notes/2015.09.md
Markdown
gpl-3.0
1,492
package org.thoughtcrime.securesms.jobs; import androidx.annotation.NonNull; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.Data; import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil; import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.recipients.RecipientUtil; import org.thoughtcrime.securesms.util.Base64; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.InvalidKeyException; import org.whispersystems.signalservice.api.SignalServiceMessageSender; import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage; import org.whispersystems.signalservice.api.push.SignalServiceAddress; import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException; import java.io.IOException; import java.util.concurrent.TimeUnit; public class MultiDeviceVerifiedUpdateJob extends BaseJob { public static final String KEY = "MultiDeviceVerifiedUpdateJob"; private static final String TAG = MultiDeviceVerifiedUpdateJob.class.getSimpleName(); private static final String KEY_DESTINATION = "destination"; private static final String KEY_IDENTITY_KEY = "identity_key"; private static final String KEY_VERIFIED_STATUS = "verified_status"; private static final String KEY_TIMESTAMP = "timestamp"; private RecipientId destination; private byte[] identityKey; private VerifiedStatus verifiedStatus; private long timestamp; public MultiDeviceVerifiedUpdateJob(@NonNull RecipientId destination, IdentityKey identityKey, VerifiedStatus verifiedStatus) { this(new Job.Parameters.Builder() .addConstraint(NetworkConstraint.KEY) .setQueue("__MULTI_DEVICE_VERIFIED_UPDATE__") .setLifespan(TimeUnit.DAYS.toMillis(1)) .setMaxAttempts(Parameters.UNLIMITED) .build(), destination, identityKey.serialize(), verifiedStatus, System.currentTimeMillis()); } private MultiDeviceVerifiedUpdateJob(@NonNull Job.Parameters parameters, @NonNull RecipientId destination, @NonNull byte[] identityKey, @NonNull VerifiedStatus verifiedStatus, long timestamp) { super(parameters); this.destination = destination; this.identityKey = identityKey; this.verifiedStatus = verifiedStatus; this.timestamp = timestamp; } @Override public @NonNull Data serialize() { return new Data.Builder().putString(KEY_DESTINATION, destination.serialize()) .putString(KEY_IDENTITY_KEY, Base64.encodeBytes(identityKey)) .putInt(KEY_VERIFIED_STATUS, verifiedStatus.toInt()) .putLong(KEY_TIMESTAMP, timestamp) .build(); } @Override public @NonNull String getFactoryKey() { return KEY; } @Override public void onRun() throws IOException, UntrustedIdentityException { try { if (!TextSecurePreferences.isMultiDevice(context)) { Log.i(TAG, "Not multi device..."); return; } if (destination == null) { Log.w(TAG, "No destination..."); return; } SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender(); Recipient recipient = Recipient.resolved(destination); VerifiedMessage.VerifiedState verifiedState = getVerifiedState(verifiedStatus); SignalServiceAddress verifiedAddress = RecipientUtil.toSignalServiceAddress(context, recipient); VerifiedMessage verifiedMessage = new VerifiedMessage(verifiedAddress, new IdentityKey(identityKey, 0), verifiedState, timestamp); messageSender.sendMessage(SignalServiceSyncMessage.forVerified(verifiedMessage), UnidentifiedAccessUtil.getAccessFor(context, recipient)); } catch (InvalidKeyException e) { throw new IOException(e); } } private VerifiedMessage.VerifiedState getVerifiedState(VerifiedStatus status) { VerifiedMessage.VerifiedState verifiedState; switch (status) { case DEFAULT: verifiedState = VerifiedMessage.VerifiedState.DEFAULT; break; case VERIFIED: verifiedState = VerifiedMessage.VerifiedState.VERIFIED; break; case UNVERIFIED: verifiedState = VerifiedMessage.VerifiedState.UNVERIFIED; break; default: throw new AssertionError("Unknown status: " + verifiedStatus); } return verifiedState; } @Override public boolean onShouldRetry(@NonNull Exception exception) { return exception instanceof PushNetworkException; } @Override public void onFailure() { } public static final class Factory implements Job.Factory<MultiDeviceVerifiedUpdateJob> { @Override public @NonNull MultiDeviceVerifiedUpdateJob create(@NonNull Parameters parameters, @NonNull Data data) { try { RecipientId destination = RecipientId.from(data.getString(KEY_DESTINATION)); VerifiedStatus verifiedStatus = VerifiedStatus.forState(data.getInt(KEY_VERIFIED_STATUS)); long timestamp = data.getLong(KEY_TIMESTAMP); byte[] identityKey = Base64.decode(data.getString(KEY_IDENTITY_KEY)); return new MultiDeviceVerifiedUpdateJob(parameters, destination, identityKey, verifiedStatus, timestamp); } catch (IOException e) { throw new AssertionError(e); } } } }
WhisperSystems/TextSecure
app/src/main/java/org/thoughtcrime/securesms/jobs/MultiDeviceVerifiedUpdateJob.java
Java
gpl-3.0
6,361
require_relative '../../spec_helper' describe TypedRb::TypeSignature::Parser do it 'parses a unit type' do result = described_class.parse('unit') expect(result).to eq(:unit) end it 'parses an atomic type' do result = described_class.parse('Bool') expect(result).to eq('Bool') end it 'parses a generic type' do result = described_class.parse('Array[Bool]') expect(result).to eq({:type => 'Array', :parameters => [{:type => 'Bool', :kind => :type_var}], :kind => :generic_type}) end it 'parses a nested generic type' do result = described_class.parse('Array[Array[Integer]]') expect(result).to eq({:type=>'Array', :parameters => [ {:type=>'Array', :parameters => [{ :type => 'Integer', :kind => :type_var }], :kind => :generic_type } ], :kind => :generic_type}) end it 'parses a nested generic type with multiple type arguments' do result = described_class.parse('Array[Hash[Symbol][String]]') expect(result).to eq({:type=>'Array', :parameters => [ {:type=>'Hash', :parameters => [{ :type => 'Symbol', :kind => :type_var }, { :type => 'String', :kind => :type_var }], :kind => :generic_type } ], :kind => :generic_type}) end it 'parses an atomic rest type' do result = described_class.parse('Bool...') expect(result).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) end it 'parses a type var rest type' do result = described_class.parse('[T]...') expect(result).to eq({:type => 'Array', :parameters => [{:type=>"T", :kind => :type_var}], :kind => :rest}) end it 'parses a function type' do result = described_class.parse('Bool -> Int') expect(result).to eq(['Bool', 'Int']) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type=>"Bool", :kind=>:type_var}], :kind => :generic_type}) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[T < Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type =>"T", :kind =>:type_var, :bound => 'Bool', :binding => '<'}], :kind => :generic_type}) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[T > Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type =>"T", :kind =>:type_var, :bound => 'Bool', :binding => '>'}], :kind => :generic_type}) end it 'parses a complex type' do result = described_class.parse('Bool -> Int -> Bool') expect(result).to eq(['Bool', 'Int', 'Bool']) end it 'parses a complex type using unit' do result = described_class.parse('Bool -> Int -> unit') expect(result).to eq(['Bool', 'Int', :unit]) end it 'parses a types with parentheses' do result = described_class.parse('(Bool -> Int) -> Bool') expect(result).to eq([['Bool', 'Int'], 'Bool']) end it 'parses a types with parentheses in the return type' do result = described_class.parse('Bool -> (Int -> Bool)') expect(result).to eq(['Bool', ['Int', 'Bool']]) end it 'parses a types with parentheses in the complex return type' do result = described_class.parse('Bool -> (Int -> (Bool -> Int))') expect(result).to eq(['Bool', ['Int', ['Bool', 'Int']]]) end it 'parses a types with complex parentheses' do result = described_class.parse('(Bool -> Bool) -> (Bool -> Int)') expect(result).to eq([['Bool', 'Bool'], ['Bool', 'Int']]) end it 'parses a types with complex parentheses' do result = described_class.parse('(Bool -> Bool) -> (Bool -> Int) -> (Int -> Int)') expect(result).to eq([['Bool', 'Bool'], ['Bool', 'Int'], ['Int', 'Int']]) end it 'parses a types with complex compound parentheses' do result = described_class.parse('((Bool -> Bool) -> (Bool -> Int)) -> (Bool -> Int)') expect(result).to eq([[['Bool','Bool'], ['Bool', 'Int']], ['Bool', 'Int']]) end it 'parses unbalanced type expressions' do result = described_class.parse('Bool -> Int -> (Bool -> Int) -> Int') expect(result).to eq(['Bool','Int', ['Bool','Int'], 'Int']) end it 'parses unbalanced type expressions with just return types' do result = described_class.parse('Bool -> Int -> (-> Int) -> Int') expect(result).to eq(['Bool','Int', ['Int'], 'Int']) end it 'parses expressions with only return type' do result = described_class.parse(' -> Int') expect(result).to eq(['Int']) end it 'parses type variables' do result = described_class.parse('[X]') expect(result).to eq({:type => 'X', :kind => :type_var }) end it 'parses type variables with lower binding' do result = described_class.parse('[X < Numeric]') expect(result).to eq({:type => 'X', :kind => :type_var, :bound => 'Numeric', :binding => '<' }) end it 'parses type variables with lower binding' do result = described_class.parse('[X > Numeric]') expect(result).to eq({:type => 'X', :kind => :type_var, :bound => 'Numeric', :binding => '>' }) end it 'parses return type variables' do result = described_class.parse(' -> [X]') expect(result).to eq([{:type => 'X', :kind => :type_var }]) end it 'parses type variables in both sides' do result = described_class.parse('[X<String] -> [Y]') expect(result).to eq([{:type => 'X', :bound => 'String', :kind => :type_var, :binding => '<' }, {:type => 'Y', :kind => :type_var }]) end it 'parses type variables in complex expressions' do result = described_class.parse('[X] -> ([Y] -> Integer)') expect(result).to eq([{:type => 'X', :kind => :type_var }, [{:type => 'Y', :kind => :type_var }, 'Integer']]) end it 'parses a block' do result = described_class.parse('Int -> unit -> &(String -> Integer)') expect(result).to eq(['Int', :unit, {:block => ['String', 'Integer'], :kind => :block_arg}]) end it 'parses parametric types' do result = described_class.parse('Array[X] -> [X]') expect(result).to eq([{:type => "Array", :parameters => [{:type => "X", :kind => :type_var}], :kind => :generic_type}, {:type => "X", :kind => :type_var}]) end it 'parses parametric types with multiple var types' do result = described_class.parse('Int -> (Bool -> Array[X][Y][Z])') expect(result).to eq(["Int", ["Bool", {:type => "Array", :parameters => [{:type => "X", :kind => :type_var}, {:type => "Y", :kind => :type_var}, {:type => "Z", :kind => :type_var}], :kind => :generic_type}]]) end it 'parses parametric types with bounds' do result = described_class.parse('Array[X<Int] -> Hash[T<String][U<Object]') expect(result).to eq([{:type => "Array", :parameters => [{:type => "X", :bound => "Int", :binding => '<', :kind => :type_var}], :kind => :generic_type}, {:type => "Hash", :parameters => [{:type => "T", :bound => "String", :binding => '<', :kind => :type_var}, {:type => "U", :bound => "Object", :binding => '<', :kind => :type_var}], :kind => :generic_type}]) end it 'parses parametric rest arguments' do result = described_class.parse('Array[X]... -> String') expect(result).to eq([{:kind=>:rest, :type=>"Array", :parameters=>[{:type=>"Array", :parameters=>[{:type=>"X", :kind=>:type_var}], :kind=>:generic_type}]}, "String"]) end it 'parses multiple type variables in sequence' do result = described_class.parse('[X][Y][Z]') expect(result).to eq([{:type=>"X", :kind=>:type_var}, {:type=>"Y", :kind=>:type_var}, {:type=>"Z", :kind=>:type_var}]) end end
antoniogarrote/typed.rb
spec/lib/type_signature/parser_spec.rb
Ruby
gpl-3.0
9,936
<form class="form-horizontal" method="POST" action="{{ request.url }}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">{{ _('Edit Participant') }}</h4> </div> <div class="modal-body" style="padding-bottom:5px; padding-top:20px;"> {{ form.hidden_tag() }} {%- for field in form -%} {%- if field.type != 'CSRFTokenField' -%} <div class="form-group {% if field.errors %}has-error{% endif %}"> {{ field.label(class_='col-sm-3 control-label') }} <div class="col-sm-7"> {% if field.name == 'supervisor' %} {{ field(class_='form-control select2-container span3 select2 select2-observers-clear', **{'data-name': participant.supervisor.name, 'data-participant_id': participant.supervisor.participant_id}) }} {% elif field.name == 'location' %} {{ field(class_='form-control select2-container span3 select2 select2-locations', **{'data-name': participant.location.name, 'data-location_type': participant.location.location_type}) }} {% else %} {{ field(class_='form-control span3') }} {% endif %} {% if field.errors %} {% for e in field.errors %} <p class="help-block">{{ e }}</p> {% endfor %} {% endif %} </div> <div class="col-sm-2"></div> </div> {%- endif -%} {%- endfor -%} </div> <div class="modal-footer"> <div class="row"> <div class="col-sm-1"></div> <div class="col-sm-10" style="padding-right:1.8em;"> <button type="submit" style="width:122px;"class="btn btn-primary">{{ _('Save') }}</button> <button type="button" style="width:122px;"class="btn btn-default" data-dismiss="modal">{{ _('Close') }}</button> </div> </div> </div> </form>
nditech/elections
apollo/frontend/templates/frontend/participant_edit_modal.html
HTML
gpl-3.0
1,808
import queue import logging import platform import threading import datetime as dt import serial import serial.threaded import serial_device from .or_event import OrEvent logger = logging.getLogger(__name__) # Flag to indicate whether queues should be polled. # XXX Note that polling performance may vary by platform. POLL_QUEUES = (platform.system() == 'Windows') class EventProtocol(serial.threaded.Protocol): def __init__(self): self.transport = None self.connected = threading.Event() self.disconnected = threading.Event() self.port = None def connection_made(self, transport): """Called when reader thread is started""" self.port = transport.serial.port logger.debug('connection_made: `%s` `%s`', self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear() def data_received(self, data): """Called with snippets received from the serial port""" raise NotImplementedError def connection_lost(self, exception): """\ Called when the serial port is closed or the reader loop terminated otherwise. """ if isinstance(exception, Exception): logger.debug('Connection to port `%s` lost: %s', self.port, exception) else: logger.debug('Connection to port `%s` closed', self.port) self.connected.clear() self.disconnected.set() class KeepAliveReader(threading.Thread): ''' Keep a serial connection alive (as much as possible). Parameters ---------- state : dict State dictionary to share ``protocol`` object reference. comport : str Name of com port to connect to. default_timeout_s : float, optional Default time to wait for serial operation (e.g., connect). By default, block (i.e., no time out). **kwargs Keyword arguments passed to ``serial_for_url`` function, e.g., ``baudrate``, etc. ''' def __init__(self, protocol_class, comport, **kwargs): super(KeepAliveReader, self).__init__() self.daemon = True self.protocol_class = protocol_class self.comport = comport self.kwargs = kwargs self.protocol = None self.default_timeout_s = kwargs.pop('default_timeout_s', None) # Event to indicate serial connection has been established. self.connected = threading.Event() # Event to request a break from the run loop. self.close_request = threading.Event() # Event to indicate thread has been closed. self.closed = threading.Event() # Event to indicate an exception has occurred. self.error = threading.Event() # Event to indicate that the thread has connected to the specified port # **at least once**. self.has_connected = threading.Event() @property def alive(self): return not self.closed.is_set() def run(self): # Verify requested serial port is available. try: if self.comport not in (serial_device .comports(only_available=True).index): raise NameError('Port `%s` not available. Available ports: ' '`%s`' % (self.comport, ', '.join(serial_device.comports() .index))) except NameError as exception: self.error.exception = exception self.error.set() self.closed.set() return while True: # Wait for requested serial port to become available. while self.comport not in (serial_device .comports(only_available=True).index): # Assume serial port was disconnected temporarily. Wait and # periodically check again. self.close_request.wait(2) if self.close_request.is_set(): # No connection is open, so nothing to close. Just quit. self.closed.set() return try: # Try to open serial device and monitor connection status. logger.debug('Open `%s` and monitor connection status', self.comport) device = serial.serial_for_url(self.comport, **self.kwargs) except serial.SerialException as exception: self.error.exception = exception self.error.set() self.closed.set() return except Exception as exception: self.error.exception = exception self.error.set() self.closed.set() return else: with serial.threaded.ReaderThread(device, self .protocol_class) as protocol: self.protocol = protocol connected_event = OrEvent(protocol.connected, self.close_request) disconnected_event = OrEvent(protocol.disconnected, self.close_request) # Wait for connection. connected_event.wait(None if self.has_connected.is_set() else self.default_timeout_s) if self.close_request.is_set(): # Quit run loop. Serial connection will be closed by # `ReaderThread` context manager. self.closed.set() return self.connected.set() self.has_connected.set() # Wait for disconnection. disconnected_event.wait() if self.close_request.is_set(): # Quit run loop. self.closed.set() return self.connected.clear() # Loop to try to reconnect to serial device. def write(self, data, timeout_s=None): ''' Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be established. By default, block until serial connection is ready. ''' self.connected.wait(timeout_s) self.protocol.transport.write(data) def request(self, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' self.connected.wait(timeout_s) return request(self, response_queue, payload, timeout_s=timeout_s, poll=poll) def close(self): self.close_request.set() # - - context manager, returns protocol def __enter__(self): """\ Enter context handler. May raise RuntimeError in case the connection could not be created. """ self.start() # Wait for protocol to connect. event = OrEvent(self.connected, self.closed) event.wait(self.default_timeout_s) return self def __exit__(self, *args): """Leave context: close port""" self.close() self.closed.wait() def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send payload to serial device and wait for response. Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' device.write(payload) if poll: # Polling enabled. Wait for response in busy loop. start = dt.datetime.now() while not response_queue.qsize(): if (dt.datetime.now() - start).total_seconds() > timeout_s: raise queue.Empty('No response received.') return response_queue.get() else: # Polling disabled. Use blocking `Queue.get()` method to wait for # response. return response_queue.get(timeout=timeout_s)
wheeler-microfluidics/serial_device
serial_device/threaded.py
Python
gpl-3.0
9,719
__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve()
hnarayanan/twist
demo/static/twist.py
Python
gpl-3.0
2,606
#include "house2.h" int House2::objCount = 0; GImage *House2::image = nullptr; House2::House2(int x, int y) { posx = x; posy = y; width = 336; height = 366; if(!objCount) image = new GImage("./assets/house-a.gif",width,height,GImage::IS_TRANSPARENT,0); objCount++; if(Debug::debug_enable()) std::cout << "House2 " << objCount-1 << " created" << std::endl; } House2::~House2() { objCount--; if(!objCount) delete image; if(Debug::debug_enable()) std::cout << "House2 " << objCount << " destroyed" << std::endl; } bool House2::show(int x) { if(posx-x+width >= 0 && posx-x <= 800) { image->show(posx-x,posy); return 1; } return 0; }
Tai-Min/Projekt-Inf2-AiR
game elements/tiles/house2.cpp
C++
gpl-3.0
730
package com.silvermatch.advancedMod.block; import com.silvermatch.advancedMod.init.ModBlocks; import com.silvermatch.advancedMod.reference.Reference; import com.silvermatch.advancedMod.utility.Names; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.world.World; public class BlockFrenchFlag extends BlockAdvancedMod{ public BlockFrenchFlag() { setBlockName(Names.Blocks.FRENCH_FLAG); setBlockTextureName(Reference.MOD_ID_LOWER + ":" + Names.Blocks.FRENCH_FLAG); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) { if (world.isAirBlock(x, y+1, z)){ world.setBlock(x, y+1, z, ModBlocks.frenchFlag); } return true; } }
SilverMatch/TutoMineMaarten
src/main/java/com/silvermatch/advancedMod/block/BlockFrenchFlag.java
Java
gpl-3.0
901
using System; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using EloBuddy; using LeagueSharp.Common; namespace ezEvade.SpecialSpells { class Darius : ChampionPlugin { static Darius() { // todo: fix for multiple darius' on same team (one for all) } public void LoadSpecialSpell(SpellData spellData) { if (spellData.spellName == "DariusCleave") { Game.OnUpdate += Game_OnUpdate; SpellDetector.OnProcessSpecialSpell += SpellDetector_OnProcessSpecialSpell; } } private void Game_OnUpdate(EventArgs args) { var darius = HeroManager.Enemies.FirstOrDefault(x => x.ChampionName == "Darius"); if (darius != null) { foreach (var spell in SpellDetector.detectedSpells.Where(x => x.Value.heroID == darius.NetworkId)) { spell.Value.startPos = darius.ServerPosition.To2D(); spell.Value.endPos = darius.ServerPosition.To2D() + spell.Value.direction * spell.Value.info.range; } } } private void SpellDetector_OnProcessSpecialSpell(Obj_AI_Base hero, GameObjectProcessSpellCastEventArgs args, SpellData spellData, SpecialSpellEventArgs specialSpellArgs) { if (spellData.spellName == "DariusCleave") { //SpellDetector.CreateSpellData(hero, start.To3D(), end.To3D(), spellData); } } } }
eliteironlix/portaio2
Core/Utility Ports/EzEvade/SpecialSpells/Darius.cs
C#
gpl-3.0
1,570
// Copyright (C) 1999-2021 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include "basepolygon.h" #include "fitsimage.h" BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b) : Marker(p, ctr, 0) { } BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, ctr, 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { } BasePolygon::BasePolygon(Base* p, const List<Vertex>& v, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, Vector(0,0), 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { // Vertex list is in ref coords angle = 0; vertex = v; // find center center = Vector(0,0); vertex.head(); do center += vertex.current()->vector; while (vertex.next()); center /= vertex.count(); // vertices are relative vertex.head(); do vertex.current()->vector *= Translate(-center) * FlipY(); // no rotation while (vertex.next()); updateBBox(); } BasePolygon::BasePolygon(const BasePolygon& a) : Marker(a) { vertex = a.vertex; } void BasePolygon::createVertex(int which, const Vector& v) { // which segment (1 to n) // v is in ref coords Matrix mm = bckMatrix(); int seg = which-1; if (seg>=0 && seg<vertex.count()) { Vertex* n = new Vertex(v * mm); vertex.insert(seg,n); recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::deleteVertex(int h) { if (h>4) { int hh = h-4-1; if (vertex.count() > 3) { Vertex* v = vertex[hh]; if (v) { vertex.extractNext(v); delete v; recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } } void BasePolygon::edit(const Vector& v, int h) { if (h < 5) { Vector s1 = v * bckMatrix(); Vector s2 = bckMap(handle[h-1],Coord::CANVAS); if (s1[0] != 0 && s1[1] != 0 && s2[0] != 0 && s2[1] != 0) { double a = fabs(s1[0]/s2[0]); double b = fabs(s1[1]/s2[1]); double s = a > b ? a : b; vertex.head(); do vertex.current()->vector *= Scale(s); while (vertex.next()); } updateBBox(); doCallBack(CallBack::EDITCB); } else { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::moveVertex(const Vector& v, int h) { Matrix mm = bckMatrix(); if (vertex[h-5]) vertex.current()->vector = v * mm; recalcCenter(); } void BasePolygon::recalcCenter() { // recalculate center Vector nc; vertex.head(); do nc += vertex.current()->vector * Rotate(angle) * FlipY(); while (vertex.next()); nc /= vertex.count(); center += nc; // update all vertices vertex.head(); do vertex.current()->vector -= nc * FlipY() * Rotate(-angle); while (vertex.next()); } void BasePolygon::rotate(const Vector& v, int h) { if (h < 5) Marker::rotate(v,h); else { // we need to check this here, because we are really rotating if (canEdit()) { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } void BasePolygon::updateHandles() { // generate handles numHandle = 4 + vertex.count(); if (handle) delete [] handle; handle = new Vector[numHandle]; // the first four are our control handles BBox bb; vertex.head(); do bb.bound(vertex.current()->vector); while (vertex.next()); Vector zz = parent->zoom(); float r = 10/zz.length(); bb.expand(r); // give us more room handle[0] = fwdMap(bb.ll,Coord::CANVAS); handle[1] = fwdMap(bb.lr(),Coord::CANVAS); handle[2] = fwdMap(bb.ur,Coord::CANVAS); handle[3] = fwdMap(bb.ul(),Coord::CANVAS); // and the rest are vertices int i=4; vertex.head(); do handle[i++] = fwdMap(vertex.current()->vector,Coord::CANVAS); while (vertex.next()); } void BasePolygon::updateCoords(const Matrix& mx) { Scale s(mx); vertex.head(); do vertex.current()->vector *= s; while (vertex.next()); Marker::updateCoords(mx); } void BasePolygon::listBase(FitsImage* ptr, ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { Matrix mm = fwdMatrix(); str << type_ << '('; int first=1; vertex.head(); do { if (!first) str << ','; first=0; ptr->listFromRef(str,vertex.current()->vector*mm,sys,sky,format); } while (vertex.next()); str << ')'; }
SAOImageDS9/SAOImageDS9
tksao/frame/basepolygon.C
C++
gpl-3.0
4,927
package pg.autyzm.friendly_plans.manager_app.view.task_create; import android.app.FragmentTransaction; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import database.repository.StepTemplateRepository; import javax.inject.Inject; import database.entities.Asset; import database.entities.TaskTemplate; import database.repository.TaskTemplateRepository; import pg.autyzm.friendly_plans.ActivityProperties; import pg.autyzm.friendly_plans.App; import pg.autyzm.friendly_plans.AppComponent; import pg.autyzm.friendly_plans.R; import pg.autyzm.friendly_plans.asset.AssetType; import pg.autyzm.friendly_plans.databinding.FragmentTaskCreateBinding; import pg.autyzm.friendly_plans.manager_app.validation.TaskValidation; import pg.autyzm.friendly_plans.manager_app.validation.Utils; import pg.autyzm.friendly_plans.manager_app.validation.ValidationResult; import pg.autyzm.friendly_plans.manager_app.view.components.SoundComponent; import pg.autyzm.friendly_plans.manager_app.view.main_screen.MainActivity; import pg.autyzm.friendly_plans.manager_app.view.step_list.StepListFragment; import pg.autyzm.friendly_plans.manager_app.view.task_type_enum.TaskType; import pg.autyzm.friendly_plans.manager_app.view.view_fragment.CreateFragment; public class TaskCreateFragment extends CreateFragment implements TaskCreateActivityEvents { private static final String REGEX_TRIM_NAME = "_([\\d]*)(?=\\.)"; @Inject TaskValidation taskValidation; @Inject TaskTemplateRepository taskTemplateRepository; @Inject StepTemplateRepository stepTemplateRepository; private TextView labelTaskName; private EditText taskName; private EditText taskDurationTime; private Long taskId; private Integer typeId; private Button steps; private RadioGroup types; private TaskType taskType = TaskType.TASK; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FragmentTaskCreateBinding binding = DataBindingUtil.inflate( inflater, R.layout.fragment_task_create, container, false); binding.setEvents(this); View view = binding.getRoot(); ImageButton playSoundIcon = (ImageButton) view.findViewById(R.id.id_btn_play_sound); AppComponent appComponent = ((App) getActivity().getApplication()).getAppComponent(); soundComponent = SoundComponent.getSoundComponent( soundId, playSoundIcon, getActivity().getApplicationContext(), appComponent); appComponent.inject(this); binding.setSoundComponent(soundComponent); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { registerViews(view); view.post(new Runnable() { // Set assets only when the layout is completely built @Override public void run() { Bundle arguments = getArguments(); if (arguments != null) { Long taskId = (Long) arguments.get(ActivityProperties.TASK_ID); if (taskId != null) { initTaskForm(taskId); } } } }); } private void registerViews(View view) { labelTaskName = (TextView) view.findViewById(R.id.id_tv_task_name_label); Utils.markFieldMandatory(labelTaskName); taskName = (EditText) view.findViewById(R.id.id_et_task_name); pictureFileName = (EditText) view.findViewById(R.id.id_et_task_picture); soundFileName = (EditText) view.findViewById(R.id.id_et_task_sound); taskDurationTime = (EditText) view.findViewById(R.id.id_et_task_duration_time); picturePreview = (ImageView) view.findViewById(R.id.iv_picture_preview); clearSound = (ImageButton) view.findViewById(R.id.id_ib_clear_sound_btn); clearPicture = (ImageButton) view.findViewById(R.id.id_ib_clear_img_btn); steps = (Button) view.findViewById(R.id.id_btn_steps); types = (RadioGroup) view.findViewById(R.id.id_rg_types); RadioButton typeTask = (RadioButton) view.findViewById(R.id.id_rb_type_task); typeTask.setChecked(true); taskType = TaskType.TASK; } private Long saveOrUpdate() { soundComponent.stopActions(); try { if (taskId != null) { if (validateName(taskId, taskName) && validateDuration(taskDurationTime)) { typeId = taskType.getId(); Integer duration = getDuration(); clearSteps(typeId, taskId); taskTemplateRepository.update(taskId, taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } else { if (validateName(taskName) && validateDuration(taskDurationTime)) { Integer duration = getDuration(); typeId = taskType.getId(); long taskId = taskTemplateRepository.create(taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } } catch (RuntimeException exception) { Log.e("Task Create View", "Error saving task", exception); showToastMessage(R.string.save_task_error_message); } return null; } private void clearSteps(Integer typeId, Long taskId) { if (typeId != 1) { stepTemplateRepository.deleteAllStepsForTask(taskId); } } private boolean validateName(Long taskId, EditText taskName) { ValidationResult validationResult = taskValidation .isUpdateNameValid(taskId, taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateName(EditText taskName) { ValidationResult validationResult = taskValidation .isNewNameValid(taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateDuration(EditText duration) { ValidationResult validationResult = taskValidation .isDurationValid(duration.getText().toString()); return handleInvalidResult(duration, validationResult); } private void initTaskForm(long taskId) { this.taskId = taskId; TaskTemplate task = taskTemplateRepository.get(taskId); taskName.setText(task.getName()); if (task.getDurationTime() != null) { taskDurationTime.setText(String.valueOf(task.getDurationTime())); } Asset picture = task.getPicture(); Asset sound = task.getSound(); if (picture != null) { setAssetValue(AssetType.PICTURE, picture.getFilename(), picture.getId()); } if (sound != null) { setAssetValue(AssetType.SOUND, sound.getFilename(), sound.getId()); } typeId = task.getTypeId(); ((RadioButton) types.getChildAt(typeId - 1)).setChecked(true); setVisibilityStepButton(Integer.valueOf(task.getTypeId().toString())); } private void setVisibilityStepButton(int typeIdValue) { if (typeIdValue == 1) { steps.setVisibility(View.VISIBLE); } else { steps.setVisibility(View.INVISIBLE); } } private void showStepsList(final long taskId) { StepListFragment fragment = new StepListFragment(); Bundle args = new Bundle(); args.putLong(ActivityProperties.TASK_ID, taskId); fragment.setArguments(args); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.replace(R.id.task_container, fragment); transaction.addToBackStack(null); transaction.commit(); } private void showMainMenu() { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } @Override protected void setAssetValue(AssetType assetType, String assetName, Long assetId) { String assetNameTrimmed = assetName.replaceAll(REGEX_TRIM_NAME, ""); if (assetType.equals(AssetType.PICTURE)) { pictureFileName.setText(assetNameTrimmed); clearPicture.setVisibility(View.VISIBLE); pictureId = assetId; showPreview(pictureId, picturePreview); } else { soundFileName.setText(assetNameTrimmed); clearSound.setVisibility(View.VISIBLE); soundId = assetId; soundComponent.setSoundId(soundId); } } private Integer getDuration() { if (!taskDurationTime.getText().toString().isEmpty() && !taskDurationTime.getText().toString().equals("0")) { return Integer.valueOf(taskDurationTime.getText().toString()); } return null; } @Override public void eventListStep(View view) { taskId = saveOrUpdate(); if (taskId != null) { showStepsList(taskId); } } @Override public void eventSelectPicture(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.PICTURE); } @Override public void eventSelectSound(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.SOUND); } @Override public void eventClearPicture(View view) { clearPicture(); } @Override public void eventClearSound(View view) { clearSound(); } @Override public void eventClickPreviewPicture(View view) { showPicture(pictureId); } @Override public void eventChangeButtonStepsVisibility(View view, int id) { if (id == R.id.id_rb_type_task) { steps.setVisibility(View.VISIBLE); taskType = TaskType.TASK; } else { steps.setVisibility(View.INVISIBLE); if (id == R.id.id_rb_type_interaction) { taskType = TaskType.INTERACTION; } else { taskType = TaskType.PRIZE; } } } @Override public void eventSaveAndFinish(View view) { Long taskId = saveOrUpdate(); if (taskId != null) { showMainMenu(); } } }
autyzm-pg/friendly-plans
Friendly-plans/app/src/main/java/pg/autyzm/friendly_plans/manager_app/view/task_create/TaskCreateFragment.java
Java
gpl-3.0
11,189
/** Copyright 2010 Christian Kästner This file is part of CIDE. CIDE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. CIDE 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 CIDE. If not, see <http://www.gnu.org/licenses/>. See http://www.fosd.de/cide/ for further information. */ package de.ovgu.cide.export.virtual.internal; import java.util.Set; import org.eclipse.jdt.core.dom.CompilationUnit; import de.ovgu.cide.export.CopiedNaiveASTFlattener; import de.ovgu.cide.export.useroptions.IUserOptionProvider; import de.ovgu.cide.features.IFeature; import de.ovgu.cide.features.source.ColoredSourceFile; /** * how to print annotations? note: we assume ifdef semantics, i.e. annotations * may be nested, but always close in the reverse order * * * @author ckaestne * */ public interface IPPExportOptions extends IUserOptionProvider { /** * should the start and end instructions be printed in a new line? (i.e. * should a line break be enforced before?) * * the instruction is responsible for the linebreak at the end itself * * @return */ boolean inNewLine(); /** * get the code statement(s) to begin an annotation block * * @param f * set of features annotated for the current element * @return */ String getStartInstruction(Set<IFeature> f); /** * get the code statement(s) to end an annotation block * * @param f * set of features annotated for the current element * @return */ String getEndInstruction(Set<IFeature> f); CopiedNaiveASTFlattener getPrettyPrinter(ColoredSourceFile sourceFile); /** * allows the developer to change the AST before printing it. can be used * for some refactorings. returns the modified AST * * @param root * @param sourceFile * @return */ CompilationUnit refactorAST(CompilationUnit root, ColoredSourceFile sourceFile); }
ckaestne/CIDE
CIDE_Export_Virtual/src/de/ovgu/cide/export/virtual/internal/IPPExportOptions.java
Java
gpl-3.0
2,375
/** * \file stack.c * * Time-stamp: "2012-03-31 13:16:41 bkorb" * * This is a special option processing routine that will save the * argument to an option in a FIFO queue. * * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. * AutoOpts is Copyright (c) 1992-2012 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control * of the user of the license. * * The GNU Lesser General Public License, version 3 or later * See the files "COPYING.lgplv3" and "COPYING.gplv3" * * The Modified Berkeley Software Distribution License * See the file "COPYING.mbsd" * * These files have the following md5sums: * * 43b91e8ca915626ed3818ffb1b71248b pkg/libopts/COPYING.gplv3 * 06a1a2e4760c90ea5e1dad8dfaac4d39 pkg/libopts/COPYING.lgplv3 * 66a5cedaf62c4b2637025f049f9b826f pkg/libopts/COPYING.mbsd */ #ifdef WITH_LIBREGEX # include REGEX_HEADER #endif /*=export_func optionUnstackArg * private: * * what: Remove option args from a stack * arg: + tOptions* + pOpts + program options descriptor + * arg: + tOptDesc* + pOptDesc + the descriptor for this arg + * * doc: * Invoked for options that are equivalenced to stacked options. =*/ void optionUnstackArg(tOptions * pOpts, tOptDesc * pOptDesc) { tArgList * pAL; (void)pOpts; if ((pOptDesc->fOptState & OPTST_RESET) != 0) return; pAL = (tArgList*)pOptDesc->optCookie; /* * IF we don't have any stacked options, * THEN indicate that we don't have any of these options */ if (pAL == NULL) { pOptDesc->fOptState &= OPTST_PERSISTENT_MASK; if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0) pOptDesc->fOptState |= OPTST_DISABLED; return; } #ifdef WITH_LIBREGEX { regex_t re; int i, ct, dIdx; if (regcomp(&re, pOptDesc->optArg.argString, REG_NOSUB) != 0) return; /* * search the list for the entry(s) to remove. Entries that * are removed are *not* copied into the result. The source * index is incremented every time. The destination only when * we are keeping a define. */ for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) { char const * pzSrc = pAL->apzArgs[ i ]; char * pzEq = strchr(pzSrc, '='); int res; if (pzEq != NULL) *pzEq = NUL; res = regexec(&re, pzSrc, (size_t)0, NULL, 0); switch (res) { case 0: /* * Remove this entry by reducing the in-use count * and *not* putting the string pointer back into * the list. */ AGFREE(pzSrc); pAL->useCt--; break; default: case REG_NOMATCH: if (pzEq != NULL) *pzEq = '='; /* * IF we have dropped an entry * THEN we have to move the current one. */ if (dIdx != i) pAL->apzArgs[ dIdx ] = pzSrc; dIdx++; } } regfree(&re); } #else /* not WITH_LIBREGEX */ { int i, ct, dIdx; /* * search the list for the entry(s) to remove. Entries that * are removed are *not* copied into the result. The source * index is incremented every time. The destination only when * we are keeping a define. */ for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) { tCC* pzSrc = pAL->apzArgs[ i ]; char* pzEq = strchr(pzSrc, '='); if (pzEq != NULL) *pzEq = NUL; if (strcmp(pzSrc, pOptDesc->optArg.argString) == 0) { /* * Remove this entry by reducing the in-use count * and *not* putting the string pointer back into * the list. */ AGFREE(pzSrc); pAL->useCt--; } else { if (pzEq != NULL) *pzEq = '='; /* * IF we have dropped an entry * THEN we have to move the current one. */ if (dIdx != i) pAL->apzArgs[ dIdx ] = pzSrc; dIdx++; } } } #endif /* WITH_LIBREGEX */ /* * IF we have unstacked everything, * THEN indicate that we don't have any of these options */ if (pAL->useCt == 0) { pOptDesc->fOptState &= OPTST_PERSISTENT_MASK; if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0) pOptDesc->fOptState |= OPTST_DISABLED; AGFREE((void*)pAL); pOptDesc->optCookie = NULL; } } /* * Put an entry into an argument list. The first argument points to * a pointer to the argument list structure. It gets passed around * as an opaque address. */ LOCAL void addArgListEntry(void** ppAL, void* entry) { tArgList* pAL = *(void**)ppAL; /* * IF we have never allocated one of these, * THEN allocate one now */ if (pAL == NULL) { pAL = (tArgList*)AGALOC(sizeof(*pAL), "new option arg stack"); if (pAL == NULL) return; pAL->useCt = 0; pAL->allocCt = MIN_ARG_ALLOC_CT; *ppAL = (void*)pAL; } /* * ELSE if we are out of room * THEN make it bigger */ else if (pAL->useCt >= pAL->allocCt) { size_t sz = sizeof(*pAL); pAL->allocCt += INCR_ARG_ALLOC_CT; /* * The base structure contains space for MIN_ARG_ALLOC_CT * pointers. We subtract it off to find our augment size. */ sz += sizeof(char*) * (pAL->allocCt - MIN_ARG_ALLOC_CT); pAL = (tArgList*)AGREALOC((void*)pAL, sz, "expanded opt arg stack"); if (pAL == NULL) return; *ppAL = (void*)pAL; } /* * Insert the new argument into the list */ pAL->apzArgs[ (pAL->useCt)++ ] = entry; } /*=export_func optionStackArg * private: * * what: put option args on a stack * arg: + tOptions* + pOpts + program options descriptor + * arg: + tOptDesc* + pOptDesc + the descriptor for this arg + * * doc: * Keep an entry-ordered list of option arguments. =*/ void optionStackArg(tOptions * pOpts, tOptDesc * pOD) { char * pz; (void)pOpts; if ((pOD->fOptState & OPTST_RESET) != 0) { tArgList* pAL = (void*)pOD->optCookie; int ix; if (pAL == NULL) return; ix = pAL->useCt; while (--ix >= 0) AGFREE(pAL->apzArgs[ix]); AGFREE(pAL); } else { if (pOD->optArg.argString == NULL) return; AGDUPSTR(pz, pOD->optArg.argString, "stack arg"); addArgListEntry(&(pOD->optCookie), (void*)pz); } } /* * Local Variables: * mode: C * c-file-style: "stroustrup" * indent-tabs-mode: nil * End: * end of autoopts/stack.c */
nobled/gnutls
src/libopts/stack.c
C
gpl-3.0
7,335