repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
anuragsolanki/ofri-Haus
vendor/gems/compass-0.10.5/lib/compass/validator.rb
221
begin require 'rubygems' require 'compass-validator' rescue LoadError raise Compass::MissingDependency, %Q{The Compass CSS Validator could not be loaded. Please install it: sudo gem install compass-validator } end
agpl-3.0
ronaldpereira/WoWAnalyzer
src/parser/shared/modules/racials/draenei/GiftOfTheNaaru.ts
1022
import SPELLS from 'common/SPELLS/index'; import RACES from 'game/RACES'; import Analyzer from 'parser/core/Analyzer'; import Abilities from 'parser/core/modules/Abilities'; /** * Heals the target for 20% of the caster's total health over 5 sec. */ class GiftOfTheNaaru extends Analyzer { static dependencies = { abilities: Abilities, }; constructor(options: any) { super(options); this.active = this.selectedCombatant.race === RACES.Draenei; if (!this.active) { return; } options.abilities.add({ spell: [ SPELLS.GIFT_OF_THE_NAARU_DK, SPELLS.GIFT_OF_THE_NAARU_HUNTER, SPELLS.GIFT_OF_THE_NAARU_MONK, SPELLS.GIFT_OF_THE_NAARU_MAGE, SPELLS.GIFT_OF_THE_NAARU_PRIEST, SPELLS.GIFT_OF_THE_NAARU_PALADIN, SPELLS.GIFT_OF_THE_NAARU_SHAMAN, SPELLS.GIFT_OF_THE_NAARU_WARRIOR, ], category: Abilities.SPELL_CATEGORIES.DEFENSIVE, cooldown: 180, gcd: null, }); } } export default GiftOfTheNaaru;
agpl-3.0
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/operator/learner/meta/SDReweightMeasures.java
4132
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.meta; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.operator.OperatorException; import com.rapidminer.tools.Tools; import java.util.Iterator; /** * A set of weighted performance measures used for subgroup discovery. * * @author Martin Scholz Exp $ */ public class SDReweightMeasures extends WeightedPerformanceMeasures { private double gamma; private boolean additive = true; /** * Instantiates a new Sd reweight measures. * * @param e the e * @throws OperatorException the operator exception */ public SDReweightMeasures(ExampleSet e) throws OperatorException { super(e); } /** * Overwrites method from super class. Examples are reweighted by the additive or multiplicative * heuristic. After reweighting the class priors are rescaled so that P(pos) = P(neg). * * @param exampleSet the example set * @param posIndex the pos index * @param coveredSubset the covered subset * @return the boolean * @throws OperatorException the operator exception */ public boolean reweightExamples(ExampleSet exampleSet, int posIndex, int coveredSubset) throws OperatorException { Iterator<Example> reader = exampleSet.iterator(); Attribute timesCoveredAttrib = null; if (this.additive) { timesCoveredAttrib = exampleSet.getAttributes().get(SDRulesetInduction.TIMES_COVERED); } double sumPosWeight = 0; double sumNegWeight = 0; while (reader.hasNext()) { Example example = reader.next(); double weight = example.getWeight(); int label = ((int) example.getLabel()); if (label == posIndex) { int predicted = ((int) example.getPredictedLabel()); if (predicted == coveredSubset) { if (this.additive == true) { int timesCovered = ((int) example.getValue(timesCoveredAttrib)) + 1; weight = this.reweightAdd(weight, timesCovered); example.setValue(timesCoveredAttrib, timesCovered); } else { weight = this.reweightMult(weight); } example.setWeight(weight); } sumPosWeight += weight; } else { sumNegWeight += weight; } } double ratio = sumPosWeight / sumNegWeight; if (Tools.isNotEqual(ratio, 1)) { reader = exampleSet.iterator(); while (reader.hasNext()) { Example example = reader.next(); if ((int) (example.getLabel()) != posIndex) { example.setWeight(example.getWeight() * ratio); } } } return true; } private double reweightAdd(double w, int timesCovered) { // old weight factor: 1/i, new weight factor 1/(i+1) return (w * timesCovered) / (timesCovered + 1); } private double reweightMult(double w) { // Weight if covered i times is: \gamma^i. // w_{i+1} = w_i * gamma return w * gamma; } /** * Sets gamma. * * @param gamma the gamma */ public void setGamma(double gamma) { this.gamma = gamma; } /** * Sets additive. * * @param additive the additive */ public void setAdditive(boolean additive) { this.additive = additive; } }
agpl-3.0
harish-patel/ecrm
modules/DocumentRevisions/metadata/detailviewdefs.php
2995
<?php /********************************************************************************* * The contents of this file are subject to the SugarCRM Master Subscription * Agreement ("License") which can be viewed at * http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf * By installing or using this file, You have unconditionally agreed to the * terms and conditions of the License, and You may not use this file except in * compliance with the License. Under the terms of the license, You shall not, * among other things: 1) sublicense, resell, rent, lease, redistribute, assign * or otherwise transfer Your rights to the Software, and 2) use the Software * for timesharing or service bureau purposes such as hosting the Software for * commercial gain and/or for the benefit of a third party. Use of the Software * may be subject to applicable fees and any use of the Software without first * paying applicable fees is strictly prohibited. You do not have the right to * remove SugarCRM copyrights from the source code or user interface. * * All copies of the Covered Code must include on each user interface screen: * (i) the "Powered by SugarCRM" logo and * (ii) the SugarCRM copyright notice * in the same form as they appear in the distribution. See full license for * requirements. * * Your Warranty, Limitations of liability and Indemnity are expressly stated * in the License. Please refer to the License for the specific language * governing these rights and limitations under the License. Portions created * by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved. ********************************************************************************/ $viewdefs['DocumentRevisions']['DetailView'] = array( 'templateMeta' => array('maxColumns' => '2', 'form' => array( 'buttons' => array(), 'hidden'=>array('<input type="hidden" name="old_id" value="{$fields.document_revision_id.value}">')), 'widths' => array( array('label' => '10', 'field' => '30'), array('label' => '10', 'field' => '30') ), ), 'panels' => array ( '' => array ( array ( 'document_name', 'latest_revision', ), array ( 'revision', ), array ( 'filename', 'doc_type', ), array ( array ( 'name' => 'date_entered', 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', ), ), array ( 'change_log', ), ), ), );
agpl-3.0
adelq/pennfoodtrucks
config/environments/production.rb
3809
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "pennfoodtrucks_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = [I18n.default_locale] # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
agpl-3.0
Igorek2312/LibreLingvo
spa/app/scripts/services/user-authorities.js
317
'use strict'; /** * @ngdoc service * @name libreLingvoApp.userAuthorities * @description * # userAuthorities * Factory in the libreLingvoApp. */ angular.module('libreLingvoApp') .factory('UserAuthorities', function ($resource, HostUrl) { return $resource(HostUrl + "/api/v1/users/me/authorities"); });
agpl-3.0
CodeSphere/termitaria
TermitariaAudit/JavaSource/ro/cs/logaudit/web/controller/root/RootAbstractController.java
3191
/******************************************************************************* * This file is part of Termitaria, a project management tool * Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro * * Termitaria is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Termitaria. If not, see <http://www.gnu.org/licenses/> . ******************************************************************************/ package ro.cs.logaudit.web.controller.root; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.MessageSource; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import ro.cs.logaudit.common.IConstant; import ro.cs.logaudit.common.Tools; /** * @author matti_joona * @author Adelina * * Controller de baza pentru controllere abstracte care se vor crea de acum in modul */ public abstract class RootAbstractController extends AbstractController{ protected MessageSource messageSource; private String view = null; public String getView() { return view; } public void setView(String view) { this.view = view; } /** * @param messages the messages to set */ public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } protected void setErrors(HttpServletRequest request, List<String> errors) { if (Tools.getInstance().voidListCondition(errors)) return; if (request.getAttribute(IConstant.REQ_ATTR_ERRORS) != null){ List<String> oldErrors = (List<String>)request.getAttribute(IConstant.REQ_ATTR_ERRORS); oldErrors.addAll(errors); }else { request.setAttribute(IConstant.REQ_ATTR_ERRORS, errors); } } protected void setMessages(HttpServletRequest request, List<String> messages) { if (Tools.getInstance().voidListCondition(messages)) return; if (request.getAttribute(IConstant.REQ_ATTR_MSGS) != null){ List<String> oldErrors = (List<String>)request.getAttribute(IConstant.REQ_ATTR_MSGS); oldErrors.addAll(messages); }else { request.setAttribute(IConstant.REQ_ATTR_MSGS, messages); } } public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { if (view == null) { throw new IllegalArgumentException(getClass().toString().concat(": View is not set !")); } return handleRequestInternal(arg0, arg1); } }
agpl-3.0
anuradha-iic/sugar
modules/AOS_PDF_Templates/generatePdf_02 Oct 2012.php
14295
<?php /** * Products, Quotations & Invoices modules. * Extensions to SugarCRM * @package Advanced OpenSales for SugarCRM * @subpackage Products * @copyright SalesAgility Ltd http://www.salesagility.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE * along with this program; if not, see http://www.gnu.org/licenses * or write to the Free Software Foundation,Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA * * @author Salesagility Ltd <support@salesagility.com> */ if(!isset($_REQUEST['uid']) || empty($_REQUEST['uid']) || !isset($_REQUEST['templateID']) || empty($_REQUEST['templateID'])){ die('Error retrieving record. This record may be deleted or you may not be authorized to view it.'); } error_reporting(0); require_once('modules/AOS_PDF_Templates/PDF_Lib/mpdf.php'); require_once('modules/AOS_PDF_Templates/templateParser.php'); require_once('modules/AOS_PDF_Templates/sendEmail.php'); require_once('modules/AOS_PDF_Templates/AOS_PDF_Templates.php'); global $mod_strings; $module_type = $_REQUEST['module']; $module_type_file = strtoupper(ltrim(rtrim($module_type,'s'),'AOS_')); $module_type_low = strtolower($module_type); $module = new $module_type(); $module->retrieve($_REQUEST['uid']); $task = $_REQUEST['task']; $lineItems = array(); $sql = "SELECT id, product_id FROM aos_products_quotes WHERE parent_type = '".$module_type."' AND parent_id = '".$module->id."' AND product_id != '0' AND deleted = 0 ORDER BY number ASC"; $res = $module->db->query($sql); while($row = $module->db->fetchByAssoc($res)){ $lineItems[$row['id']] = $row['product_id']; } $serviceLineItems = array(); $sql = "SELECT id, product_id FROM aos_products_quotes WHERE parent_type = '".$module_type."' AND parent_id = '".$module->id."' AND product_id = '0' AND deleted = 0 ORDER BY number ASC"; $res = $module->db->query($sql); while($row = $module->db->fetchByAssoc($res)){ $serviceLineItems[$row['id']] = $row['product_id']; } $template = new AOS_PDF_Templates(); $template->retrieve($_REQUEST['templateID']); $templateName = $template->name; $SummaryDetails = $module->fetched_row; $quoteName = $SummaryDetails['name']; //echo "<pre>"; //print_r($SummaryDetails); die; function formatMoney($number, $fractional=false) { if ($fractional) { $number = sprintf('%.2f', $number); } while (true) { $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number); if ($replaced != $number) { $number = $replaced; } else { break; } } return $number; } $object_arr = array(); $object_arr[$module_type] = $module->id; $object_arr['Accounts'] = $module->billing_account_id; $object_arr['Contacts'] = $module->billing_contact_id; $object_arr['Users'] = $module->assigned_user_id; $search = array ('@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags '@([\r\n])[\s]+@', // Strip out white space '@&(quot|#34);@i', // Replace HTML entities '@&(amp|#38);@i', '@&(lt|#60);@i', '@&(gt|#62);@i', '@&(nbsp|#160);@i', '@&(iexcl|#161);@i', '@&#(\d+);@e', '@<address[^>]*?>@si' ); $replace = array ('', '', '\1', '"', '&', '<', '>', ' ', chr(161), 'chr(\1)', '<br>' ); $header = preg_replace($search, $replace, $template->pdfheader); //echo $template->pdfheader; die; $footer = preg_replace($search, $replace, $template->pdffooter); $text = preg_replace($search, $replace, $template->description); $text = preg_replace('/\{DATE\s+(.*?)\}/e',"date('\\1')",$text ); $text = str_replace("\$aos_quotes","\$".$module_type_low,$text); $text = str_replace("\$aos_invoices","\$".$module_type_low,$text); $text = str_replace("\$total_amt","\$".$module_type_low."_total_amt",$text); $text = str_replace("\$discount_amount","\$".$module_type_low."_discount_amount",$text); $text = str_replace("\$subtotal_amount","\$".$module_type_low."_subtotal_amount",$text); $text = str_replace("\$tax_amount","\$".$module_type_low."_tax_amount",$text); $text = str_replace("\$shipping_amount","\$".$module_type_low."_shipping_amount",$text); $text = str_replace("\$total_amount","\$".$module_type_low."_total_amount",$text); $text = str_replace("\$total_nrc","\$".$module_type_low."_total_nrc",$text); $text = str_replace("\$OneTimeGrandTotal","\$".$module_type_low."_OneTimeGrandTotal",$text); $firstValue = ''; $firstNum = 0; $lastValue = ''; $lastNum = 0; //Find first and last valid line values $product_quote = new AOS_Products_Quotes(); foreach($product_quote->field_defs as $name => $arr){ if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){ $curNum = strpos($text,'$aos_products_quotes_'.$name); if($curNum) { if($curNum < $firstNum || $firstNum == 0) { $firstValue = '$aos_products_quotes_'.$name; $firstNum = $curNum; } else if($curNum > $lastNum) { $lastValue = '$aos_products_quotes_'.$name; $lastNum = $curNum; } } } } $product = new AOS_Products(); foreach($product->field_defs as $name => $arr){ if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){ $curNum = strpos($text,'$aos_products_'.$name); if($curNum) { if($curNum < $firstNum || $firstNum == 0) { $firstValue = '$aos_products_'.$name; $firstNum = $curNum; } else if($curNum > $lastNum) { $lastValue = '$aos_products_'.$name; $lastNum = $curNum; } } } } if($firstValue !== '' && $lastvalue !== ''){ //Converting Text $parts = explode($firstValue,$text); $text = $parts[0]; $parts = explode($lastValue,$parts[1]); $linePart = $firstValue . $parts[0] . $lastValue; if(count($lineItems) != 0){ //Read line start <tr> value $tcount = strrpos($text,"<tr"); $lsValue = substr($text,$tcount); $tcount=strpos($lsValue,">")+1; $lsValue = substr($lsValue,0,$tcount); //Read line end values $tcount=strpos($parts[1],"</tr>")+5; $leValue = substr($parts[1],0,$tcount); //Converting Line Items $obb = array(); $sep = ''; $tdTemp = explode($lsValue,$text); foreach($lineItems as $id => $productId){ $obb['AOS_Products_Quotes'] = $id; $obb['AOS_Products'] = $productId; //echo "Verma: <pre>"; print_r($obb); $text .= $sep . templateParser::parse_template($linePart, $obb, $SummaryDetails); $sep = $leValue. $lsValue . $tdTemp[count($tdTemp)-1]; } } else{ $tcount = strrpos($text,"<tr"); $text = substr($text,0,$tcount); $tcount=strpos($parts[1],"</tr>")+5; $parts[1]= substr($parts[1],$tcount); } $text .= $parts[1]; } $firstValue = ''; $firstNum = 0; $lastValue = ''; $lastNum = 0; $text = str_replace("\$aos_services_quotes_service","\$aos_services_quotes_product",$text); //Find first and last valid line values $product_quote = new AOS_Products_Quotes(); foreach($product_quote->field_defs as $name => $arr){ if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){ $curNum = strpos($text,'$aos_services_quotes_'.$name); if($curNum) { if($curNum < $firstNum || $firstNum == 0) { $firstValue = '$aos_products_quotes_'.$name; $firstNum = $curNum; } else if($curNum > $lastNum) { $lastValue = '$aos_products_quotes_'.$name; $lastNum = $curNum; } } } } if($firstValue !== '' && $lastvalue !== '') { $text = str_replace("\$aos_products","\$aos_null",$text); $text = str_replace("\$aos_services","\$aos_products",$text); $parts = explode($firstValue,$text); $text = $parts[0]; $parts = explode($lastValue,$parts[1]); $linePart = $firstValue . $parts[0] . $lastValue; if(count($serviceLineItems) != 0){ //Read line start <tr> value $tcount = strrpos($text,"<tr"); $lsValue = substr($text,$tcount); $tcount=strpos($lsValue,">")+1; $lsValue = substr($lsValue,0,$tcount); //Read line end values $tcount=strpos($parts[1],"</tr>")+5; $leValue = substr($parts[1],0,$tcount); //Converting ServiceLine Items $obb = array(); $sep = ''; $tdTemp = explode($lsValue,$text); foreach($serviceLineItems as $id => $productId){ $obb['AOS_Products_Quotes'] = $id; $obb['AOS_Products'] = $productId; //$text .= $sep . templateParser::parse_template($linePart, $obb)."$"; $text .= $sep . templateParser::parse_template($linePart, $obb, $SummaryDetails); $sep = $leValue. $lsValue . $tdTemp[count($tdTemp)-1]; } } else{ //Remove Line if no values $tcount = strrpos($text,"<tr"); $text = substr($text,0,$tcount); $tcount=strpos($parts[1],"</tr>")+5; $parts[1]= substr($parts[1],$tcount); } $text .= $parts[1]; } // sample DISCOUNTS AND TOTALS SECTION $stringtoaddinPDF $pos = strpos($template->description, "sample DISCOUNTS AND TOTALS SECTION"); if ($pos === false) { //echo "The string '$findme' was not found in the string '$mystring'"; $stringA = $text; $stringB = $stringtoaddinPDF; $length = strlen($text); $strHTMLTags = htmlentities($stringA); $pos2 = strpos($stringA, "term.]"); if ($pos2 === false) { //echo "The string '$findme' was not found in the string '$mystring'"; $text .= $stringtoaddinPDF; } else { //echo "The string //echo "<hr>Enjoy!! <br><br><br><br><br><br>"; $stringFirstPart = substr($stringA,0,$pos2+6); $stringSeconPart = substr($stringA,$pos2+7,$length); $stringSeconPartlength = strlen($stringSeconPart); $stringSeconPart2 = substr($stringSeconPart,5,$stringSeconPartlength); //$secPartHTMLTags = htmlentities($stringSeconPart); //$secPartHTMLTags = str_replace('pacing="2" cellpadding="2"> <tbody> <tr style="text-align: left;"> <td style="text-align: left;">', '<table border="0" width="100%" cellpadding="0" cellspacing="0"> <tbody> <tr style="text-align: left;"> <td style="text-align: left;">', $secPartHTMLTags); //echo $stringSeconPart = html_entity_decode($secPartHTMLTags); //echo $stringFirstPartHTMLTags = htmlentities($stringFirstPart); // $stringFirstPart = str_replace('br />', '<br />', $stringFirstPart); //echo html_entity_decode($stringFirstPart)."<br><br>Mahajan<br>".html_entity_decode($stringSeconPart); //$text = html_entity_decode($stringFirstPart).$stringtoaddinPDF.html_entity_decode($stringSeconPart); $text = $stringFirstPart.$stringtoaddinPDF.$stringSeconPart2; } } else { //echo "The string '$findme' was found in the string '$mystring'"; $text = str_replace($existed, $stringtoaddinPDF, $text); } // text-transform: uppercase; // echo $text; die; CalculatedTaxAmount //if($templateName != "NLI Quotes Template V 1.3") //{ CalculatedTaxAmount $service_subtotal_nrc = $SummaryDetails['service_subtotal_nrc']; $product_subtotal_nrc = $SummaryDetails['product_subtotal_nrc']; $build_field = "$".formatMoney($service_subtotal_nrc + $product_subtotal_nrc, true); $text = str_replace("BUILD FIELD", $build_field, $text); /*$aos_quotes_tax_amount = (1 - ($SummaryDetails['order_discount']/$SummaryDetails['product_subtotal_mrc'])) * $SummaryDetails['tax_amount']; $aos_quotes_tax_amount_Final = "$".formatMoney($aos_quotes_tax_amount, true); $text = str_replace("CalculatedTaxAmount", $aos_quotes_tax_amount_Final, $text); $aos_quotes_grand_total_nrc = "$".formatMoney(($service_subtotal_nrc + $product_subtotal_nrc) - $SummaryDetails['order_nrc_discont'], true); $text = str_replace('aos_quotes_grand_total_nrc', $aos_quotes_grand_total_nrc, $text); */ $aos_quotes_grand_total_nrc2 = ( (($service_subtotal_nrc + $product_subtotal_nrc) - $SummaryDetails['order_nrc_discont']) + $SummaryDetails['shipping_amount'] + $SummaryDetails['product_subtotal_lmd'] ); $grandtotal = "$".formatMoney($aos_quotes_grand_total_nrc2, true); $text = str_replace('aosQuotes_grand_total', $grandtotal, $text); //echo $text; //die; //} $converted = templateParser::parse_template($text, $object_arr, $SummaryDetails); $converted = html_entity_decode(str_replace('&nbsp;',' ',$converted)); $header = templateParser::parse_template($header, $object_arr, $SummaryDetails); $footer = templateParser::parse_template($footer, $object_arr, $SummaryDetails); $printable = str_replace("\n","<br />",$converted); if($task == 'pdf' || $task == 'emailpdf') { $file_name = $mod_strings['LBL_PDF_NAME']."_".str_replace(" ","_",$module->name).".pdf"; ob_clean(); try{ $pdf=new mPDF('en','A4','','DejaVuSans',15,15,16,16,8,8); $pdf->setAutoFont(); $pdf->SetHTMLHeader($header); $pdf->SetHTMLFooter($footer); //$pdf->SetHTMLFooter('<p style="text-align: center;">'.$quoteName."</p>"); //echo $printable; die; $pdf->writeHTML($printable); if($task == 'pdf'){ $pdf->Output($file_name, "D"); }else{ $fp = fopen('cache/upload/attachfile.pdf','wb'); fclose($fp); $pdf->Output('cache/upload/attachfile.pdf','F'); sendEmail::send_email($module,$module_type, '',$file_name, true); } }catch(mPDF_exception $e){ echo $e; } } else if($task == 'email') { sendEmail::send_email($module,$module_type, $printable,'', false); } ?>
agpl-3.0
pavlovicnemanja/superdesk-client-core
scripts/apps/archive/constants.ts
1972
export enum ITEM_STATE { /** * Item created in user workspace. */ DRAFT = 'draft', /** * Ingested item in ingest collection, not production. */ INGESTED = 'ingested', /** * Automatically ingested to desk. */ ROUTED = 'routed', /** * Item manually fetched from ingest to desk. */ FETCHED = 'fetched', /** * Item is sent to a desk. */ SUBMITTED = 'submitted', /** * Work started on a desk. */ IN_PROGRESS = 'in_progress', /** * Removed from a desk. */ SPIKED = 'spiked', /** * Published. */ PUBLISHED = 'published', /** * Scheduled for publishing. */ SCHEDULED = 'scheduled', /** * Correction is published. */ CORRECTED = 'corrected', /** * Killed, never publish again. */ KILLED = 'killed', /** * Sort of killed, never publish again. */ RECALLED = 'recalled', /** * Unpublished, might be published again. */ UNPUBLISHED = 'unpublished', } /** * Item was published once (or will be soon for scheduled) * * PUBLISHED | SCHEDULED | CORRECTED | KILLED | RECALLED | UNPUBLISHED */ export const PUBLISHED_STATES = [ ITEM_STATE.PUBLISHED, ITEM_STATE.SCHEDULED, ITEM_STATE.CORRECTED, ITEM_STATE.KILLED, ITEM_STATE.RECALLED, ITEM_STATE.UNPUBLISHED, ]; /** * Not published atm, but it was once * * KILLED | RECALLED | UNPUBLISHED */ export const KILLED_STATES = [ ITEM_STATE.KILLED, ITEM_STATE.RECALLED, ]; /** * Item is canceled before or after publishing * * KILLED | RECALLED | UNPUBLISHED | SPIKED */ export const CANCELED_STATES = KILLED_STATES.concat([ITEM_STATE.SPIKED]); /** * Such items can't be edited without further action (or ever) * * KILLED | RECALLED | UNPUBLISHED | SPIKED | SCHEDULED */ export const READONLY_STATES = CANCELED_STATES.concat([ITEM_STATE.SCHEDULED]);
agpl-3.0
adejoux/djouxblog
app/controllers/comments_controller.rb
2449
class CommentsController < ApplicationController load_and_authorize_resource # GET /comments # GET /comments.json def index @comments = Comment.all respond_to do |format| format.html # index.html.erb format.json { render json: @comments } end end # GET /comments/1 # GET /comments/1.json def show @comment = Comment.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @comment } end end # GET /comments/new # GET /comments/new.json def new @comment = Comment.new respond_to do |format| format.html # new.html.erb format.json { render json: @comment } end end # GET /comments/1/edit def edit @comment = Comment.find(params[:id]) end # POST /comments # POST /comments.json def create @comment = Comment.new(comment_params) respond_to do |format| if @comment.save UserMailer.posted_comment(@comment).deliver format.html { case @comment.page.category when "wiki" redirect_to wiki_path(@comment.page, :format => 'html'), :notice =>"Your comment was added. Thank You." when "posts" redirect_to post_path(@comment.page, :format => 'html'), :notice =>"Your comment was added. Thank You." else redirect_to page_path(@comment.page, :format => 'html'), :notice =>"Your comment was added. Thank You." end } else format.html { render :js => "alert('error saving comment');" } end end end # PUT /comments/1 # PUT /comments/1.json def update @comment = Comment.find(params[:id]) respond_to do |format| if @comment.update_attributes(comment_params) format.html { redirect_to @comment, notice: 'Comment was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end # DELETE /comments/1 # DELETE /comments/1.json def destroy @comment = Comment.find(params[:id]) if @comment.destroy render :json => @comment, :status => :ok else render :js => "alert('error deleting comment');" end end private def comment_params params.require(:comment).permit(:body, :email, :name, :page_id) end end
agpl-3.0
WireShoutLLC/votehaus
public/endpoints/process_election_modify.php
827
<?php require_once('../includes/config.php'); require_once('../includes/credentials.php'); $errors = array(); $data = array(); if(isset($_POST['csrf']) && session_csrf_check($_POST['csrf']) && session_get_type() == "user") { if((isset($_POST['name']) && !empty($_POST['name'])) && (isset($_POST['pk']) && !empty($_POST['pk']) && is_numeric($_POST['pk'])) && (isset($_POST['value']) && !empty($_POST['value']))) { if($_POST['name'] == "election_name") { $data['success'] = true; $data['message'] = 'Success!'; } else { $errors['name'] = 'Invalid name.'; } } else { $errors['name'] = 'Invalid name.'; } } else { $errors['req'] = 'Request is invalid.'; } if(!empty($errors)) { $data['success'] = false; $data['errors'] = $errors; } echo json_encode($data);
agpl-3.0
techorix/semtix
src/main/java/org/semtix/shared/elements/ComboBoxSemester.java
2533
/* * Semtix Semesterticketbüroverwaltungssoftware entwickelt für das * Semesterticketbüro der Humboldt-Universität Berlin * * Copyright (c) 2015. Michael Mertins (MichaelMertins@gmail.com) * 2011-2014 Jürgen Schmelzle (j.schmelzle@web.de) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.semtix.shared.elements; import org.semtix.db.DBHandlerSemester; import org.semtix.db.dao.Semester; import org.semtix.shared.daten.enums.Uni; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * Formularkomponente für eine ComboBox zur Anzeige der Semester, die in der Datenbank gespeichert sind. * */ @SuppressWarnings("serial") public class ComboBoxSemester extends JComboBox { private List<Semester> semesterListe; /** * Erstellt eine ComboBox mit Semestereinträgen für eine bestimmte Universität. * @param uni ausgewählte Universität */ public ComboBoxSemester(Uni uni) { semesterListe = new ArrayList<Semester>(); fillList(uni); } /** * Füllt die Liste mit Semestereinträgen für eine bestimmte Universität und übergibt der ComboBox das Model * @param uni ausgewählte Universität */ public void fillList(Uni uni) { // DBHandler erstellen DBHandlerSemester dbHandlerSemester = new DBHandlerSemester(); // Holt die Liste der Semester semesterListe = dbHandlerSemester.getSemesterListe(uni); if(semesterListe.size() > 0) { // Model erstellen DefaultComboBoxModel modelSemester = new DefaultComboBoxModel(); for(Semester s : semesterListe) modelSemester.addElement(s); // Der ComboBox wird das Model zugewiesen setModel(modelSemester); } } /** * Liefert die Liste mit den Semestereinträgen. * @return Semester-Liste */ public List<Semester> getSemesterListe() { return semesterListe; } }
agpl-3.0
teoincontatto/engine
mongodb/repl/src/main/java/com/torodb/mongodb/repl/sharding/isolation/TransDecorator.java
4537
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.mongodb.repl.sharding.isolation; import com.torodb.core.cursors.Cursor; import com.torodb.core.exceptions.user.CollectionNotFoundException; import com.torodb.core.exceptions.user.IndexNotFoundException; import com.torodb.core.language.AttributeReference; import com.torodb.kvdocument.values.KvValue; import com.torodb.torod.CollectionInfo; import com.torodb.torod.IndexInfo; import com.torodb.torod.TorodConnection; import com.torodb.torod.TorodTransaction; import com.torodb.torod.cursors.TorodCursor; import org.jooq.lambda.tuple.Tuple2; import java.util.Collection; import java.util.List; import java.util.stream.Stream; public abstract class TransDecorator<D extends TorodTransaction, C extends TorodConnection> implements TorodTransaction { private final C connection; private final D decorated; public TransDecorator(C connection, D decorated) { this.connection = connection; this.decorated = decorated; } protected D getDecorated() { return decorated; } @Override public boolean isClosed() { return decorated.isClosed(); } @Override public C getConnection() { return connection; } @Override public boolean existsDatabase(String dbName) { return decorated.existsDatabase(dbName); } @Override public boolean existsCollection(String dbName, String colName) { return decorated.existsCollection(dbName, colName); } @Override public List<String> getDatabases() { return decorated.getDatabases(); } @Override public long getDatabaseSize(String dbName) { return decorated.getDatabaseSize(dbName); } @Override public long countAll(String dbName, String colName) { return decorated.countAll(dbName, colName); } @Override public long getCollectionSize(String dbName, String colName) { return decorated.getCollectionSize(dbName, colName); } @Override public long getDocumentsSize(String dbName, String colName) { return decorated.getDocumentsSize(dbName, colName); } @Override public TorodCursor findAll(String dbName, String colName) { return decorated.findAll(dbName, colName); } @Override public TorodCursor findByAttRef(String dbName, String colName, AttributeReference attRef, KvValue<?> value) { return decorated.findByAttRef(dbName, colName, attRef, value); } @Override public TorodCursor findByAttRefIn(String dbName, String colName, AttributeReference attRef, Collection<KvValue<?>> values) { return decorated.findByAttRefIn(dbName, colName, attRef, values); } @Override public Cursor<Tuple2<Integer, KvValue<?>>> findByAttRefInProjection(String dbName, String colName, AttributeReference attRef, Collection<KvValue<?>> values) { return decorated.findByAttRefInProjection(dbName, colName, attRef, values); } @Override public TorodCursor fetch(String dbName, String colName, Cursor<Integer> didCursor) { return decorated.fetch(dbName, colName, didCursor); } @Override public Stream<CollectionInfo> getCollectionsInfo(String dbName) { return decorated.getCollectionsInfo(dbName); } @Override public CollectionInfo getCollectionInfo(String dbName, String colName) throws CollectionNotFoundException { return decorated.getCollectionInfo(dbName, colName); } @Override public Stream<IndexInfo> getIndexesInfo(String dbName, String colName) { return decorated.getIndexesInfo(dbName, colName); } @Override public IndexInfo getIndexInfo(String dbName, String colName, String idxName) throws IndexNotFoundException { return decorated.getIndexInfo(dbName, colName, idxName); } @Override public void close() { decorated.close(); } @Override public void rollback() { decorated.rollback(); } }
agpl-3.0
flyrightsister/boxcharter
client/src/app/SplashPage.js
1250
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Splash Page component for BoxCharter * @module * SplashPage */ import React from 'react'; const SplashPage = () => ( <div className="splash-page"> <div className="splash-blurb"> <h1> <img className="boxcharter-splash" alt="boxcharter-logo" src="/public/images/logos/boxcharter-75.png" /> BoxCharter </h1> <h4>Create box charts. Download PDFs. Make music with friends.</h4> </div> </div> ); export default SplashPage;
agpl-3.0
ANAXRIDER/OpenAI
OpenAI/OpenAI/Penalties/Pen_EX1_573b.cs
285
using System; using System.Collections.Generic; using System.Text; namespace OpenAI { class Pen_EX1_573b : PenTemplate //shandoslesson { public override float getPlayPenalty(Playfield p, Handmanager.Handcard hc, Minion target, int choice, bool isLethal) { return 0; } } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc2x3tc1/IfcSpecificHeatCapacityMeasure.java
5387
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc2x3tc1; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Specific Heat Capacity Measure</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValue <em>Wrapped Value</em>}</li> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}</li> * </ul> * * @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcSpecificHeatCapacityMeasure() * @model * @generated */ public interface IfcSpecificHeatCapacityMeasure extends IfcDerivedMeasureValue { /** * Returns the value of the '<em><b>Wrapped Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Wrapped Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Wrapped Value</em>' attribute. * @see #isSetWrappedValue() * @see #unsetWrappedValue() * @see #setWrappedValue(double) * @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcSpecificHeatCapacityMeasure_WrappedValue() * @model unsettable="true" * @generated */ double getWrappedValue(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Wrapped Value</em>' attribute. * @see #isSetWrappedValue() * @see #unsetWrappedValue() * @see #getWrappedValue() * @generated */ void setWrappedValue(double value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetWrappedValue() * @see #getWrappedValue() * @see #setWrappedValue(double) * @generated */ void unsetWrappedValue(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValue <em>Wrapped Value</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Wrapped Value</em>' attribute is set. * @see #unsetWrappedValue() * @see #getWrappedValue() * @see #setWrappedValue(double) * @generated */ boolean isSetWrappedValue(); /** * Returns the value of the '<em><b>Wrapped Value As String</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Wrapped Value As String</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Wrapped Value As String</em>' attribute. * @see #isSetWrappedValueAsString() * @see #unsetWrappedValueAsString() * @see #setWrappedValueAsString(String) * @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcSpecificHeatCapacityMeasure_WrappedValueAsString() * @model unsettable="true" * @generated */ String getWrappedValueAsString(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Wrapped Value As String</em>' attribute. * @see #isSetWrappedValueAsString() * @see #unsetWrappedValueAsString() * @see #getWrappedValueAsString() * @generated */ void setWrappedValueAsString(String value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetWrappedValueAsString() * @see #getWrappedValueAsString() * @see #setWrappedValueAsString(String) * @generated */ void unsetWrappedValueAsString(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcSpecificHeatCapacityMeasure#getWrappedValueAsString <em>Wrapped Value As String</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Wrapped Value As String</em>' attribute is set. * @see #unsetWrappedValueAsString() * @see #getWrappedValueAsString() * @see #setWrappedValueAsString(String) * @generated */ boolean isSetWrappedValueAsString(); } // IfcSpecificHeatCapacityMeasure
agpl-3.0
nextcloud/spreed
src/utils/webrtc/shims/MediaStreamTrack.js
3705
/** * * @copyright Copyright (c) 2020, Daniel Calviño Sánchez (danxuliu@gmail.com) * * @license AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ if (window.MediaStreamTrack) { const originalMediaStreamTrackClone = window.MediaStreamTrack.prototype.clone window.MediaStreamTrack.prototype.clone = function() { const newTrack = originalMediaStreamTrackClone.apply(this, arguments) this.dispatchEvent(new CustomEvent('cloned', { detail: newTrack })) return newTrack } const originalMediaStreamTrackStop = window.MediaStreamTrack.prototype.stop window.MediaStreamTrack.prototype.stop = function() { const wasAlreadyEnded = this.readyState === 'ended' originalMediaStreamTrackStop.apply(this, arguments) if (!wasAlreadyEnded) { this.dispatchEvent(new Event('ended')) } } // Event implementations do not support advanced parameters like "options" // or "useCapture". const originalMediaStreamTrackDispatchEvent = window.MediaStreamTrack.prototype.dispatchEvent const originalMediaStreamTrackAddEventListener = window.MediaStreamTrack.prototype.addEventListener const originalMediaStreamTrackRemoveEventListener = window.MediaStreamTrack.prototype.removeEventListener window.MediaStreamTrack.prototype.dispatchEvent = function(event) { if (this._listeners && this._listeners[event.type]) { this._listeners[event.type].forEach(listener => { listener.apply(this, [event]) }) } return originalMediaStreamTrackDispatchEvent.apply(this, arguments) } let isMediaStreamTrackDispatchEventSupported window.MediaStreamTrack.prototype.addEventListener = function(type, listener) { if (isMediaStreamTrackDispatchEventSupported === undefined) { isMediaStreamTrackDispatchEventSupported = false const testDispatchEventSupportHandler = () => { isMediaStreamTrackDispatchEventSupported = true } originalMediaStreamTrackAddEventListener.apply(this, ['test-dispatch-event-support', testDispatchEventSupportHandler]) originalMediaStreamTrackDispatchEvent.apply(this, [new Event('test-dispatch-event-support')]) originalMediaStreamTrackRemoveEventListener(this, ['test-dispatch-event-support', testDispatchEventSupportHandler]) console.debug('Is MediaStreamTrack.dispatchEvent() supported?: ', isMediaStreamTrackDispatchEventSupported) } if (!isMediaStreamTrackDispatchEventSupported) { if (!this._listeners) { this._listeners = [] } if (!Object.prototype.hasOwnProperty.call(this._listeners, type)) { this._listeners[type] = [listener] } else if (!this._listeners[type].includes(listener)) { this._listeners[type].push(listener) } } return originalMediaStreamTrackAddEventListener.apply(this, arguments) } window.MediaStreamTrack.prototype.removeEventListener = function(type, listener) { if (this._listeners && this._listeners[type]) { const index = this._listeners[type].indexOf(listener) if (index >= 0) { this._listeners[type].splice(index, 1) } } return originalMediaStreamTrackRemoveEventListener.apply(this, arguments) } }
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/quest/naboo/tamvar_senzen.lua
803
tamvar_senzen = Creature:new { objectName = "", customName = "Tamvar Senzen", socialGroup = "townsperson", faction = "townsperson", level = 100, chanceHit = 1, damageMin = 645, damageMax = 1000, baseXp = 9429, baseHAM = 24000, baseHAMmax = 30000, armor = 0, resists = {0,0,0,0,0,0,0,0,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = NONE, creatureBitmask = PACK, optionsBitmask = AIENABLED + CONVERSABLE, diet = HERBIVORE, templates = {"object/mobile/dressed_tamvar_senzen.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "tamvar_senzen_mission_giver_convotemplate", attacks = { } } CreatureTemplates:addCreatureTemplate(tamvar_senzen, "tamvar_senzen")
agpl-3.0
laclasse-com/service-annuaire
spec/api/api_portail_flux_spec.rb
6855
# coding: utf-8 require_relative '../helper' describe PortailFluxAPI do include Rack::Test::Methods def app Rack::Builder.parse_file('config.ru').first end url_prefix = Configuration::API_PATH + '/portail/flux' dataset = FluxPortail.select(:id).all it 'should return all flux_portail' do resp = get(url_prefix + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data.length.should eq 3 json_data[0]['id'].should eq dataset[0].id json_data[0]['etab_id'].should eq 1 json_data[0]['nb'].should eq 3 json_data[0]['icon'].should eq 'icon1.pbg' json_data[0]['flux'].should eq 'http://totot.flux' json_data[0]['title'].should eq 'title1' json_data[1]['id'].should eq dataset[1].id json_data[1]['etab_id'].should eq 1 json_data[1]['nb'].should eq 4 json_data[1]['icon'].should eq 'icon2.pbg' json_data[1]['flux'].should eq 'http://totot.flux2' json_data[1]['title'].should eq 'title2' json_data[2]['id'].should eq dataset[2].id json_data[2]['etab_id'].should eq 2 json_data[2]['nb'].should eq 4 json_data[2]['icon'].should eq 'icon3.pbg' json_data[2]['flux'].should eq 'http://totot.flux3' json_data[2]['title'].should eq 'title3' end it 'should retrun the right flux_portail for the given id' do resp = get(url_prefix + '/' + dataset[0].id.to_s + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data['id'].should eq dataset[0].id json_data['etab_id'].should eq 1 json_data['nb'].should eq 3 json_data['icon'].should eq 'icon1.pbg' json_data['flux'].should eq 'http://totot.flux' json_data['title'].should eq 'title1' resp = get(url_prefix + '/' + dataset[1].id.to_s + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data['id'].should eq dataset[1].id json_data['etab_id'].should eq 1 json_data['nb'].should eq 4 json_data['icon'].should eq 'icon2.pbg' json_data['flux'].should eq 'http://totot.flux2' json_data['title'].should eq 'title2' resp = get(url_prefix + '/' + dataset[2].id.to_s + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data['id'].should eq dataset[2].id json_data['etab_id'].should eq 2 json_data['nb'].should eq 4 json_data['icon'].should eq 'icon3.pbg' json_data['flux'].should eq 'http://totot.flux3' json_data['title'].should eq 'title3' resp = get(url_prefix + '/' + (dataset[2].id + 2 ).to_s + SECURITY_INFOS) resp.status.should eq 404 end it 'should return all flux_portail of etab' do resp = get(url_prefix + '/etablissement/0699999Z' + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data.length.should eq 2 json_data[0]['id'].should eq dataset[0].id json_data[0]['etab_id'].should eq 1 json_data[0]['nb'].should eq 3 json_data[0]['icon'].should eq 'icon1.pbg' json_data[0]['flux'].should eq 'http://totot.flux' json_data[0]['title'].should eq 'title1' json_data[1]['id'].should eq dataset[1].id json_data[1]['etab_id'].should eq 1 json_data[1]['nb'].should eq 4 json_data[1]['icon'].should eq 'icon2.pbg' json_data[1]['flux'].should eq 'http://totot.flux2' json_data[1]['title'].should eq 'title2' resp = get(url_prefix + '/etablissement/0696666A' + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data.length.should eq 1 json_data[0]['id'].should eq dataset[2].id json_data[0]['etab_id'].should eq 2 json_data[0]['nb'].should eq 4 json_data[0]['icon'].should eq 'icon3.pbg' json_data[0]['flux'].should eq 'http://totot.flux3' json_data[0]['title'].should eq 'title3' resp = get(url_prefix + '/etablissement/9699999Z' + SECURITY_INFOS) resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data.length.should eq 0 end it 'should delete and flux_portail ' do resp = delete(url_prefix + '/' + dataset[2].id.to_s + SECURITY_INFOS) resp.status.should eq 200 FluxPortail.select(:id).all.length.should eq 2 # invalid id resp = delete(url_prefix + '/' + dataset[2].id.to_s + SECURITY_INFOS) resp.status.should eq 404 end it 'should create a flux portail' do resp = post(url_prefix + SECURITY_INFOS ) resp.status.should eq 400 json_data = JSON.parse(resp.body) json_data.length.should eq 3 resp = post(url_prefix + SECURITY_INFOS, etab_code_uai: '0696666A') resp.status.should eq 400 json_data = JSON.parse(resp.body) json_data.length.should eq 2 resp = post(url_prefix + SECURITY_INFOS, etab_code_uai: '0696666A', flux: 'http://flux') resp.status.should eq 400 json_data = JSON.parse(resp.body) json_data.length.should eq 1 resp = post(url_prefix + SECURITY_INFOS, etab_code_uai: '0696666A', flux: 'http://flux', title: 'title') resp.status.should eq 201 json_data = JSON.parse(resp.body) json_data['id'].should eq FluxPortail.select(:id).order(Sequel.desc(:id)).all[0].id json_data['etab_id'].should eq 2 json_data['nb'].should eq 4 json_data['icon'].should eq nil json_data['flux'].should eq 'http://flux' json_data['title'].should eq 'title' resp = post(url_prefix + SECURITY_INFOS, etab_code_uai: '0699999Z', flux: 'http://flux', title: 'titleCREATE', nb: 10, icon: 'iconCREATE') resp.status.should eq 201 json_data = JSON.parse(resp.body) json_data['id'].should eq FluxPortail.select(:id).order(Sequel.desc(:id)).all[0].id json_data['etab_id'].should eq 1 json_data['nb'].should eq 10 json_data['icon'].should eq 'iconCREATE' json_data['flux'].should eq 'http://flux' json_data['title'].should eq 'titleCREATE' FluxPortail.all.length.should eq 5 end it 'should update an flux_portail' do resp = put(url_prefix + '/' + dataset[1].id.to_s + SECURITY_INFOS, nb: 10, title: 'title new', flux: 'url new', icon: 'iconNew.png') resp.status.should eq 200 json_data = JSON.parse(resp.body) json_data['id'].should eq dataset[1].id json_data['etab_id'].should eq 1 json_data['nb'].should eq 10 json_data['icon'].should eq 'iconNew.png' json_data['flux'].should eq 'url new' json_data['title'].should eq 'title new' # no id and no index resp = put(url_prefix + '/' + dataset[1].id.to_s + SECURITY_INFOS, libelle: 'label new', description: 'desc new', url: 'url new', icon: 'iconNew.png', color: 'pinkNew', active: false) resp.status.should eq 400 # invalid id resp = put(url_prefix + '/' + (dataset[2].id + 1000).to_s + SECURITY_INFOS, nb: 10, title: 'title new', flux: 'url new', icon: 'iconNew.png') resp.status.should eq 404 end end # class
agpl-3.0
twreporter/twreporter-react
src/testing-server.js
4649
/* eslint camelcase: ["error", {ignoreDestructuring: true}] */ import apiEndpoints from '@twreporter/redux/lib/constants/api-endpoints' import Express from 'express' import get from 'lodash/get' import net from 'net' // mock api response import mockIndexPageResponse from './mock-data/index-page' import { mockAPostResponse, mockPostsResponse } from './mock-data/posts' import { mockATopicResponse, mockTopicsResponse } from './mock-data/topics' import { mockAuthorsResponse, mockAuthorDetailResponse, mockAuthorCollectionsResponse, } from './mock-data/authors' const app = Express() const host = process.env.HOST || 'localhost' const port = process.env.PORT || 8080 const router = Express.Router() const _ = { get: get, } const _checkIfPortIsTaken = port => new Promise((resolve, reject) => { const tester = net .createServer() .once('error', err => err.code === 'EADDRINUSE' ? resolve(true) : reject(err) ) .once('listening', function() { tester .once('close', function() { resolve(false) }) .close() }) .listen(port) }) app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'X-Requested-With') next() }) router.use((req, res, next) => { console.log(req.method, req.url) // eslint-disable-line no-console next() }) router.route(`/${apiEndpoints.posts}/:slug`).get((req, res) => { const slug = req.params.slug const full = _.get(req, 'query.full', false) const apiResponse = mockAPostResponse(slug, full) switch (apiResponse.status) { case 'success': { res.json(apiResponse) return } case 'fail': { res.status(404).json(apiResponse) return } case 'error': default: { res.status(500).json(apiResponse) } } }) router.route(`/${apiEndpoints.posts}/`).get((req, res) => { const { limit = '10', offset = '0', id, category_id, tag_id } = req.query const _limit = Number(limit) const _offset = Number(offset) res.json(mockPostsResponse(_limit, _offset, id, category_id, tag_id)) }) router.route(`/${apiEndpoints.topics}/`).get((req, res) => { const { limit = '10', offset = '0' } = req.query const _limit = Number(limit) const _offset = Number(offset) res.json(mockTopicsResponse(_limit, _offset)) }) router.route(`/${apiEndpoints.topics}/:slug`).get((req, res) => { const slug = req.params.slug const full = _.get(req, 'query.full', false) const apiResponse = mockATopicResponse(slug, full) switch (apiResponse.status) { case 'success': { res.json(apiResponse) return } case 'fail': { res.status(404).json(apiResponse) return } case 'error': default: { res.status(500).json(apiResponse) } } }) router.param('searchParam', (req, res, next, searchParam) => { req.searchParam = searchParam next() }) router.route(`/${apiEndpoints.authors}/`).get((req, res) => { const { offset, limit } = req.query const _limit = Number(limit) const _offset = Number(offset) res.json( mockAuthorsResponse({ limit: _limit || 10, offset: _offset || 0, }) ) }) router.route(`/${apiEndpoints.authors}/:authorId/`).get((req, res) => { const authorId = req.params.authorId res.json(mockAuthorDetailResponse(authorId)) }) router.route(`/${apiEndpoints.authors}/:authorId/posts/`).get((req, res) => { const { offset, limit } = req.query const authorId = req.params.authorId const _limit = Number(limit) const _offset = Number(offset) res.json( mockAuthorCollectionsResponse({ limit: _limit || 10, offset: _offset || 0, authorId, }) ) }) router.route(`/${apiEndpoints.indexPage}/`).get((req, res) => { res.json(mockIndexPageResponse()) }) app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(err) // eslint-disable-line no-console if (_.get(err, 'statusCode') === 404) { res.redirect('/error/404') } else { res.redirect('/error/500') } }) _checkIfPortIsTaken(port) .then(thePortIsTaken => { if (!thePortIsTaken) { app.use('/v2/', router) app.listen(port, err => { if (err) throw new Error(err) console.log( '==> 💻 Started testing server at http://%s:%s', host, port ) // eslint-disable-line no-console }) } else { console.error('==> WARNINIG: The port %s is being used', port) // eslint-disable-line no-console } }) .catch(err => { console.error(err) // eslint-disable-line no-console })
agpl-3.0
ghjansen/cas
cas-core/src/main/java/com/ghjansen/cas/core/physics/Universe.java
1544
/* * CAS - Cellular Automata Simulator * Copyright (C) 2016 Guilherme Humberto Jansen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ghjansen.cas.core.physics; import com.ghjansen.cas.core.exception.InvalidSpaceException; import com.ghjansen.cas.core.exception.InvalidTimeException; /** * @author Guilherme Humberto Jansen (contact.ghjansen@gmail.com) */ public abstract class Universe<S extends Space, T extends Time> { private S space; private T time; protected Universe(S space, T time) throws InvalidSpaceException, InvalidTimeException { if (space == null) { throw new InvalidSpaceException(); } if (time == null) { throw new InvalidTimeException(); } this.space = space; this.time = time; } public S getSpace() { return space; } public T getTime() { return time; } }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-core/src/main/java/org/kuali/kfs/integration/cg/ContractsAndGrantsAwardAccount.java
1535
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.integration.cg; import org.kuali.rice.krad.bo.ExternalizableBusinessObject; public interface ContractsAndGrantsAwardAccount extends ExternalizableBusinessObject { public long getAwardId(); public String getAwardTitle(); public String getErrorMessage(); public boolean getFederalSponsor(); public String getGrantNumber(); public long getInstitutionalproposalId(); public String getProjectDirector(); public String getProposalFederalPassThroughAgencyNumber(); public String getProposalNumber(); public String getSponsorCode(); public String getSponsorName(); public String getPrimeSponsorCode(); public String getPrimeSponsorName(); }
agpl-3.0
digineo/invoice_collector-java
de.digineo.invoicecollector.core/src/main/java/de/digineo/invoicecollector/sdk/crawler/Keyweb.java
2622
package de.digineo.invoicecollector.sdk.crawler; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import de.digineo.invoicecollector.sdk.objects.Account; import de.digineo.invoicecollector.sdk.objects.Invoice; public class Keyweb extends Crawler { private HtmlAnchor invoiceLink; public Keyweb(String username, String password, Account account) { super(username, password, account); } public void login() throws LoginException, IOException { getPage("https://kcm.keyweb.de/index.cgi"); HtmlForm form = getFirstForm(); form.getInputByName("loginname").setValueAttribute(username); form.getInputByName("loginpasswd").setValueAttribute(password); currentPage = getFirstButton(form).click(); List<HtmlElement> anchors = (List<HtmlElement>) currentPage.getElementsByTagName("a"); for(HtmlElement link : anchors) { if(link.getAttribute("href").contains("rechnungonline")) { invoiceLink = (HtmlAnchor) link; break; } } if(invoiceLink == null) throw new LoginException(); } public ArrayList<Invoice> crawl() throws CrawlerException { ArrayList<Invoice> invoices = new ArrayList<Invoice>(); try { currentPage = invoiceLink.click(); DomNodeList<HtmlElement> formList = currentPage.getElementsByTagName("form"); DomNodeList<HtmlElement> cells; DomNodeList<HtmlElement> links; HtmlAnchor pdfLink; Invoice invoice; String number; for(HtmlElement elem : formList) { if(!elem.getAttribute("name").equals("RNR")) continue; pdfLink = null; cells = elem.getElementsByTagName("td"); links = elem.getElementsByTagName("a"); if(cells.size() < 7) continue; if(links.size() < 1) continue; pdfLink = (HtmlAnchor) links.get(0); number = null; Matcher matcher = Pattern.compile("\\d+").matcher(cells.get(6).asText()); if(matcher.find()) number = matcher.group(0); if(number != null) { invoice = createInvoice(number, cells.get(4).asText(), cells.get(2).asText(), pdfLink); if(invoice != null) invoices.add(invoice); } } } catch(Exception e) { e.printStackTrace(); throw new CrawlerException(e.getMessage(),e); } return invoices; } public void logout() throws LogoutException { // gibt es nicht. } }
agpl-3.0
objective-solutions/taskboard
dashboard-scenario/web-app/src/app/scenario/scenario/dialog/scenario-dialog.component.ts
691
import { Component, Input, ViewChild } from '@angular/core'; import { DialogComponent } from 'objective-design-system'; @Component({ selector: 'dbs-scenario-dialog', templateUrl: './scenario-dialog.component.html', styleUrls: ['./scenario-dialog.component.scss'] }) export class ScenarioDialogComponent { @Input() title: string; @Input() description: string; @ViewChild(DialogComponent) scenarioComponentDialog: DialogComponent; callback: Function; open(callback: Function) { this.callback = callback; this.scenarioComponentDialog.open(); } confirm() { this.callback(); this.scenarioComponentDialog.close(); } }
agpl-3.0
grupozeety/CDerpnext
erpnext/stock/doctype/stock_entry/stock_entry.py
39289
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe import frappe.defaults from frappe import _ from frappe.utils import cstr, cint, flt, comma_or, getdate, nowdate from erpnext.stock.utils import get_incoming_rate from erpnext.stock.stock_ledger import get_previous_sle, NegativeStockError from erpnext.stock.get_item_details import get_bin_details, get_default_cost_center, get_conversion_factor from erpnext.manufacturing.doctype.bom.bom import validate_bom_no import json class IncorrectValuationRateError(frappe.ValidationError): pass class DuplicateEntryForProductionOrderError(frappe.ValidationError): pass class OperationsNotCompleteError(frappe.ValidationError): pass from erpnext.controllers.stock_controller import StockController form_grid_templates = { "items": "templates/form_grid/stock_entry_grid.html" } class StockEntry(StockController): def get_feed(self): return _("From {0} to {1}").format(self.from_warehouse, self.to_warehouse) def onload(self): for item in self.get("items"): item.update(get_bin_details(item.item_code, item.s_warehouse)) def validate(self): self.pro_doc = None if self.production_order: self.pro_doc = frappe.get_doc('Production Order', self.production_order) self.validate_posting_time() self.validate_purpose() self.validate_item() self.set_transfer_qty() self.validate_uom_is_integer("uom", "qty") self.validate_uom_is_integer("stock_uom", "transfer_qty") self.validate_warehouse() self.validate_production_order() self.validate_bom() self.validate_finished_goods() self.validate_with_material_request() self.validate_batch() self.set_actual_qty() self.calculate_rate_and_amount() def on_submit(self): self.update_stock_ledger() self.updateProyeccion() from erpnext.stock.doctype.serial_no.serial_no import update_serial_nos_after_submit update_serial_nos_after_submit(self, "items") self.update_production_order() self.validate_purchase_order() self.make_gl_entries() def on_cancel(self): self.rollbackproyeccion() self.update_stock_ledger() self.update_production_order() self.make_gl_entries_on_cancel() def validate_purpose(self): valid_purposes = ["Material Issue", "Material Receipt", "Material Transfer", "Material Transfer for Manufacture", "Manufacture", "Repack", "Subcontract"] if self.purpose not in valid_purposes: frappe.throw(_("Purpose must be one of {0}").format(comma_or(valid_purposes))) if self.purpose in ("Manufacture", "Repack") and not self.difference_account: self.difference_account = frappe.db.get_value("Company", self.company, "default_expense_account") def set_transfer_qty(self): for item in self.get("items"): if not flt(item.qty): frappe.throw(_("Row {0}: Qty is mandatory").format(item.idx)) if not flt(item.conversion_factor): frappe.throw(_("Row {0}: UOM Conversion Factor is mandatory").format(item.idx)) item.transfer_qty = flt(item.qty * item.conversion_factor, self.precision("transfer_qty", item)) def validate_item(self): stock_items = self.get_stock_items() serialized_items = self.get_serialized_items() for item in self.get("items"): if item.item_code not in stock_items: frappe.throw(_("{0} is not a stock Item").format(item.item_code)) item_details = self.get_item_details(frappe._dict({"item_code": item.item_code, "company": self.company, "project": self.project, "uom": item.uom}), for_update=True) for f in ("uom", "stock_uom", "description", "item_name", "expense_account", "cost_center", "conversion_factor"): if f in ["stock_uom", "conversion_factor"] or not item.get(f): item.set(f, item_details.get(f)) if self.difference_account and not item.expense_account: item.expense_account = self.difference_account if not item.transfer_qty and item.qty: item.transfer_qty = item.qty * item.conversion_factor if (self.purpose in ("Material Transfer", "Material Transfer for Manufacture") and not item.serial_no and item.item_code in serialized_items): frappe.throw(_("Row #{0}: Please specify Serial No for Item {1}").format(item.idx, item.item_code), frappe.MandatoryError) def validate_warehouse(self): """perform various (sometimes conditional) validations on warehouse""" source_mandatory = ["Material Issue", "Material Transfer", "Subcontract", "Material Transfer for Manufacture"] target_mandatory = ["Material Receipt", "Material Transfer", "Subcontract", "Material Transfer for Manufacture"] validate_for_manufacture_repack = any([d.bom_no for d in self.get("items")]) if self.purpose in source_mandatory and self.purpose not in target_mandatory: self.to_warehouse = None for d in self.get('items'): d.t_warehouse = None elif self.purpose in target_mandatory and self.purpose not in source_mandatory: self.from_warehouse = None for d in self.get('items'): d.s_warehouse = None for d in self.get('items'): if not d.s_warehouse and not d.t_warehouse: d.s_warehouse = self.from_warehouse d.t_warehouse = self.to_warehouse if not (d.s_warehouse or d.t_warehouse): frappe.throw(_("Atleast one warehouse is mandatory")) if self.purpose in source_mandatory and not d.s_warehouse: if self.from_warehouse: d.s_warehouse = self.from_warehouse else: frappe.throw(_("Source warehouse is mandatory for row {0}").format(d.idx)) if self.purpose in target_mandatory and not d.t_warehouse: if self.to_warehouse: d.t_warehouse = self.to_warehouse else: frappe.throw(_("Target warehouse is mandatory for row {0}").format(d.idx)) if self.purpose in ["Manufacture", "Repack"]: if validate_for_manufacture_repack: if d.bom_no: d.s_warehouse = None if not d.t_warehouse: frappe.throw(_("Target warehouse is mandatory for row {0}").format(d.idx)) elif self.pro_doc and cstr(d.t_warehouse) != self.pro_doc.fg_warehouse: frappe.throw(_("Target warehouse in row {0} must be same as Production Order").format(d.idx)) else: d.t_warehouse = None if not d.s_warehouse: frappe.throw(_("Source warehouse is mandatory for row {0}").format(d.idx)) if cstr(d.s_warehouse) == cstr(d.t_warehouse): frappe.throw(_("Source and target warehouse cannot be same for row {0}").format(d.idx)) def validate_production_order(self): if self.purpose in ("Manufacture", "Material Transfer for Manufacture"): # check if production order is entered if self.purpose=="Manufacture" and self.production_order: if not self.fg_completed_qty: frappe.throw(_("For Quantity (Manufactured Qty) is mandatory")) self.check_if_operations_completed() self.check_duplicate_entry_for_production_order() elif self.purpose != "Material Transfer": self.production_order = None def check_if_operations_completed(self): """Check if Time Logs are completed against before manufacturing to capture operating costs.""" prod_order = frappe.get_doc("Production Order", self.production_order) for d in prod_order.get("operations"): total_completed_qty = flt(self.fg_completed_qty) + flt(prod_order.produced_qty) if total_completed_qty > flt(d.completed_qty): frappe.throw(_("Row #{0}: Operation {1} is not completed for {2} qty of finished goods in Production Order # {3}. Please update operation status via Time Logs") .format(d.idx, d.operation, total_completed_qty, self.production_order), OperationsNotCompleteError) def check_duplicate_entry_for_production_order(self): other_ste = [t[0] for t in frappe.db.get_values("Stock Entry", { "production_order": self.production_order, "purpose": self.purpose, "docstatus": ["!=", 2], "name": ["!=", self.name] }, "name")] if other_ste: production_item, qty = frappe.db.get_value("Production Order", self.production_order, ["production_item", "qty"]) args = other_ste + [production_item] fg_qty_already_entered = frappe.db.sql("""select sum(transfer_qty) from `tabStock Entry Detail` where parent in (%s) and item_code = %s and ifnull(s_warehouse,'')='' """ % (", ".join(["%s" * len(other_ste)]), "%s"), args)[0][0] if fg_qty_already_entered >= qty: frappe.throw(_("Stock Entries already created for Production Order ") + self.production_order + ":" + ", ".join(other_ste), DuplicateEntryForProductionOrderError) def set_actual_qty(self): allow_negative_stock = cint(frappe.db.get_value("Stock Settings", None, "allow_negative_stock")) for d in self.get('items'): previous_sle = get_previous_sle({ "item_code": d.item_code, "warehouse": d.s_warehouse or d.t_warehouse, "posting_date": self.posting_date, "posting_time": self.posting_time }) # get actual stock at source warehouse d.actual_qty = previous_sle.get("qty_after_transaction") or 0 # validate qty during submit if d.docstatus==1 and d.s_warehouse and not allow_negative_stock and d.actual_qty < d.transfer_qty: frappe.throw(_("""Row {0}: Qty not avalable in warehouse {1} on {2} {3}. Available Qty: {4}, Transfer Qty: {5}""").format(d.idx, d.s_warehouse, self.posting_date, self.posting_time, d.actual_qty, d.transfer_qty), NegativeStockError) def get_stock_and_rate(self): self.set_transfer_qty() self.set_actual_qty() self.calculate_rate_and_amount() def calculate_rate_and_amount(self, force=False): self.set_basic_rate(force) self.distribute_additional_costs() self.update_valuation_rate() self.set_total_incoming_outgoing_value() self.set_total_amount() def set_basic_rate(self, force=False): """get stock and incoming rate on posting date""" raw_material_cost = 0.0 for d in self.get('items'): args = frappe._dict({ "item_code": d.item_code, "warehouse": d.s_warehouse or d.t_warehouse, "posting_date": self.posting_date, "posting_time": self.posting_time, "qty": d.s_warehouse and -1*flt(d.transfer_qty) or flt(d.transfer_qty), "serial_no": d.serial_no, }) # get basic rate if not d.bom_no: if not flt(d.basic_rate) or d.s_warehouse or force: basic_rate = flt(get_incoming_rate(args), self.precision("basic_rate", d)) if basic_rate > 0: d.basic_rate = basic_rate d.basic_amount = flt(flt(d.transfer_qty) * flt(d.basic_rate), d.precision("basic_amount")) if not d.t_warehouse: raw_material_cost += flt(d.basic_amount) self.set_basic_rate_for_finished_goods(raw_material_cost) def set_basic_rate_for_finished_goods(self, raw_material_cost): if self.purpose in ["Manufacture", "Repack"]: number_of_fg_items = len([t.t_warehouse for t in self.get("items") if t.t_warehouse]) for d in self.get("items"): if d.bom_no or (d.t_warehouse and number_of_fg_items == 1): d.basic_rate = flt(raw_material_cost / flt(d.transfer_qty), d.precision("basic_rate")) d.basic_amount = flt(raw_material_cost, d.precision("basic_amount")) def distribute_additional_costs(self): if self.purpose == "Material Issue": self.additional_costs = [] self.total_additional_costs = sum([flt(t.amount) for t in self.get("additional_costs")]) total_basic_amount = sum([flt(t.basic_amount) for t in self.get("items") if t.t_warehouse]) for d in self.get("items"): if d.t_warehouse and total_basic_amount: d.additional_cost = (flt(d.basic_amount) / total_basic_amount) * self.total_additional_costs else: d.additional_cost = 0 def update_valuation_rate(self): for d in self.get("items"): d.amount = flt(d.basic_amount + flt(d.additional_cost), d.precision("amount")) d.valuation_rate = flt( flt(d.basic_rate) + (flt(d.additional_cost) / flt(d.transfer_qty)), d.precision("valuation_rate")) def set_total_incoming_outgoing_value(self): self.total_incoming_value = self.total_outgoing_value = 0.0 for d in self.get("items"): if d.t_warehouse: self.total_incoming_value += flt(d.amount) if d.s_warehouse: self.total_outgoing_value += flt(d.amount) self.value_difference = self.total_incoming_value - self.total_outgoing_value def set_total_amount(self): self.total_amount = sum([flt(item.amount) for item in self.get("items")]) def validate_purchase_order(self): """Throw exception if more raw material is transferred against Purchase Order than in the raw materials supplied table""" if self.purpose == "Subcontract" and self.purchase_order: purchase_order = frappe.get_doc("Purchase Order", self.purchase_order) for se_item in self.items: total_allowed = sum([flt(d.required_qty) for d in purchase_order.supplied_items \ if d.rm_item_code == se_item.item_code]) if not total_allowed: frappe.throw(_("Item {0} not found in 'Raw Materials Supplied' table in Purchase Order {1}") .format(se_item.item_code, self.purchase_order)) total_supplied = frappe.db.sql("""select sum(qty) from `tabStock Entry Detail`, `tabStock Entry` where `tabStock Entry`.purchase_order = %s and `tabStock Entry`.docstatus = 1 and `tabStock Entry Detail`.item_code = %s and `tabStock Entry Detail`.parent = `tabStock Entry`.name""", (self.purchase_order, se_item.item_code))[0][0] if total_supplied > total_allowed: frappe.throw(_("Not allowed to tranfer more {0} than {1} against Purchase Order {2}").format(se_item.item_code, total_allowed, self.purchase_order)) def validate_bom(self): for d in self.get('items'): if d.bom_no: validate_bom_no(d.item_code, d.bom_no) def validate_finished_goods(self): """validation: finished good quantity should be same as manufacturing quantity""" items_with_target_warehouse = [] for d in self.get('items'): if d.bom_no and flt(d.transfer_qty) != flt(self.fg_completed_qty): frappe.throw(_("Quantity in row {0} ({1}) must be same as manufactured quantity {2}"). \ format(d.idx, d.transfer_qty, self.fg_completed_qty)) if self.production_order and self.purpose == "Manufacture" and d.t_warehouse: items_with_target_warehouse.append(d.item_code) if self.production_order and self.purpose == "Manufacture": production_item = frappe.db.get_value("Production Order", self.production_order, "production_item") if production_item not in items_with_target_warehouse: frappe.throw(_("Finished Item {0} must be entered for Manufacture type entry") .format(production_item)) def update_stock_ledger(self): sl_entries = [] # make sl entries for source warehouse first, then do for target warehouse for d in self.get('items'): if cstr(d.s_warehouse): sl_entries.append(self.get_sl_entries(d, { "warehouse": cstr(d.s_warehouse), "actual_qty": -flt(d.transfer_qty), "incoming_rate": 0 })) for d in self.get('items'): if cstr(d.t_warehouse): sl_entries.append(self.get_sl_entries(d, { "warehouse": cstr(d.t_warehouse), "actual_qty": flt(d.transfer_qty), "incoming_rate": flt(d.valuation_rate) })) # On cancellation, make stock ledger entry for # target warehouse first, to update serial no values properly # if cstr(d.s_warehouse) and self.docstatus == 2: # sl_entries.append(self.get_sl_entries(d, { # "warehouse": cstr(d.s_warehouse), # "actual_qty": -flt(d.transfer_qty), # "incoming_rate": 0 # })) if self.docstatus == 2: sl_entries.reverse() self.make_sl_entries(sl_entries, self.amended_from and 'Yes' or 'No') def get_gl_entries(self, warehouse_account): expenses_included_in_valuation = self.get_company_default("expenses_included_in_valuation") gl_entries = super(StockEntry, self).get_gl_entries(warehouse_account) for d in self.get("items"): additional_cost = flt(d.additional_cost, d.precision("additional_cost")) if additional_cost: gl_entries.append(self.get_gl_dict({ "account": expenses_included_in_valuation, "against": d.expense_account, "cost_center": d.cost_center, "remarks": self.get("remarks") or _("Accounting Entry for Stock"), "credit": additional_cost })) gl_entries.append(self.get_gl_dict({ "account": d.expense_account, "against": expenses_included_in_valuation, "cost_center": d.cost_center, "remarks": self.get("remarks") or _("Accounting Entry for Stock"), "credit": -1 * additional_cost # put it as negative credit instead of debit purposefully })) return gl_entries def update_production_order(self): def _validate_production_order(pro_doc): if flt(pro_doc.docstatus) != 1: frappe.throw(_("Production Order {0} must be submitted").format(self.production_order)) if pro_doc.status == 'Stopped': frappe.throw(_("Transaction not allowed against stopped Production Order {0}").format(self.production_order)) if self.production_order: pro_doc = frappe.get_doc("Production Order", self.production_order) _validate_production_order(pro_doc) pro_doc.run_method("update_status") if self.fg_completed_qty: pro_doc.run_method("update_production_order_qty") if self.purpose == "Manufacture": pro_doc.run_method("update_planned_qty") def get_item_details(self, args=None, for_update=False): item = frappe.db.sql("""select stock_uom, description, image, item_name, expense_account, buying_cost_center, item_group from `tabItem` where name = %s and disabled=0 and (end_of_life is null or end_of_life='0000-00-00' or end_of_life > %s)""", (args.get('item_code'), nowdate()), as_dict = 1) if not item: frappe.throw(_("Item {0} is not active or end of life has been reached").format(args.get("item_code"))) item = item[0] ret = { 'uom' : item.stock_uom, 'stock_uom' : item.stock_uom, 'description' : item.description, 'image' : item.image, 'item_name' : item.item_name, 'expense_account' : args.get("expense_account"), 'cost_center' : get_default_cost_center(args, item), 'qty' : 0, 'transfer_qty' : 0, 'conversion_factor' : 1, 'batch_no' : '', 'actual_qty' : 0, 'basic_rate' : 0 } for d in [["Account", "expense_account", "default_expense_account"], ["Cost Center", "cost_center", "cost_center"]]: company = frappe.db.get_value(d[0], ret.get(d[1]), "company") if not ret[d[1]] or (company and self.company != company): ret[d[1]] = frappe.db.get_value("Company", self.company, d[2]) if d[2] else None # update uom if args.get("uom") and for_update: ret.update(self.get_uom_details(args)) if not ret["expense_account"]: ret["expense_account"] = frappe.db.get_value("Company", self.company, "stock_adjustment_account") args['posting_date'] = self.posting_date args['posting_time'] = self.posting_time stock_and_rate = args.get('warehouse') and get_warehouse_details(args) or {} ret.update(stock_and_rate) return ret def get_uom_details(self, args): """Returns dict `{"conversion_factor": [value], "transfer_qty": qty * [value]}` :param args: dict with `item_code`, `uom` and `qty`""" conversion_factor = get_conversion_factor(args.get("item_code"), args.get("uom")).get("conversion_factor") if not conversion_factor: frappe.msgprint(_("UOM coversion factor required for UOM: {0} in Item: {1}") .format(args.get("uom"), args.get("item_code"))) ret = {'uom' : ''} else: ret = { 'conversion_factor' : flt(conversion_factor), 'transfer_qty' : flt(args.get("qty")) * flt(conversion_factor) } return ret def get_items(self): self.set('items', []) self.validate_production_order() if not self.posting_date or not self.posting_time: frappe.throw(_("Posting date and posting time is mandatory")) if not getattr(self, "pro_doc", None): self.pro_doc = None if self.production_order: # common validations if not self.pro_doc: self.pro_doc = frappe.get_doc('Production Order', self.production_order) if self.pro_doc: self.bom_no = self.pro_doc.bom_no else: # invalid production order self.production_order = None if self.bom_no: if self.purpose in ["Material Issue", "Material Transfer", "Manufacture", "Repack", "Subcontract", "Material Transfer for Manufacture"]: if self.production_order and self.purpose == "Material Transfer for Manufacture": item_dict = self.get_pending_raw_materials() if self.to_warehouse and self.pro_doc: for item in item_dict.values(): item["to_warehouse"] = self.pro_doc.wip_warehouse self.add_to_stock_entry_detail(item_dict) elif self.production_order and self.purpose == "Manufacture" and \ frappe.db.get_single_value("Manufacturing Settings", "backflush_raw_materials_based_on")== "Material Transferred for Manufacture": self.get_transfered_raw_materials() else: if not self.fg_completed_qty: frappe.throw(_("Manufacturing Quantity is mandatory")) item_dict = self.get_bom_raw_materials(self.fg_completed_qty) for item in item_dict.values(): if self.pro_doc: item["from_warehouse"] = self.pro_doc.wip_warehouse item["to_warehouse"] = self.to_warehouse if self.purpose=="Subcontract" else "" self.add_to_stock_entry_detail(item_dict) # add finished goods item if self.purpose in ("Manufacture", "Repack"): self.load_items_from_bom() self.set_actual_qty() self.calculate_rate_and_amount() def load_items_from_bom(self): if self.production_order: item_code = self.pro_doc.production_item to_warehouse = self.pro_doc.fg_warehouse else: item_code = frappe.db.get_value("BOM", self.bom_no, "item") to_warehouse = self.to_warehouse item = frappe.db.get_value("Item", item_code, ["item_name", "description", "stock_uom", "expense_account", "buying_cost_center", "name", "default_warehouse"], as_dict=1) if not self.production_order and not to_warehouse: # in case of BOM to_warehouse = item.default_warehouse self.add_to_stock_entry_detail({ item.name: { "to_warehouse": to_warehouse, "from_warehouse": "", "qty": self.fg_completed_qty, "item_name": item.item_name, "description": item.description, "stock_uom": item.stock_uom, "expense_account": item.expense_account, "cost_center": item.buying_cost_center, } }, bom_no = self.bom_no) def get_bom_raw_materials(self, qty): from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict # item dict = { item_code: {qty, description, stock_uom} } item_dict = get_bom_items_as_dict(self.bom_no, self.company, qty=qty, fetch_exploded = self.use_multi_level_bom) for item in item_dict.values(): item.from_warehouse = self.from_warehouse or item.default_warehouse return item_dict def get_transfered_raw_materials(self): transferred_materials = frappe.db.sql(""" select item_name, item_code, sum(qty) as qty, sed.t_warehouse as warehouse, description, stock_uom, expense_account, cost_center from `tabStock Entry` se,`tabStock Entry Detail` sed where se.name = sed.parent and se.docstatus=1 and se.purpose='Material Transfer for Manufacture' and se.production_order= %s and ifnull(sed.t_warehouse, '') != '' group by sed.item_code, sed.t_warehouse """, self.production_order, as_dict=1) materials_already_backflushed = frappe.db.sql(""" select item_code, sed.s_warehouse as warehouse, sum(qty) as qty from `tabStock Entry` se, `tabStock Entry Detail` sed where se.name = sed.parent and se.docstatus=1 and se.purpose='Manufacture' and se.production_order= %s and ifnull(sed.s_warehouse, '') != '' group by sed.item_code, sed.s_warehouse """, self.production_order, as_dict=1) backflushed_materials= {} for d in materials_already_backflushed: backflushed_materials.setdefault(d.item_code,[]).append({d.warehouse: d.qty}) po_qty = frappe.db.sql("""select qty, produced_qty, material_transferred_for_manufacturing from `tabProduction Order` where name=%s""", self.production_order, as_dict=1)[0] manufacturing_qty = flt(po_qty.qty) produced_qty = flt(po_qty.produced_qty) trans_qty = flt(po_qty.material_transferred_for_manufacturing) for item in transferred_materials: qty= item.qty if manufacturing_qty > (produced_qty + flt(self.fg_completed_qty)): qty = (qty/trans_qty) * flt(self.fg_completed_qty) elif backflushed_materials.get(item.item_code): for d in backflushed_materials.get(item.item_code): if d.get(item.warehouse): qty-= d.get(item.warehouse) if qty > 0: self.add_to_stock_entry_detail({ item.item_code: { "from_warehouse": item.warehouse, "to_warehouse": "", "qty": qty, "item_name": item.item_name, "description": item.description, "stock_uom": item.stock_uom, "expense_account": item.expense_account, "cost_center": item.buying_cost_center, } }) def get_pending_raw_materials(self): """ issue (item quantity) that is pending to issue or desire to transfer, whichever is less """ item_dict = self.get_bom_raw_materials(1) issued_item_qty = self.get_issued_qty() max_qty = flt(self.pro_doc.qty) for item in item_dict: pending_to_issue = (max_qty * item_dict[item]["qty"]) - issued_item_qty.get(item, 0) desire_to_transfer = flt(self.fg_completed_qty) * item_dict[item]["qty"] if desire_to_transfer <= pending_to_issue: item_dict[item]["qty"] = desire_to_transfer elif pending_to_issue > 0: item_dict[item]["qty"] = pending_to_issue else: item_dict[item]["qty"] = 0 # delete items with 0 qty for item in item_dict.keys(): if not item_dict[item]["qty"]: del item_dict[item] # show some message if not len(item_dict): frappe.msgprint(_("""All items have already been transferred for this Production Order.""")) return item_dict def get_issued_qty(self): issued_item_qty = {} result = frappe.db.sql("""select t1.item_code, sum(t1.qty) from `tabStock Entry Detail` t1, `tabStock Entry` t2 where t1.parent = t2.name and t2.production_order = %s and t2.docstatus = 1 and t2.purpose = 'Material Transfer for Manufacture' group by t1.item_code""", self.production_order) for t in result: issued_item_qty[t[0]] = flt(t[1]) return issued_item_qty def add_to_stock_entry_detail(self, item_dict, bom_no=None): expense_account, cost_center = frappe.db.get_values("Company", self.company, \ ["default_expense_account", "cost_center"])[0] for d in item_dict: se_child = self.append('items') se_child.s_warehouse = item_dict[d].get("from_warehouse") se_child.t_warehouse = item_dict[d].get("to_warehouse") se_child.item_code = cstr(d) se_child.item_name = item_dict[d]["item_name"] se_child.description = item_dict[d]["description"] se_child.uom = item_dict[d]["stock_uom"] se_child.stock_uom = item_dict[d]["stock_uom"] se_child.qty = flt(item_dict[d]["qty"]) se_child.expense_account = item_dict[d]["expense_account"] or expense_account se_child.cost_center = item_dict[d]["cost_center"] or cost_center if se_child.s_warehouse==None: se_child.s_warehouse = self.from_warehouse if se_child.t_warehouse==None: se_child.t_warehouse = self.to_warehouse # in stock uom se_child.transfer_qty = flt(item_dict[d]["qty"]) se_child.conversion_factor = 1.00 # to be assigned for finished item se_child.bom_no = bom_no def validate_with_material_request(self): for item in self.get("items"): if item.material_request: mreq_item = frappe.db.get_value("Material Request Item", {"name": item.material_request_item, "parent": item.material_request}, ["item_code", "warehouse", "idx"], as_dict=True) if mreq_item.item_code != item.item_code or \ mreq_item.warehouse != (item.s_warehouse if self.purpose== "Material Issue" else item.t_warehouse): frappe.throw(_("Item or Warehouse for row {0} does not match Material Request").format(item.idx), frappe.MappingMismatchError) def validate_batch(self): if self.purpose in ["Material Transfer for Manufacture", "Manufacture", "Repack", "Subcontract"]: for item in self.get("items"): if item.batch_no: expiry_date = frappe.db.get_value("Batch", item.batch_no, "expiry_date") if expiry_date: if getdate(self.posting_date) > getdate(expiry_date): frappe.throw(_("Batch {0} of Item {1} has expired.").format(item.batch_no, item.item_code)) def updateProyeccion(self): if self.purpose=="Material Transfer": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code proyeccion_valor=get_proyeccion__valor(proyeccion, elemento) proyeccion_project = get_proyeccion_proyect(proyeccion, elemento) qty_proyeccion = flt(proyeccion_valor) - flt(item.qty) if (qty_proyeccion<0): frappe.throw(_("No hay disponibilidad en la proyeccion para su solicitud del producto {0}").format(item.item_code)) else: proyeccion_update = update_proyeccion(item.qty,qty_proyeccion, proyeccion_project, elemento) frappe.msgprint(_("Nuevo valor de Proyeccion para el item {0} igual a {1} ").format(item.item_code,qty_proyeccion)) if self.purpose=="Material Issue": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code proyeccion_valor=get_proyeccion__valor(proyeccion, elemento) proyeccion_project = get_proyeccion_proyect(proyeccion, elemento) qty_proyeccion = flt(proyeccion_valor) - flt(item.qty) salida_update = update_salida(item.qty,qty_proyeccion, proyeccion_project, elemento) frappe.msgprint(_("Nuevo valor de Salida para el item {0} igual a {1} ").format(item.item_code,qty_proyeccion)) if self.purpose=="Material Receipt": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code devolucion=update_devolucion(item.qty, proyeccion, elemento) frappe.msgprint(_("Reporte de devoluciones actualizado. ")) def rollbackproyeccion(self): if self.purpose=="Material Transfer": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code proyeccion_valor=get_proyeccion__valor(proyeccion, elemento) proyeccion_project = get_proyeccion_proyect(proyeccion, elemento) qty_proyeccion = flt(proyeccion_valor) + flt(item.qty) proyeccion_update = back_proyeccion(item.qty,qty_proyeccion, proyeccion_project, elemento) frappe.msgprint(_("Nuevo valor de Proyeccion para el item {0} igual a {1} ").format(item.item_code,qty_proyeccion)) if self.purpose=="Material Issue": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code proyeccion_valor=get_proyeccion__valor(proyeccion, elemento) proyeccion_project = get_proyeccion_proyect(proyeccion, elemento) qty_proyeccion = flt(proyeccion_valor) + flt(item.qty) salida_update = back_salida(item.qty,qty_proyeccion, proyeccion_project, elemento) frappe.msgprint(_("Nuevo valor de Salida para el item {0} igual a {1} ").format(item.item_code,qty_proyeccion)) if self.purpose=="Material Receipt": for item in self.get("items"): adquisicion=get_adquisicion(item.item_code); if adquisicion==1: proyeccion=self.project elemento=item.item_code devolucion=back_devolucion(item.qty, proyeccion, elemento) frappe.msgprint(_("Reporte de devoluciones actualizado. ")) @frappe.whitelist() def get_production_order_details(production_order): production_order = frappe.get_doc("Production Order", production_order) pending_qty_to_produce = flt(production_order.qty) - flt(production_order.produced_qty) return { "from_bom": 1, "bom_no": production_order.bom_no, "use_multi_level_bom": production_order.use_multi_level_bom, "wip_warehouse": production_order.wip_warehouse, "fg_warehouse": production_order.fg_warehouse, "fg_completed_qty": pending_qty_to_produce, "additional_costs": get_additional_costs(production_order, fg_qty=pending_qty_to_produce) } def get_additional_costs(production_order=None, bom_no=None, fg_qty=None): additional_costs = [] operating_cost_per_unit = get_operating_cost_per_unit(production_order, bom_no) if operating_cost_per_unit: additional_costs.append({ "description": "Operating Cost as per Production Order / BOM", "amount": operating_cost_per_unit * flt(fg_qty) }) if production_order and production_order.additional_operating_cost: additional_operating_cost_per_unit = \ flt(production_order.additional_operating_cost) / flt(production_order.qty) additional_costs.append({ "description": "Additional Operating Cost", "amount": additional_operating_cost_per_unit * flt(fg_qty) }) return additional_costs def get_operating_cost_per_unit(production_order=None, bom_no=None): operating_cost_per_unit = 0 if production_order: if not bom_no: bom_no = production_order.bom_no for d in production_order.get("operations"): if flt(d.completed_qty): operating_cost_per_unit += flt(d.actual_operating_cost) / flt(d.completed_qty) else: operating_cost_per_unit += flt(d.planned_operating_cost) / flt(production_order.qty) # Get operating cost from BOM if not found in production_order. if not operating_cost_per_unit and bom_no: bom = frappe.db.get_value("BOM", bom_no, ["operating_cost", "quantity"], as_dict=1) operating_cost_per_unit = flt(bom.operating_cost) / flt(bom.quantity) return operating_cost_per_unit @frappe.whitelist() def get_warehouse_details(args): if isinstance(args, basestring): args = json.loads(args) args = frappe._dict(args) ret = {} if args.warehouse and args.item_code: args.update({ "posting_date": args.posting_date, "posting_time": args.posting_time, }) ret = { "actual_qty" : get_previous_sle(args).get("qty_after_transaction") or 0, "basic_rate" : get_incoming_rate(args) } return ret #Queries para ejecutar la actualizacion de proyeccion de materiales @frappe.whitelist() def get_proyeccion__valor(proyeccion, elemento): proyeccion_valor = frappe.db.sql("""select value from `tabProductos a Proyectar` join `tabProyectar` on `tabProyectar`.name =`tabProductos a Proyectar`.parent where `tabProductos a Proyectar`.item = %s AND `tabProyectar`.project=%s """, (elemento,proyeccion)) if not proyeccion_valor: frappe.throw(_("El elemento {0} no posee proyeccion en el proyecto {1}.").format(elemento,proyeccion)) proyeccion_valor=proyeccion_valor[0][0] return proyeccion_valor @frappe.whitelist() def get_proyeccion_proyect(proyeccion, elemento): proyeccion_project = frappe.db.sql("""select `tabProductos a Proyectar`.parent, adquisicion from `tabProductos a Proyectar` join `tabProyectar` on `tabProyectar`.name =`tabProductos a Proyectar`.parent join `tabItem` on `tabProductos a Proyectar`.item=`tabItem`.item_code where `tabProductos a Proyectar`.item = %s AND adquisicion=1 AND `tabProyectar`.project=%s """, (elemento,proyeccion))[0][0] return proyeccion_project @frappe.whitelist() def get_adquisicion(elemento): adquisicion = frappe.db.sql("""select `tabItem`.adquisicion from `tabItem` where `tabItem`.item_code = %s """, (elemento)) if not adquisicion: frappe.throw(_("El elemento {0} no posee proyeccion en el proyecto.").format(elemento)) adquisicion=adquisicion[0][0] return adquisicion @frappe.whitelist() def update_proyeccion(qty, qty_proyeccion, proyeccion, elemento): proyeccion_update = frappe.db.sql("""update `tabProductos a Proyectar` set value= %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty_proyeccion, elemento,proyeccion)) return proyeccion_update @frappe.whitelist() def back_proyeccion(qty, qty_proyeccion, proyeccion, elemento): proyeccion_update = frappe.db.sql("""update `tabProductos a Proyectar` set value= %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty_proyeccion, elemento,proyeccion)) return proyeccion_update @frappe.whitelist() def update_salida(qty, qty_proyeccion, proyeccion, elemento): proyeccion_update = frappe.db.sql("""update `tabProductos a Proyectar` set cantidad_salida=cantidad_salida + %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty, elemento,proyeccion)) return proyeccion_update @frappe.whitelist() def back_salida(qty, qty_proyeccion, proyeccion, elemento): proyeccion_update = frappe.db.sql("""update `tabProductos a Proyectar` set cantidad_salida=cantidad_salida - %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty, elemento,proyeccion)) return proyeccion_update @frappe.whitelist() def update_devolucion(qty,proyeccion, elemento): devolucion_update= frappe.db.sql("""update `tabProductos a Proyectar` set cantidad_devolucion= cantidad_devolucion + %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty, elemento,proyeccion)) return devolucion_update @frappe.whitelist() def back_devolucion(qty,proyeccion, elemento): devolucion_update= frappe.db.sql("""update `tabProductos a Proyectar` set cantidad_devolucion= cantidad_devolucion - %s where `tabProductos a Proyectar`.item = %s and `tabProductos a Proyectar`.parent= %s """, (qty, elemento,proyeccion)) return devolucion_update
agpl-3.0
FacilMap/facilmap
server/src/webserver.ts
5104
import compression from "compression"; import ejs from "ejs"; import express, { Request, Response, NextFunction } from "express"; import fs from "fs"; import { createServer, Server as HttpServer } from "http"; import { dirname } from "path"; import { PadId } from "facilmap-types"; import { createTable } from "./export/table"; import Database from "./database/database"; import { exportGeoJson } from "./export/geojson"; import { exportGpx } from "./export/gpx"; import domainMiddleware from "express-domain-middleware"; const frontendPath = dirname(require.resolve("facilmap-frontend/package.json")); // Do not resolve main property const isDevMode = !!process.env.FM_DEV; /* eslint-disable @typescript-eslint/no-var-requires */ const webpackCompiler = isDevMode ? (() => { const webpack = require(require.resolve("webpack", { paths: [ require.resolve("facilmap-frontend/package.json") ] })); const webpackConfig = require("facilmap-frontend/webpack.config"); return webpack(webpackConfig({}, { mode: "development" }).find((conf: any) => conf.name == "app")); })() : undefined; const staticMiddleware = isDevMode ? require("webpack-dev-middleware")(webpackCompiler, { // require the stuff here so that it doesn't fail if devDependencies are not installed publicPath: "/" }) : express.static(frontendPath + "/dist/"); const hotMiddleware = isDevMode ? require("webpack-hot-middleware")(webpackCompiler) : undefined; type PathParams = { padId: PadId } export async function initWebserver(database: Database, port: number, host?: string): Promise<HttpServer> { const padMiddleware = function(req: Request<PathParams>, res: Response<string>, next: NextFunction) { Promise.all([ getFrontendFile("map.ejs"), (async () => { if(req.params && req.params.padId) { return database.pads.getPadDataByAnyId(req.params.padId).then((padData) => { if (!padData) throw new Error(); return padData; }).catch(() => { // Error will be handled on the client side when it tries to fetch the pad data return { id: undefined, searchEngines: false, description: "" }; }); } })() ]).then(([ template, padData ]) => { res.type("html"); if (padData && padData.id == null) { res.status(404); } res.send(ejs.render(template, { padData: padData, isReadOnly: padData?.id == req.params.padId, config: {} })); }).catch(next); }; const app = express(); app.use(domainMiddleware); app.use(compression()); app.get("/frontend-:hash.js", function(req, res, next) { res.setHeader('Cache-Control', 'public, max-age=31557600'); // one year next(); }); app.get("/", padMiddleware); app.get("/map.ejs", padMiddleware); app.get("/table.ejs", padMiddleware); app.use(staticMiddleware); if(isDevMode) { app.use(hotMiddleware); } // If no file with this name has been found, we render a pad app.get("/:padId", padMiddleware); app.get("/:padId/gpx", async function(req: Request<PathParams>, res: Response<string>, next) { try { const padData = await database.pads.getPadDataByAnyId(req.params.padId); if(!padData) throw new Error(`Map with ID ${req.params.padId} could not be found.`); res.set("Content-type", "application/gpx+xml"); res.attachment(padData.name.replace(/[\\/:*?"<>|]+/g, '_') + ".gpx"); exportGpx(database, padData ? padData.id : req.params.padId, req.query.useTracks == "1", req.query.filter as string | undefined).pipe(res); } catch (e) { next(e); } }); app.get("/:padId/table", async function(req: Request<PathParams>, res: Response<string>, next) { try { const renderedTable = await createTable(database, req.params.padId, req.query.filter as string | undefined, req.query.hide ? (req.query.hide as string).split(',') : []); res.type("html"); res.send(renderedTable); } catch (e) { next(e); } }); app.get("/:padId/geojson", async function(req: Request<PathParams>, res: Response<string>, next) { try { const padData = await database.pads.getPadData(req.params.padId); if(!padData) throw new Error(`Map with ID ${req.params.padId} could not be found.`); res.set("Content-type", "application/geo+json"); res.attachment(padData.name.replace(/[\\/:*?"<>|]+/g, '_') + ".geojson"); exportGeoJson(database, req.params.padId, req.query.filter as string | undefined).pipe(res); } catch (e) { next(e); } }); const server = createServer(app); await new Promise<void>((resolve) => { server.listen({ port, host }, resolve); }); return server; } export function getFrontendFile(path: string): Promise<string> { if (isDevMode) { return new Promise((resolve) => { staticMiddleware.waitUntilValid(resolve); }).then(() => { return webpackCompiler.outputFileSystem.readFileSync(`${webpackCompiler.outputPath}${path}`, "utf8"); }); } else { // We don't want express.static's ETag handling, as it sometimes returns an empty template, // so we have to read it directly from the file system return fs.promises.readFile(`${frontendPath}/dist/${path}`, "utf8"); } }
agpl-3.0
grafana/grafana
public/app/core/components/NavBar/NavBarSection.tsx
1105
import React, { ReactNode } from 'react'; import { css, cx } from '@emotion/css'; import { GrafanaTheme2 } from '@grafana/data'; import { useTheme2 } from '@grafana/ui'; import { config } from '@grafana/runtime'; export interface Props { children: ReactNode; className?: string; } export function NavBarSection({ children, className }: Props) { const newNavigationEnabled = Boolean(config.featureToggles.newNavigation); const theme = useTheme2(); const styles = getStyles(theme, newNavigationEnabled); return ( <ul data-testid="navbar-section" className={cx(styles.container, className)}> {children} </ul> ); } const getStyles = (theme: GrafanaTheme2, newNavigationEnabled: boolean) => ({ container: css` display: none; list-style: none; ${theme.breakpoints.up('md')} { background-color: ${newNavigationEnabled ? theme.colors.background.primary : 'inherit'}; border: ${newNavigationEnabled ? `1px solid ${theme.components.panel.borderColor}` : 'none'}; border-radius: 2px; display: flex; flex-direction: inherit; } `, });
agpl-3.0
grimhaven/grimhaven
server/obj/saddle.cc
625
#include "obj/base_clothing.h" #include "obj/saddle.h" TSaddle::TSaddle() : TBaseClothing() { } TSaddle::TSaddle(const TSaddle &a) : TBaseClothing(a) { } TSaddle & TSaddle::operator=(const TSaddle &a) { if (this == &a) return *this; TBaseClothing::operator=(a); return *this; } TSaddle::~TSaddle() { } void TSaddle::assignFourValues(int , int , int , int ) { } void TSaddle::getFourValues(int *x1, int *x2, int *x3, int *x4) const { *x1 = 0; *x2 = 0; *x3 = 0; *x4 = 0; } sstring TSaddle::statObjInfo() const { sstring a(""); return a; } void TSaddle::lowCheck() { TBaseClothing::lowCheck(); }
agpl-3.0
pgdurand/BeeDeeM
src/bzh/plealog/dbmirror/reader/DBFormatEntry.java
8753
/* Copyright (C) 2007-2017 Patrick G. Durand * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * You may obtain a copy of the License at * * https://www.gnu.org/licenses/agpl-3.0.txt * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. */ package bzh.plealog.dbmirror.reader; import bzh.plealog.dbmirror.lucenedico.Dicos; import bzh.plealog.dbmirror.util.conf.DBMirrorConfig; public class DBFormatEntry { public static DBFormatEntry fastaProteic = new DBFormatEntry( DBUtils.FP_DB_FORMAT, "Fasta Proteic", DBMirrorConfig.BLASTP_READER); public static DBFormatEntry fastaNucleic = new DBFormatEntry( DBUtils.FN_DB_FORMAT, "Fasta Nucleic", DBMirrorConfig.BLASTN_READER); public static DBFormatEntry uniprot = new DBFormatEntry( DBUtils.SW_DB_FORMAT, "Uniprot (TrEMBL, SwissProt)", DBMirrorConfig.UP_READER); public static DBFormatEntry genpept = new DBFormatEntry( DBUtils.GP_DB_FORMAT, "Genpept/Refseq Protein", DBMirrorConfig.GP_READER); public static DBFormatEntry genbank = new DBFormatEntry( DBUtils.GB_DB_FORMAT, "Genbank/Refseq Nucleic", DBMirrorConfig.GB_READER); public static DBFormatEntry embl = new DBFormatEntry( DBUtils.EM_DB_FORMAT, "EMBL", DBMirrorConfig.EM_READER); public static DBFormatEntry silva = new DBFormatEntry( DBUtils.FN_DB_FORMAT, "Silva Fasta Nucleic", DBMirrorConfig.BLASTN_READER, DBUtils.SILVA_HEADER_FORMAT); public static DBFormatEntry bold = new DBFormatEntry( DBUtils.FN_DB_FORMAT, "BOLD Barcode DNA", DBMirrorConfig.GB_READER, DBUtils.BOLD_HEADER_FORMAT); public static DBFormatEntry fastaProteicWithTaxon = new DBFormatEntry( DBUtils.FN_DB_FORMAT, "Fasta Proteic with annotation data", DBMirrorConfig.BLASTP_READER, DBUtils.TAXONOMY_HEADER_FORMAT); public static DBFormatEntry fastaNucleicWithTaxon = new DBFormatEntry( DBUtils.FN_DB_FORMAT, "Fasta Nucleic with annotation data", DBMirrorConfig.BLASTN_READER, DBUtils.TAXONOMY_HEADER_FORMAT); public static DBFormatEntry geneOntology = new DBFormatEntry( Dicos.GENE_ONTOLOGY); public static DBFormatEntry interPro = new DBFormatEntry( Dicos.INTERPRO); public static DBFormatEntry pfam = new DBFormatEntry( Dicos.PFAM); public static DBFormatEntry enzyme = new DBFormatEntry( Dicos.ENZYME); public static DBFormatEntry taxonomy = new DBFormatEntry( Dicos.NCBI_TAXONOMY); public static DBFormatEntry cdd = new DBFormatEntry( Dicos.CDD); private int type; private String name; private String reader; private int headerFormat; /** * * @param entryName * * @return a known entry which name is the string given in parameter */ public static DBFormatEntry getEntry(String entryName) { if (DBFormatEntry.fastaProteic.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.fastaProteic; if (DBFormatEntry.fastaNucleic.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.fastaNucleic; if (DBFormatEntry.uniprot.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.uniprot; if (DBFormatEntry.genpept.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.genpept; if (DBFormatEntry.genbank.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.genbank; if (DBFormatEntry.embl.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.embl; if (DBFormatEntry.silva.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.silva; if (DBFormatEntry.bold.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.bold; if (DBFormatEntry.fastaProteicWithTaxon.getName().equalsIgnoreCase( entryName)) return DBFormatEntry.fastaProteicWithTaxon; if (DBFormatEntry.fastaNucleicWithTaxon.getName().equalsIgnoreCase( entryName)) return DBFormatEntry.fastaNucleicWithTaxon; if (DBFormatEntry.geneOntology.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.geneOntology; if (DBFormatEntry.interPro.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.interPro; if (DBFormatEntry.pfam.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.pfam; if (DBFormatEntry.enzyme.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.enzyme; if (DBFormatEntry.taxonomy.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.taxonomy; if (DBFormatEntry.cdd.getName().equalsIgnoreCase(entryName)) return DBFormatEntry.cdd; return null; } public DBFormatEntry(int type, String name, String reader) { super(); this.type = type; this.name = name; this.reader = reader; } public DBFormatEntry(int type, String name, String reader, int headerFormat) { this(type, name, reader); this.headerFormat = headerFormat; } public DBFormatEntry(Dicos dico) { this(dico.format, dico.description, dico.readerId); } public int getType() { return type; } public String getReader() { return reader; } public String getName() { return name; } public String toString() { return name; } public int getHeaderFormat() { return headerFormat; } /** * Figures out if this entry is SILVA */ public boolean isSilva() { return (this.getHeaderFormat() == DBUtils.SILVA_HEADER_FORMAT); } /** * Figures out if this entry is BOLD */ public boolean isBOLD() { return (this.getHeaderFormat() == DBUtils.BOLD_HEADER_FORMAT); } /** * Returns the db format type. Values are one of DBMirrorConfig.XXX_READER * values. This is because it is the reader type that is stored in dbmirror * config file. */ public String getDBType() { return this.getReader(); } /** * Figures out if we are installing a Fasta-taxonomic based databank. */ public boolean isTaxonomy() { return (this.getHeaderFormat() == DBUtils.TAXONOMY_HEADER_FORMAT); } }
agpl-3.0
system7-open-source/imamd
imam/locations/tests/test_models.py
709
__author__ = 'Tomasz J. Kotarba <tomasz@kotarba.net>' from model_mommy import mommy import django.db import django.utils.timezone import django.test import django.forms.models import locations.models class LocationTypeTest(django.test.TestCase): def test_code_field_unique(self): """Issue 112 suggests that the code field should be unique. """ mommy.make(locations.models.LocationType, code='adm0', _quantity=1) # no second object with the same code allowed with self.assertRaisesRegexp( django.db.IntegrityError, r'.*code.*already exists\..*'): mommy.make(locations.models.LocationType, code='adm0', _quantity=1)
agpl-3.0
pligor/predicting-future-product-prices
03_good_deal/mylibs/tf_helper.py
2569
# -*- coding: utf-8 -*- """Tensorflow Helper""" import tensorflow as tf from py_helper import merge_dicts def tfMSE(outputs, targets): #return tf.reduce_mean(tf.square(tf.sub(targets, outputs))) return tf.reduce_mean(tf.squared_difference(targets, outputs)) def tfRMSE(outputs, targets): return tf.sqrt(tfMSE(outputs, targets)) def fully_connected_layer(inputs, input_dim, output_dim, nonlinearity=tf.nn.relu, avoidDeadNeurons=0., w=None, b=None): weights = tf.Variable( tf.truncated_normal([input_dim, output_dim], stddev=2. / (input_dim + output_dim)**0.5) if w is None else w, 'weights' ) biases = tf.Variable(avoidDeadNeurons * tf.ones([output_dim]) if b is None else b, 'biases') outputs = nonlinearity(tf.matmul(inputs, weights) + biases) return outputs def trainEpoch(inputs, targets, sess, train_data, train_step, error, accuracy, extraFeedDict=None): if extraFeedDict is None: extraFeedDict = {} train_error = 0. train_accuracy = 0. num_batches = train_data.num_batches for step, (input_batch, target_batch) in enumerate(train_data): _, batch_error, batch_acc = sess.run( [train_step, error, accuracy], feed_dict= merge_dicts({inputs: input_batch, targets: target_batch}, extraFeedDict) ) train_error += batch_error train_accuracy += batch_acc train_error /= num_batches train_accuracy /= num_batches return train_error, train_accuracy def validateEpoch(inputs, targets, sess, valid_data, error, accuracy, keep_prob_keys=None, extraFeedDict=None): if keep_prob_keys is None: keep_prob_keys = [] if extraFeedDict is None: extraFeedDict = {} valid_error = 0. valid_accuracy = 0. num_batches = valid_data.num_batches validationKeepProbability = 1. #it is always 100% for validation keep_prob_dict = dict() for keep_prob_key in keep_prob_keys: keep_prob_dict[keep_prob_key] = validationKeepProbability for step, (input_batch, target_batch) in enumerate(valid_data): batch_error, batch_acc = sess.run( [error, accuracy], feed_dict= merge_dicts({inputs: input_batch, targets: target_batch}, keep_prob_dict, extraFeedDict) ) valid_error += batch_error valid_accuracy += batch_acc valid_error /= num_batches valid_accuracy /= num_batches return valid_error, valid_accuracy
agpl-3.0
ihanli/puzzlesBackEnd
db/migrate/20110505094258_add_target_id_to_card.rb
178
class AddTargetIdToCard < ActiveRecord::Migration def self.up add_column :cards, :target_id, :integer end def self.down remove_column :cards, :target_id end end
agpl-3.0
pculture/unisubs
settings.py
25639
# -*- coding: utf-8 -*- # Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see # http://www.gnu.org/licenses/agpl-3.0.html. # Django settings for unisubs project. import os, sys from datetime import datetime from unilangs import get_language_name_mapping import optionalapps PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) DEFAULT_PROTOCOL = 'http' HOSTNAME = 'localhost' LOCALE_PATHS = [ os.path.join(PROJECT_ROOT, 'locale') ] def rel(*x): return os.path.join(PROJECT_ROOT, *x) def env_flag_set(name): value = os.environ.get(name) return bool(value and value != '0') def calc_locale_choices(): """Get a list of language (code, label) tuples for each supported locale This is the list of languages that we can translate our interface into (at least partially) """ localedir = os.path.join(PROJECT_ROOT, 'locale') codes = set() for name in os.listdir(localedir): if not os.path.isdir(os.path.join(localedir, name)): continue name = name.split('.', 1)[0] name = name.replace('_', '-').lower() codes.add(name) mapping = get_language_name_mapping('gettext') return [ (lc, mapping[lc]) for lc in sorted(codes) if lc in mapping ] # Rebuild the language dicts to support more languages. # ALL_LANGUAGES is a deprecated name for LANGUAGES. ALL_LANGUAGES = LANGUAGES = calc_locale_choices() # Languages representing metadata METADATA_LANGUAGES = ( ('meta-tw', 'Metadata: Twitter'), ('meta-geo', 'Metadata: Geo'), ('meta-wiki', 'Metadata: Wikipedia'), ) DEBUG = True ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) ALARM_EMAIL = None MANAGERS = ADMINS P3P_COMPACT = 'CP="CURa ADMa DEVa OUR IND DSP CAO COR"' SECRET_KEY = 'replace-me-with-an-actual-secret' DEFAULT_FROM_EMAIL = '"Amara" <feedback@universalsubtitles.org>' WIDGET_LOG_EMAIL = 'widget-logs@universalsubtitles.org' BILLING_CUTOFF = datetime(2013, 3, 1, 0, 0, 0) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': rel('unisubs.sqlite3'), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } CSS_USE_COMPILED = True COMPRESS_YUI_BINARY = "java -jar ./css-compression/yuicompressor-2.4.6.jar" COMPRESS_OUTPUT_DIRNAME = "static-cache" USER_LANGUAGES_COOKIE_NAME = 'unisub-languages-cookie' LANGUAGE_COOKIE_NAME = 'language' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" STATIC_ROOT = rel('media')+'/' MEDIA_ROOT = rel('user-data')+'/' CSS_ROOT = os.path.join(STATIC_ROOT, 'amara/css') LOGO_URL = "https://s3.amazonaws.com/amara/assets/LogoAndWordmark.svg" PCF_LOGO_URL = "https://s3.amazonaws.com/amara/assets/PCFLogo.png" # Prefix for assets from the amara-assets repo. This is currently needed to # keep them separate from ones from the staticmedia app. Once everything is # using futureui, we can get rid of this. ASSETS_S3_PREFIX = 'assets/' # List of callables that know how to import templates from various sources. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ rel('templates'), ], 'OPTIONS': { 'context_processors': ( 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'utils.context_processors.current_site', 'utils.context_processors.current_commit', 'utils.context_processors.custom', 'utils.context_processors.user_languages', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'staticmedia.context_processors.staticmedia', ), 'loaders': ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader' ), } }, ] MIDDLEWARE_CLASSES = ( 'middleware.AmaraSecurityMiddleware', 'caching.middleware.AmaraCachingMiddleware', 'middleware.LogRequest', 'middleware.StripGoogleAnalyticsCookieMiddleware', 'utils.ajaxmiddleware.AjaxErrorMiddleware', 'localeurl.middleware.LocaleURLMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'auth.middleware.AmaraAuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'openid_consumer.middleware.OpenIDMiddleware', 'middleware.P3PHeaderMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'api.middleware.CORSMiddleware', ) HOMEPAGE_VIEW = 'views.home' ROOT_URLCONF = 'urls' INSTALLED_APPS = ( # this needs to be first, yay for app model loading mess 'auth', # django stock apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # third party apps 'rest_framework', 'django_rq', # third party apps forked on our repo 'localeurl', 'openid_consumer', # our apps 'accountlinker', 'activity', 'amara', 'amaradotorg', 'api', 'caching', 'codefield', 'comments', 'externalsites', 'guitests', 'messages', 'mysqltweaks', 'notifications', 'profiles', 'search', 'staff', 'staticmedia', 'styleguide', 'teams', 'testhelpers', 'thirdpartyaccounts', 'ui', 'unisubs_compressor', 'utils', 'videos', 'widget', 'subtitles', 'captcha', 'raven.contrib.django.raven_compat', ) STARTUP_MODULES = [ 'externalsites.signalhandlers', ] # Queue settings RQ_QUEUES = { 'default': { 'USE_REDIS_CACHE': 'storage', }, 'high': { 'USE_REDIS_CACHE': 'storage', }, 'low': { 'USE_REDIS_CACHE': 'storage', } } RUN_JOBS_EAGERLY = False # feedworker management command setup FEEDWORKER_PASS_DURATION=3600 REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework_yaml.parsers.YAMLParser', 'rest_framework_xml.parsers.XMLParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework_yaml.renderers.YAMLRenderer', 'api.renderers.AmaraBrowsableAPIRenderer', 'rest_framework_xml.renderers.XMLRenderer', ), 'URL_FORMAT_OVERRIDE': 'format', 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'api.negotiation.AmaraContentNegotiation', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.auth.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_PAGINATION_CLASS': 'api.pagination.AmaraPagination', 'ORDERING_PARAM': 'order_by', 'VIEW_NAME_FUNCTION': 'api.viewdocs.amara_get_view_name', 'VIEW_DESCRIPTION_FUNCTION': 'api.viewdocs.amara_get_view_description', 'NON_FIELD_ERRORS_KEY': 'general_errors', } ################# import re LOCALE_INDEPENDENT_PATHS = [ re.compile('^/media/'), re.compile('^/assets/'), re.compile('^/widget/'), re.compile('^/api/'), re.compile('^/api2/'), re.compile('^/jstest/'), re.compile('^/externalsites/youtube-callback'), re.compile('^/auth/set-hidden-message-id/'), re.compile('^/auth/twitter_login_done'), re.compile('^/auth/twitter_login_done_confirm'), re.compile('^/crossdomain.xml'), re.compile('^/embedder-widget-iframe/'), re.compile('^/__debug__/'), ] OPENID_SREG = {"required": "nickname, email", "optional":"postcode, country", "policy_url": ""} OPENID_AX = [{"type_uri": "http://axschema.org/contact/email", "count": 1, "required": True, "alias": "email"}, {"type_uri": "fullname", "count": 1 , "required": False, "alias": "fullname"}] FACEBOOK_API_KEY = '' FACEBOOK_SECRET_KEY = '' VIMEO_API_KEY = None VIMEO_API_SECRET = None WUFOO_API_KEY = None WUFOO_API_BASE_URL = 'https://participatoryculture.wufoo.com/api/v3/' # NOTE: all of these backends store the User.id value in the session data, # which we rely on in AmaraAuthenticationMiddleware. Other backends should # use the same system. AUTHENTICATION_BACKENDS = ( 'auth.backends.CustomUserBackend', 'externalsites.auth_backends.OpenIDConnectBackend', 'thirdpartyaccounts.auth_backends.TwitterAuthBackend', 'thirdpartyaccounts.auth_backends.FacebookAuthBackend', 'django.contrib.auth.backends.ModelBackend', ) # Use cookie storage always since it works the best with our caching system MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' # We actually use pytest to run our tests, but this settings prevents a # spurious warning TEST_RUNNER = 'django.test.runner.DiscoverRunner' LOGIN_URL = '/auth/login/' LOGIN_REDIRECT_URL = '/' MINIMUM_PASSWORD_SCORE = 2 PASSWORD_RESET_TIMEOUT_DAYS = 1 AUTH_PROFILE_MODULE = 'profiles.Profile' ACCOUNT_ACTIVATION_DAYS = 9999 # we are using registration only to verify emails SESSION_COOKIE_AGE = 2419200 # 4 weeks SESSION_COOKIE_HTTPONLY = True SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' RECENT_ACTIVITIES_ONPAGE = 10 ACTIVITIES_ONPAGE = 20 REVISIONS_ONPAGE = 20 FEEDBACK_EMAIL = 'socmedia@pculture.org' FEEDBACK_EMAILS = [FEEDBACK_EMAIL] FEEDBACK_ERROR_EMAIL = 'universalsubtitles-errors@pculture.org' FEEDBACK_SUBJECT = 'Amara Feedback' FEEDBACK_RESPONSE_SUBJECT = 'Thanks for trying Amara' FEEDBACK_RESPONSE_EMAIL = 'universalsubtitles@pculture.org' FEEDBACK_RESPONSE_TEMPLATE = 'feedback_response.html' #teams TEAMS_ON_PAGE = 12 PROJECT_VERSION = '0.5' EDIT_END_THRESHOLD = 120 ANONYMOUS_USER_ID = 10000 ANONYMOUS_DEFAULT_USERNAME = u"amara-bot" ANONYMOUS_FULL_NAME = u"Amara Bot" #Use on production GOOGLE_TAG_MANAGER_ID = None GOOGLE_ANALYTICS_NUMBER = None GOOGLE_ADWORDS_CODE = None # API integration settings GOOGLE_CLIENT_ID = None GOOGLE_CLIENT_SECRET = None GOOGLE_API_KEY = None GOOGLE_SERVICE_ACCOUNT = None GOOGLE_SERVICE_ACCOUNT_SECRET = None try: from commit import LAST_COMMIT_GUID except ImportError: LAST_COMMIT_GUID = "dev" AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' DEFAULT_BUCKET = '' AWS_USER_DATA_BUCKET_NAME = '' STATIC_MEDIA_USES_S3 = USE_AMAZON_S3 = False STATIC_MEDIA_COMPRESSED = True STATIC_MEDIA_EXPERIMENTAL_EDITOR_BUCKET = 's3.staging.amara.org' # django-storages related settings PRIVATE_STORAGE_BUCKET = os.environ.get('AMARA_PRIVATE_STORAGE_BUCKET') PRIVATE_STORAGE_PREFIX = os.environ.get('AMARA_PRIVATE_STORAGE_PREFIX') AWS_DEFAULT_ACL = None AVATAR_MAX_SIZE = 1024*1024 THUMBNAILS_SIZE = ( (100, 100), (50, 50), (30, 30), (120, 90), (240, 240) ) EMAIL_BCC_LIST = [] CACHES = { 'default': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://{}:{}/{}".format( os.environ.get('REDIS_HOST', 'redis'), os.environ.get('REDIS_PORT', 6379), 0), "OPTIONS": { "PARSER_CLASS": "redis.connection.HiredisParser", }, }, 'storage': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://{}:{}/{}".format( os.environ.get('REDIS_HOST', 'redis'), os.environ.get('REDIS_PORT', 6379), 1), "OPTIONS": { "PARSER_CLASS": "redis.connection.HiredisParser", }, }, } #for unisubs.example.com RECAPTCHA_PUBLIC = '6LdoScUSAAAAANmmrD7ALuV6Gqncu0iJk7ks7jZ0' RECAPTCHA_SECRET = ' 6LdoScUSAAAAALvQj3aI1dRL9mHgh85Ks2xZH1qc' ROSETTA_EXCLUDED_APPLICATIONS = ( 'openid_consumer', 'rosetta' ) # List of modules to extract docstrings from for the update_docs management # command. API_DOCS_MODULES = [ 'api.views.languages', 'api.views.videos', 'api.views.subtitles', 'api.views.users', 'api.views.activity', 'api.views.messages', 'api.views.teams', ] MEDIA_BUNDLES = { "base.css": { "files": ( "css/jquery.jgrowl.css", "css/jquery.alerts.css", "css/960.css", "css/reset.css", "css/html.css", "css/about_faq.css", "css/breadcrumb.css", "css/buttons.css", "css/chosen.css", "css/classes.css", "css/forms.css", "css/index.css", "css/layout.css", "css/profile_pages.css", "css/revision_history.css", "css/teams.css", "css/transcripts.css", "css/background.css", "css/activity_stream.css", "css/settings.css", "css/messages.css", "css/global.css", "css/top_user_panel.css", "css/services.css", "css/solutions.css", "css/watch.css", "css/v1.scss", "css/bootstrap.css", # Hack to make the new headers/footers work "amara/css/variables.scss", "amara/css/mixins.scss", "amara/css/global/dropdowns.scss", "amara/css/elements/_page_header.scss", "amara/css/elements/_navigation.scss", "amara/css/elements/_consolidate-header.scss", "amara/css/elements/page_footer.scss", "css/marketing-integration.scss", ), }, "new-base.css": { "files": [ 'src/css/site/colors.scss', 'src/css/site/layout.scss', 'src/css/site/type.scss', 'src/css/site/buttons.scss', 'src/css/site/forms.scss', 'src/css/site/links.scss', 'src/css/site/lists.scss', 'src/css/site/cards.scss', 'src/css/site/tables.scss', 'src/css/site/graphs.scss', 'src/css/site/header.scss', 'src/css/site/tabs.scss', 'src/css/site/split-view.scss', 'src/css/site/bottom-sheet.scss', 'src/css/site/pagination.scss', 'src/css/site/menus.scss', 'src/css/site/modals.scss', 'src/css/site/tooltips.scss', 'src/css/site/banner.scss', 'src/css/site/messages.scss', 'src/css/site/footer.scss', 'src/css/site/teams.scss', 'src/css/third-party/jquery-ui-1.11.4.custom.css', 'src/css/third-party/jquery-ui.theme-1.11.4.custom.css', 'src/css/third-party/jquery-ui.structure-1.11.4.custom.css', ], "include_path": 'src/css/site', }, "home.css": { "files": ( "css/new_index.css", ), }, "hands_home.css": { "files": ( "css/hands-static.css", "css/hands-main.css", # Hack to make the new headers/footers work "amara/css/variables.scss", "amara/css/mixins.scss", "amara/css/global/grid.scss", "amara/css/global/dropdowns.scss", "amara/css/elements/_navigation.scss", "amara/css/elements/_page_header.scss", "amara/css/elements/_consolidate-header.scss", "amara/css/elements/page_footer.scss", "css/marketing-integration.scss", ) }, "api.css": { "files": ( "src/css/api.css", ), }, "hands_home.js": { "files": ( "js/hands-plugins.js", "js/hands-modernizr-2.6.2.min.js", ) }, "site.js": { "files": ( "js/jquery-1.4.3.js", "js/jquery-ui-1.8.16.custom.min.js", "js/jgrowl/jquery.jgrowl.js", "js/jalerts/jquery.alerts.js", "js/jquery.form.js", "js/jquery.metadata.js", "js/jquery.mod.js", "js/jquery.rpc.js", "js/jquery.input_replacement.min.js", "js/messages.js", "js/escape.js", "js/dropdown-hack.js", "js/libs/chosen.jquery.min.js", "js/libs/chosen.ajax.jquery.js", "js/libs/jquery.cookie.js", "src/js/third-party/js.cookie.js", "js/unisubs.site.js", "src/js/unisubs.variations.js", ), }, "new-site.js": { "files": [ 'src/js/third-party/jquery-2.1.3.js', 'src/js/third-party/jquery-ui-1.11.4.custom.js', 'src/js/third-party/jquery.form.js', 'src/js/third-party/jquery.formset.js', 'src/js/third-party/behaviors.js', "src/js/third-party/js.cookie.js", 'src/js/site/announcements.js', 'src/js/site/copytext.js', 'src/js/site/menus.js', 'src/js/site/modals.js', 'src/js/site/querystring.js', 'src/js/site/tooltips.js', 'src/js/site/pagination.js', 'src/js/site/autocomplete.js', 'src/js/site/thumb-lists.js', 'src/js/site/bottom-sheet.js', 'src/js/site/team-videos.js', 'src/js/site/team-bulk-move.js', 'src/js/site/team-members.js', 'src/js/site/team-integration-settings.js', 'src/js/site/dates.js', 'src/js/site/formsets.js', ], }, "api.js": { "files": ( "js/jquery-1.4.3.js", "src/js/api.js", ), }, "teams.js": { "files": ( "js/libs/ICanHaz.js", "js/libs/classy.js", "js/libs/underscore.js", "js/libs/chosen.jquery.min.js", "js/libs/chosen.ajax.jquery.js", "js/jquery.mod.js", "js/teams/create-task.js", ), }, 'editor.js': { 'files': ( 'src/js/third-party/jquery-1.12.4.js', 'js/jquery.form.js', 'src/js/third-party/jquery.autosize.js', 'src/js/third-party/angular.1.2.9.js', 'src/js/third-party/angular-cookies.js', 'src/js/third-party/underscore.1.8.3.js', 'src/js/third-party/popcorn.js', 'src/js/third-party/Blob.js', 'src/js/third-party/FileSaver.js', 'src/js/popcorn/popcorn.amara.js', 'src/js/third-party/modal-helper.js', 'src/js/third-party/json2.min.js', 'src/js/dfxp/dfxp.js', 'src/js/uri.js', 'src/js/popcorn/popcorn.flash-fallback.js', #'src/js/popcorn/popcorn.netflix.js', 'src/js/subtitle-editor/app.js', 'src/js/subtitle-editor/dom.js', 'src/js/subtitle-editor/durationpicker.js', 'src/js/subtitle-editor/gettext.js', 'src/js/subtitle-editor/help.js', 'src/js/subtitle-editor/lock.js', 'src/js/subtitle-editor/preferences.js', 'src/js/subtitle-editor/modal.js', 'src/js/subtitle-editor/notes.js', 'src/js/subtitle-editor/blob.js', 'src/js/subtitle-editor/session.js', 'src/js/subtitle-editor/shifttime.js', 'src/js/subtitle-editor/toolbar.js', 'src/js/subtitle-editor/workflow.js', 'src/js/subtitle-editor/subtitles/controllers.js', 'src/js/subtitle-editor/subtitles/directives.js', 'src/js/subtitle-editor/subtitles/filters.js', 'src/js/subtitle-editor/subtitles/models.js', 'src/js/subtitle-editor/subtitles/services.js', 'src/js/subtitle-editor/timeline/controllers.js', 'src/js/subtitle-editor/timeline/directives.js', 'src/js/subtitle-editor/video/controllers.js', 'src/js/subtitle-editor/video/directives.js', 'src/js/subtitle-editor/video/services.js', ), }, 'editor.css': { 'files': ( 'src/css/third-party/reset.css', 'src/css/subtitle-editor/subtitle-editor.scss', ), }, "embedder.js":{ "files": ( "src/js/third-party/json2.min.js", 'src/js/third-party/underscore.min.js', 'src/js/third-party/jquery-1.8.3.min.js', 'src/js/third-party/backbone.min.js', 'src/js/third-party/popcorn.js', 'src/js/popcorn/popcorn.flash-fallback.js', 'src/js/third-party/jquery.mCustomScrollbar.concat.min.js', 'src/js/popcorn/popcorn.amaratranscript.js', 'src/js/popcorn/popcorn.amarasubtitle.js', 'src/js/popcorn/popcorn.amara.js', 'src/js/embedder/embedder.js' ), 'add_amara_conf': True, }, "embedder.css": { "files": ( "src/css/embedder/jquery.mCustomScrollbar.css", "src/css/embedder/embedder.scss", ), }, 'ie8.css': { 'files': ( 'css/ie8.css', ), }, 'ajax-paginator.js': { 'files': ( 'js/jquery.address-1.4.fixed.js', 'js/escape.js', 'js/jquery.ajax-paginator.js', ), }, 'prepopulate.js': { 'files': ( 'js/urlify.js', 'js/prepopulate.min.js', ), }, # used by the old editor 'unisubs-api.js': { 'files': ( 'legacy-js/unisubs-api.js', ), }, # used by the old embedder -- hopefully going away soon 'unisubs-offsite-compiled.js': { 'files': ( 'legacy-js/unisubs-offsite-compiled.js', ), }, # used by both the old embedder and old editor "widget.css": { "files": ( "css/unisubs-widget.css", ), }, 'login.js': { 'files': ( 'src/js/site/login.js', 'src/js/site/facebook.js', ), }, } # Where we should tell OAuth providers to redirect the user to. We want to # use https for production to prevent attackers from seeing the access token. # For development, we care less about that so we typically use http OAUTH_CALLBACK_PROTOCOL = 'https' ENABLE_LOGIN_CAPTCHA = not os.environ.get('DISABLE_LOGIN_CAPTCHA') EMAIL_BACKEND = "utils.safemail.InternalOnlyBackend" EMAIL_FILE_PATH = '/tmp/unisubs-messages' # on staging and dev only the emails listed bellow will receive actual mail EMAIL_NOTIFICATION_RECEIVERS = ("arthur@stimuli.com.br", "steve@stevelosh.com", "@pculture.org") def log_handler_info(): rv = { 'formatter': 'standard' , } if env_flag_set('DB_LOGGING'): rv['level'] = 'DEBUG' else: rv['level'] = 'INFO' if env_flag_set('JSON_LOGGING'): rv['class'] = 'utils.jsonlogging.JSONHandler' else: rv['class'] = 'logging.StreamHandler' return rv LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'INFO', 'handlers': ['main'], }, 'formatters': { 'standard': { 'format': '%(levelname)s %(asctime)s %(name)s %(message)s' }, }, 'handlers': { 'main': log_handler_info(), }, 'loggers': { "rq.worker": { "level": "INFO" }, 'requests.packages.urllib3.connectionpool': { 'level': 'WARNING', } }, } if env_flag_set('DB_LOGGING'): LOGGING['loggers']['django.db'] = { 'level': 'DEBUG' } TMP_FOLDER = "/tmp/" SOUTH_MIGRATION_MODULES = { 'captcha': 'captcha.south_migrations', } from task_settings import * optionalapps.exec_repository_scripts('settings_extra.py', globals(), locals())
agpl-3.0
madbob/GASdottoNG
code/database/migrations/2021_08_13_234743_fix_variants_table.php
652
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class FixVariantsTable extends Migration { public function up() { if (Schema::hasColumn('variants', 'has_offset')) { Schema::table('variants', function (Blueprint $table) { $table->dropColumn('has_offset'); }); } if (Schema::hasColumn('variant_values', 'price_offset')) { Schema::table('variant_values', function (Blueprint $table) { $table->dropColumn('price_offset'); }); } } public function down() { // } }
agpl-3.0
timelapseplus/VIEW
node_modules/segfault/src/segfault-handler.cpp
3650
#include <string.h> #include <execinfo.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <assert.h> #include <stdarg.h> #include <node.h> #include <time.h> #include <node_buffer.h> #include <node_object_wrap.h> #include <v8-debug.h> #include <nan.h> using namespace v8; using namespace node; #define STDERR_FD 2 static char *dir = NULL; static void segfault_handler(int sig, siginfo_t *si, void *unused) { void *array[32]; // Array to store backtrace symbols size_t size; // To store the size of the stack backtrace char sbuff[128]; int n; // chars written to buffer int fd; time_t now; int pid; const char * signame; if (sig == SIGSEGV) { signame = "SIGSEGV\0"; } else if (sig == SIGABRT) { signame = "SIGABRT\0"; } else { signame = "UNKNOWN\0"; } // Construct a filename time(&now); pid = getpid(); snprintf(sbuff, sizeof(sbuff), "%s/stacktrace-%d-%d.log", dir, (int)now, pid ); // Open the File fd = open(sbuff, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IRGRP | S_IROTH); // Write the header line n = snprintf(sbuff, sizeof(sbuff), "PID %d received %s for address: 0x%lx\n", pid, signame, (long) si->si_addr); if(fd > 0) write(fd, sbuff, n); write(STDERR_FD, sbuff, n); // Write the Backtrace size = backtrace(array, 32); if(fd > 0) backtrace_symbols_fd(array, size, fd); backtrace_symbols_fd(array, size, STDERR_FD); // Exit violently close(fd); exit(-1); } // create some stack frames to inspect from CauseSegfault __attribute__ ((noinline)) void segfault_stack_frame_1() { // DDOPSON-2013-04-16 using the address "1" instead of "0" prevents a nasty compiler over-optimization // When using "0", the compiler will over-optimize (unless using -O0) and generate a UD2 instruction // UD2 is x86 for "Invalid Instruction" ... (yeah, they have a valid code that means invalid) // Long story short, we don't get our SIGSEGV. Which means no pretty demo of stacktraces. // Instead, you see "Illegal Instruction: 4" on the console and the program stops. int *foo = (int*)1; printf("NodeSegfaultHandlerNative: about to dereference NULL (will cause a SIGSEGV)\n"); *foo = 78; // trigger a SIGSEGV } __attribute__ ((noinline)) void segfault_stack_frame_2(void) { // use a function pointer to thwart inlining void (*fn_ptr)() = segfault_stack_frame_1; fn_ptr(); } NAN_METHOD(CauseSegfault) { NanScope(); // use a function pointer to thwart inlining void (*fn_ptr)() = segfault_stack_frame_2; fn_ptr(); NanReturnUndefined(); // this line never runs } NAN_METHOD(CauseAbort) { NanScope(); assert(dir == NULL); NanReturnUndefined(); // this line never runs } NAN_METHOD(RegisterHandler) { NanUtf8String *str; NanScope(); dir = (char *)malloc(64); /* never freed, used by sigaction */ str = new NanUtf8String(args[0]); if (str->length() > 0 && str->length() < 64) { char * src = **str; strncpy(dir, src, 64); } else { dir[0] = '.'; dir[1] = '\0'; } struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = segfault_handler; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGABRT, &sa, NULL); NanReturnUndefined(); } extern "C" { void init(Handle<Object> target) { NODE_SET_METHOD(target, "registerHandler", RegisterHandler); NODE_SET_METHOD(target, "causeSegfault", CauseSegfault); NODE_SET_METHOD(target, "causeAbort", CauseAbort); } NODE_MODULE(segfault_handler, init); }
agpl-3.0
mwasilew/testmanager
testmanager/testmanualrunner/migrations/0012_testrun_closed.py
448
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('testmanualrunner', '0011_testrunresult_bugs'), ] operations = [ migrations.AddField( model_name='testrun', name='closed', field=models.BooleanField(default=False), preserve_default=True, ), ]
agpl-3.0
Audiveris/audiveris
src/main/org/audiveris/omr/ui/util/UIPredicates.java
5795
//------------------------------------------------------------------------------------------------// // // // U I P r e d i c a t e s // // // //------------------------------------------------------------------------------------------------// // <editor-fold defaultstate="collapsed" desc="hdr"> // // Copyright © Audiveris 2021. All rights reserved. // // This program is free software: you can redistribute it and/or modify it under the terms of the // GNU Affero General Public License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License along with this // program. If not, see <http://www.gnu.org/licenses/>. //------------------------------------------------------------------------------------------------// // </editor-fold> package org.audiveris.omr.ui.util; import org.audiveris.omr.WellKnowns; import static java.awt.event.InputEvent.*; import java.awt.event.MouseEvent; import javax.swing.SwingUtilities; /** * Class <code>UIPredicates</code> gathers convenient methods to check user gesture. * * @author Hervé Bitteur */ public abstract class UIPredicates { //~ Constructors ------------------------------------------------------------------------------- /** * Not meant to be instantiated. */ private UIPredicates () { } //~ Methods ------------------------------------------------------------------------------------ //------------------// // isAdditionWanted // //------------------// /** * Predicate to check if an additional selection is wanted. * Default is the typical selection (left button), while control key is pressed. * * @param e the mouse context * @return the predicate result */ public static boolean isAdditionWanted (MouseEvent e) { if (WellKnowns.MAC_OS_X) { boolean command = e.isMetaDown(); boolean left = SwingUtilities.isLeftMouseButton(e); return left && command && !e.isPopupTrigger(); } else { return (SwingUtilities.isRightMouseButton(e) != SwingUtilities.isLeftMouseButton(e)) && e.isControlDown(); } } //-----------------// // isContextWanted // //-----------------// /** * Predicate to check if a context selection is wanted. * Default is the typical pressing with Right button only. * * @param e the mouse context * @return the predicate result */ public static boolean isContextWanted (MouseEvent e) { return SwingUtilities.isRightMouseButton(e) && !SwingUtilities.isLeftMouseButton(e); } //--------------// // isDragWanted // //--------------// /** * Predicate to check whether the zoomed display must be dragged. * This method can simply be overridden to adapt to another policy. * Default is to have both left and right buttons, or just middle button, pressed when moving. * * @param e the mouse event to check * @return true if drag is desired */ public static boolean isDragWanted (MouseEvent e) { if (WellKnowns.MAC_OS_X) { return e.isAltDown(); } else { // Mouse buttons 1 & 3 pressed and only those ones int onmask = BUTTON1_DOWN_MASK | BUTTON3_DOWN_MASK; int offmask = 0; if ((e.getModifiersEx() & (onmask | offmask)) == onmask) { return true; } // Mouse button 2 (wheel) pressed and only this one int onmask2 = BUTTON2_DOWN_MASK; int offmask2 = 0; if ((e.getModifiersEx() & (onmask2 | offmask2)) == onmask2) { return true; } return false; } } //----------------// // isRezoomWanted // //----------------// /** * Predicate to check if the display should be rezoomed to fit as * close as possible to the rubber definition. * Default is to have both Shift and Control keys pressed when the mouse is * released. * * @param e the mouse context * @return the predicate result */ public static boolean isRezoomWanted (MouseEvent e) { if (WellKnowns.MAC_OS_X) { return e.isMetaDown() && e.isShiftDown(); } else { return e.isControlDown() && e.isShiftDown(); } } //----------------// // isRubberWanted // //----------------// /** * Predicate to check if the rubber must be extended while the * mouse is being moved. * Default is the typical pressing of Shift key while moving the mouse. * * @param e the mouse context * @return the predicate result */ public static boolean isRubberWanted (MouseEvent e) { int onmask = BUTTON1_DOWN_MASK | SHIFT_DOWN_MASK; int offmask = BUTTON2_DOWN_MASK | BUTTON3_DOWN_MASK; return (e.getModifiersEx() & (onmask | offmask)) == onmask; } }
agpl-3.0
ingadhoc/product
product_replenishment_cost/wizards/product_update_from_replenishment_cost_wizard.py
964
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, _ from odoo.exceptions import UserError class ProductUpdateFromReplenishmentCostWizard(models.TransientModel): _name = 'product.update_from_replenishment_cost.wizard' _description = 'Update product cost from replenishment cost' def confirm(self): self.ensure_one() active_ids = self._context.get('active_ids') active_model = self._context.get('active_model') if active_model != 'product.template': raise UserError(_( 'Update from replenishment cost must be called from product ' 'template')) return self.env[active_model].browse( active_ids)._update_cost_from_replenishment_cost()
agpl-3.0
zvini/website
www/fns/ReceivedContacts/addDeleted.php
2584
<?php namespace ReceivedContacts; function addDeleted ($mysqli, $id, $sender_address, $sender_id_users, $sender_username, $receiver_id_users, $full_name, $alias, $address, $email1, $email1_label, $email2, $email2_label, $phone1, $phone1_label, $phone2, $phone2_label, $birthday_time, $username, $timezone, $tags, $notes, $favorite, $archived, $insert_time, $photo_id) { if ($sender_address === null) $sender_address = 'null'; else $sender_address = "'".$mysqli->real_escape_string($sender_address)."'"; if ($sender_id_users === null) $sender_id_users = 'null'; $sender_username = $mysqli->real_escape_string($sender_username); $full_name = $mysqli->real_escape_string($full_name); $alias = $mysqli->real_escape_string($alias); $address = $mysqli->real_escape_string($address); $email1 = $mysqli->real_escape_string($email1); $email1_label = $mysqli->real_escape_string($email1_label); $email2 = $mysqli->real_escape_string($email2); $email2_label = $mysqli->real_escape_string($email2_label); $phone1 = $mysqli->real_escape_string($phone1); $phone1_label = $mysqli->real_escape_string($phone1_label); $phone2 = $mysqli->real_escape_string($phone2); $phone2_label = $mysqli->real_escape_string($phone2_label); if ($birthday_time === null) $birthday_time = 'null'; $username = $mysqli->real_escape_string($username); if ($timezone === null) $timezone = 'null'; $tags = $mysqli->real_escape_string($tags); $notes = $mysqli->real_escape_string($notes); $favorite = $favorite ? '1' : '0'; $archived = $archived ? '1' : '0'; if ($photo_id === null) $photo_id = 'null'; $sql = 'insert into received_contacts' .' (id, sender_address, sender_id_users, sender_username,' .' receiver_id_users, full_name, alias, address,' .' email1, email1_label, email2, email2_label,' .' phone1, phone1_label, phone2, phone2_label,' .' birthday_time, username, timezone, tags,' .' notes, favorite, archived, insert_time, photo_id)' ." values ($id, $sender_address, $sender_id_users, '$sender_username'," ." $receiver_id_users, '$full_name', '$alias', '$address'," ." '$email1', '$email1_label', '$email2', '$email2_label'," ." '$phone1', '$phone1_label', '$phone2', '$phone2_label'," ." $birthday_time, '$username', $timezone, '$tags'," ." '$notes', $favorite, $archived, $insert_time, $photo_id)"; include_once __DIR__.'/../mysqli_query_exit.php'; mysqli_query_exit($mysqli, $sql); }
agpl-3.0
aluxnimm/outlookcaldavsynchronizer
CalDavSynchronizer/ProfileTypes/ConcreteTypes/WebDeProfile.cs
3031
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using CalDavSynchronizer.Contracts; using CalDavSynchronizer.Ui.Options; using CalDavSynchronizer.Ui.Options.Models; using CalDavSynchronizer.Ui.Options.ViewModels; namespace CalDavSynchronizer.ProfileTypes.ConcreteTypes { class WebDeProfile : ProfileTypeBase { public override string Name { get; } = "Web.de"; public override string ImageUrl { get; } = "pack://application:,,,/CalDavSynchronizer;component/Resources/ProfileLogos/logo_webde.png"; public override IProfileModelFactory CreateModelFactory(IOptionsViewModelParent optionsViewModelParent, IOutlookAccountPasswordProvider outlookAccountPasswordProvider, IReadOnlyList<string> availableCategories, IOptionTasks optionTasks, GeneralOptions generalOptions, IViewOptions viewOptions, OptionModelSessionData sessionData) { return new ProfileModelFactory(this, optionsViewModelParent, outlookAccountPasswordProvider, availableCategories, optionTasks, generalOptions, viewOptions, sessionData); } public override Contracts.Options CreateOptions() { var data = base.CreateOptions(); data.CalenderUrl = "https://caldav.web.de"; data.MappingConfiguration = CreateEventMappingConfiguration(); return data; } public override EventMappingConfiguration CreateEventMappingConfiguration() { var data = base.CreateEventMappingConfiguration(); data.UseIanaTz = true; return data; } class ProfileModelFactory : ProfileModelFactoryBase { public ProfileModelFactory(IProfileType profileType, IOptionsViewModelParent optionsViewModelParent, IOutlookAccountPasswordProvider outlookAccountPasswordProvider, IReadOnlyList<string> availableCategories, IOptionTasks optionTasks, GeneralOptions generalOptions, IViewOptions viewOptions, OptionModelSessionData sessionData) : base(profileType, optionsViewModelParent, outlookAccountPasswordProvider, availableCategories, optionTasks, generalOptions, viewOptions, sessionData) { } } } }
agpl-3.0
OCA/bank-payment
account_banking_mandate/models/res_partner.py
2011
# Copyright 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # Copyright 2017 Carlos Dauden <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" mandate_count = fields.Integer( compute="_compute_mandate_count", string="Number of Mandates", readonly=True ) valid_mandate_id = fields.Many2one( comodel_name="account.banking.mandate", compute="_compute_valid_mandate_id", string="First Valid Mandate", ) def _compute_mandate_count(self): mandate_data = self.env["account.banking.mandate"].read_group( [("partner_id", "in", self.ids)], ["partner_id"], ["partner_id"] ) mapped_data = { mandate["partner_id"][0]: mandate["partner_id_count"] for mandate in mandate_data } for partner in self: partner.mandate_count = mapped_data.get(partner.id, 0) def _compute_valid_mandate_id(self): # Dict for reducing the duplicated searches on parent/child partners company_id = self.env.company.id if company_id: company = self.env["res.company"].browse(company_id) else: company = self.env.company mandates_dic = {} for partner in self: commercial_partner_id = partner.commercial_partner_id.id if commercial_partner_id in mandates_dic: partner.valid_mandate_id = mandates_dic[commercial_partner_id] else: mandates = partner.commercial_partner_id.bank_ids.mapped( "mandate_ids" ).filtered(lambda x: x.state == "valid" and x.company_id == company) first_valid_mandate_id = mandates[:1].id partner.valid_mandate_id = first_valid_mandate_id mandates_dic[commercial_partner_id] = first_valid_mandate_id
agpl-3.0
LYY/code2docx
vendor/baliance.com/gooxml/_examples/spreadsheet/image/main.go
1139
// Copyright 2017 Baliance. All rights reserved. package main import ( "log" "math" "baliance.com/gooxml/common" "baliance.com/gooxml/measurement" "baliance.com/gooxml/spreadsheet" ) func main() { ss := spreadsheet.New() // add a single sheet sheet := ss.AddSheet() img, err := common.ImageFromFile("gophercolor.png") if err != nil { log.Fatalf("unable to create image: %s", err) } iref, err := ss.AddImage(img) if err != nil { log.Fatalf("unable to add image to workbook: %s", err) } dwng := ss.AddDrawing() sheet.SetDrawing(dwng) for i := float64(0); i < 360; i += 30 { anc := dwng.AddImage(iref, spreadsheet.AnchorTypeAbsolute) ang := i * math.Pi / 180 x := 2 + 2*math.Cos(ang) y := 2 + +2*math.Sin(ang) anc.SetColOffset(measurement.Distance(x) * measurement.Inch) anc.SetRowOffset(measurement.Distance(y) * measurement.Inch) // set the image to 1x1 inches var w measurement.Distance = 1 * measurement.Inch anc.SetWidth(w) anc.SetHeight(iref.RelativeHeight(w)) } if err := ss.Validate(); err != nil { log.Fatalf("error validating sheet: %s", err) } ss.SaveToFile("image.xlsx") }
agpl-3.0
mjirayu/sit_academy
lms/djangoapps/student_account/views.py
15614
""" Views for a student's account information. """ import logging import json import urlparse from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseForbidden ) from django.shortcuts import redirect from django.http import HttpRequest from django_countries import countries from django.core.urlresolvers import reverse, resolve from django.utils.translation import ugettext as _ from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_http_methods from lang_pref.api import released_languages from edxmako.shortcuts import render_to_response from microsite_configuration import microsite from external_auth.login_and_register import ( login as external_auth_login, register as external_auth_register ) from student.models import UserProfile, Tag from student.views import ( signin_user as old_login_view, register_user as old_register_view ) from student.helpers import get_next_url_for_login_page import third_party_auth from third_party_auth import pipeline from util.bad_request_rate_limiter import BadRequestRateLimiter from openedx.core.djangoapps.user_api.accounts.api import request_password_change from openedx.core.djangoapps.user_api.errors import UserNotFound AUDIT_LOG = logging.getLogger("audit") @require_http_methods(['GET']) @ensure_csrf_cookie def login_and_registration_form(request, initial_mode="login"): """Render the combined login/registration form, defaulting to login This relies on the JS to asynchronously load the actual form from the user_api. Keyword Args: initial_mode (string): Either "login" or "register". """ # Determine the URL to redirect to following login/registration/third_party_auth redirect_to = get_next_url_for_login_page(request) # If we're already logged in, redirect to the dashboard if request.user.is_authenticated(): return redirect(redirect_to) # Retrieve the form descriptions from the user API form_descriptions = _get_form_descriptions(request) # If this is a microsite, revert to the old login/registration pages. # We need to do this for now to support existing themes. # Microsites can use the new logistration page by setting # 'ENABLE_COMBINED_LOGIN_REGISTRATION' in their microsites configuration file. if microsite.is_request_in_microsite() and not microsite.get_value('ENABLE_COMBINED_LOGIN_REGISTRATION', False): if initial_mode == "login": return old_login_view(request) elif initial_mode == "register": return old_register_view(request) # Allow external auth to intercept and handle the request ext_auth_response = _external_auth_intercept(request, initial_mode) if ext_auth_response is not None: return ext_auth_response # Our ?next= URL may itself contain a parameter 'tpa_hint=x' that we need to check. # If present, we display a login page focused on third-party auth with that provider. third_party_auth_hint = None if '?' in redirect_to: try: next_args = urlparse.parse_qs(urlparse.urlparse(redirect_to).query) provider_id = next_args['tpa_hint'][0] if third_party_auth.provider.Registry.get(provider_id=provider_id): third_party_auth_hint = provider_id initial_mode = "hinted_login" except (KeyError, ValueError, IndexError): pass # Otherwise, render the combined login/registration page context = { 'login_redirect_url': redirect_to, # This gets added to the query string of the "Sign In" button in the header 'disable_courseware_js': True, 'initial_mode': initial_mode, 'third_party_auth': json.dumps(_third_party_auth_context(request, redirect_to)), 'third_party_auth_hint': third_party_auth_hint or '', 'platform_name': settings.PLATFORM_NAME, 'responsive': True, # Include form descriptions retrieved from the user API. # We could have the JS client make these requests directly, # but we include them in the initial page load to avoid # the additional round-trip to the server. 'login_form_desc': form_descriptions['login'], 'registration_form_desc': form_descriptions['registration'], 'password_reset_form_desc': form_descriptions['password_reset'], } return render_to_response('student_account/login_and_register.html', context) @require_http_methods(['POST']) def password_change_request_handler(request): """Handle password change requests originating from the account page. Uses the Account API to email the user a link to the password reset page. Note: The next step in the password reset process (confirmation) is currently handled by student.views.password_reset_confirm_wrapper, a custom wrapper around Django's password reset confirmation view. Args: request (HttpRequest) Returns: HttpResponse: 200 if the email was sent successfully HttpResponse: 400 if there is no 'email' POST parameter, or if no user with the provided email exists HttpResponse: 403 if the client has been rate limited HttpResponse: 405 if using an unsupported HTTP method Example usage: POST /account/password """ limiter = BadRequestRateLimiter() if limiter.is_rate_limit_exceeded(request): AUDIT_LOG.warning("Password reset rate limit exceeded") return HttpResponseForbidden() user = request.user # Prefer logged-in user's email email = user.email if user.is_authenticated() else request.POST.get('email') if email: try: request_password_change(email, request.get_host(), request.is_secure()) except UserNotFound: AUDIT_LOG.info("Invalid password reset attempt") # Increment the rate limit counter limiter.tick_bad_request_counter(request) return HttpResponseBadRequest(_("No user with the provided email address exists.")) return HttpResponse(status=200) else: return HttpResponseBadRequest(_("No email address provided.")) def _third_party_auth_context(request, redirect_to): """Context for third party auth providers and the currently running pipeline. Arguments: request (HttpRequest): The request, used to determine if a pipeline is currently running. redirect_to: The URL to send the user to following successful authentication. Returns: dict """ context = { "currentProvider": None, "providers": [], "secondaryProviders": [], "finishAuthUrl": None, "errorMessage": None, } if third_party_auth.is_enabled(): for enabled in third_party_auth.provider.Registry.enabled(): info = { "id": enabled.provider_id, "name": enabled.name, "iconClass": enabled.icon_class, "loginUrl": pipeline.get_login_url( enabled.provider_id, pipeline.AUTH_ENTRY_LOGIN, redirect_url=redirect_to, ), "registerUrl": pipeline.get_login_url( enabled.provider_id, pipeline.AUTH_ENTRY_REGISTER, redirect_url=redirect_to, ), } context["providers" if not enabled.secondary else "secondaryProviders"].append(info) running_pipeline = pipeline.get(request) if running_pipeline is not None: current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline) context["currentProvider"] = current_provider.name context["finishAuthUrl"] = pipeline.get_complete_url(current_provider.backend_name) if current_provider.skip_registration_form: # As a reliable way of "skipping" the registration form, we just submit it automatically context["autoSubmitRegForm"] = True # Check for any error messages we may want to display: for msg in messages.get_messages(request): if msg.extra_tags.split()[0] == "social-auth": # msg may or may not be translated. Try translating [again] in case we are able to: context['errorMessage'] = _(unicode(msg)) # pylint: disable=translation-of-non-string break return context def _get_form_descriptions(request): """Retrieve form descriptions from the user API. Arguments: request (HttpRequest): The original request, used to retrieve session info. Returns: dict: Keys are 'login', 'registration', and 'password_reset'; values are the JSON-serialized form descriptions. """ return { 'login': _local_server_get('/user_api/v1/account/login_session/', request.session), 'registration': _local_server_get('/user_api/v1/account/registration/', request.session), 'password_reset': _local_server_get('/user_api/v1/account/password_reset/', request.session) } def _local_server_get(url, session): """Simulate a server-server GET request for an in-process API. Arguments: url (str): The URL of the request (excluding the protocol and domain) session (SessionStore): The session of the original request, used to get past the CSRF checks. Returns: str: The content of the response """ # Since the user API is currently run in-process, # we simulate the server-server API call by constructing # our own request object. We don't need to include much # information in the request except for the session # (to get past through CSRF validation) request = HttpRequest() request.method = "GET" request.session = session # Call the Django view function, simulating # the server-server API call view, args, kwargs = resolve(url) response = view(request, *args, **kwargs) # Return the content of the response return response.content def _external_auth_intercept(request, mode): """Allow external auth to intercept a login/registration request. Arguments: request (Request): The original request. mode (str): Either "login" or "register" Returns: Response or None """ if mode == "login": return external_auth_login(request) elif mode == "register": return external_auth_register(request) @login_required @require_http_methods(['GET']) def account_settings(request): """Render the current user's account settings page. Args: request (HttpRequest) Returns: HttpResponse: 200 if the page was sent successfully HttpResponse: 302 if not logged in (redirect to login page) HttpResponse: 405 if using an unsupported HTTP method Example usage: GET /account/settings """ return render_to_response('student_account/account_settings.html', account_settings_context(request)) @login_required @require_http_methods(['GET']) def finish_auth(request): # pylint: disable=unused-argument """ Following logistration (1st or 3rd party), handle any special query string params. See FinishAuthView.js for details on the query string params. e.g. auto-enroll the user in a course, set email opt-in preference. This view just displays a "Please wait" message while AJAX calls are made to enroll the user in the course etc. This view is only used if a parameter like "course_id" is present during login/registration/third_party_auth. Otherwise, there is no need for it. Ideally this view will finish and redirect to the next step before the user even sees it. Args: request (HttpRequest) Returns: HttpResponse: 200 if the page was sent successfully HttpResponse: 302 if not logged in (redirect to login page) HttpResponse: 405 if using an unsupported HTTP method Example usage: GET /account/finish_auth/?course_id=course-v1:blah&enrollment_action=enroll """ return render_to_response('student_account/finish_auth.html', { 'disable_courseware_js': True, }) def account_settings_context(request): """ Context for the account settings page. Args: request: The request object. Returns: dict """ user = request.user year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS] print released_languages() tags = [] all_tags = Tag.objects.all() for tag in all_tags: tags.append([unicode(tag.id), unicode(tag.name)]) context = { 'auth': {}, 'duplicate_provider': None, 'fields': { 'country': { 'options': list(countries), }, 'gender': { 'options': [(choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES], # pylint: disable=translation-of-non-string }, 'language': { 'options': released_languages(), }, 'level_of_education': { 'options': [(choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES], # pylint: disable=translation-of-non-string }, 'password': { 'url': reverse('password_reset'), }, 'year_of_birth': { 'options': year_of_birth_options, }, 'preferred_language': { 'options': settings.ALL_LANGUAGES, }, 'interesting_tag': { 'options': tags, }, }, 'platform_name': settings.PLATFORM_NAME, 'user_accounts_api_url': reverse("accounts_api", kwargs={'username': user.username}), 'user_preferences_api_url': reverse('preferences_api', kwargs={'username': user.username}), 'disable_courseware_js': True, } if third_party_auth.is_enabled(): # If the account on the third party provider is already connected with another edX account, # we display a message to the user. context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request)) auth_states = pipeline.get_provider_user_states(user) context['auth']['providers'] = [{ 'id': state.provider.provider_id, 'name': state.provider.name, # The name of the provider e.g. Facebook 'connected': state.has_account, # Whether the user's edX account is connected with the provider. # If the user is not connected, they should be directed to this page to authenticate # with the particular provider. 'connect_url': pipeline.get_login_url( state.provider.provider_id, pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS, # The url the user should be directed to after the auth process has completed. redirect_url=reverse('account_settings'), ), # If the user is connected, sending a POST request to this url removes the connection # information for this provider from their edX account. 'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id), } for state in auth_states] return context
agpl-3.0
precog/platform
quirrel/src/main/scala/com/precog/quirrel/typer/ProvenanceChecker.scala
55725
/* * ____ ____ _____ ____ ___ ____ * | _ \ | _ \ | ____| / ___| / _/ / ___| Precog (R) * | |_) | | |_) | | _| | | | | /| | | _ Advanced Analytics Engine for NoSQL Data * | __/ | _ < | |___ | |___ |/ _| | | |_| | Copyright (C) 2010 - 2013 SlamData, Inc. * |_| |_| \_\ |_____| \____| /__/ \____| All Rights Reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ package com.precog.quirrel package typer import java.util.concurrent.atomic.{AtomicInteger, AtomicReference} import com.precog.bytecode.IdentityPolicy import com.precog.util.IdGen import scalaz._ import scalaz.Ordering._ import scalaz.std.option._ import scalaz.std.set._ import scalaz.std.anyVal._ import scalaz.std.tuple._ import scalaz.syntax.apply._ import scalaz.syntax.semigroup._ import scalaz.syntax.order._ import scalaz.syntax.monoid._ trait ProvenanceChecker extends parser.AST with Binder { import library._ import Function._ import Utils._ import ast._ private val currentId = new AtomicInteger(0) private val commonIds = new AtomicReference[Map[ExprWrapper, Int]](Map()) override def checkProvenance(expr: Expr): Set[Error] = { def handleBinary( expr: Expr, left: Expr, right: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) val unified = unifyProvenance(relations)(left.provenance, right.provenance) val (provenance, contribErrors, contribConstr) = { if ((left.provenance == InfiniteProvenance || right.provenance == InfiniteProvenance) && expr.disallowsInfinite) { val provenance = NullProvenance val errors = Set(Error(expr, CannotUseDistributionWithoutSampling)) (provenance, errors, Set()) } else if (left.provenance.isParametric || right.provenance.isParametric) { if (unified.isDefined) { (unified.get, Set(), Set()) } else { val provenance = UnifiedProvenance(left.provenance, right.provenance) (provenance, Set(), Set(Related(left.provenance, right.provenance))) } } else { val provenance = unified getOrElse NullProvenance (provenance, if (unified.isDefined) Set() else Set(Error(expr, OperationOnUnrelatedSets)), Set()) } } (provenance, (leftErrors ++ rightErrors ++ contribErrors, leftConstr ++ rightConstr ++ contribConstr)) } def handleNary( expr: Expr, values: Vector[Expr], relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (errorsVec, constrVec) = values map { loop(_, relations, constraints) } unzip val errors = errorsVec reduceOption { _ ++ _ } getOrElse Set() val constr = constrVec reduceOption { _ ++ _ } getOrElse Set() if (values.isEmpty) { (ValueProvenance, (Set(), Set())) } else { val provenances: Vector[(Provenance, Set[ProvConstraint], Set[Error])] = values map { expr => (expr.provenance, Set[ProvConstraint](), Set[Error]()) } val (prov, constrContrib, errorsContrib) = provenances reduce { (pair1, pair2) => val (prov1, constr1, error1) = pair1 val (prov2, constr2, error2) = pair2 val addedErrors = error1 ++ error2 val addedConstr = constr1 ++ constr2 val unified = unifyProvenance(relations)(prov1, prov2) if ((prov1 == InfiniteProvenance || prov2 == InfiniteProvenance) && expr.disallowsInfinite) { val errors = Set(Error(expr, CannotUseDistributionWithoutSampling)) (NullProvenance, addedConstr, addedErrors ++ errors) } else if (prov1.isParametric || prov2.isParametric) { if (unified.isDefined) { (unified.get, addedConstr, addedErrors): (Provenance, Set[ProvConstraint], Set[Error]) } else { val prov = UnifiedProvenance(prov1, prov2) (prov, addedConstr ++ Set(Related(prov1, prov2)), addedErrors): (Provenance, Set[ProvConstraint], Set[Error]) } } else if (unified.isDefined) { (unified.get, addedConstr, addedErrors): (Provenance, Set[ProvConstraint], Set[Error]) } else { val errors = Set(Error(expr, OperationOnUnrelatedSets)) (NullProvenance, addedConstr, addedErrors ++ errors): (Provenance, Set[ProvConstraint], Set[Error]) } } (prov, (errors ++ errorsContrib, constr ++ constrContrib)) } } def handleUnionLike(tpe: ErrorType)(left: Provenance, right: Provenance) = { lazy val leftCard = left.cardinality lazy val rightCard = right.cardinality if (left == right) (left, Set(), Set()) else if (left == NullProvenance || right == NullProvenance) (NullProvenance, Set(), Set()) else if (left == InfiniteProvenance || right == InfiniteProvenance) (NullProvenance, Set(Error(expr, CannotUseDistributionWithoutSampling)), Set()) else if (left == UndefinedProvenance) (right, Set(), Set()) else if (right == UndefinedProvenance) (left, Set(), Set()) else if (left.isParametric || right.isParametric) (DerivedUnionProvenance(left, right), Set(), Set(SameCard(left, right, tpe))) else if (leftCard == rightCard) (CoproductProvenance(left, right), Set(), Set()) else (NullProvenance, Set(Error(expr, tpe)), Set()) } // Similar to handleUnion but must ensure that pred's provenance // can be unified with both sides. def handleCond( expr: Expr, pred: Expr, left: Expr, right: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (predErrors, predConstr) = loop(pred, relations, constraints) val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) val (provenance, errors, constr) = { if (pred.provenance == NullProvenance || left.provenance == NullProvenance || right.provenance == NullProvenance) { (NullProvenance, Set(), Set()) } else if (pred.provenance == InfiniteProvenance || left.provenance == InfiniteProvenance || right.provenance == InfiniteProvenance) { (NullProvenance, Set(Error(expr, CannotUseDistributionWithoutSampling)), Set()) } else { val leftUnified = unifyProvenance(relations)(pred.provenance, left.provenance) val rightUnified = unifyProvenance(relations)(pred.provenance, right.provenance) (leftUnified |@| rightUnified) (handleUnionLike(CondProvenanceDifferentLength)) getOrElse { (NullProvenance, Set(Error(expr, OperationOnUnrelatedSets)), Set()) } } } val finalErrors = predErrors ++ leftErrors ++ rightErrors ++ errors val finalConstr = predConstr ++ leftConstr ++ rightConstr ++ constr (provenance, (finalErrors, finalConstr)) } def handleUnion( expr: Expr, left: Expr, right: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) val (provenance, errors, constr) = if (left.provenance == InfiniteProvenance || right.provenance == InfiniteProvenance) { val errors = Set(Error(expr, CannotUseDistributionWithoutSampling)) (NullProvenance, errors, Set()) } else { handleUnionLike(UnionProvenanceDifferentLength)(left.provenance, right.provenance) } val finalErrors = leftErrors ++ rightErrors ++ errors val finalConstrs = leftConstr ++ rightConstr ++ constr (provenance, (finalErrors, finalConstrs)) } // different from unifyProvenace in that: // unifyProvenance(foo&bar, bar&baz) = Some((foo&bar)&baz) // hasCommonality(foo&bar, bar&baz) = false // this way we can statically reject this query: // | //foo ~ //bar ~ //baz // | (//foo + //bar) intersect (//bar + //baz) def hasCommonality(left: Provenance, right: Provenance): Boolean = (left, right) match { case (CoproductProvenance(prov1, prov2), pr) => hasCommonality(prov1, pr) || hasCommonality(prov2, pr) case (pl, CoproductProvenance(prov1, prov2)) => hasCommonality(pl, prov1) || hasCommonality(pl, prov2) case (ProductProvenance(l1, l2), ProductProvenance(r1, r2)) => { val leftOk = hasCommonality(l1, r1) || hasCommonality(l1, r2) val rightOk = hasCommonality(l2, r1) || hasCommonality(l2, r2) leftOk && rightOk } case (pl, pr) => pl == pr } // A DynamicProvenance being involved in either side means // we can't _prove_ the data is coming from different sets, // since `(new //foo) intersect (new //foo)` returns `new //foo` def dynamicPossibility(prov: Provenance) = prov.possibilities exists { case DynamicProvenance(_) => true case _ => false } def hasDynamic(left: Provenance, right: Provenance) = dynamicPossibility(left) && dynamicPossibility(right) def handleIntersect( expr: Expr, left: Expr, right: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) lazy val isCommon = hasCommonality(left.provenance, right.provenance) lazy val isDynamic = hasDynamic(left.provenance, right.provenance) lazy val leftCard = left.provenance.cardinality lazy val rightCard = right.provenance.cardinality val (prov, errors, constr) = { if (left.provenance == right.provenance) (left.provenance, Set(), Set()) else if (left.provenance == NullProvenance || right.provenance == NullProvenance) (NullProvenance, Set(), Set()) else if (left.provenance == UndefinedProvenance && right.provenance == UndefinedProvenance) (UndefinedProvenance, Set(), Set()) else if (left.provenance == UndefinedProvenance || right.provenance == UndefinedProvenance) (NullProvenance, Set(Error(expr, IntersectWithNoCommonalities)), Set()) else if (left.provenance == InfiniteProvenance || right.provenance == InfiniteProvenance) (NullProvenance, Set(Error(expr, CannotUseDistributionWithoutSampling)), Set()) else if (left.provenance.isParametric || right.provenance.isParametric) { val provenance = DerivedIntersectProvenance(left.provenance, right.provenance) val sameCard = SameCard(left.provenance, right.provenance, IntersectProvenanceDifferentLength) val commonality = Commonality(left.provenance, right.provenance, IntersectWithNoCommonalities) (provenance, Set(), Set(sameCard, commonality)) } else if (!(leftCard == rightCard)) (NullProvenance, Set(Error(expr, IntersectProvenanceDifferentLength)), Set()) else if (isCommon) { val unified = unifyProvenance(relations)(left.provenance, right.provenance) val prov = unified getOrElse CoproductProvenance(left.provenance, right.provenance) (prov, Set(), Set()) } else if (isDynamic) (CoproductProvenance(left.provenance, right.provenance), Set(), Set()) // Can prove that result set is empty. Operation disallowed. else (NullProvenance, Set(Error(expr, IntersectWithNoCommonalities)), Set()) } val finalErrors = leftErrors ++ rightErrors ++ errors val finalConstr = leftConstr ++ rightConstr ++ constr (prov, (finalErrors, finalConstr)) } def handleDifference( expr: Expr, left: Expr, right: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Provenance, (Set[Error], Set[ProvConstraint])) = { val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) lazy val isCommon = hasCommonality(left.provenance, right.provenance) lazy val isDynamic = hasDynamic(left.provenance, right.provenance) lazy val leftCard = left.provenance.cardinality lazy val rightCard = right.provenance.cardinality val (prov, errors, constr) = { if (left.provenance == right.provenance) (left.provenance, Set(), Set()) else if (left.provenance == NullProvenance || right.provenance == NullProvenance) (NullProvenance, Set(), Set()) else if (left.provenance == UndefinedProvenance && right.provenance == UndefinedProvenance) (UndefinedProvenance, Set(), Set()) else if (left.provenance == UndefinedProvenance || right.provenance == UndefinedProvenance) (NullProvenance, Set(Error(expr, DifferenceWithNoCommonalities)), Set()) else if (left.provenance == InfiniteProvenance || right.provenance == InfiniteProvenance) (NullProvenance, Set(Error(expr, CannotUseDistributionWithoutSampling)), Set()) else if (left.provenance.isParametric || right.provenance.isParametric) { val provenance = DerivedDifferenceProvenance(left.provenance, right.provenance) val sameCard = SameCard(left.provenance, right.provenance, DifferenceProvenanceDifferentLength) val commonality = Commonality(left.provenance, right.provenance, DifferenceWithNoCommonalities) (provenance, Set(), Set(sameCard, commonality)) } else if (!(leftCard == rightCard)) (NullProvenance, Set(Error(expr, DifferenceProvenanceDifferentLength)), Set()) // (foo|bar difference foo) provenance may have foo|bar provenance else if (isCommon || isDynamic) (left.provenance, Set(), Set()) // Can prove that result set is the entire LHS. Operation disallowed. else (NullProvenance, Set(Error(expr, DifferenceWithNoCommonalities)), Set()) } val finalErrors = leftErrors ++ rightErrors ++ errors val finalConstr = leftConstr ++ rightConstr ++ constr (prov, (finalErrors, finalConstr)) } def loop(expr: Expr, relations: Map[Provenance, Set[Provenance]], constraints: Map[Provenance, Expr]): (Set[Error], Set[ProvConstraint]) = { val back: (Set[Error], Set[ProvConstraint]) = expr match { case expr @ Let(_, _, _, left, right) => { val (leftErrors, leftConst) = loop(left, relations, constraints) expr.constraints = leftConst expr.resultProvenance = left.provenance val (rightErrors, rightConst) = loop(right, relations, constraints) expr.provenance = right.provenance (leftErrors ++ rightErrors, rightConst) } case Solve(_, solveConstr, child) => { val (errorsVec, constrVec) = solveConstr map { loop(_, relations, constraints) } unzip val constrErrors = errorsVec reduce { _ ++ _ } val constrConstr = constrVec reduce { _ ++ _ } val (errors, constr) = loop(child, relations, constraints) val errorSet = constrErrors ++ errors if (errorSet.nonEmpty) expr.provenance = NullProvenance else expr.provenance = DynamicProvenance(currentId.getAndIncrement()) (errorSet, constrConstr ++ constr) } case Assert(_, pred, child) => { val (predErrors, predConst) = loop(pred, relations, constraints) val (childErrors, childConst) = loop(child, relations, constraints) val assertErrors = { if (pred.provenance == InfiniteProvenance) Set(Error(expr, CannotUseDistributionWithoutSampling)) else Set() } if (pred.provenance != NullProvenance && pred.provenance != InfiniteProvenance) expr.provenance = child.provenance else expr.provenance = NullProvenance (predErrors ++ childErrors ++ assertErrors, predConst ++ childConst) } case Observe(_, data, samples) => { val (dataErrors, dataConst) = loop(data, relations, constraints) val (samplesErrors, samplesConst) = loop(samples, relations, constraints) val observeDataErrors = if (data.provenance == InfiniteProvenance) { Set(Error(expr, CannotUseDistributionWithoutSampling)) } else { Set() } val observeSamplesErrors = if (samples.provenance != InfiniteProvenance) { Set(Error(expr, CannotUseDistributionWithoutSampling)) } else { Set() } if (data.provenance != InfiniteProvenance && samples.provenance == InfiniteProvenance) expr.provenance = data.provenance else expr.provenance = NullProvenance (dataErrors ++ samplesErrors ++ observeDataErrors ++ observeSamplesErrors, dataConst ++ samplesConst) } case New(_, child) => { val (errors, constr) = loop(child, relations, constraints) if (errors.nonEmpty) expr.provenance = NullProvenance else if (child.provenance == InfiniteProvenance) expr.provenance = InfiniteProvenance else if (child.provenance.isParametric) // We include an identity in ParametricDynamicProvenance so that we can // distinguish two `New` nodes that have the same `child`, each assigning // different identities. // | f(x) := // | y := new x // | z := new x // | y + z // | f(5) expr.provenance = ParametricDynamicProvenance(child.provenance, currentId.getAndIncrement()) else expr.provenance = DynamicProvenance(currentId.getAndIncrement()) (errors, constr) } case Relate(_, from, to, in) => { val (fromErrors, fromConstr) = loop(from, relations, constraints) val (toErrors, toConstr) = loop(to, relations, constraints) val unified = unifyProvenance(relations)(from.provenance, to.provenance) val (contribErrors, contribConstr) = if (from.provenance == InfiniteProvenance || to.provenance == InfiniteProvenance) { (Set(Error(expr, CannotUseDistributionWithoutSampling)), Set()) } else if (from.provenance.isParametric || to.provenance.isParametric) { (Set(), Set(NotRelated(from.provenance, to.provenance))) } else { if (unified.isDefined && unified != Some(NullProvenance)) (Set(Error(expr, AlreadyRelatedSets)), Set()) else (Set(), Set()) } val relations2 = relations + (from.provenance -> (relations.getOrElse(from.provenance, Set()) + to.provenance)) val relations3 = relations2 + (to.provenance -> (relations.getOrElse(to.provenance, Set()) + from.provenance)) val constraints2 = constraints + (from.provenance -> from) + (to.provenance -> to) val (inErrors, inConstr) = loop(in, relations3, constraints2) if (from.provenance == NullProvenance || to.provenance == NullProvenance || from.provenance == InfiniteProvenance || to.provenance == InfiniteProvenance) { expr.provenance = NullProvenance } else if (unified.isDefined || unified == Some(NullProvenance)) { expr.provenance = NullProvenance } else if (in.provenance == InfiniteProvenance) { expr.provenance = InfiniteProvenance } else { expr.provenance = in.provenance } val finalErrors = fromErrors ++ toErrors ++ inErrors ++ contribErrors val finalConstrs = fromConstr ++ toConstr ++ inConstr ++ contribConstr (finalErrors, finalConstrs) } case UndefinedLit(_) => { expr.provenance = UndefinedProvenance (Set(), Set()) } case TicVar(_, _) | Literal(_) => { expr.provenance = ValueProvenance (Set(), Set()) } case expr @ Dispatch(_, name, actuals) => { expr.binding match { case LetBinding(let) => { val (errorsVec, constrVec) = actuals map { loop(_, relations, constraints) } unzip val actualErrors = errorsVec.fold(Set[Error]()) { _ ++ _ } val actualConstr = constrVec.fold(Set[ProvConstraint]()) { _ ++ _ } val ids = let.params map { Identifier(Vector(), _) } val zipped = ids zip (actuals map { _.provenance }) def sub(target: Provenance): Provenance = { zipped.foldLeft(target) { case (target, (id, sub)) => substituteParam(id, let, target, sub) } } val constraints2 = let.constraints map { case Related(left, right) => { val left2 = resolveUnifications(relations)(sub(left)) val right2 = resolveUnifications(relations)(sub(right)) Related(left2, right2) } case NotRelated(left, right) => { val left2 = resolveUnifications(relations)(sub(left)) val right2 = resolveUnifications(relations)(sub(right)) NotRelated(left2, right2) } case SameCard(left, right, tpe) => { val left2 = resolveUnifications(relations)(sub(left)) val right2 = resolveUnifications(relations)(sub(right)) SameCard(left2, right2, tpe) } case Commonality(left, right, tpe) => { val left2 = resolveUnifications(relations)(sub(left)) val right2 = resolveUnifications(relations)(sub(right)) Commonality(left2, right2, tpe) } } val mapped = constraints2 flatMap { case Related(left, right) if !left.isParametric && !right.isParametric => { if (!unifyProvenance(relations)(left, right).isDefined) Some(Left(Error(expr, OperationOnUnrelatedSets))) else None } case NotRelated(left, right) if !left.isParametric && !right.isParametric => { if (unifyProvenance(relations)(left, right).isDefined) Some(Left(Error(expr, AlreadyRelatedSets))) else None } case SameCard(left, right, tpe) if !left.isParametric && !right.isParametric => { if (left.cardinality != right.cardinality) Some(Left(Error(expr, tpe))) else None } case Commonality(left, right, tpe) if !left.isParametric && !right.isParametric => { if (!hasCommonality(left, right)) Some(Left(Error(expr, tpe))) else None } case constr => Some(Right(constr)) } val constrErrors = mapped collect { case Left(error) => error } val constraints3 = mapped collect { case Right(constr) => constr } expr.provenance = resolveUnifications(relations)(sub(let.resultProvenance)) val finalErrors = actualErrors ++ constrErrors if (!finalErrors.isEmpty) { expr.provenance = NullProvenance } (finalErrors, actualConstr ++ constraints3) } case FormalBinding(let) => { expr.provenance = ParamProvenance(name, let) (Set(), Set()) } case ReductionBinding(_) => { val (errors, constr) = loop(actuals.head, relations, constraints) val reductionErrors = if (actuals.head.provenance == InfiniteProvenance) { Set(Error(expr, CannotUseDistributionWithoutSampling)) } else { Set() } if (actuals.head.provenance == InfiniteProvenance) { expr.provenance = NullProvenance } else { expr.provenance = ValueProvenance } (errors ++ reductionErrors, constr) } case DistinctBinding => { val (errors, constr) = loop(actuals.head, relations, constraints) val distinctErrors = if (actuals.head.provenance == InfiniteProvenance) { Set(Error(expr, CannotUseDistributionWithoutSampling)) } else { Set() } if (actuals.head.provenance == InfiniteProvenance) { expr.provenance = NullProvenance } else { expr.provenance = DynamicProvenance(currentId.getAndIncrement()) } (errors ++ distinctErrors, constr) } case LoadBinding | RelLoadBinding => { // FIXME not the same as StaticProvenance! val (errors, constr) = loop(actuals.head, relations, constraints) expr.provenance = actuals.head match { case StrLit(_, path) => StaticProvenance(path) case d @ Dispatch(_, _, Vector(StrLit(_, path))) if d.binding == ExpandGlobBinding => StaticProvenance(path) case param if param.provenance != NullProvenance => DynamicProvenance(currentId.getAndIncrement()) case _ => NullProvenance } (errors, constr) } case ExpandGlobBinding => { val (errors, constr) = loop(actuals.head, relations, constraints) expr.provenance = actuals.head.provenance (errors, constr) } /* There are some subtle issues here regarding consistency between the compiler's * notion of `cardinality` and the evaluators's notion of `identities`. If a morphism * (of 1 or 2 parameters) has IdentityPolicy.Product(_, _), then we correctly unify * the provenances of the LHS and RHS, and the notions of identities will be equivalent. * But if a morphism has IdentityPolicy.Cross, were the LHS and RHS share some provenances, * then we have no notion of provenance that will capture this information. Just for the * sake of understanding the problem, we *could* have `CrossProvenance(_, _)`, but this * type would only serve to alert us to the fact that there are definitely identities * coming from both sides. And this is not the correct thing to do. Once we have record- * based identities, we will no longer need to do cardinality checking in the compiler, * and this problem will go away. */ case Morphism1Binding(morph1) => { val (errors, constr) = loop(actuals.head, relations, constraints) expr.provenance = { if (morph1.isInfinite) { InfiniteProvenance } else { def rec(policy: IdentityPolicy): Provenance = policy match { case IdentityPolicy.Product(left, right) => { val recLeft = rec(left) val recRight = rec(right) unifyProvenance(relations)(recLeft, recRight) getOrElse ProductProvenance(recLeft, recRight) } case (_: IdentityPolicy.Retain) => actuals.head.provenance case IdentityPolicy.Synthesize => { if (actuals.head.provenance.isParametric) ParametricDynamicProvenance(actuals.head.provenance, currentId.getAndIncrement()) else DynamicProvenance(currentId.getAndIncrement()) } case IdentityPolicy.Strip => ValueProvenance } rec(morph1.idPolicy) } } (errors, constr) } case Morphism2Binding(morph2) => { // oddly, handleBinary doesn't seem to work here (premature fixation of expr.provenance) val left = actuals(0) val right = actuals(1) val (leftErrors, leftConstr) = loop(left, relations, constraints) val (rightErrors, rightConstr) = loop(right, relations, constraints) val unified = unifyProvenance(relations)(left.provenance, right.provenance) def compute(paramProv: Provenance, prov: Provenance): (Set[Error], Set[ProvConstraint], Provenance) = { if (left.provenance.isParametric || right.provenance.isParametric) { if (unified.isDefined) (Set(), Set(), paramProv) else (Set(), Set(Related(left.provenance, right.provenance)), paramProv) } else { if (unified.isDefined) (Set(), Set(), prov) else (Set(Error(expr, OperationOnUnrelatedSets)), Set(), NullProvenance) } } def rec(policy: IdentityPolicy): (Set[Error], Set[ProvConstraint], Provenance) = policy match { case IdentityPolicy.Product(left0, right0) => val (leftErrors, leftConst, leftProv) = rec(left0) val (rightErrors, rightConst, rightProv) = rec(right0) val prov = unifyProvenance(relations)(leftProv, rightProv) getOrElse ProductProvenance(leftProv, rightProv) val (err, const, finalProv) = compute(prov, prov) val errors = leftErrors ++ rightErrors ++ err val consts = leftConst ++ rightConst ++ const (errors, consts, finalProv) /* TODO The `Cross` case is not currently correct! * When we call `cardinality` on a morphism with this IdentityPolicy * if left.provenance and right.provenance contain equivalent provenances, * incorrect cardinality will be returned. For example, if we have Cross * where LHS=//foo and RHS=//foo, the `cardinality` will be size 1, * when it should be size 2. (See above comment. This bug will be able to be * smoothly resolved with the addition of record-based ids.) */ case IdentityPolicy.Retain.Cross => { val product = ProductProvenance(left.provenance, right.provenance) val prov = unifyProvenance(relations)(left.provenance, right.provenance) getOrElse product compute(prov, prov) } case IdentityPolicy.Retain.Left => compute(left.provenance, left.provenance) case IdentityPolicy.Retain.Right => compute(right.provenance, right.provenance) case IdentityPolicy.Retain.Merge => { val paramProv = UnifiedProvenance(left.provenance, right.provenance) val prov = unified getOrElse NullProvenance compute(paramProv, prov) } case IdentityPolicy.Synthesize => { val paramProv = ParametricDynamicProvenance(UnifiedProvenance(left.provenance, right.provenance), currentId.getAndIncrement()) val prov = DynamicProvenance(currentId.getAndIncrement()) compute(paramProv, prov) } case IdentityPolicy.Strip => compute(ValueProvenance, ValueProvenance) } val (errors, constr, prov) = rec(morph2.idPolicy) expr.provenance = prov (leftErrors ++ rightErrors ++ errors, leftConstr ++ rightConstr ++ constr) } case Op1Binding(_) => { val (errors, constr) = loop(actuals.head, relations, constraints) expr.provenance = actuals.head.provenance (errors, constr) } case Op2Binding(_) => val (provenance, result) = handleBinary(expr, actuals(0), actuals(1), relations, constraints) expr.provenance = provenance result case NullBinding => { val (errorsVec, constrVec) = actuals map { loop(_, relations, constraints) } unzip val errors = errorsVec reduceOption { _ ++ _ } getOrElse Set() val constr = constrVec reduceOption { _ ++ _ } getOrElse Set() expr.provenance = NullProvenance (errors, constr) } } } case Cond(_, pred, left, right) => { val (provenance, result) = handleCond(expr, pred, left, right, relations, constraints) expr.provenance = provenance result } case Union(_, left, right) => { val (provenance, result) = handleUnion(expr, left, right, relations, constraints) expr.provenance = provenance result } case Intersect(_, left, right) => { val (provenance, result) = handleIntersect(expr, left, right, relations, constraints) expr.provenance = provenance result } case Difference(_, left, right) => { val (provenance, result) = handleDifference(expr, left, right, relations, constraints) expr.provenance = provenance result } case UnaryOp(_, child) => { val (errors, constr) = loop(child, relations, constraints) expr.provenance = child.provenance (errors, constr) } case BinaryOp(_, left, right) => { val (provenance, result) = handleBinary(expr, left, right, relations, constraints) expr.provenance = provenance result } // TODO change to NaryOp(_, values) once scalac bugs are resolved case expr: NaryOp => { val (provenance, result) = handleNary(expr, expr.values, relations, constraints) expr.provenance = provenance result } } expr.constrainingExpr = constraints get expr.provenance expr.relations = relations back } val (errors, constraints) = loop(expr, Map(), Map()) val lastErrors = { if (expr.provenance == InfiniteProvenance) Set(Error(expr, CannotUseDistributionWithoutSampling)) else Set() } errors ++ lastErrors } def unifyProvenance(relations: Map[Provenance, Set[Provenance]])(p1: Provenance, p2: Provenance): Option[Provenance] = (p1, p2) match { case (p1, p2) if p1 == p2 => Some(p1) case (p1, p2) if pathExists(relations, p1, p2) || pathExists(relations, p2, p1) => Some(p1 & p2) case (NullProvenance, p) => Some(NullProvenance) case (p, NullProvenance) => Some(NullProvenance) case (UndefinedProvenance, _) => Some(UndefinedProvenance) case (_, UndefinedProvenance) => Some(UndefinedProvenance) case (ValueProvenance, p) => Some(p) case (p, ValueProvenance) => Some(p) case (ProductProvenance(left, right), p2) => { val leftP = unifyProvenance(relations)(left, p2) val rightP = unifyProvenance(relations)(right, p2) val unionP = (leftP |@| rightP) { case (p1, p2) => p1 & p2 } lazy val unionLeft = leftP map { ProductProvenance(_, right) } lazy val unionRight = rightP map { ProductProvenance(left, _) } unionP orElse unionLeft orElse unionRight } case (p1, ProductProvenance(left, right)) => { val leftP = unifyProvenance(relations)(p1, left) val rightP = unifyProvenance(relations)(p1, right) val unionP = (leftP |@| rightP) { case (p1, p2) => p1 & p2 } lazy val unionLeft = leftP map { ProductProvenance(_, right) } lazy val unionRight = rightP map { ProductProvenance(left, _) } unionP orElse unionLeft orElse unionRight } case (CoproductProvenance(left, right), p2) => { val leftP = unifyProvenance(relations)(left, p2) val rightP = unifyProvenance(relations)(right, p2) val unionP = (leftP |@| rightP) { case (p1, p2) => p1 | p2 } unionP orElse leftP orElse rightP } case (p1, CoproductProvenance(left, right)) => { val leftP = unifyProvenance(relations)(p1, left) val rightP = unifyProvenance(relations)(p1, right) val unionP = (leftP |@| rightP) { case (p1, p2) => p1 | p2 } unionP orElse leftP orElse rightP } case _ => None } private def pathExists(graph: Map[Provenance, Set[Provenance]], from: Provenance, to: Provenance): Boolean = { // not actually DFS, but that's alright since we can't have cycles def dfs(seen: Set[Provenance])(from: Provenance): Boolean = { if (seen contains from) { false } else if (from == to) { true } else { val next = graph.getOrElse(from, Set()) val seen2 = seen + from next exists dfs(seen2) } } dfs(Set())(from) } def components(prov: Provenance, target: Provenance): Boolean = { def recursePair(left: Provenance, right: Provenance) = components(left, target) || components(right, target) prov match { case DerivedUnionProvenance(left, right) => recursePair(left, right) case DerivedIntersectProvenance(left, right) => recursePair(left, right) case DerivedDifferenceProvenance(left, right) => recursePair(left, right) case UnifiedProvenance(left, right) => recursePair(left, right) case ProductProvenance(left, right) => recursePair(left, right) case CoproductProvenance(left, right) => recursePair(left, right) case ParametricDynamicProvenance(p, _) => components(p, target) case _ => prov == target } } // errors are propagated through provenance constraints // hence are not needed here def substituteParam(id: Identifier, let: ast.Let, target: Provenance, sub: Provenance): Provenance = target match { case ParamProvenance(`id`, `let`) => sub case ParametricDynamicProvenance(prov, _) if components(prov, ParamProvenance(`id`, `let`)) => DynamicProvenance(currentId.getAndIncrement()) case UnifiedProvenance(left, right) => UnifiedProvenance(substituteParam(id, let, left, sub), substituteParam(id, let, right, sub)) case ProductProvenance(left, right) => ProductProvenance(substituteParam(id, let, left, sub), substituteParam(id, let, right, sub)) case CoproductProvenance(left, right) => CoproductProvenance(substituteParam(id, let, left, sub), substituteParam(id, let, right, sub)) case DerivedUnionProvenance(left, right) => { val left2 = substituteParam(id, let, left, sub) val right2 = substituteParam(id, let, right, sub) if (left2 == right2) left2 else if (!(left2.isParametric && right2.isParametric)) CoproductProvenance(left2, right2) else DerivedUnionProvenance(left2, right2) } case DerivedIntersectProvenance(left, right) => { val left2 = substituteParam(id, let, left, sub) val right2 = substituteParam(id, let, right, sub) if (left2 == right2) { left2 } else if (!(left2.isParametric && right2.isParametric)) { val unified = unifyProvenance(Map())(left2, right2) unified getOrElse CoproductProvenance(left2, right2) } else { DerivedIntersectProvenance(left2, right2) } } case DerivedDifferenceProvenance(left, right) => { val left2 = substituteParam(id, let, left, sub) val right2 = substituteParam(id, let, right, sub) if (left2 == right2 || (!(left2.isParametric && right2.isParametric))) left2 else DerivedDifferenceProvenance(left2, right2) } case _ => target } def resolveUnifications(relations: Map[Provenance, Set[Provenance]])(prov: Provenance): Provenance = prov match { case UnifiedProvenance(left, right) if !left.isParametric && !right.isParametric => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) val optResult = unifyProvenance(relations)(left2, right2) optResult getOrElse (left2 & right2) } case UnifiedProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) UnifiedProvenance(left2, right2) } case ProductProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) left2 & right2 } case CoproductProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) left2 | right2 } case DerivedUnionProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) DerivedUnionProvenance(left2, right2) } case DerivedIntersectProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) DerivedIntersectProvenance(left2, right2) } case DerivedDifferenceProvenance(left, right) => { val left2 = resolveUnifications(relations)(left) val right2 = resolveUnifications(relations)(right) DerivedDifferenceProvenance(left2, right2) } case ParamProvenance(_, _) | ParametricDynamicProvenance(_, _) | StaticProvenance(_) | DynamicProvenance(_) | ValueProvenance | UndefinedProvenance | NullProvenance | InfiniteProvenance => prov } sealed trait Provenance { def &(that: Provenance) = (this, that) match { case (`that`, `that`) => that case (NullProvenance, _) => that case (_, NullProvenance) => this case _ => ProductProvenance(this, that) } def |(that: Provenance) = (this, that) match { case (`that`, `that`) => that case (NullProvenance, _) => NullProvenance case (_, NullProvenance) => NullProvenance case _ => CoproductProvenance(this, that) } def isParametric: Boolean def possibilities = Set(this) def cardinality: Option[Int] private def associateLeft: Provenance = this match { case UnifiedProvenance(_, _) => findChildren(this, true).toList sorted Provenance.order.toScalaOrdering reduceLeft UnifiedProvenance case ProductProvenance(_, _) => findChildren(this, false).toList sorted Provenance.order.toScalaOrdering reduceLeft ProductProvenance case CoproductProvenance(_, _) => findChildren(this, false).toList sorted Provenance.order.toScalaOrdering reduceLeft CoproductProvenance case DerivedUnionProvenance(_, _) => findChildren(this, false).toList sorted Provenance.order.toScalaOrdering reduceLeft DerivedUnionProvenance case DerivedIntersectProvenance(_, _) => findChildren(this, false).toList sorted Provenance.order.toScalaOrdering reduceLeft DerivedIntersectProvenance case DerivedDifferenceProvenance(_, _) => findChildren(this, false).toList sorted Provenance.order.toScalaOrdering reduceLeft DerivedDifferenceProvenance case prov => prov } // TODO is this too slow? private def findChildren(prov: Provenance, unified: Boolean): Set[Provenance] = prov match { case UnifiedProvenance(left, right) if unified => findChildren(left, unified) ++ findChildren(right, unified) case ProductProvenance(left, right) if !unified => findChildren(left, unified) ++ findChildren(right, unified) case CoproductProvenance(left, right) if !unified => findChildren(left, unified) ++ findChildren(right, unified) case DerivedUnionProvenance(left, right) if !unified => findChildren(left, unified) ++ findChildren(right, unified) case DerivedIntersectProvenance(left, right) if !unified => findChildren(left, unified) ++ findChildren(right, unified) case DerivedDifferenceProvenance(left, right) if !unified => findChildren(left, unified) ++ findChildren(right, unified) case _ => Set(prov) } def makeCanonical: Provenance = { this match { case UnifiedProvenance(left, right) => UnifiedProvenance(left.makeCanonical, right.makeCanonical).associateLeft case ProductProvenance(left, right) => ProductProvenance(left.makeCanonical, right.makeCanonical).associateLeft case CoproductProvenance(left, right) => CoproductProvenance(left.makeCanonical, right.makeCanonical).associateLeft case DerivedUnionProvenance(left, right) => DerivedUnionProvenance(left.makeCanonical, right.makeCanonical) case DerivedIntersectProvenance(left, right) => DerivedIntersectProvenance(left.makeCanonical, right.makeCanonical) case DerivedDifferenceProvenance(left, right) => DerivedDifferenceProvenance(left.makeCanonical, right.makeCanonical) case prov => prov } } } object Provenance { implicit def order: Order[Provenance] = new Order[Provenance] { def order(p1: Provenance, p2: Provenance): Ordering = (p1, p2) match { case (ParamProvenance(id1, let1), ParamProvenance(id2, let2)) => { if (id1.id == id2.id) { if (let1 == let2) EQ else if (let1.loc.lineNum == let2.loc.lineNum) { if (let1.loc.colNum == let2.loc.colNum) EQ // wtf?? else if (let1.loc.colNum < let2.loc.colNum) LT else GT } else if (let1.loc.lineNum < let2.loc.lineNum) LT else GT } else if (id1.id < id2.id) LT else GT } case (ParamProvenance(_, _), _) => GT case (_, ParamProvenance(_, _)) => LT case (ParametricDynamicProvenance(prov1, id1), ParametricDynamicProvenance(prov2, id2)) => { if (prov1 == prov2) { if (id1 == id2) EQ else if (id1 < id2) LT else GT } else { prov1 ?|? prov2 } } case (ParametricDynamicProvenance(_, _), _) => GT case (_, ParametricDynamicProvenance(_, _)) => LT case (DerivedUnionProvenance(left1, right1), DerivedUnionProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (DerivedUnionProvenance(_, _), _) => GT case (_, DerivedUnionProvenance(_, _)) => LT case (DerivedIntersectProvenance(left1, right1), DerivedIntersectProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (DerivedIntersectProvenance(_, _), _) => GT case (_, DerivedIntersectProvenance(_, _)) => LT case (DerivedDifferenceProvenance(left1, right1), DerivedDifferenceProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (DerivedDifferenceProvenance(_, _), _) => GT case (_, DerivedDifferenceProvenance(_, _)) => LT case (UnifiedProvenance(left1, right1), UnifiedProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (UnifiedProvenance(_, _), _) => GT case (_, UnifiedProvenance(_, _)) => LT case (ProductProvenance(left1, right1), ProductProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (ProductProvenance(_, _), _) => GT case (_, ProductProvenance(_, _)) => LT case (CoproductProvenance(left1, right1), CoproductProvenance(left2, right2)) => (left1 ?|? left2) |+| (right1 ?|? right2) case (CoproductProvenance(_, _), _) => GT case (_, CoproductProvenance(_, _)) => LT case (StaticProvenance(v1), StaticProvenance(v2)) => { if (v1 == v2) EQ else if (v1 < v2) LT else GT } case (StaticProvenance(_), _) => GT case (_, StaticProvenance(_)) => LT case (DynamicProvenance(v1), DynamicProvenance(v2)) => { if (v1 == v2) EQ else if (v1 < v2) LT else GT } case (DynamicProvenance(_), _) => GT case (_, DynamicProvenance(_)) => LT case (ValueProvenance, _) => GT case (_, ValueProvenance) => LT case (UndefinedProvenance, UndefinedProvenance) => EQ case (UndefinedProvenance, _) => GT case (_, UndefinedProvenance) => LT case (InfiniteProvenance, InfiniteProvenance) => EQ case (InfiniteProvenance, _) => GT case (_, InfiniteProvenance) => LT case (NullProvenance, NullProvenance) => EQ } } } case class ParamProvenance(id: Identifier, let: ast.Let) extends Provenance { override val toString = "$" + id.id val isParametric = true def cardinality: Option[Int] = None } case class DerivedUnionProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "@@U<" + left.toString + "|" + right.toString + ">" val isParametric = left.isParametric || right.isParametric override def possibilities = left.possibilities ++ right.possibilities + this def cardinality: Option[Int] = None } case class DerivedIntersectProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "@@I<" + left.toString + "|" + right.toString + ">" val isParametric = left.isParametric || right.isParametric override def possibilities = left.possibilities ++ right.possibilities + this def cardinality: Option[Int] = None } case class DerivedDifferenceProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "@@D<" + left.toString + "|" + right.toString + ">" val isParametric = left.isParametric || right.isParametric override def possibilities = left.possibilities ++ right.possibilities + this def cardinality: Option[Int] = None } case class UnifiedProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "(%s >< %s)".format(left, right) val isParametric = left.isParametric || right.isParametric def cardinality: Option[Int] = left.cardinality |+| right.cardinality } case class ProductProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "(%s & %s)".format(left, right) val isParametric = left.isParametric || right.isParametric override def possibilities = left.possibilities ++ right.possibilities + this def cardinality = left.cardinality |+| right.cardinality } case class CoproductProvenance(left: Provenance, right: Provenance) extends Provenance { override val toString = "(%s | %s)".format(left, right) val isParametric = left.isParametric || right.isParametric override def possibilities = left.possibilities ++ right.possibilities + this def cardinality: Option[Int] = if (left.cardinality == right.cardinality) { left.cardinality } else { sys.error("cardinality invariant not upheld") } } case class StaticProvenance(path: String) extends Provenance { override val toString = path val isParametric = false def cardinality: Option[Int] = Some(1) } case class DynamicProvenance(id: Int) extends Provenance { override val toString = "@" + id val isParametric = false def cardinality: Option[Int] = Some(1) } case class ParametricDynamicProvenance(prov: Provenance, id: Int) extends Provenance { override val toString = "@@" + prov.toString val isParametric = true def cardinality: Option[Int] = Some(1) } case object ValueProvenance extends Provenance { override val toString = "<value>" val isParametric = false def cardinality: Option[Int] = Some(0) } case object InfiniteProvenance extends Provenance { override val toString = "<infinite>" val isParametric = false def cardinality: Option[Int] = None //todo remove me ahhhhhh } case object UndefinedProvenance extends Provenance { override val toString = "<undefined>" val isParametric = false def cardinality: Option[Int] = None } case object NullProvenance extends Provenance { override val toString = "<null>" val isParametric = false def cardinality: Option[Int] = None } sealed trait ProvConstraint case class Related(left: Provenance, right: Provenance) extends ProvConstraint case class NotRelated(left: Provenance, right: Provenance) extends ProvConstraint case class SameCard(left: Provenance, right: Provenance, tpe: ErrorType) extends ProvConstraint case class Commonality(left: Provenance, right: Provenance, tpe: ErrorType) extends ProvConstraint }
agpl-3.0
goruha/phd_code
src/test/IntervalAnalysis/Buildings/testBuildingCounter.java
2767
package test.IntervalAnalysis.Buildings; import junit.framework.TestCase; import libiada.IntervalAnalysis.Buildings.BuildingCounter; import org.junit.Test; /** * Created by IntelliJ IDEA. * User: Alex * Date: 20.03.11 * Time: 22:30 */ public class testBuildingCounter extends TestCase { @Test public void testCounterWithL1M1() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(1, 1); assertEquals(count, 1); } @Test public void testCounterWithL2M2() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(2, 2); assertEquals(count, 2); } @Test public void testCounterWithL3M3() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(3, 3); assertEquals(count, 5); } @Test public void testCounterWithL4M4() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(4, 4); assertEquals(count, 15); } @Test public void testCounterWithL5M5() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(5, 5); assertEquals(count, 52); } @Test public void testCounterWithL4M2() throws Exception { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(4, 2); assertEquals(count, 8); } @Test public void testCounterWithZeroLength() { try { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(0, 1); } catch (Exception e) { return; } fail(); } @Test public void testCounterWithZeroAlphabetPower() { try { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(2, 0); } catch (Exception e) { return; } fail(); } @Test public void testCounterWithAboveZeroLength() { try { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(-3, 1); } catch (Exception e) { return; } fail(); } @Test public void testCounterWithAboveZeroAlphabetPower() { try { BuildingCounter counter = new BuildingCounter(); int count = counter.calculate(2, -51); } catch (Exception e) { return; } fail(); } }
agpl-3.0
cyberitsolutions/alloc
person/person.php
10877
<?php /* * Copyright (C) 2006-2020 Alex Lance, Clancy Malcolm, Cyber IT Solutions * Pty. Ltd. * * This file is part of the allocPSA application <info@cyber.com.au>. * * allocPSA is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * allocPSA is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with allocPSA. If not, see <http://www.gnu.org/licenses/>. */ require_once("../alloc.php"); function show_perm_select() { global $person; if ($person->have_perm(PERM_PERSON_WRITE_ROLES)) { $selected = explode(",", $person->get_value("perms")); $ops = role::get_roles_array("person"); foreach ($ops as $p => $l) { unset($sel); in_array($p, $selected) and $sel = " checked"; echo $br."<input type=\"checkbox\" name=\"perm_select[]\" value=\"".$p."\"".$sel."> ".$l; $br = "<br>"; } } else { $selected = explode(",", $person->get_value("perms")); $ops = role::get_roles_array("person"); foreach ($selected as $sel) { echo $br.$ops[$sel]; $br = "<br>"; } } } function show_absence_forms($template) { global $personID; $db = new db_alloc(); $query = prepare("SELECT * FROM absence WHERE personID=%d", $personID); $db->query($query); $absence = new absence(); while ($db->next_record()) { $absence->read_db_record($db); $absence->set_values("absence_"); include_template($template); } } function show_action_buttons() { global $person; global $TPL; if ($person->have_perm(PERM_DELETE)) { echo '<button type="submit" name="delete" value="1" class="delete_button">Delete<i class="icon-trash"></i></button> '; } echo '<button type="submit" name="save" value="1" class="save_button default">Save<i class="icon-ok-sign"></i></button> '; } function include_employee_fields() { global $person; show_skills_list(); include_template("templates/personEmployeeFieldsS.tpl"); } function include_employee_skill_fields() { global $person; include_template("templates/personEmployeeSkillFieldsS.tpl"); } function show_person_areasOfExpertise($template) { global $TPL; global $personID; global $skill_header; global $skill_prof; global $skills_got; $TPL["personExpertiseItem_buttons"] = ' <button type="submit" name="personExpertiseItem_delete" value="1" class="delete_button">Delete<i class="icon-trash"></i></button> <button type="submit" name="personExpertiseItem_save" value="1" class="save_button">Save<i class="icon-ok-sign"></i></button> '; $proficiencys = array("Novice"=>"Novice", "Junior"=>"Junior", "Intermediate"=>"Intermediate", "Advanced"=>"Advanced", "Senior"=>"Senior"); # step through the list of skills ordered by skillclass $db = new db_alloc(); // $query = "SELECT * FROM skill ORDER BY skillClass,skillName"; $query = "SELECT * FROM skill LEFT JOIN proficiency ON skill.skillID=proficiency.skillID"; $query.= prepare(" WHERE proficiency.personID=%d", $personID); $query.= " ORDER BY skillClass,skillName"; $db->query($query); $currSkillClass = null; while ($db->next_record()) { $skill = new skill(); $skill->read_db_record($db); $skill->set_tpl_values(); $skillProficiencys = new proficiency(); $skillProficiencys->read_db_record($db); $skillProficiencys->set_values(); # if they do and there is no heading for this segment put a heading $thisSkillClass = $skill->get_value('skillClass'); if ($currSkillClass != $thisSkillClass) { $currSkillClass = $thisSkillClass; $skill_header = true; } else { $skill_header = false; } $skill_prof = $skillProficiencys->get_value('skillProficiency'); $TPL["skill_proficiencys"] = page::select_options($proficiencys, $skill_prof); # display rating if there is one include_template($template); } } function show_skills_list() { global $TPL; global $personID; global $skills; $db = new db_alloc(); $query = prepare("SELECT * FROM proficiency WHERE personID=%d", $personID); $db->query($query); $skills_got = array(); while ($db->next_record()) { $skill = new skill(); $skill->read_db_record($db); array_push($skills_got, $skill->get_id()); } $query = "SELECT * FROM skill ORDER BY skillClass"; $db->query($query); while ($db->next_record()) { $skill = new skill(); $skill->read_db_record($db); if (in_array($skill->get_id(), $skills_got)) { // dont show this item } else { $skills[$skill->get_id()] = sprintf("%s - %s", $skill->get_value('skillClass'), $skill->get_value('skillName')); } } if (count($skills) > 0) { $TPL["skills"] = page::select_options($skills, ""); } } function check_optional_person_skills_header() { global $skill_header; return $skill_header; } function include_management_fields() { global $person; if ($person->have_perm(PERM_PERSON_READ_MANAGEMENT)) { include_template("templates/personManagementFieldsS.tpl"); } } $skill_header = false; $person = new person(); $personID = $_POST["personID"] or $personID = $_GET["personID"]; if ($personID) { $person->set_id($personID); $person->select(); } if ($_POST["personExpertiseItem_add"] || $_POST["personExpertiseItem_save"] || $_POST["personExpertiseItem_delete"]) { $proficiency = new proficiency(); $proficiency->read_globals(); if ($_POST["skillID"] != null) { if ($_POST["personExpertiseItem_delete"]) { $proficiency->delete(); } else if ($_POST["personExpertiseItem_save"]) { $proficiency->save(); } else if ($_POST["personExpertiseItem_add"]) { // skillID is an array if when adding but not when saving or deleting $skillProficiency = $proficiency->get_value('skillProficiency'); for ($i = 0; $i < count($_POST["skillID"]); $i++) { $proficiency = new proficiency(); $proficiency->set_value('skillID', $_POST["skillID"][$i]); $proficiency->set_value('skillProficiency', $_POST["skillProficiency"]); $proficiency->set_value('personID', $personID); $db = new db_alloc(); $query = prepare("SELECT * FROM proficiency WHERE personID = %d", $personID); $query.= prepare(" AND skillID = %d", $_POST["skillID"][$i]); $db->query($query); if (!$db->next_record()) { $proficiency->save(); } } } } } if ($_POST["save"]) { $person->read_globals(); if ($person->can_write_field("perms")) { $_POST["perm_select"] or $_POST["perm_select"] = array(); $person->set_value("perms", implode(",", $_POST["perm_select"])); } if ($_POST["password1"] && $_POST["password1"] == $_POST["password2"]) { $person->set_value('password', password_hash($_POST["password1"], PASSWORD_BCRYPT)); } else if (!$_POST["password1"] && $personID) { // nothing required here, just don't update the password field } else { alloc_error("Please re-type the passwords"); } if ($_POST["username"]) { $q = prepare("SELECT personID FROM person WHERE username = '%s'", $_POST["username"]); $db = new db_alloc(); $db->query($q); $num_rows = $db->num_rows(); $row = $db->row(); if (($num_rows > 0 && !$person->get_id()) || ($num_rows > 0 && $person->get_id() != $row["personID"])) { alloc_error("That username is already taken. Please select another."); } } else { alloc_error("Please enter a username."); } $person->set_value("personActive", $_POST["personActive"] ? 1 : "0"); $max_alloc_users = get_max_alloc_users(); if (!$person->get_id() && $max_alloc_users && get_num_alloc_users() >= $max_alloc_users && $_POST["personActive"]) { alloc_error(get_max_alloc_users_message()); } if (!$TPL["message"]) { $person->set_value("availability", rtrim($person->get_value("availability"))); $person->set_value("areasOfInterest", rtrim($person->get_value("areasOfInterest"))); $person->set_value("comments", rtrim($person->get_value("comments"))); $person->set_value("emergencyContact", rtrim($person->get_value("emergencyContact"))); $person->set_value("managementComments", rtrim($person->get_value("managementComments"))); $person->currency = config::get_config_item('currency'); $person->save(); alloc_redirect($TPL["url_alloc_personList"]); } } else if ($_POST["delete"]) { $person->delete(); alloc_redirect($TPL["url_alloc_personList"]); } #$person = new person(); #$person->set_id($personID); #$person->select(); $person->set_values("person_"); if ($person->get_id()) { $q = prepare( "SELECT tfPerson.tfID AS value, tf.tfName AS label FROM tf, tfPerson WHERE tf.tfID = tfPerson.tfID AND tfPerson.personID = %d AND (tf.tfActive = 1 OR tf.tfID = %d)", $person->get_id(), $person->get_value("preferred_tfID") ); $TPL["preferred_tfID_options"] = page::select_options($q, $person->get_value("preferred_tfID")); $tf = new tf(); $tf->set_id($person->get_value("preferred_tfID")); $tf->select(); } $TPL["absence_url"] = $TPL["url_alloc_absence"]."personID=".$personID; $TPL["personActive"] = (!$person->get_id() || $person->get_value("personActive")) ? " checked" : ""; if (has("time")) { $timeUnit = new timeUnit(); $rate_type_array = $timeUnit->get_assoc_array("timeUnitID", "timeUnitLabelB"); } $TPL["timeSheetRateUnit_select"] = page::select_options($rate_type_array, $person->get_value("defaultTimeSheetRateUnitID")); $TPL["timeSheetRateUnit_label"] = $rate_type_array[$person->get_value("defaultTimeSheetRateUnitID")]; if ($personID) { $TPL["main_alloc_title"] = "Person Details: " . $person->get_value("username")." - ".APPLICATION_NAME; } else { $TPL["main_alloc_title"] = "New Person - ".APPLICATION_NAME; } include_template("templates/personM.tpl");
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/gui/renderer/itemsets/FrequentItemSetsTableRenderer.java
1983
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.renderer.itemsets; import com.rapidminer.gui.renderer.AbstractTableModelTableRenderer; import com.rapidminer.gui.viewer.FrequentItemSetVisualization; import com.rapidminer.gui.viewer.FrequentItemSetsTableModel; import com.rapidminer.operator.IOContainer; import com.rapidminer.operator.learner.associations.FrequentItemSets; import java.awt.Component; import javax.swing.table.TableModel; /** * A renderer for the table view of frequent item sets. * * @author Ingo Mierswa */ public class FrequentItemSetsTableRenderer extends AbstractTableModelTableRenderer { @Override public TableModel getTableModel(Object renderable, IOContainer ioContainer, boolean isReporting) { FrequentItemSets frequentItemSets = (FrequentItemSets) renderable; frequentItemSets.sortSets(); return new FrequentItemSetsTableModel(frequentItemSets); } @Override public Component getVisualizationComponent(Object renderable, IOContainer ioContainer) { FrequentItemSets frequentItemSets = (FrequentItemSets) renderable; return new FrequentItemSetVisualization(frequentItemSets); } }
agpl-3.0
panterch/future_kids
db/migrate/20151113110517_create_substitutions.rb
453
class CreateSubstitutions < ActiveRecord::Migration[4.2] def change create_table :substitutions do |t| t.date :start_at, null: false t.date :end_at, null: false t.boolean :inactive, null: false, default: false t.timestamps null: false t.belongs_to :mentor, index: true # constraint t.belongs_to :secondary_mentor, class_name: 'Mentor', index: true t.belongs_to :kid, index: true end end end
agpl-3.0
Intermesh/groupoffice-webclient
app/modules/groupoffice/files/models/drive.js
1476
'use strict'; angular.module('GO.Modules.GroupOffice.Files') .factory('GO.Modules.GroupOffice.Files.Model.Drive', [ 'GO.Core.Factories.Data.Model', '$http', 'GO.Core.Services.ServerAPI', function (Model, $http, ServerAPI) { //Extend the base model and set default return proeprties var Drive = GO.extend(Model, function () { this.$parent.constructor.call(this, arguments); }); var units = ['B', 'KB', 'MB', 'GB', 'TB']; Drive.prototype.$returnProperties = "*,groups"; Drive.prototype.usage = 0; Drive.prototype.quota = 0; Drive.prototype.save = function() { var multiplier = units.indexOf(this.quotaUnit); this.quota = this.quotaText * Math.pow(1024, multiplier); delete this.quotaText; delete this.quotaUnit; return this.$parent.save.apply(this, arguments); }; Drive.prototype.loadData = function(data, clearModified) { this.$parent.loadData.apply(this, arguments); var multiplier = Math.floor(Math.log(this.quota) / Math.log(1024)); this.quotaText = Math.round(this.quota / Math.pow(1024, Math.floor(multiplier))); this.quotaUnit = units[multiplier]; }; Drive.prototype.getStoreRoute = function() { return 'drives'; }; Drive.prototype.percentage = function() { return Math.round((100/this.quota)*this.usage); }; Drive.prototype.mount = function() { //bool return $http.post(ServerAPI.url('drives/'+this.id+'/mount',{mount:this.isMounted=='0'?false:true})); }; return Drive; }]);
agpl-3.0
dice-group/LIMES
limes-core/src/main/java/org/aksw/limes/core/execution/engine/partialrecallengine/refinement/PartialRecallRefinementOperator.java
7074
/* * LIMES Core Library - LIMES – Link Discovery Framework for Metric Spaces. * Copyright © 2011 Data Science Group (DICE) (ngonga@uni-paderborn.de) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.aksw.limes.core.execution.engine.partialrecallengine.refinement; import org.aksw.limes.core.execution.planning.plan.Plan; import org.aksw.limes.core.execution.planning.planner.LigerPlanner; import org.aksw.limes.core.io.cache.ACache; import org.aksw.limes.core.io.ls.LinkSpecification; import org.apache.log4j.Logger; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; public abstract class PartialRecallRefinementOperator { protected static final Logger logger = Logger.getLogger(PartialRecallRefinementOperator.class.getName()); protected PartialRecallRefinementNode root; protected PartialRecallRefinementNode best; protected double desiredSelectivity = 0.0d; protected ACache source; protected ACache target; protected long timeLimit; protected double k; protected long maxOpt; public double getRecall() { return k; } public long getOptimizationTime() { return maxOpt; } public PartialRecallRefinementNode getBest() { return best; } public double getDesiredSelectivity() { return desiredSelectivity; } protected List<Double> thresholds = Arrays.asList(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0); protected LinkedList<PartialRecallRefinementNode> buffer = new LinkedList<PartialRecallRefinementNode>(); protected HashSet<String> total = new HashSet<String>(); public PartialRecallRefinementOperator(ACache s, ACache t, double recall, long optTime, LinkSpecification spec) { this.source = s; this.target = t; if (optTime < 0) { logger.info("\nOptimization time cannot be negative. Your input value is " + optTime + ".\nSetting it to the default value: 0ms."); this.maxOpt = 0l; } else this.maxOpt = optTime; if (recall < 0.0 || recall > 1.0) { logger.info("\nExpected selectivity must be between 0.0 and 1.0. Your input value is " + k + ".\nSetting it to the default value: 1.0."); this.k = 1.0d; } else this.k = recall; this.init(spec); } public abstract void optimize(); /** * Compares an input selectivity value with the desired selectivity. If the * input selectivity is equal to the desired selectivity, the function * returns 0. If the input selectivity is lower than the desired * selectivity, it returns a value lower than 0. If the input selectivity is * larger than the desired selectivity, it returns a value larger than 0. * * @param selectivity * @return */ protected int checkSelectivity(double selectivity) { // selectivity = desiredSelectivity -> com = 0 - STOP // selectivity < desiredSelectivity -> com < 0 - STOP // selectivity > desiredSelectivity -> com > 0 - continue return Double.compare(selectivity, desiredSelectivity); } /** * Implements the next function. For an input threshold, it returns the * first larger threshold from a set of predefined thresholds. The returned * value can be at most 1.0. If the input threshold is already 1.0, it * returns a negative number that indicates that the link specification, to * which the input threshold belongs to, can not be refined any further. * * @param currentThreshold, * the input threshold * @return a value that is the first larger value than currentThreshold from * a set of predefined values, or a negative number if the * currentThreshold is already 1.0 */ protected double next(double currentThreshold) { if (currentThreshold < 0.0d || currentThreshold > 1.0) return -1.0d; if (Double.compare(currentThreshold, 1.0d) == 0) { return -1.0d; } else { for (double f : this.thresholds) { if (Double.compare(currentThreshold, f) < 0) return f; } } return -1.0d; } /** * Initializes refinement procedure. It computes the canonical plan of the * input LS and based on its estimated selectivity, it computes the minimum * expected selectivity that a rapidly executable link specification * subsumed by L must achieve, based on the minimal expected recall * requirement set by the user. It also adds the input link specification to * the buffer and total structure. The buffer structure serves as a queue * and includes link specifications obtained by refining the initial * specifications, but have not yet been refined. All specifications, that * were generated through the refinement procedure as well as the input * specification, are stored in the total set. By keeping track of these * specifications, LIGER avoids refining a specification more than once and * address the redundancy of the refinement operator. This function also * initializes the best specification with the initial specification. The * best specification is updated via the main LIGER function, optimize(). * The best specification is the subsumed specification with the lowest * runtime estimation, that abides to the minimal expected recall * requirement. * * * @param spec, * the input link specification */ protected void init(LinkSpecification spec) { if (spec == null) { logger.error("Link Specification is empty, I am going to stop here."); throw new RuntimeException(); } LinkSpecification initLSClone = spec.clone(); LigerPlanner planner = new LigerPlanner(this.source, this.target); Plan initPlan = planner.plan(initLSClone); this.best = new PartialRecallRefinementNode(initLSClone, initPlan); this.desiredSelectivity = (double) (initPlan.getSelectivity() * this.k); this.buffer.addFirst(best); this.total.add(best.getLinkSpecification().toString()); // for safe keeping this.root = new PartialRecallRefinementNode(spec.clone(), initPlan); } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcRelConnectsStructuralMember.java
15253
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc4; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Rel Connects Structural Member</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getRelatingStructuralMember <em>Relating Structural Member</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getRelatedStructuralConnection <em>Related Structural Connection</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAppliedCondition <em>Applied Condition</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAdditionalConditions <em>Additional Conditions</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLength <em>Supported Length</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLengthAsString <em>Supported Length As String</em>}</li> * <li>{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getConditionCoordinateSystem <em>Condition Coordinate System</em>}</li> * </ul> * * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember() * @model * @generated */ public interface IfcRelConnectsStructuralMember extends IfcRelConnects { /** * Returns the value of the '<em><b>Relating Structural Member</b></em>' reference. * It is bidirectional and its opposite is '{@link cn.dlb.bim.models.ifc4.IfcStructuralMember#getConnectedBy <em>Connected By</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Relating Structural Member</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Relating Structural Member</em>' reference. * @see #setRelatingStructuralMember(IfcStructuralMember) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_RelatingStructuralMember() * @see cn.dlb.bim.models.ifc4.IfcStructuralMember#getConnectedBy * @model opposite="ConnectedBy" * @generated */ IfcStructuralMember getRelatingStructuralMember(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getRelatingStructuralMember <em>Relating Structural Member</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Relating Structural Member</em>' reference. * @see #getRelatingStructuralMember() * @generated */ void setRelatingStructuralMember(IfcStructuralMember value); /** * Returns the value of the '<em><b>Related Structural Connection</b></em>' reference. * It is bidirectional and its opposite is '{@link cn.dlb.bim.models.ifc4.IfcStructuralConnection#getConnectsStructuralMembers <em>Connects Structural Members</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Related Structural Connection</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Related Structural Connection</em>' reference. * @see #setRelatedStructuralConnection(IfcStructuralConnection) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_RelatedStructuralConnection() * @see cn.dlb.bim.models.ifc4.IfcStructuralConnection#getConnectsStructuralMembers * @model opposite="ConnectsStructuralMembers" * @generated */ IfcStructuralConnection getRelatedStructuralConnection(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getRelatedStructuralConnection <em>Related Structural Connection</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Related Structural Connection</em>' reference. * @see #getRelatedStructuralConnection() * @generated */ void setRelatedStructuralConnection(IfcStructuralConnection value); /** * Returns the value of the '<em><b>Applied Condition</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Applied Condition</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Applied Condition</em>' reference. * @see #isSetAppliedCondition() * @see #unsetAppliedCondition() * @see #setAppliedCondition(IfcBoundaryCondition) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_AppliedCondition() * @model unsettable="true" * @generated */ IfcBoundaryCondition getAppliedCondition(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAppliedCondition <em>Applied Condition</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Applied Condition</em>' reference. * @see #isSetAppliedCondition() * @see #unsetAppliedCondition() * @see #getAppliedCondition() * @generated */ void setAppliedCondition(IfcBoundaryCondition value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAppliedCondition <em>Applied Condition</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetAppliedCondition() * @see #getAppliedCondition() * @see #setAppliedCondition(IfcBoundaryCondition) * @generated */ void unsetAppliedCondition(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAppliedCondition <em>Applied Condition</em>}' reference is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Applied Condition</em>' reference is set. * @see #unsetAppliedCondition() * @see #getAppliedCondition() * @see #setAppliedCondition(IfcBoundaryCondition) * @generated */ boolean isSetAppliedCondition(); /** * Returns the value of the '<em><b>Additional Conditions</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Additional Conditions</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Additional Conditions</em>' reference. * @see #isSetAdditionalConditions() * @see #unsetAdditionalConditions() * @see #setAdditionalConditions(IfcStructuralConnectionCondition) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_AdditionalConditions() * @model unsettable="true" * @generated */ IfcStructuralConnectionCondition getAdditionalConditions(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAdditionalConditions <em>Additional Conditions</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Additional Conditions</em>' reference. * @see #isSetAdditionalConditions() * @see #unsetAdditionalConditions() * @see #getAdditionalConditions() * @generated */ void setAdditionalConditions(IfcStructuralConnectionCondition value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAdditionalConditions <em>Additional Conditions</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetAdditionalConditions() * @see #getAdditionalConditions() * @see #setAdditionalConditions(IfcStructuralConnectionCondition) * @generated */ void unsetAdditionalConditions(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getAdditionalConditions <em>Additional Conditions</em>}' reference is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Additional Conditions</em>' reference is set. * @see #unsetAdditionalConditions() * @see #getAdditionalConditions() * @see #setAdditionalConditions(IfcStructuralConnectionCondition) * @generated */ boolean isSetAdditionalConditions(); /** * Returns the value of the '<em><b>Supported Length</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Supported Length</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Supported Length</em>' attribute. * @see #isSetSupportedLength() * @see #unsetSupportedLength() * @see #setSupportedLength(double) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_SupportedLength() * @model unsettable="true" * @generated */ double getSupportedLength(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLength <em>Supported Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Supported Length</em>' attribute. * @see #isSetSupportedLength() * @see #unsetSupportedLength() * @see #getSupportedLength() * @generated */ void setSupportedLength(double value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLength <em>Supported Length</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetSupportedLength() * @see #getSupportedLength() * @see #setSupportedLength(double) * @generated */ void unsetSupportedLength(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLength <em>Supported Length</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Supported Length</em>' attribute is set. * @see #unsetSupportedLength() * @see #getSupportedLength() * @see #setSupportedLength(double) * @generated */ boolean isSetSupportedLength(); /** * Returns the value of the '<em><b>Supported Length As String</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Supported Length As String</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Supported Length As String</em>' attribute. * @see #isSetSupportedLengthAsString() * @see #unsetSupportedLengthAsString() * @see #setSupportedLengthAsString(String) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_SupportedLengthAsString() * @model unsettable="true" * @generated */ String getSupportedLengthAsString(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLengthAsString <em>Supported Length As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Supported Length As String</em>' attribute. * @see #isSetSupportedLengthAsString() * @see #unsetSupportedLengthAsString() * @see #getSupportedLengthAsString() * @generated */ void setSupportedLengthAsString(String value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLengthAsString <em>Supported Length As String</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetSupportedLengthAsString() * @see #getSupportedLengthAsString() * @see #setSupportedLengthAsString(String) * @generated */ void unsetSupportedLengthAsString(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getSupportedLengthAsString <em>Supported Length As String</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Supported Length As String</em>' attribute is set. * @see #unsetSupportedLengthAsString() * @see #getSupportedLengthAsString() * @see #setSupportedLengthAsString(String) * @generated */ boolean isSetSupportedLengthAsString(); /** * Returns the value of the '<em><b>Condition Coordinate System</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Condition Coordinate System</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Condition Coordinate System</em>' reference. * @see #isSetConditionCoordinateSystem() * @see #unsetConditionCoordinateSystem() * @see #setConditionCoordinateSystem(IfcAxis2Placement3D) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcRelConnectsStructuralMember_ConditionCoordinateSystem() * @model unsettable="true" * @generated */ IfcAxis2Placement3D getConditionCoordinateSystem(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getConditionCoordinateSystem <em>Condition Coordinate System</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Condition Coordinate System</em>' reference. * @see #isSetConditionCoordinateSystem() * @see #unsetConditionCoordinateSystem() * @see #getConditionCoordinateSystem() * @generated */ void setConditionCoordinateSystem(IfcAxis2Placement3D value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getConditionCoordinateSystem <em>Condition Coordinate System</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetConditionCoordinateSystem() * @see #getConditionCoordinateSystem() * @see #setConditionCoordinateSystem(IfcAxis2Placement3D) * @generated */ void unsetConditionCoordinateSystem(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcRelConnectsStructuralMember#getConditionCoordinateSystem <em>Condition Coordinate System</em>}' reference is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Condition Coordinate System</em>' reference is set. * @see #unsetConditionCoordinateSystem() * @see #getConditionCoordinateSystem() * @see #setConditionCoordinateSystem(IfcAxis2Placement3D) * @generated */ boolean isSetConditionCoordinateSystem(); } // IfcRelConnectsStructuralMember
agpl-3.0
jpaoletti/java-presentation-manager
modules/jpm-core/src/main/java/jpaoletti/jpm/core/EntityContainer.java
4551
package jpaoletti.jpm.core; import java.util.ArrayList; import java.util.List; /** * @author jpaoletti * * This class encapsulate an entity, its list and everything associated to an * entity. An instance of this class is inserted in session under demand and * stay in session for fast reference. * */ public class EntityContainer { private String id; private Entity entity; private PaginatedList list; private List<InstanceId> selectedInstances; private EntityInstanceWrapper selected; private boolean selectedNew; private EntityFilter filter; private EntityContainer owner; private Operation operation; /** * Main constructor * * @param entity The contained entity * @param sid The session id */ public EntityContainer(Entity entity) { super(); this.entity = entity; this.id = buildId(entity.getId()); this.selectedNew = false; } /** * Builds a string based on a session id and the entity id. Not implemented. * * @param sid A session id * @param eid The entity id * @return The resulting string */ public static String buildId(String eid) { //return sid.substring(0,20) + eid.hashCode() + sid.substring(20); return eid; } /** * Getter for the id * * @return The id */ public String getId() { return id; } /** * * @param id */ public void setId(String id) { this.id = id; } /** * Getter for the entity * * @return The entity */ public Entity getEntity() { return entity; } /** * * @param entity */ public void setEntity(Entity entity) { this.entity = entity; } /** * Getter for the list * * @return The list */ public PaginatedList getList() { return list; } /** * * @param list */ public void setList(PaginatedList list) { this.list = list; } /** * Setter for selected instance * * @param selected */ public void setSelected(EntityInstanceWrapper selected) { this.selected = selected; setSelectedNew(false); } /** * Getter for the selected instance wrapper * * @return The wrapper */ public EntityInstanceWrapper getSelected() { return selected; } /** * * @param new_ */ public void setSelectedNew(boolean new_) { this.selectedNew = new_; } /** * Indicate if the actual selected is new * * @return true when selected is new */ public boolean isSelectedNew() { return selectedNew; } /** * @param filter the filter to set */ public void setFilter(EntityFilter filter) { this.filter = filter; } /** * @return the filter */ public EntityFilter getFilter() { return filter; } /** * @return the selected instances ids */ public List<InstanceId> getSelectedInstanceIds() { if (selectedInstances == null) { selectedInstances = new ArrayList<InstanceId>(); } return selectedInstances; } /** * Getter for the owner * * @return The owner */ public EntityContainer getOwner() { return owner; } /** * * @param owner */ public void setOwner(EntityContainer owner) { this.owner = owner; } /** * Getter for the operation * * @return The operation */ public Operation getOperation() { return operation; } /** * * @param operation */ public void setOperation(Operation operation) { this.operation = operation; } public boolean isSelected(InstanceId id) { return getSelectedInstanceIds().contains(id); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final EntityContainer other = (EntityContainer) obj; if ((this.getId() == null) ? (other.getId() != null) : !this.getId().equals(other.getId())) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + (this.getId() != null ? this.getId().hashCode() : 0); return hash; } }
agpl-3.0
agroknow/fiware-pep-steelskin
test/unit/httpOptions_test.js
5270
/* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-pep-steelskin * * fiware-pep-steelskin is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * fiware-pep-steelskin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with fiware-pep-steelskin. * If not, seehttp://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License * please contact with::[daniel.moranjimenez@telefonica.com] */ 'use strict'; var serverMocks = require('../tools/serverMocks'), proxyLib = require('../../lib/fiware-pep-steelskin'), orionPlugin = require('../../lib/plugins/orionPlugin'), config = require('../../config'), async = require('async'), utils = require('../tools/utils'), request = require('request'), originalAuthenticationModule; process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; describe('HTTPS Options', function() { var proxy, mockTarget, mockTargetApp, mockAccess, mockAccessApp, mockOAuth, mockOAuthApp; beforeEach(function(done) { originalAuthenticationModule = config.authentication.module; config.authentication.module = 'idm'; config.ssl.active = true; config.ssl.certFile = 'test/certs/pepTest.crt'; config.ssl.keyFile = 'test/certs/pepTest.key'; proxyLib.start(function(error, proxyObj) { proxy = proxyObj; proxy.middlewares.push(orionPlugin.extractCBAction); serverMocks.start(config.resource.original.port, function(error, server, app) { mockTarget = server; mockTargetApp = app; serverMocks.start(config.access.port, function(error, serverAccess, appAccess) { mockAccess = serverAccess; mockAccessApp = appAccess; serverMocks.start(config.authentication.options.port, function(error, serverAuth, appAuth) { mockOAuth = serverAuth; mockOAuthApp = appAuth; mockOAuthApp.handler = function(req, res) { if (req.url.match(/\/v2.0\/token.*/)) { res.json(200, utils.readExampleFile('./test/authorizationResponses/authorize.json')); } else { res.json(200, utils.readExampleFile('./test/authorizationResponses/rolesOfUser.json')); } }; async.series([ async.apply(serverMocks.mockPath, '/user', mockOAuthApp), async.apply(serverMocks.mockPath, '/pdp/v3', mockAccessApp) ], done); }); }); }); }); }); afterEach(function(done) { config.authentication.module = originalAuthenticationModule; config.ssl.active = false; proxyLib.stop(proxy, function(error) { serverMocks.stop(mockTarget, function() { serverMocks.stop(mockAccess, function() { serverMocks.stop(mockOAuth, done); }); }); }); }); describe('When a request to the CB arrives to the proxy with HTTPS', function() { var options = { uri: 'https://localhost:' + config.resource.proxy.port + '/NGSI10/updateContext', method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Fiware-Service': 'frn:contextbroker:admin_domain:::', 'Fiware-ServicePath': 'admin_domain', 'X-Auth-Token': 'UAidNA9uQJiIVYSCg0IQ8Q' }, json: utils.readExampleFile('./test/orionRequests/entityCreation.json') }; beforeEach(function(done) { serverMocks.mockPath('/validate', mockAccessApp, done); serverMocks.mockPath('/NGSI10/updateContext', mockTargetApp, done); }); it('should proxy the request to the destination', function(done) { var mockExecuted = false; mockAccessApp.handler = function(req, res) { res.set('Content-Type', 'application/xml'); res.send(utils.readExampleFile('./test/accessControlResponses/permitResponse.xml', true)); }; mockTargetApp.handler = function(req, res) { mockExecuted = true; res.json(200, {}); }; request(options, function(error, response, body) { mockExecuted.should.equal(true); done(); }); }); }); });
agpl-3.0
DBezemer/server
plugins/content/caption/base/lib/captionManagers/webVttCaptionsContentManager.php
6384
<?php /** * @package plugins.caption * @subpackage lib */ class webVttCaptionsContentManager extends kCaptionsContentManager { const WEBVTT_TIMECODE_PATTERN = '#^((?:[0-9]{2}:)?[0-9]{2}:[0-9]{2}\.[0-9]{3}) --> ((?:[0-9]{2}:)?[0-9]{2}:[0-9]{2}\.[0-9]{3})( .*)?$#'; const BOM_CODE = "\xEF\xBB\xBF"; const WEBVTT_PATTERN = 'WEBVTT'; /** * @var array */ protected $parsingErrors = array(); /** * @var array */ public $headerInfo = array(); /* (non-PHPdoc) * @see kCaptionsContentManager::parse() */ public function parse($content) { $itemsData = $this->parseWebVTT($content); foreach ($itemsData as &$itemData ) { foreach ($itemData['content'] as &$curChunk) { $val = strip_tags($curChunk['text']); $curChunk['text'] = $val; } } return $itemsData; } /** * @param $parsing_errors * @return array */ public function validateWebVttHeader($signature) { if (substr($signature, 0, 6) !== 'WEBVTT' && substr($signature, 0, 9) !== self::BOM_CODE.'WEBVTT') { $this->parsingErrors[] = 'Missing "WEBVTT" at the beginning of the file'; return false; } if (strlen($signature) > 6 && substr($signature, 0, 6) === 'WEBVTT') { if (substr($signature, 0, 7) === 'WEBVTT ') { $fileDescription = substr($signature, 7); if (strpos($fileDescription, '-->') !== false) { $this->parsingErrors[] = 'File description must not contain "-->"'; return false; } return true; } else { $this->parsingErrors[] = 'Invalid file header (must be "WEBVTT" with optional description)'; return false; } } elseif (strlen($signature) > 9 && substr($signature, 0, 9) === self::BOM_CODE.'WEBVTT') { if (substr($signature, 0, 10) === self::BOM_CODE.'WEBVTT ') { $fileDescription = substr($signature, 10); if (strpos($fileDescription, '-->') !== false) { $this->parsingErrors[] = 'File description must not contain "-->"'; return false; } return true; } else { $this->parsingErrors[] = 'Invalid file header (must be "WEBVTT" with optional description)'; return false; } } return true; } /** * @param $timeStr * @return string */ public function parseWebvttStrTTTime($timeStr) { list ($timeInMilliseconds, $error) = kCaptionsContentManager::parseStrTTTime($timeStr); if($error) $this->parsingErrors[] = $error; return $timeInMilliseconds; } /* (non-PHPdoc) * @see kCaptionsContentManager::getContent() */ public function getContent($content) { $itemsData = null; try { $itemsData = $this->parseWebVTT($content); $content = ''; foreach ($itemsData as $itemData) { foreach ($itemData['content'] as $curChunk) { $text = strip_tags($curChunk['text']); $content .= $text. ' '; } } } catch (Exception $e) { KalturaLog::err($e->getMessage()); return null; } return trim(preg_replace('/\s+/', ' ', $content)); } /** * @return webVttCaptionsContentManager */ public static function get() { return new webVttCaptionsContentManager(); } /** * @param $content * @return array */ public function parseWebVTT($content) { $this->headerInfo = array(); $foundFirstTimeCode = false; $itemsData = array(); $fileContentArray = self::getFileContentAsArray($content); // Parse signature. $header = self::getNextValueFromArray($fileContentArray); if (!$this->validateWebVttHeader($header)) { KalturaLog::err("Error Parsing WebVTT file. The following errors were found while parsing the file: \n" . print_r($this->parsingErrors, true)); return array(); } $this->headerInfo[] = $header.self::UNIX_LINE_ENDING; // Parse text - ignore comments, ids, styles, notes, etc while (($line = self::getNextValueFromArray($fileContentArray)) !== false) { // Timecode. $matches = array(); $timecode_match = preg_match(self::WEBVTT_TIMECODE_PATTERN, $line, $matches); if ($timecode_match) { $foundFirstTimeCode = true; $start = $this->parseCaptionTime($matches[1]); $stop = $this->parseCaptionTime($matches[2]); $text = ''; while (trim($line = self::getNextValueFromArray($fileContentArray)) !== '') { $line = $this->handleTextLines($line); $text .= $line . self::UNIX_LINE_ENDING; } $itemsData[] = array('startTime' => $start, 'endTime' => $stop, 'content' => array(array('text' => $text))); }elseif ($foundFirstTimeCode == false) $this->headerInfo[] = $line . self::UNIX_LINE_ENDING; }; if (count($this->parsingErrors) > 0) { KalturaLog::err("Error Parsing WebVTT file. The following errors were found while parsing the file: \n" . print_r($this->parsingErrors, true)); return array(); } return $itemsData; } public function buildFile($content, $clipStartTime, $clipEndTime, $globalOffset = 0) { $newFileContent = $this->createCaptionsFile($content, $clipStartTime, $clipEndTime, self::WEBVTT_TIMECODE_PATTERN, $globalOffset); return $newFileContent; } protected function createAdjustedTimeLine($matches, $clipStartTime, $clipEndTime, $globalOffset) { $startCaption = $this->parseWebvttStrTTTime($matches[1]); $endCaption = $this->parseWebvttStrTTTime($matches[2]); if (!kCaptionsContentManager::onTimeRange($startCaption, $endCaption, $clipStartTime, $clipEndTime)) return null; $adjustedStartTime = kCaptionsContentManager::getAdjustedStartTime($startCaption, $clipStartTime, $globalOffset); $adjustedEndTime = kCaptionsContentManager::getAdjustedEndTime($clipStartTime, $clipEndTime, $endCaption, $globalOffset); $settings = isset($matches[3]) ? trim($matches[3]) : ''; $timeLine = kWebVTTGenerator::formatWebVTTTimeStamp($adjustedStartTime) . ' --> ' . kWebVTTGenerator::formatWebVTTTimeStamp($adjustedEndTime). $settings . kCaptionsContentManager::UNIX_LINE_ENDING; return $timeLine; } /** * @param string $content * @param string $toAppend * @return string */ public function merge($content, $toAppend) { if (!$toAppend) return $content; $originalFileContentArray = kCaptionsContentManager::getFileContentAsArray($toAppend); while (($line = kCaptionsContentManager::getNextValueFromArray($originalFileContentArray)) !== false) { if (strpos($line,self::WEBVTT_PATTERN) === false) $content .= $line . kCaptionsContentManager::UNIX_LINE_ENDING; } return $content; } }
agpl-3.0
crunchbutton/crunchbutton
include/library/Crunchbutton/Session/Token.php
1117
<?php class Crunchbutton_Session_Token extends Cana_Table { public function generateAndSaveToken($user, $admin, $session) { if (($this->id_user || $this->id_admin) && !$this->token) { $fields = '-=d4sh0fs4|t?&4ndM4YB350m35ymb0||0v3!!!!!!=-'.$this->id_session.$this->id_user.$this->id_admin.uniqid(); $this->token = strtoupper(hash('sha512', $fields)); $this->save(); } } public static function token($token) { if (!$token) return false; $res = Cana::db()->query('select * from session where token=?', [$token]); $session = $res->fetch(); //$session->closeCursor(); if ($session->id_session) { return $session; } return false; } public static function deleteToken($token) { if (!$token) return false; Cana::dbWrite()->query('delete from session where token=?',[$token]); } public function auth() { if (!isset($this->_auth)) { $this->_auth = new Crunchbutton_User_Auth($this->id_user_auth); } return $this->_auth; } public function __construct($id = null) { parent::__construct(); $this ->table('session') ->idVar('id_session') ->load($id); } }
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_leggings.lua
4799
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_wearables_armor_bounty_hunter_armor_bounty_hunter_leggings = object_tangible_wearables_armor_bounty_hunter_shared_armor_bounty_hunter_leggings:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bith_female.iff", "object/mobile/vendor/bith_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/gran_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/ishi_tib_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/nikto_male.iff", "object/mobile/vendor/quarren_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/twilek_female.iff", "object/mobile/vendor/twilek_male.iff", "object/mobile/vendor/weequay_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff" }, templateType = ARMOROBJECT, objectMenuComponent = "ArmorObjectMenuComponent", vulnerability = BLAST + ELECTRICITY + HEAT + COLD + ACID + LIGHTSABER, specialResists = STUN, -- These are default Blue Frog stats healthEncumbrance = 70, actionEncumbrance = 265, mindEncumbrance = 65, maxCondition = 30000, -- LIGHT, MEDIUM, HEAVY rating = LIGHT, kinetic = 40, energy = 40, electricity = 0, stun = 55, blast = 0, heat = 0, cold = 0, acid = 0, lightSaber = 0, } ObjectTemplates:addTemplate(object_tangible_wearables_armor_bounty_hunter_armor_bounty_hunter_leggings, "object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_leggings.iff")
agpl-3.0
jenskohler/SeDiCo
SeDiCoIntegration-ejb/ejbModule/com/sedico/generictableadapter/ColumnType.java
870
package com.sedico.generictableadapter; /** * Diese Klasse implementiert den Kolumnentyp * @author jens * @version 1.0 */ public class ColumnType { /** * Membervariablen */ private String columnType; private String columnName; /** * Getter der Membervariable columnType * @return columnType - ColumnType */ public String getColumnType() { return columnType; } /** * Setter der Membervariable columnType * @param columnType */ public void setColumnType(String columnType) { this.columnType = columnType; } /** * Getter der Membervariable columnName * @return columnName - Name der Column */ public String getColumnName() { return columnName; } /** * Setter der Membervariable columnName * @param columnName- Name der Column */ public void setColumnName(String columnName) { this.columnName = columnName; } }
agpl-3.0
rockneurotiko/wirecloud
src/wirecloud/commons/static/js/StyledElements/Expander.js
5784
/* * Copyright (c) 2008-2015 CoNWeT Lab., Universidad Politécnica de Madrid * * This file is part of Wirecloud Platform. * * Wirecloud Platform is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Wirecloud is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Wirecloud Platform. If not, see * <http://www.gnu.org/licenses/>. * */ /*globals CSSPrimitiveValue, StyledElements */ (function () { "use strict"; var Expander = function Expander(options) { var defaultOptions = { 'buttonFloat': 'left', 'class': '', 'expandButton': true, 'listenOnTitle': false, 'state': 'default', 'title': null }; options = StyledElements.Utils.merge(defaultOptions, options); if (!options.expandButton && !options.listenOnTitle) { throw new TypeError(); } StyledElements.StyledElement.call(this, ['expandChange']); this.wrapperElement = document.createElement('div'); this.wrapperElement.className = StyledElements.Utils.appendWord("panel se-expander", options['class']); if (options.state != null && options.state.trim() !== "") { this.addClassName('panel-' + options.state); } var header = document.createElement('div'); header.className = 'panel-heading'; this.wrapperElement.appendChild(header); this.toggleButton = null; if (options.expandButton) { this.toggleButton = new StyledElements.ToggleButton({ 'class': 'icon-expand', 'plain': true }); this.toggleButton.insertInto(header); } this.titleContainer = new StyledElements.Container({'class': 'title'}); this.titleContainer.insertInto(header); if (options.title) { this.titleContainer.appendChild(document.createTextNode(options.title)); } this.contentContainer = new StyledElements.Container({'class': 'panel-body'}); this.contentContainer.insertInto(this.wrapperElement); // Internal event handlers var callback = function () { this.setExpanded(!this.isExpanded()); }.bind(this); if (this.toggleButton) { this.toggleButton.addEventListener('click', callback); } if (options.listenOnTitle) { this.titleContainer.wrapperElement.style.cursor = "pointer"; this.titleContainer.wrapperElement.addEventListener('click', callback, false); } }; Expander.prototype = new StyledElements.StyledElement(); Expander.prototype.repaint = function repaint(temporal) { var height, computedStyle; if (this.isExpanded()) { height = this.wrapperElement.clientHeight; if (height == null) { return; // nothing to do } computedStyle = document.defaultView.getComputedStyle(this.titleContainer.wrapperElement, null); height -= this.titleContainer.wrapperElement.offsetHeight; height -= computedStyle.getPropertyCSSValue('margin-top').getFloatValue(CSSPrimitiveValue.CSS_PX); height -= computedStyle.getPropertyCSSValue('margin-bottom').getFloatValue(CSSPrimitiveValue.CSS_PX); computedStyle = document.defaultView.getComputedStyle(this.contentContainer.wrapperElement, null); height -= computedStyle.getPropertyCSSValue('border-top-width').getFloatValue(CSSPrimitiveValue.CSS_PX); height -= computedStyle.getPropertyCSSValue('border-bottom-width').getFloatValue(CSSPrimitiveValue.CSS_PX); height -= computedStyle.getPropertyCSSValue('padding-top').getFloatValue(CSSPrimitiveValue.CSS_PX); height -= computedStyle.getPropertyCSSValue('padding-bottom').getFloatValue(CSSPrimitiveValue.CSS_PX); if (height < 0) { height = 0; } this.contentContainer.wrapperElement.style.height = height + 'px'; this.contentContainer.repaint(temporal); } }; Expander.prototype.isExpanded = function isExpanded() { return this.hasClassName('expanded'); }; Expander.prototype.setExpanded = function setExpanded(expanded) { if (this.isExpanded() == expanded) { return; } if (expanded) { this.addClassName('expanded'); } else { this.removeClassName('expanded'); this.contentContainer.wrapperElement.style.height = ''; } if (this.toggleButton) { this.toggleButton.active = expanded; } this.events.expandChange.dispatch(this, expanded); }; Expander.prototype.getTitleContainer = function getTitleContainer() { return this.titleContainer; }; Expander.prototype.appendChild = function appendChild(element) { this.contentContainer.appendChild(element); }; Expander.prototype.removeChild = function removeChild(element) { this.contentContainer.removeChild(element); }; Expander.prototype.clear = function clear() { this.contentContainer.clear(); }; StyledElements.Expander = Expander; })();
agpl-3.0
gosh-project/gosh-officer
LibNMeCab/Core/PriorityQueue.cs
1893
using System; using System.Collections.Generic; using System.Text; namespace NMeCab.Core { public class PriorityQueue<T> where T : IComparable<T> { private class Node { public T Value; public readonly LinkedList<Node> Childs = new LinkedList<Node>(); public Node(T value) { this.Value = value; } } private Node rootNode; public int Count { get; private set; } public T First { get { return this.rootNode.Value; } } public void Clear() { this.rootNode = null; this.Count = 0; } public void Push(T item) { this.rootNode = this.Merge(this.rootNode, new Node(item)); this.Count++; } public T Pop() { T ret = this.First; this.RemoveFirst(); return ret; } public void RemoveFirst() { this.rootNode = this.Unify(this.rootNode.Childs); this.Count--; } private Node Merge(Node l, Node r) { if (l == null) return r; if (r == null) return l; if (l.Value.CompareTo(r.Value) > 0) { r.Childs.AddFirst(l); return r; } else { l.Childs.AddLast(r); return l; } } private Node Unify(LinkedList<Node> nodes) { if (nodes == null || nodes.Count == 0) return null; Node x = nodes.First.Value; nodes.RemoveFirst(); if (nodes.Count == 0) return x; Node y = nodes.First.Value; nodes.RemoveFirst(); return this.Merge(this.Merge(x, y), this.Unify(nodes)); } } }
agpl-3.0
hltn/opencps
portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/dossiermgt/service/persistence/DossierFinderUtil.java
6754
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.opencps.dossiermgt.service.persistence; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.util.ReferenceRegistry; /** * @author trungnt */ public class DossierFinderUtil { public static int countDossierByKeywordDomainAndStatus(long groupId, java.lang.String keyword, java.lang.String domainCode, java.util.List<java.lang.String> govAgencyCodes, java.lang.String dossierStatus) { return getFinder() .countDossierByKeywordDomainAndStatus(groupId, keyword, domainCode, govAgencyCodes, dossierStatus); } public static int countDossierByUser(long groupId, long userId, java.lang.String keyword, java.lang.String serviceDomainTreeIndex, java.lang.String dossierStatus) { return getFinder() .countDossierByUser(groupId, userId, keyword, serviceDomainTreeIndex, dossierStatus); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByKeywordDomainAndStatus( long groupId, java.lang.String keyword, java.lang.String domainCode, java.util.List<java.lang.String> govAgencyCodes, java.lang.String dossierStatus, int start, int end, com.liferay.portal.kernel.util.OrderByComparator obc) { return getFinder() .searchDossierByKeywordDomainAndStatus(groupId, keyword, domainCode, govAgencyCodes, dossierStatus, start, end, obc); } public static java.util.List searchDossierByUser(long groupId, long userId, java.lang.String keyword, java.lang.String serviceDomainTreeIndex, java.lang.String dossierStatus, int start, int end, com.liferay.portal.kernel.util.OrderByComparator obc) { return getFinder() .searchDossierByUser(groupId, userId, keyword, serviceDomainTreeIndex, dossierStatus, start, end, obc); } public static int countDossierForRemoteService( java.lang.String dossiertype, java.lang.String organizationcode, java.lang.String processStepId, java.lang.String status, java.lang.String fromdate, java.lang.String todate, int documentyear, java.lang.String customername) { return getFinder() .countDossierForRemoteService(dossiertype, organizationcode, processStepId, status, fromdate, todate, documentyear, customername); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierForRemoteService( java.lang.String dossiertype, java.lang.String organizationcode, java.lang.String processStepId, java.lang.String status, java.lang.String fromdate, java.lang.String todate, int documentyear, java.lang.String customername, int start, int end) { return getFinder() .searchDossierForRemoteService(dossiertype, organizationcode, processStepId, status, fromdate, todate, documentyear, customername, start, end); } public static int countDossierByUserAssignProcessOrder(long userId) { return getFinder().countDossierByUserAssignProcessOrder(userId); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByUserAssignByProcessOrder( long userId, int start, int end) { return getFinder() .searchDossierByUserAssignByProcessOrder(userId, start, end); } public static int countDossierByP_S_U(java.lang.String processNo, java.lang.String stepNo, long userId) { return getFinder().countDossierByP_S_U(processNo, stepNo, userId); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByP_S_U( java.lang.String processNo, java.lang.String stepNo, long userId, int start, int end) { return getFinder() .searchDossierByP_S_U(processNo, stepNo, userId, start, end); } public static int countDossierByP_SN_U(java.lang.String processNo, java.lang.String stepName, long userId) { return getFinder().countDossierByP_SN_U(processNo, stepName, userId); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByP_SN_U( java.lang.String processNo, java.lang.String stepName, long userId, int start, int end) { return getFinder() .searchDossierByP_SN_U(processNo, stepName, userId, start, end); } public static int countDossierByDS_RD_SN_U(long userId, java.lang.String dossierStatus, java.lang.String serviceNo, java.lang.String fromDate, java.lang.String toDate) { return getFinder() .countDossierByDS_RD_SN_U(userId, dossierStatus, serviceNo, fromDate, toDate); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByDS_RD_SN_U( java.lang.String dossierStatus, java.lang.String serviceNo, java.lang.String fromDate, java.lang.String toDate, long userId, int start, int end) { return getFinder() .searchDossierByDS_RD_SN_U(dossierStatus, serviceNo, fromDate, toDate, userId, start, end); } public static int countDossierByP_PS_U(java.lang.String processNo, java.lang.String processStepNo, long userId) { return getFinder().countDossierByP_PS_U(processNo, processStepNo, userId); } public static java.util.List<org.opencps.dossiermgt.model.Dossier> searchDossierByP_PS_U( java.lang.String processNo, java.lang.String processStepNo, long userId, int start, int end) { return getFinder() .searchDossierByP_PS_U(processNo, processStepNo, userId, start, end); } public static int countDossierByUserNewRequest(long groupId, long userId) { return getFinder().countDossierByUserNewRequest(groupId, userId); } public static java.util.List searchDossierByUserNewRequest(long groupId, long userId, int start, int end, com.liferay.portal.kernel.util.OrderByComparator obc) { return getFinder() .searchDossierByUserNewRequest(groupId, userId, start, end, obc); } public static DossierFinder getFinder() { if (_finder == null) { _finder = (DossierFinder)PortletBeanLocatorUtil.locate(org.opencps.dossiermgt.service.ClpSerializer.getServletContextName(), DossierFinder.class.getName()); ReferenceRegistry.registerReference(DossierFinderUtil.class, "_finder"); } return _finder; } public void setFinder(DossierFinder finder) { _finder = finder; ReferenceRegistry.registerReference(DossierFinderUtil.class, "_finder"); } private static DossierFinder _finder; }
agpl-3.0
HoerTech-gGmbH/openMHA
mha/plugins/complex_scale_channel/complex_scale_channel.cpp
6701
// This file is part of the HörTech Open Master Hearing Aid (openMHA) // Copyright © 2005 2006 2009 2010 2013 2017 2020 2021 HörTech gGmbH // // openMHA is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, version 3 of the License. // // openMHA is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License, version 3 for more details. // // You should have received a copy of the GNU Affero General Public License, // version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>. /* * A simple example MHA plugin written in C++ * * This is a modified example 5, using a complex number to scale one * channel, instead of a real number. * * This plugin scales one channel of the input signal, working in the * spectral domain. The complex scale factor and the scaled channel * number is made accessible to the configuration structure. * * This plugin implementation uses the C++ macros for standard MHA * plugins and a template class for algorithms with a thread safe * configuration space. The second item is important if the * configuration will be changed at runtime. */ #include "mha_plugin.hh" /* * The definition of the signal processing run time configuration. The * constructor is used to initialize and validate the run time * configuration, based on the general (parser) configuration. If the * constructor failes, the parser command which caused the failure * will be rejected. The signal processing thread will not be affected. * * The constructor and destructor are called from the * control/configuration thread. All other functions and variables * should only be accessed from the signal processing thread. */ class cfg_t { public: cfg_t(unsigned int ichannel, unsigned int numchannels, const mha_complex_t & iscale); unsigned int channel; mha_complex_t scale; }; /* * The definition of a simple signal processing class, containing a * constructor, a processing method and two variables. * * The base class MHAParser::parser_t provides the configuration * interface, the base class MHAPlugin::plugin_t provides standard * methods for MHA plugins (i.e. error handling) and functionality for * thread safe runtime configuration. * * Implementation see below. */ class complex_scale_channel_t : public MHAPlugin::plugin_t<cfg_t> { public: complex_scale_channel_t(algo_comm_t iac, const std::string & configured_name); mha_spec_t* process(mha_spec_t*); void prepare(mhaconfig_t&); private: void update_cfg(); MHAEvents::patchbay_t<complex_scale_channel_t> patchbay; /* integer variable of MHA-parser: */ MHAParser::int_t scale_ch; /* complex variable of MHA-parser: */ MHAParser::complex_t factor; }; /* * Constructor of the runtime configuration class. * * This constructor is called in the configuration thread. This * allowes slow initialization processes (memory allocation, * configuration processing) even at run time. */ cfg_t::cfg_t(unsigned int ichannel, unsigned int numchannels, const mha_complex_t & iscale) : channel(ichannel),scale(iscale) { if( channel >= numchannels ) throw MHA_Error(__FILE__,__LINE__, "Invalid channel index %u (only %u channels configured)", channel,numchannels); } /* * Constructor of the simple signal processing class. */ complex_scale_channel_t::complex_scale_channel_t(algo_comm_t iac, const std::string &) : MHAPlugin::plugin_t<cfg_t>("example plugin configuration structure",iac), scale_ch("index of channel to be scaled","0","[0,["), factor("complex scale factor","1.0","],[") { /* Register variables to the configuration parser: */ insert_item("channel",&scale_ch); insert_item("factor",&factor); /* * On write access to the parser variables a notify callback of * this class will be called. That funtion will update the runtime * configuration. */ patchbay.connect(&scale_ch.writeaccess,this, &complex_scale_channel_t::update_cfg); patchbay.connect(&factor.writeaccess,this, &complex_scale_channel_t::update_cfg); } /* * Signal processing method. One channel of the input signal is scaled * by a factor. The factor and channel number can be changed at any * time using the configuration parser of the framework. */ mha_spec_t* complex_scale_channel_t::process(mha_spec_t* spec) { poll_config(); unsigned int fr; /* Scale channel at index "scale_ch" by "factor": */ for(fr = 0; fr < spec->num_frames; fr++){ spec->buf[fr + cfg->channel * spec->num_frames] *= cfg->scale; } return spec; } /* * Handle the prepare request of the framework. After this callback * was called, a valid run time configuration has to be * available. Domain and channel numbers of input and output are * passed to the algorithm and can be modified by the algorithm. If * not modified by the algorithm, than the output and input parameters * are equal. The default domain depends on the output domain of * preceeding algorithms. */ void complex_scale_channel_t::prepare(mhaconfig_t& cfg) { /* spectral input is needed, spectral data is returned: */ if( cfg.domain != MHA_SPECTRUM ) throw MHA_ErrorMsg("complex_scale_channel: Only spectral processing is supported."); /* remember the transform configuration (i.e. channel numbers): */ tftype = cfg; /* make sure that a valid runtime configuration exists: */ update_cfg(); } /* * This function adds a valid runtime configuration. In this case, the * channel number has to be configured for a valid configuration (see * prepare() callback). */ void complex_scale_channel_t::update_cfg() { if( tftype.channels ) push_config(new cfg_t(scale_ch.data,tftype.channels,factor.data)); } /* * This macro wraps the required ANSI-C interface around the algorithm * class. The first argument is the algorithm class name, the other * arguments define the input and output domain of the algorithm. */ MHAPLUGIN_CALLBACKS(complex_scale_channel,complex_scale_channel_t,spec,spec) MHAPLUGIN_DOCUMENTATION(complex_scale_channel,"testing","") // Local Variables: // compile-command: "make" // c-basic-offset: 4 // indent-tabs-mode: nil // coding: utf-8-unix // End:
agpl-3.0
dataminerconsulting/hlplife
custom/Extension/modules/Accounts/Ext/Vardefs/sugarfield_business_owner_c.php
128
<?php // created: 2014-07-25 08:52:26 $dictionary['Account']['fields']['business_owner_c']['labelValue']='Business Owner'; ?>
agpl-3.0
jitsni/k3po
lang/src/main/java/org/kaazing/robot/lang/ast/AstDisconnectedNode.java
1395
/* * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com) * * This file is part of Robot. * * Robot is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kaazing.robot.lang.ast; public class AstDisconnectedNode extends AstEventNode { @Override public <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception { return visitor.visit(this, parameter); } @Override public int hashCode() { return hashTo(); } @Override public boolean equals(Object obj) { return (this == obj) || ((obj instanceof AstDisconnectedNode) && equalTo((AstDisconnectedNode) obj)); } @Override protected void formatNode(StringBuilder sb) { super.formatNode(sb); sb.append("disconnected\n"); } }
agpl-3.0
bietiekay/hacs
hacs/Libraries/Newtonsoft.Json/Linq/JObject.cs
26228
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; #if !PORTABLE using System.Collections.Specialized; #endif using System.ComponentModel; #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE) using System.Dynamic; using System.Linq.Expressions; #endif using System.IO; using Newtonsoft.Json.Utilities; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON object. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) , ICustomTypeDescriptor #endif #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE) , INotifyPropertyChanging #endif { private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _properties; } } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE) /// <summary> /// Occurs when a property value is changing. /// </summary> public event PropertyChangingEventHandler PropertyChanging; #endif /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class. /// </summary> public JObject() { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class from another <see cref="JObject"/> object. /// </summary> /// <param name="other">A <see cref="JObject"/> object to copy from.</param> public JObject(JObject other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JObject t = node as JObject; if (t == null) return false; return _properties.Compare(t._properties); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) return; base.InsertItem(index, item, skipParentCheck); } internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, "o"); if (o.Type != JTokenType.Property) throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); JProperty newProperty = (JProperty) o; if (existing != null) { JProperty existingProperty = (JProperty) existing; if (newProperty.Name == existingProperty.Name) return; } if (_properties.TryGetValue(newProperty.Name, out existing)) throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); } internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) if (_listChanged != null) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); #endif #if SILVERLIGHT || !(NET20 || NET35 || PORTABLE) if (_collectionChanged != null) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); #endif } internal void InternalPropertyChanging(JProperty childProperty) { #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE) OnPropertyChanging(childProperty.Name); #endif } internal override JToken CloneToken() { return new JObject(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Object; } } /// <summary> /// Gets an <see cref="IEnumerable{JProperty}"/> of this object's properties. /// </summary> /// <returns>An <see cref="IEnumerable{JProperty}"/> of this object's properties.</returns> public IEnumerable<JProperty> Properties() { return _properties.Cast<JProperty>(); } /// <summary> /// Gets a <see cref="JProperty"/> the specified name. /// </summary> /// <param name="name">The property name.</param> /// <returns>A <see cref="JProperty"/> with the specified name or null.</returns> public JProperty Property(string name) { if (name == null) return null; JToken property; _properties.TryGetValue(name, out property); return (JProperty)property; } /// <summary> /// Gets an <see cref="JEnumerable{JToken}"/> of this object's property values. /// </summary> /// <returns>An <see cref="JEnumerable{JToken}"/> of this object's property values.</returns> public JEnumerable<JToken> PropertyValues() { return new JEnumerable<JToken>(Properties().Select(p => p.Value)); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); string propertyName = key as string; if (propertyName == null) throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return this[propertyName]; } set { ValidationUtils.ArgumentNotNull(key, "o"); string propertyName = key as string; if (propertyName == null) throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); this[propertyName] = value; } } /// <summary> /// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <value></value> public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, "propertyName"); JProperty property = Property(propertyName); return (property != null) ? property.Value : null; } set { JProperty property = Property(propertyName); if (property != null) { property.Value = value; } else { #if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE) OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } } /// <summary> /// Loads an <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JObject Load(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, "reader"); if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartObject) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); o.SetLineInfo(reader as IJsonLineInfo); o.ReadTokenFrom(reader); return o; } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public static new JObject Parse(string json) { JsonReader reader = new JsonTextReader(new StringReader(json)); JObject o = Load(reader); if (reader.Read() && reader.TokenType != JsonToken.Comment) throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return o; } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object</returns> public static new JObject FromObject(object o) { return FromObject(o, new JsonSerializer()); } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); return (JObject)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); for (int i = 0; i < _properties.Count; i++) { _properties[i].WriteTo(writer, converters); } writer.WriteEndObject(); } #region IDictionary<string,JToken> Members /// <summary> /// Adds the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } bool IDictionary<string, JToken>.ContainsKey(string key) { return _properties.Contains(key); } ICollection<string> IDictionary<string, JToken>.Keys { // todo: make order the collection returned match JObject order get { return _properties.Keys; } } /// <summary> /// Removes the property with the specified name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>true if item was successfully removed; otherwise, false.</returns> public bool Remove(string propertyName) { JProperty property = Property(propertyName); if (property == null) return false; property.Remove(); return true; } /// <summary> /// Tries the get value. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <returns>true if a value was successfully retrieved; otherwise, false.</returns> public bool TryGetValue(string propertyName, out JToken value) { JProperty property = Property(propertyName); if (property == null) { value = null; return false; } value = property.Value; return true; } ICollection<JToken> IDictionary<string, JToken>.Values { get { // todo: need to wrap _properties.Values with a collection to get the JProperty value throw new NotImplementedException(); } } #endregion #region ICollection<KeyValuePair<string,JToken>> Members void ICollection<KeyValuePair<string,JToken>>.Add(KeyValuePair<string, JToken> item) { Add(new JProperty(item.Key, item.Value)); } void ICollection<KeyValuePair<string, JToken>>.Clear() { RemoveAll(); } bool ICollection<KeyValuePair<string,JToken>>.Contains(KeyValuePair<string, JToken> item) { JProperty property = Property(item.Key); if (property == null) return false; return (property.Value == item.Value); } void ICollection<KeyValuePair<string,JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); if (arrayIndex >= array.Length && arrayIndex != 0) throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); if (Count > array.Length - arrayIndex) throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); int index = 0; foreach (JProperty property in _properties) { array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value); index++; } } bool ICollection<KeyValuePair<string,JToken>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<string,JToken>>.Remove(KeyValuePair<string, JToken> item) { if (!((ICollection<KeyValuePair<string,JToken>>)this).Contains(item)) return false; ((IDictionary<string, JToken>)this).Remove(item.Key); return true; } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<string, JToken>> GetEnumerator() { foreach (JProperty property in _properties) { yield return new KeyValuePair<string, JToken>(property.Name, property.Value); } } /// <summary> /// Raises the <see cref="PropertyChanged"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE || NET20) /// <summary> /// Raises the <see cref="PropertyChanging"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanging(string propertyName) { if (PropertyChanging != null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } #endif #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor /// <summary> /// Returns the properties for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the properties for this component instance. /// </returns> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(null); } private static Type GetTokenPropertyType(JToken token) { if (token is JValue) { JValue v = (JValue)token; return (v.Value != null) ? v.Value.GetType() : typeof(object); } return token.GetType(); } /// <summary> /// Returns the properties for this instance of a component using the attribute array as a filter. /// </summary> /// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"/> that represents the filtered properties for this component instance. /// </returns> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); foreach (KeyValuePair<string, JToken> propertyValue in this) { descriptors.Add(new JPropertyDescriptor(propertyValue.Key, GetTokenPropertyType(propertyValue.Value))); } return descriptors; } /// <summary> /// Returns a collection of custom attributes for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.AttributeCollection"/> containing the attributes for this object. /// </returns> AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; } /// <summary> /// Returns the class name of this instance of a component. /// </summary> /// <returns> /// The class name of the object, or null if the class does not have a name. /// </returns> string ICustomTypeDescriptor.GetClassName() { return null; } /// <summary> /// Returns the name of this instance of a component. /// </summary> /// <returns> /// The name of the object, or null if the object does not have a name. /// </returns> string ICustomTypeDescriptor.GetComponentName() { return null; } /// <summary> /// Returns a type converter for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.TypeConverter"/> that is the converter for this object, or null if there is no <see cref="T:System.ComponentModel.TypeConverter"/> for this object. /// </returns> TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } /// <summary> /// Returns the default event for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptor"/> that represents the default event for this object, or null if this object does not have events. /// </returns> EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } /// <summary> /// Returns the default property for this instance of a component. /// </summary> /// <returns> /// A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the default property for this object, or null if this object does not have properties. /// </returns> PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } /// <summary> /// Returns an editor of the specified type for this instance of a component. /// </summary> /// <param name="editorBaseType">A <see cref="T:System.Type"/> that represents the editor for this object.</param> /// <returns> /// An <see cref="T:System.Object"/> of the specified type that is the editor for this object, or null if the editor cannot be found. /// </returns> object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } /// <summary> /// Returns the events for this instance of a component using the specified attribute array as a filter. /// </summary> /// <param name="attributes">An array of type <see cref="T:System.Attribute"/> that is used as a filter.</param> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the filtered events for this component instance. /// </returns> EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return EventDescriptorCollection.Empty; } /// <summary> /// Returns the events for this instance of a component. /// </summary> /// <returns> /// An <see cref="T:System.ComponentModel.EventDescriptorCollection"/> that represents the events for this component instance. /// </returns> EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return EventDescriptorCollection.Empty; } /// <summary> /// Returns an object that contains the property described by the specified property descriptor. /// </summary> /// <param name="pd">A <see cref="T:System.ComponentModel.PropertyDescriptor"/> that represents the property whose owner is to be found.</param> /// <returns> /// An <see cref="T:System.Object"/> that represents the owner of the specified property. /// </returns> object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return null; } #endregion #endif #if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE) /// <summary> /// Returns the <see cref="T:System.Dynamic.DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="T:System.Dynamic.DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JObject>(parameter, this, new JObjectDynamicProxy(), true); } private class JObjectDynamicProxy : DynamicProxy<JObject> { public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) { // result can be null result = instance[binder.Name]; return true; } public override bool TrySetMember(JObject instance, SetMemberBinder binder, object value) { JToken v = value as JToken; // this can throw an error if value isn't a valid for a JValue if (v == null) v = new JValue(value); instance[binder.Name] = v; return true; } public override IEnumerable<string> GetDynamicMemberNames(JObject instance) { return instance.Properties().Select(p => p.Name); } } #endif } }
agpl-3.0
headsupdev/agile
agile-web/src/main/java/org/headsupdev/agile/web/components/issues/IssueListPanel.java
13438
/* * HeadsUp Agile * Copyright 2009-2014 Heads Up Development. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.headsupdev.agile.web.components.issues; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.markup.html.CSSPackageResource; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.Model; import org.headsupdev.agile.api.Manager; import org.headsupdev.agile.api.User; import org.headsupdev.agile.storage.HibernateStorage; import org.headsupdev.agile.storage.StoredProject; import org.headsupdev.agile.storage.issues.Duration; import org.headsupdev.agile.storage.issues.Issue; import org.headsupdev.agile.storage.issues.Milestone; import org.headsupdev.agile.web.DurationTextField; import org.headsupdev.agile.web.HeadsUpPage; import org.headsupdev.agile.web.HeadsUpSession; import org.headsupdev.agile.web.components.HeadsUpTooltip; import org.headsupdev.agile.web.components.IssueTypeDropDownChoice; import org.headsupdev.agile.web.components.StripedDataView; import org.headsupdev.agile.web.components.UserDropDownChoice; import org.headsupdev.agile.web.components.milestones.MilestoneDropDownChoice; import org.headsupdev.agile.web.wicket.StyledPagingNavigator; import org.hibernate.Session; import org.hibernate.Transaction; import org.wicketstuff.animator.Animator; import org.wicketstuff.animator.IAnimatorSubject; import org.wicketstuff.animator.MarkupIdModel; import java.util.Iterator; //import org.headsupdev.agile.app.issues.event.CreateIssueEvent; //import org.headsupdev.agile.app.issues.permission.IssueEditPermission; /** * A panel that displays a formatted, coloured list of the issues passed in * * @author Andrew Williams * @version $Id$ * @since 1.0 */ public class IssueListPanel extends Panel { private static final int ITEMS_PER_PAGE = 25; private final boolean hideMilestone; private final boolean hideProject; private StyledPagingNavigator pagingHeader, pagingFooter; private Issue quickIssue; private HeadsUpPage page; private Milestone milestone; private final WebMarkupContainer rowAdd; private WebMarkupContainer quickAdd; private Component icon; public IssueListPanel( String id, final SortableDataProvider<Issue> issues, final HeadsUpPage page, final boolean hideProject, final boolean hideMilestone, final Milestone milestone ) { super( id ); add( CSSPackageResource.getHeaderContribution( getClass(), "issue.css" ) ); this.page = page; this.milestone = milestone; this.hideMilestone = hideMilestone; this.hideProject = hideProject; quickIssue = createIssue(); final boolean timeEnabled = Boolean.parseBoolean( page.getProject().getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_ENABLED ) ); rowAdd = new WebMarkupContainer( "rowAdd" ); rowAdd.setMarkupId( "rowAdd" ); Form<Issue> inlineForm = getInlineForm(); add( inlineForm ); inlineForm.add( new WebMarkupContainer( "hours-header" ).setVisible( timeEnabled ) ); final DataView dataView = new StripedDataView<Issue>( "issues", issues, ITEMS_PER_PAGE ) { protected void populateItem( final Item<Issue> item ) { super.populateItem( item ); Issue issue = item.getModelObject(); item.add( new IssuePanelRow( "issue", issue, page, hideProject, hideMilestone, false ) ); } }; inlineForm.add( dataView ); AttributeModifier colspanModifier = new AttributeModifier( "colspan", true, new Model<Integer>() { @Override public Integer getObject() { int cols = 9; if ( hideMilestone ) { cols--; } if ( hideProject ) { cols--; } return cols; } } ); pagingFooter = new StyledPagingNavigator( "footerPaging", dataView ); pagingFooter.setOutputMarkupPlaceholderTag( true ); inlineForm.add( pagingFooter.add( colspanModifier ).setVisible( issues.size() > ITEMS_PER_PAGE ) ); pagingHeader = new StyledPagingNavigator( "headerPaging", dataView ); pagingHeader.setOutputMarkupPlaceholderTag( true ); inlineForm.add( pagingHeader.add( colspanModifier ).setVisible( issues.size() > ITEMS_PER_PAGE ) ); inlineForm.add( new OrderByBorder( "orderById", "id.id", issues ) ); inlineForm.add( quickAdd ); inlineForm.add( new OrderByBorder( "orderBySummary", "summary", issues ) ); inlineForm.add( new OrderByBorder( "orderByStatus", "status", issues ) ); inlineForm.add( new OrderByBorder( "orderByPriority", "priority", issues ) ); inlineForm.add( new OrderByBorder( "orderByOrder", "rank", issues ) ); inlineForm.add( new OrderByBorder( "orderByAssigned", "assignee", issues ) ); inlineForm.add( new OrderByBorder( "orderByMilestone", "milestone.name", issues ).setVisible( !hideMilestone ) ); inlineForm.add( new OrderByBorder( "orderByProject", "id.project.id", issues ).setVisible( !hideProject ) ); final WebMarkupContainer totalRow = new WebMarkupContainer( "totals" ); inlineForm.add( totalRow.setVisible( issues.size() > ITEMS_PER_PAGE || timeEnabled ) ); final WebMarkupContainer allCell = new WebMarkupContainer( "allCell" ); totalRow.add( allCell.add( new AttributeModifier( "colspan", true, new Model<Integer>() { @Override public Integer getObject() { int cols = 7; if ( hideMilestone ) { cols--; } if ( hideProject ) { cols--; } return cols; } } ) ) ); allCell.add( new Link( "allLink" ) { @Override public void onClick() { dataView.setItemsPerPage( Integer.MAX_VALUE ); setVisible( false ); totalRow.setVisible( timeEnabled ); pagingFooter.setVisible( false ); pagingHeader.setVisible( false ); } }.setVisible( issues.size() > ITEMS_PER_PAGE ) ); totalRow.add( new WebMarkupContainer( "requiredlabel" ).setVisible( timeEnabled ) ); totalRow.add( new Label( "hours", new IssueTotalHoursModel( (Iterator<Issue>) issues.iterator( 0, issues.size() ), page.getProject() ) { @Override public String getObject() { setIssues( issues.iterator( 0, dataView.getItemCount() ) ); // we could do this if the total is suppose to reflect the current page // setIssues( issues.iterator( dataView.getCurrentPage() * dataView.getItemsPerPage(), dataView.getItemsPerPage() ) ); return super.getObject(); } } ).setVisible( timeEnabled ) ); } private Form<Issue> getInlineForm() { CompoundPropertyModel<Issue> formPropertyModel = new CompoundPropertyModel<Issue>( quickIssue ) { @Override public Issue getObject() { return quickIssue; } }; Form<Issue> inlineForm = new Form<Issue>( "IssueInlineForm", formPropertyModel ) { @Override protected void onSubmit() { super.onSubmit(); quickIssue.setReporter( page.getSession().getUser() ); quickIssue.getWatchers().add( page.getSession().getUser() ); quickIssue.setTimeRequired( quickIssue.getTimeEstimate() ); saveIssue( quickIssue ); //TODO: problem with dependency below // page.getHeadsUpApplication().addEvent( new CreateIssueEvent( quickIssue, quickIssue.getProject() ) ); quickIssue = createIssue(); } }; Component[] rowAddComponents = new Component[9]; rowAddComponents[0] = new WebMarkupContainer( "submit" ).setMarkupId( "add" ); rowAddComponents[1] = new TextField<String>( "summary" ).setRequired( true ).setMarkupId( "summary" ); rowAddComponents[2] = new Label( "status", IssueUtils.getStatusName( Issue.STATUS_NEW ) ).setMarkupId( "status" ); rowAddComponents[3] = new IssueTypeDropDownChoice( "type", IssueUtils.getTypes() ).setRequired( true ).setMarkupId( "type" ); rowAddComponents[4] = new TextField<Integer>( "rank", new Model<Integer>() { @Override public void setObject( Integer object ) { quickIssue.setOrder( object ); } @Override public Integer getObject() { if ( quickIssue.getOrder() == null || quickIssue.getOrder().equals( Issue.ORDER_NO_ORDER ) ) { return null; } return quickIssue.getOrder(); } } ).setType( Integer.class ).setMarkupId( "rank" ); rowAddComponents[5] = new UserDropDownChoice( "assignee" ).setMarkupId( "assignee" ); rowAddComponents[6] = new Label( "project", page.getProject().toString() ).setVisible( !hideProject ).setMarkupId( "pro" ); rowAddComponents[7] = new MilestoneDropDownChoice( "milestone", page.getProject() ).setNullValid( true ).setVisible( !hideMilestone ).setMarkupId( "milestone" ); rowAddComponents[8] = new DurationTextField( "timeEstimate", new Model<Duration>() { @Override public void setObject( Duration duration ) { quickIssue.setTimeEstimate( duration ); } @Override public Duration getObject() { if ( quickIssue.getTimeEstimate().equals( new Duration( 0 ) ) ) { return null; } return quickIssue.getTimeEstimate(); } } ).setType( Duration.class ).setMarkupId( "timeEstimate" ); addAnimatorToForm( rowAddComponents ); inlineForm.add( rowAdd ); return inlineForm; } private void addAnimatorToForm( Component[] rowAddComponents ) { User currentUser = ( (HeadsUpSession) getSession() ).getUser(); quickAdd = new WebMarkupContainer( "quickAdd" ); quickAdd.add( new HeadsUpTooltip( "Quick-add an issue" ) ); quickAdd.setVisible( Permissions.canEditIssue( currentUser, page.getProject() ) ); icon = new WebMarkupContainer( "icon" ); Animator animator = new Animator(); animator.addCssStyleSubject( new MarkupIdModel( rowAdd.setMarkupId( "rowAdd" ) ), "rowhidden", "rowshown" ); for ( Component rowAddComponent : rowAddComponents ) { rowAdd.add( rowAddComponent ); if ( rowAddComponent.isVisible() ) { animator.addCssStyleSubject( new MarkupIdModel( rowAddComponent ), "hidden", "shown" ); } } animator.addSubject( new IAnimatorSubject() { public String getJavaScript() { return "moveIconBackground"; } } ); animator.attachTo( quickAdd, "onclick", Animator.Action.toggle() ); quickAdd.add( icon ); } private Issue createIssue() { Issue issue = new Issue( page.getProject() ); issue.setTimeEstimate( new Duration( 0, Duration.UNIT_HOURS ) ); issue.setMilestone( milestone ); return issue; } private void saveIssue( Issue issue ) { Session session = ( (HibernateStorage) Manager.getStorageInstance() ).getHibernateSession(); Transaction tx = session.beginTransaction(); session.save( issue ); tx.commit(); } }
agpl-3.0
et304383/passbolt_api
app/webroot/js/app/component/profile_dropdown.js
2749
import 'mad/component/component'; import 'mad/component/button_dropdown'; import 'app/model/user'; import 'app/view/template/component/profile_dropdown.ejs!'; /** * @inherits mad.Component * @parent index * * @constructor * Creates a new Profile Dropdown * * @param {HTMLElement} element the element this instance operates on. * @param {Object} [options] option values for the controller. These get added to * this.options and merged with defaults static variable * @return {passbolt.component.ProfileDropdown} */ var ProfileDropdown = passbolt.component.ProfileDropdown = mad.component.ButtonDropdown.extend('passbolt.component.ProfileDropdown', /** @static */ { defaults: { label: null, cssClasses: [], templateBased: true, templateUri: 'app/view/template/component/profile_dropdown.ejs', contentElement: '#js_app_profile_dropdown .dropdown-content', user: null } }, /** @prototype */ { /** * After start hook. * @see {mad.Component} */ afterStart: function() { this._super(); var self = this; // Set current user. self.options.user = passbolt.model.User.getCurrent(); // Add my profile action. var action = new mad.model.Action({ id: uuid(), label: 'my profile', //'cssClasses': ['separator-after'], action: function (menu) { mad.bus.trigger('request_workspace', 'settings'); mad.bus.trigger('request_settings_section', 'profile'); self.view.close(); } }); this.options.menu.insertItem(action); // Add manage your keys action. var action = new mad.model.Action({ id: uuid(), label: 'manage your keys', //cssClasses: ['separator-after'], action: function (menu) { mad.bus.trigger('request_workspace', 'settings'); mad.bus.trigger('request_settings_section', 'keys'); self.view.close(); } }); this.options.menu.insertItem(action); // Add my profile action var action = new mad.model.Action({ id: uuid(), label: 'logout', //'cssClasses': ['separator-after'], action: function (menu) { document.location.href = APP_URL + '/logout'; } }); this.options.menu.insertItem(action); }, /** * Before render. */ beforeRender: function() { this._super(); this.setViewData('user', this.options.user); }, /* ************************************************************** */ /* LISTEN TO THE MODEL EVENTS */ /* ************************************************************** */ /** * Observe when the user is updated * @param {passbolt.model.User} user The updated user */ '{user} updated': function (user) { // The reference of the user does not change, refresh the component if(!this.state.is('disabled') && !this.state.is(null)) { this.refresh(); } } }); export default ProfileDropdown;
agpl-3.0
panterch/future_kids
db/migrate/20180531175849_add_creator_to_comments.rb
132
class AddCreatorToComments < ActiveRecord::Migration[5.2] def change add_column :comments, :created_by_id, :integer end end
agpl-3.0
DemandCube/NeverwinterDP-Commons
hadoop-framework/src/main/java/com/neverwinterdp/hadoop/storm/wordcount/TextSpout.java
1476
/** * Taken from the storm-starter project on GitHub * https://github.com/nathanmarz/storm-starter/ */ package com.neverwinterdp.hadoop.storm.wordcount; import java.util.Map; import backtype.storm.Config; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; /** * Reads Twitter's sample feed using the twitter4j library. * * @author davidk */ @SuppressWarnings({ "rawtypes", "serial" }) public class TextSpout extends BaseRichSpout { private SpoutOutputCollector collector; @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; } @Override public void nextTuple() { Utils.sleep(1000); collector.emit(new Values("This is a test")); System.out.println("emit: This is a test") ; } @Override public void close() { } @Override public Map<String, Object> getComponentConfiguration() { Config ret = new Config(); ret.setMaxTaskParallelism(1); return ret; } @Override public void ack(Object id) { } @Override public void fail(Object id) { } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("text")); } }
agpl-3.0
CoordCulturaDigital-Minc/eleicoescnpc
inscricoes/candidate-check-informations.php
4903
<?php /** * Este template mostra todos os dados do candidato * ele é chamado no arquivo inscricoes-step3.php **/ if( !$pid) return false; $current_user_ID = get_current_user_id(); // verificar se o usuário atual tem privilégio para imprimir o documento. if( $current_user_ID != $userID && !current_user_can('curate')) { // wp_redirect(site_url('inscricoes')); return false; } $avatar_file_id = get_post_meta($pid, 'candidate-avatar', true); $portfolio_file_id = get_post_meta($pid, 'candidate-portfolio', true); $activity_file_id = get_post_meta($pid, 'candidate-activity-history', true); $diploma_file_id = get_post_meta($pid, 'candidate-diploma', true); $step1 = load_step(1, $pid); $step2 = load_step(2, $pid); $f = array_merge($step1['fields'], $step2['fields']); $current_user_ID = get_current_user_id(); $userID = get_post_field( 'post_author', $pid ); $user = get_user_by( 'id', $userID); $user_meta = array_map( function( $a ){ return $a[0]; }, get_user_meta( $userID ) ); ?> <div class="form-step-content"> <fieldset> <div class="row"> <div class="col-md-3 col-xs-12"> <strong>Foto:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo wp_get_attachment_image($avatar_file_id, 'avatar_candidate'); ?> </div> <div class="col-md-3 col-xs-12"> <strong>Nome:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $user_meta['user_name'];?> </div> <div class="col-md-3 col-xs-12"> <strong>Nome do candidato:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo isset( $f['candidate-display-name'] ) ? $f['candidate-display-name'] : "Não informado"; ?> </div> <div class="col-md-3 col-xs-12"> <strong>Nascimento:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo restore_format_date( $user_meta['date_birth'] );?> </div> <div class="col-md-3 col-xs-12"> <strong>CPF:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $user_meta['cpf'];?> </div> <div class="col-md-3 col-xs-12"> <strong>Setorial:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo get_label_setorial_by_slug($user_meta['setorial']); ?> </div> <div class="col-md-3 col-xs-12"> <strong>Estado:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $user_meta['UF']; ?> </div> <div class="col-md-3 col-xs-12"> <strong>E-mail:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $user->user_email;?> </div> <div class="col-md-3 col-xs-12"> <strong>Telefone 1:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $f['candidate-phone-1'];?> </div> <div class="col-md-3 col-xs-12"> <strong>Afro-brasileiro:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo( $f['candidate-race'] == 'true') ? 'Sim' : 'Não';?> </div> <div class="col-md-3 col-xs-12"> <strong>Sexo:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo ucfirst($f['candidate-genre']);?> </div> <div class="col-md-3 col-xs-12"> <strong>Breve experiência no setor:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $f['candidate-experience'];?> </div> <div class="col-md-3 col-xs-12"> <strong>Exposição de motivos para a candidatura:</strong> </div> <div class="col-md-9 col-xs-12"> <?php echo $f['candidate-explanatory'];?> </div> </div> <div class="row"> <div class="col-md-3 col-xs-12"> <strong>Currículo e/ou Portfólio:</strong> </div> <div class="col-md-9 col-xs-12 file"> <?php if( $portfolio_file_id ) : ?> <?php $filename = clear_pdf_file_name( $portfolio_file_id ); ?> <?php echo wp_get_attachment_link($portfolio_file_id,'','','',$filename );?> <?php else : ?> Não enviado <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-3 col-xs-12"> <strong>Histórico de atividades realizadas no setor e/ou descrição da atuação profissional autônoma:</strong> </div> <div class="col-md-9 col-xs-12 file"> <?php if( $activity_file_id ) : ?> <?php $filename = clear_pdf_file_name( $activity_file_id ); ?> <?php echo wp_get_attachment_link( $activity_file_id,'','','',$filename );?> <?php else : ?> Não enviado <?php endif; ?> </div> </div> <div class="row"> <div class="col-md-3 col-xs-12"> <strong>Diploma Profissional e/ou Registro profissional:</strong> </div> <div class="col-md-9 col-xs-12 file"> <?php if( $diploma_file_id ) : ?> <?php $filename = clear_pdf_file_name( $diploma_file_id ); ?> <?php echo wp_get_attachment_link($diploma_file_id,'','','',$filename );?> <?php else : ?> Não enviado <?php endif; ?> </div> </div> </fieldset> </div> <!-- #formstep-1 -->
agpl-3.0
NicolasEYSSERIC/Silverpeas-Components
resources-manager/resources-manager-jar/src/main/java/org/silverpeas/resourcemanager/model/Resource.java
10978
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have recieved a copy of the * text describing the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.resourcemanager.model; import com.silverpeas.util.StringUtil; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; import static org.silverpeas.resourcemanager.model.ResourceStatus.*; @Entity @Table(name = "sc_resources_resource") public class Resource { @Id @TableGenerator(name = "UNIQUE_RESOURCE_ID_GEN", table = "uniqueId", pkColumnName = "tablename", valueColumnName = "maxId", pkColumnValue = "sc_resources_resource",allocationSize=1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "UNIQUE_RESOURCE_ID_GEN") private Long id; @ManyToOne(optional = true, fetch = FetchType.EAGER) @JoinColumn(name = "categoryid", nullable = true, updatable = true) private Category category; @Column private String name; @Column private String creationDate; @Column private String updateDate; @Column private Integer bookable; @Column private String description; @Column private String createrId; @Column private String updaterId; @Column private String instanceId; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="resource") private List<ResourceValidator> managers = new ArrayList<ResourceValidator>(); @Transient private String status; public boolean isBookable() { return bookable == 1; } public void setBookable(boolean bookable) { if (bookable) { this.bookable = 1; } else { this.bookable = 0; } } public String getCreaterId() { return createrId; } public void setCreaterId(String createrId) { this.createrId = createrId; } public Date getCreationDate() { if (StringUtil.isLong(creationDate)) { Date create = new Date(); create.setTime(Long.parseLong(creationDate)); return create; } return null; } public void setCreationDate(Date creationDate) { if (creationDate != null) { this.creationDate = String.valueOf(creationDate.getTime()); } else { creationDate = null; } } public Date getUpdateDate() { if (StringUtil.isLong(updateDate)) { Date update = new Date(); update.setTime(Long.parseLong(updateDate)); return update; } return null; } public void setUpdateDate(Date updateDate) { if (updateDate != null) { this.updateDate = String.valueOf(updateDate.getTime()); } } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getId() { return String.valueOf(id); } public Long getIntegerId() { return id; } public final void setId(String id) { if (StringUtil.isLong(id)) { this.id = Long.parseLong(id); } } public String getCategoryId() { if (category != null) { return category.getId(); } return null; } public void setCategory(Category category) { this.category = category; } public Category getCategory() { return category; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUpdaterId() { return updaterId; } public void setUpdaterId(String updaterId) { this.updaterId = updaterId; } public List<ResourceValidator> getManagers() { return managers; } public void setManagers(List<ResourceValidator> managers) { this.managers = managers; } public Resource() { } public void merge(Resource resource) { this.bookable = resource.bookable; this.category = resource.category; this.createrId = resource.createrId; this.creationDate = resource.creationDate; this.description = resource.description; this.instanceId = resource.instanceId; this.name = resource.name; this.updateDate = resource.updateDate; this.updaterId = resource.updaterId; } public Resource(String name, Category category, boolean bookable) { this.name = name; this.category = category; setBookable(bookable); } public Resource(String name, Category category, String description, boolean bookable) { this.category = category; this.name = name; this.description = description; setBookable(bookable); } public Resource(String id, Category category, String name, Date creationDate, Date updateDate, String description, String createrId, String updaterId, String instanceId, boolean bookable) { setId(id); this.category = category; this.name = name; setCreationDate(creationDate); setUpdateDate(updateDate); this.description = description; this.createrId = createrId; this.updaterId = updaterId; this.instanceId = instanceId; setBookable(bookable); } public Resource(String id, Category category, String name, Date creationDate, Date updateDate, String description, String createrId, String updaterId, String instanceId, boolean bookable, String status) { setId(id); this.category = category; this.name = name; setCreationDate(creationDate); setUpdateDate(updateDate); this.description = description; this.createrId = createrId; this.updaterId = updaterId; this.instanceId = instanceId; setBookable(bookable); this.setStatus(status); } public Resource(String id, Category category, String name, String description, boolean bookable) { setId(id); this.category = category; this.name = name; this.description = description; setBookable(bookable); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Resource other = (Resource) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } if (this.category != other.category && (this.category == null || !this.category.equals( other.category))) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.creationDate == null) ? (other.creationDate != null) : !this.creationDate.equals( other.creationDate)) { return false; } if ((this.updateDate == null) ? (other.updateDate != null) : !this.updateDate.equals( other.updateDate)) { return false; } if (this.bookable != other.bookable && (this.bookable == null || !this.bookable.equals( other.bookable))) { return false; } if ((this.description == null) ? (other.description != null) : !this.description.equals( other.description)) { return false; } if ((this.createrId == null) ? (other.createrId != null) : !this.createrId.equals( other.createrId)) { return false; } if ((this.updaterId == null) ? (other.updaterId != null) : !this.updaterId.equals( other.updaterId)) { return false; } if ((this.instanceId == null) ? (other.instanceId != null) : !this.instanceId.equals( other.instanceId)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.id != null ? this.id.hashCode() : 0); hash = 29 * hash + (this.category != null ? this.category.hashCode() : 0); hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 29 * hash + (this.creationDate != null ? this.creationDate.hashCode() : 0); hash = 29 * hash + (this.updateDate != null ? this.updateDate.hashCode() : 0); hash = 29 * hash + (this.bookable != null ? this.bookable.hashCode() : 0); hash = 29 * hash + (this.description != null ? this.description.hashCode() : 0); hash = 29 * hash + (this.createrId != null ? this.createrId.hashCode() : 0); hash = 29 * hash + (this.updaterId != null ? this.updaterId.hashCode() : 0); hash = 29 * hash + (this.instanceId != null ? this.instanceId.hashCode() : 0); return hash; } @Override public String toString() { return "Resource{" + "id=" + id + ", category= {" + category + "}, name=" + name + ", creationDate=" + creationDate + ", updateDate=" + updateDate + ", description=" + description + ", createrId=" + createrId + ", updaterId=" + updaterId + ", instanceId=" + instanceId + ", bookable=" + bookable + ", managers=" + managers + ", status=" + getStatus() + '}'; } public boolean isValidated() { return STATUS_VALIDATE.equals(getStatus()); } public boolean isRefused() { return STATUS_REFUSED.equals(getStatus()); } public boolean isValidationRequired() { return STATUS_FOR_VALIDATION.equals(getStatus()); } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
agpl-3.0
moskiteau/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/enums/KalturaIpAddressRestrictionType.java
2155
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2015 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.enums; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ public enum KalturaIpAddressRestrictionType implements KalturaEnumAsInt { RESTRICT_LIST (0), ALLOW_LIST (1); public int hashCode; KalturaIpAddressRestrictionType(int hashCode) { this.hashCode = hashCode; } public int getHashCode() { return this.hashCode; } public void setHashCode(int hashCode) { this.hashCode = hashCode; } public static KalturaIpAddressRestrictionType get(int hashCode) { switch(hashCode) { case 0: return RESTRICT_LIST; case 1: return ALLOW_LIST; default: return RESTRICT_LIST; } } }
agpl-3.0
pollopolea/core
apps/testing/lib/Occ.php
1925
<?php /** * ownCloud * * @author Artur Neumann <artur@jankaritech.com> * @copyright Copyright (c) 2017 Artur Neumann artur@jankaritech.com * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\Testing; use OC\OCS\Result; use OCP\IRequest; /** * run the occ command from an API call * * @author Artur Neumann <artur@jankaritech.com> * */ class Occ { /** * * @var IRequest */ private $request; /** * * @param IRequest $request */ public function __construct(IRequest $request) { $this->request = $request; } /** * * @return Result */ public function execute() { $command = $this->request->getParam("command", ""); $args = preg_split("/[\s,]+/", $command); $args = array_map( function ($arg) { return escapeshellarg($arg); }, $args ); $args = implode(' ', $args); $descriptor = [ 0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $process = proc_open( 'php console.php ' . $args, $descriptor, $pipes, realpath("../") ); $lastStdOut = stream_get_contents($pipes[1]); $lastStdErr = stream_get_contents($pipes[2]); $lastCode = proc_close($process); $result = [ "code" => $lastCode, "stdOut" => $lastStdOut, "stdErr" => $lastStdErr ]; $resultCode = $lastCode + 100; return new Result($result, $resultCode); } }
agpl-3.0
gnosygnu/xowa_android
_100_core/src/main/java/gplx/GfoMsg.java
1754
package gplx; import gplx.core.interfaces.*; public interface GfoMsg { String Key(); GfoMsg CloneNew(); String To_str(); GfoMsg Clear(); GfoMsg Parse_(boolean v); int Args_count(); Keyval Args_getAt(int i); GfoMsg Args_ovr(String k, Object v); void Args_reset(); GfoMsg Add(String k, Object v); int Subs_count(); GfoMsg Subs_getAt(int i); GfoMsg Subs_add(GfoMsg m); GfoMsg Subs_(GfoMsg... ary); boolean ReadBool(String k); boolean ReadBoolOr(String k, boolean or); boolean ReadBoolOrFalse(String k); boolean ReadBoolOrTrue(String k); int ReadInt(String k); int ReadIntOr(String k, int or); long ReadLong(String k); long ReadLongOr(String k, long or); float ReadFloat(String k); float ReadFloatOr(String k, float or); double ReadDouble(String k); double ReadDoubleOr(String k, double or); DateAdp ReadDate(String k); DateAdp ReadDateOr(String k, DateAdp or); Decimal_adp ReadDecimal(String k); Decimal_adp ReadDecimalOr(String k, Decimal_adp or); String ReadStr(String k); String ReadStrOr(String k, String or); Io_url ReadIoUrl(String k); Io_url ReadIoUrlOr(String k, Io_url url); boolean ReadYn(String k); boolean ReadYn_toggle(String k, boolean cur); boolean ReadYnOrY(String k); byte ReadByte(String k); byte[] ReadBry(String k); byte[] ReadBryOr(String k, byte[] or); Object ReadObj(String k); Object ReadObj(String k, ParseAble parseAble); Object ReadObjOr(String k, ParseAble parseAble, Object or); String[]ReadStrAry(String k, String spr); String[]ReadStrAryIgnore(String k, String spr, String ignore); byte[][]ReadBryAry(String k, byte spr); Object ReadValAt(int i); Object CastObj(String k); Object CastObjOr(String k, Object or); }
agpl-3.0
RBSChange/modules.catalog
lib/services/ProductService.class.php
47521
<?php /** * catalog_ProductService * @package modules.catalog */ class catalog_ProductService extends f_persistentdocument_DocumentService { /** * Singleton * @var catalog_ProductService */ private static $instance = null; /** * @return catalog_ProductService */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = self::getServiceClassInstance(get_class()); } return self::$instance; } /** * @return catalog_persistentdocument_product */ public function getNewDocumentInstance() { return $this->getNewDocumentInstanceByModelName('modules_catalog/product'); } /** * Create a query based on 'modules_catalog/product' model * @return f_persistentdocument_criteria_Query */ public function createQuery() { return $this->pp->createQuery('modules_catalog/product'); } /** * @param catalog_persistentdocument_product $document * @param string $bockName * @return array with entries 'module' and 'template'. */ public function getSolrsearchResultItemTemplate($document, $bockName) { return array('module' => 'catalog', 'template' => 'Catalog-Inc-ProductResultDetail'); } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @return string */ public function getPathForShop($product, $shop) { $primaryShelf = $this->getShopPrimaryShelf($product, $shop); if ($primaryShelf === null) { return ''; } $path = array(); foreach ($primaryShelf->getDocumentService()->getAncestorsOf($primaryShelf) as $ancestor) { if ($ancestor instanceof catalog_persistentdocument_shelf) { $path[] = $ancestor->getLabel(); } } $path[] = $primaryShelf->getLabel(); return implode(' > ', $path); } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @return media_persistentdocument_media */ public function getDefaultVisual($product, $shop) { // get visual from the product. $visual = $product->getVisual(); // ... or from shop. if ($visual === null && $shop !== null) { $visual = $shop->getDefaultDetailVisual(); } // ... or from module preferences. if ($visual === null) { $visual = ModuleService::getInstance()->getPreferenceValue('catalog', 'defaultDetailVisual'); } return $visual; } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop */ public function getListVisual($product, $shop) { // get visual from the product. $visual = $product->getVisual(); // ... or from shop if ($visual === null && $shop !== null) { $visual = $shop->getDefaultListVisual(); } // ... or from module preferences if ($visual === null) { $visual = ModuleService::getInstance()->getPreferenceValue('catalog', 'defaultListVisual'); } return $visual; } /** * @param string $codeReference * @return array<catalog_persistentdocument_product> */ public function getByCodeReference($codeReference) { return $this->createQuery('modules_catalog/product')->add(Restrictions::eq('codeReference', $codeReference))->find(); } /** * @param integer $articleId * @return array<catalog_persistentdocument_product> */ public function getByArticleId($articleId) { return $this->createQuery('modules_catalog/product')->add(Restrictions::eq('articleId', $articleId))->find(); } /** * @param catalog_persistentdocument_product $article * @return array<catalog_persistentdocument_product> */ public function getByArticle($article) { return $this->getByArticleId($article->getId()); } /** * @param Integer $brandId * @return f_persistentdocument_criteria_Query */ public function getByBrandId($brandId) { return $this->createQuery()->add(Restrictions::eq('brand.id', $brandId))->find(); } /** * @param Integer $brandId * @return array<catalog_persistentdocument_product> */ public function getByBrand($brand) { return $this->getByBrandId($brand->getId()); } /** * @param catalog_persistentdocument_product $document * @param Integer $websiteId */ public function getRatingAverage($document, $websiteId = null) { if (catalog_ModuleService::getInstance()->areCommentsEnabled()) { return comment_CommentService::getInstance()->getRatingAverageByTargetId($document->getId(), $websiteId); } return null; } /** * @param catalog_persistentdocument_product $document * @param catalog_persistentdocument_shop $shop * @return integer[] */ public function filterIdsForDisplay($productIds, $shop = null) { if (!$shop || f_util_ArrayUtils::isEmpty($productIds)) { return null; } $query = catalog_ProductService::getInstance()->createQuery() ->add(Restrictions::published()) ->add(Restrictions::in('id', $productIds)) ->setProjection(Projections::property('id')); $query->createCriteria('compiledproduct') ->add(Restrictions::published()) ->add(Restrictions::eq('shopId', $shop->getId())); $result = array_intersect($productIds, $query->findColumn('id')); return count($result) ? $result : null; } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @param Double $quantity * @param Array<String, Mixed> $properties * @return catalog_persistentdocument_product * @see order_CartService::addProduct() */ public function getProductToAddToCart($product, $shop, $quantity, &$properties) { if (intval($product->getShippingModeId()) > 0) { $properties['shippingModeId'] = $product->getShippingModeId(); } else if (isset($properties['shippingModeId'])) { unset($properties['shippingModeId']); } return $product; } /** * @param catalog_persistentdocument_product $product * @param array $properties * @return void */ public function updateProductFromCartProperties($product, $properties) { return; } /** * @param catalog_persistentdocument_kit $product * @param array $cartLineProperties * @param order_persistentdocument_orderline $orderLine * @param order_persistentdocument_order $order */ public function updateOrderLineProperties($product, &$cartLineProperties, $orderLine, $order) { $shop = $order->getShop(); $cp = $product->getDocumentService()->getPrimaryCompiledProductForShop($product, $shop); if ($cp !== null) { $cartLineProperties['shelf'] = catalog_persistentdocument_shelf::getInstanceById($cp->getTopshelfId())->getLabel(); $cartLineProperties['subshelf'] = $cp->getShelf()->getLabel(); } } /** * @param catalog_persistentdocument_product $product * @param array $properties * @return void */ public function updateProductFromRequestParameters($product, $parameters) { return; } /** * @param catalog_persistentdocument_product $document * @return integer */ public function getWebsiteId($document) { return null; } /** * @param catalog_persistentdocument_product $document * @return integer[] | null */ public function getWebsiteIds($document) { $ids = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product', $document)) ->setProjection(Projections::groupProperty('websiteId', 'id')) ->findColumn('id'); return $ids; } /** * @param catalog_persistentdocument_product $document * @param string $forModuleName * @param array $allowedSections * @return array */ public function getResume($document, $forModuleName, $allowedSections = null) { unset($allowedSections['urlrewriting']); $ls = LocaleService::getInstance(); $data = parent::getResume($document, $forModuleName, $allowedSections); $rc = RequestContext::getInstance(); $contextlang = $rc->getLang(); $lang = $document->isLangAvailable($contextlang) ? $contextlang : $document->getLang(); $data['properties']['compiled'] = $ls->transBO('f.boolean.' . ($document->getCompiled() ? 'true' : 'false'), array('ucf')); $data['properties']['alertCount'] = catalog_AlertService::getInstance()->getPublishedCountByProduct($document); try { $rc->beginI18nWork($lang); $urlData = array(); $query = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('lang', $lang)) ->add(Restrictions::eq('product.id', $document->getId())) ->add(Restrictions::eq('primary', true)); foreach ($query->find() as $compiledProduct) { if ($compiledProduct instanceof catalog_persistentdocument_compiledproduct) { $shop = $compiledProduct->getShop(); $website = $compiledProduct->getWebsite(); $href = website_UrlRewritingService::getInstance()->getDocumentLinkForWebsite($compiledProduct, $website, $lang)->setArgSeparator('&')->getUrl(); $urlData[] = array( 'label' => $ls->transBO('m.catalog.bo.doceditor.url-for-website', array('ucf'), array('website' => $website->getLabel())), 'href' => $href, 'class' => ($shop->isPublished() && $compiledProduct->isPublished()) ? 'link' : '' ); } } $data['urlrewriting'] = $urlData; $rc->endI18nWork(); } catch (Exception $e) { $rc->endI18nWork($e); } return $data; } /** * Used in productexporter to specify the products urls. * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @param string $lang * @param array $parameters * @return string */ public function generateUrlForExporter($product, $shop, $lang = null, $parameters = array()) { if (!$shop->getIsDefault()) { $parameters['catalogParam']['shopId'] = $shop->getId(); } return LinkHelper::getDocumentUrlForWebsite($product, $shop->getWebsite(), $lang, $parameters); } /** * @param catalog_persistentdocument_product $document * @param Integer $parentNodeId Parent node ID where to save the document (optionnal). * @return void */ protected function preSave($document, $parentNodeId) { if ($document->isPropertyModified('stockQuantity') && !$document->isPropertyModified('stockLevel')) { $this->updateStockLevel($document); } // Trim SKU codes. if ($document->isPropertyModified('codeSKU')) { $document->setCodeSKU(trim($document->getCodeSKU())); } } /** * @param catalog_persistentdocument_product $document * @param Integer $parentNodeId Parent node ID where to save the document. * @return void */ protected function postSave($document, $parentNodeId) { if ($document->isPropertyModified('shelf') && $document->isPublished()) { $this->onShelfPropertyModified($document); } $this->synchronizeFields($document); // Generate compiled products. $this->updateCompiledProperty($document, false); //Send low stock alert notification catalog_StockService::getInstance()->handleStockAlert($document); } /** * @param catalog_persistentdocument_product $document */ protected function onShelfPropertyModified($document) { $oldIds = $document->getShelfOldValueIds(); $currentShelves = $document->getShelfArray(); $ss = catalog_ShelfService::getInstance(); $currentIds = array(); foreach ($currentShelves as $shelf) { if (!in_array($shelf->getId(), $oldIds)) { $ss->productPublished($shelf, $document); } $currentIds[] = $shelf->getId(); } foreach ($oldIds as $shelfId) { if (!in_array($shelfId, $currentIds)) { $shelf = DocumentHelper::getDocumentInstance($shelfId); $ss->productUnpublished($shelf, $document); } } } /** * @param catalog_persistentdocument_product $document */ protected function synchronizeFields($document) { // Handle similar and complementary products synchronization. $cms = catalog_ModuleService::getInstance(); if ($document->isPropertyModified('complementary') && $cms->isComplementarySynchroEnabled()) { $this->synchronizeField($document, 'complementary'); } if ($document->isPropertyModified('similar') && $cms->isSimilarSynchroEnabled()) { $this->synchronizeField($document, 'similar'); } } /** * @param catalog_persistentdocument_product $document * @param String $fieldName */ protected function synchronizeField($document, $fieldName) { $ucfirstFieldName = ucfirst($fieldName); $oldIds = $document->{'get'.$ucfirstFieldName.'OldValueIds'}(); $currentProducts = $document->{'get'.$ucfirstFieldName.'Array'}(); // Update added products. $currentIds = array(); foreach ($currentProducts as $product) { if (!in_array($product->getId(), $oldIds)) { $product->getDocumentService()->addProductToTargetField($product, $fieldName, $document); } $currentIds[] = $product->getId(); } // Update removed products. foreach ($oldIds as $productId) { if (!in_array($productId, $currentIds)) { $product = DocumentHelper::getDocumentInstance($productId); $product->getDocumentService()->removeProductFromTargetField($product, $fieldName, $document); } } } /** * * @param catalog_persistentdocument_product $targetProduct * @param string $fieldName * @param catalog_persistentdocument_product $product */ public function addProductToTargetField($targetProduct, $fieldName, $product) { if ($targetProduct === $product) {return;} $ucfirstFieldName = ucfirst($fieldName); if ($targetProduct->{'getIndexof'.$ucfirstFieldName}($product) == -1) { $targetProduct->{'add'.$ucfirstFieldName}($product); $this->save($targetProduct); } } /** * @param catalog_persistentdocument_product $targetProduct * @param string $fieldName * @param catalog_persistentdocument_product $product */ public function removeProductFromTargetField($targetProduct, $fieldName, $product) { $ucfirstFieldName = ucfirst($fieldName); if ($targetProduct->{'getIndexof'.$ucfirstFieldName}($product) != -1) { $targetProduct->{'remove'.$ucfirstFieldName}($product); $this->save($targetProduct); } } /** * @param catalog_persistentdocument_product $document * @param Integer $parentNodeId Parent node ID where to save the document (optionnal). * @return void */ protected function preInsert($document, $parentNodeId) { parent::preInsert($document, $parentNodeId); $document->setInsertInTree(false); } /** * @param catalog_persistentdocument_product $document * @param Integer $parentNodeId Parent node ID where to save the document (optionnal). * @return void */ protected function preUpdate($document, $parentNodeId) { $document->persistHasNewTranslation(); if ($document->getCodeSKU() === null) { $document->setCodeSKU(strval($document->getId())); } $this->updateRelatedProductsMetas($document, 'complementary'); $this->updateRelatedProductsMetas($document, 'similar'); $this->updateRelatedProductsMetas($document, 'upsell'); } /** * @param catalog_persistentdocument_product $document * @return void */ protected function preDelete($document) { // Delete compiled products. $this->deleteRelatedCompiledProducts($document); catalog_PriceService::getInstance()->deleteForProductId($document->getId()); } /** * @param f_persistentdocument_PersistentDocument $document */ protected function postDeleteLocalized($document) { $this->updateCompiledProperty($document, false); } /** * @param catalog_persistentdocument_product $document */ protected function deleteRelatedCompiledProducts($document) { catalog_CompiledproductService::getInstance()->deleteForProduct($document); } /** * @param catalog_persistentdocument_product $product */ public function fullDelete($product) { if (Framework::isDebugEnabled()) { Framework::debug(__METHOD__ . ' START for product: ' . $product->__toString()); } try { $this->tm->beginTransaction(); $langs = array_reverse($product->getI18nInfo()->getLangs()); $rc = RequestContext::getInstance(); foreach ($langs as $lang) { try { $rc->beginI18nWork($lang); $product->delete(); $rc->endI18nWork(); } catch (Exception $rce) { $rc->endI18nWork($rce); } } $this->tm->commit(); } catch (Exception $tme) { $this->tm->rollBack($tme); throw $tme; } if (Framework::isDebugEnabled()) { Framework::debug(__METHOD__ . ' END for product: ' . $product->__toString()); } } /** * @param catalog_persistentdocument_product $document * @param String $oldPublicationStatus * @return void */ protected function publicationStatusChanged($document, $oldPublicationStatus, $params) { $this->refreshShelfPublicationStatus($document, $oldPublicationStatus); // Handle compilation and republish kits. if (!isset($params['cause']) || $params["cause"] != "delete") { if ($document->isPublished() || $oldPublicationStatus == 'PUBLICATED') { $this->updateCompiledProperty($document, false); catalog_KititemService::getInstance()->publishIfPossibleByProduct($document); } } } /** * @param catalog_persistentdocument_product $document * @param String $oldPublicationStatus */ protected function refreshShelfPublicationStatus($document, $oldPublicationStatus) { // Status transit from ACTIVE to PUBLICATED. if ($document->isPublished()) { $ss = catalog_ShelfService::getInstance(); foreach ($document->getShelfArray() as $shelf) { $ss->productPublished($shelf, $document); } } // Status transit from PUBLICATED to ACTIVE. else if ($oldPublicationStatus == 'PUBLICATED') { $ss = catalog_ShelfService::getInstance(); foreach ($document->getShelfArray() as $shelf) { $ss->productUnpublished($shelf, $document); } } } /** * @return Boolean */ public function hasIdsForSitemap() { return false; } /** * @param catalog_persistentdocument_product $document * @return website_persistentdocument_page */ public function getDisplayPage($document) { if ($document->isPublished()) { $shopService = catalog_ShopService::getInstance(); $request = HttpController::getInstance()->getContext()->getRequest(); $topicId = intval($request->getModuleParameter('catalog', 'topicId')); if ($topicId > 0) { $cp = catalog_CompiledproductService::getInstance()->getByProductInContext($document, $topicId, RequestContext::getInstance()->getLang()); if ($cp) { $shopService->setCurrentShop($cp->getShop()); return website_PageService::getInstance()->createQuery()->add(Restrictions::published()) ->add(Restrictions::childOf($topicId)) ->add(Restrictions::hasTag('functional_catalog_product-detail')) ->findUnique(); } } $shop = $shopService->getShopFromRequest('shopId'); if ($shop === null) { $website = website_WebsiteModuleService::getInstance()->getCurrentWebsite(); $shop = $shopService->getDefaultByWebsite($website); if ($shop === null) { return null; } } $shopService->setCurrentShop($shop); $shelf = $this->getShopPrimaryShelf($document, $shop, true); if ($shelf !== null) { $topic = $shelf->getDocumentService()->getRelatedTopicByShop($shelf, $shop); if ($topic !== null) { return website_PageService::getInstance()->createQuery()->add(Restrictions::published()) ->add(Restrictions::childOf($topic->getId())) ->add(Restrictions::hasTag('functional_catalog_product-detail')) ->findUnique(); } } } return null; } /** * @return boolean * @see catalog_ModuleService::getProductModelsThatMayAppearInCarts() * @see markergas_lib_cMarkergasEditorTagReplacer::preRun() */ public function mayAppearInCarts() { return false; } /** * @return boolean * @see markergas_lib_cMarkergasEditorTagReplacer::preRun() */ public function getPropertyNamesForMarkergas() { return array(); } /** * * @param integer $lastId * @param integer $chunkSize * @param boolean $compileAll * @return integer[] */ public final function getProductIdsToCompile($lastId = 0, $chunkSize = 100, $compileAll = false) { $query = $this->createQuery(); if (!$compileAll) { $query->add(Restrictions::eq('compiled', false)); } $query->add(Restrictions::gt('id', $lastId))->addOrder(Order::asc('id'))->setMaxResults($chunkSize); return $query->setProjection(Projections::property('id', 'id'))->findColumn('id'); } /** * @return integer */ public final function getCountProductIdsToCompile() { $data = $this->createQuery() ->add(Restrictions::eq('compiled', false)) ->setProjection(Projections::rowCount('count')) ->findColumn('count'); return $data[0]; } /** * @return integer[] */ public final function getAllProductIdsToCompile() { return $this->createQuery()->setProjection(Projections::property('id', 'id'))->findColumn('id'); } /** * @return integer[] */ public final function getAllProductIdsToFeedRelated() { return $this->createQuery()->setProjection(Projections::property('id', 'id'))->findColumn('id'); } /** * @param catalog_persistentdocument_shelf $shelf * @param boolean $recursive * @return integer[] */ protected final function getCompiledProductIdsForShelf($shelf, $recursive = true) { if ($recursive) { $shelfIds = catalog_ShelfService::getInstance()->createQuery() ->add(Restrictions::descendentOf($shelf->getId())) ->setProjection(Projections::groupProperty('id', 'id')) ->findColumn('id'); $shelfIds[] = $shelf->getId(); } else { $shelfIds = array($shelf->getId()); } $productIds = $this->createQuery()->add(Restrictions::eq('compiled', true)) ->add(Restrictions::in('shelf.id', $shelfIds)) ->setProjection(Projections::groupProperty('id', 'id')) ->findColumn('id'); return $productIds; } /** * @param integer[] $productIds */ public function setNeedCompile($productIds) { if (f_util_ArrayUtils::isNotEmpty($productIds)) { $tm = $this->getTransactionManager(); try { $tm->beginTransaction(); foreach ($productIds as $productId) { $product = $this->getDocumentInstance($productId, 'modules_catalog/product'); $product->getDocumentService()->updateCompiledProperty($product, false); } $tm->commit(); } catch (Exception $e) { $tm->rollBack($e); } } } /** * @param catalog_persistentdocument_shop $shop */ public function setNeedCompileForShop($shop) { if (Framework::isInfoEnabled()) { Framework::info(__METHOD__); } if (catalog_ModuleService::getInstance()->useAsyncWebsiteUpdate()) { $shelfIds = array(); foreach ($shop->getTopShelfArray() as $topShelf) { $shelfIds[] = $topShelf->getId(); } if (count($shelfIds)) { catalog_ModuleService::getInstance()->addAsyncWebsiteUpdateIds($shelfIds); } } else { $productIds = array(); foreach ($shop->getTopShelfArray() as $topShelf) { $productIds = array_merge($productIds, $this->getCompiledProductIdsForShelf($topShelf)); } $compiledProdIds = $this->createQuery()->add(Restrictions::eq('compiled', true)) ->add(Restrictions::eq('compiledproduct.shopId', $shop->getId())) ->setProjection(Projections::groupProperty('id', 'id')) ->findColumn('id'); $productIds = array_unique(array_merge($productIds, $compiledProdIds)); $this->setNeedCompile($productIds); } } /** * @param catalog_persistentdocument_shelf $shelf * @param boolean $recursive */ public function setNeedCompileForShelf($shelf, $recursive = true) { if (Framework::isInfoEnabled()) { Framework::info(__METHOD__); } if ($recursive && catalog_ModuleService::getInstance()->useAsyncWebsiteUpdate()) { catalog_ModuleService::getInstance()->addAsyncWebsiteUpdateIds(array($shelf->getId())); } else { $ids = $this->getCompiledProductIdsForShelf($shelf, $recursive); $this->setNeedCompile($ids); } } /** * @param brand_persistentdocument_brand $brand */ public function setNeedCompileForBrand($brand) { $ids = $this->createQuery()->add(Restrictions::eq('compiled', true)) ->add(Restrictions::eq('brand', $brand)) ->setProjection(Projections::groupProperty('id', 'id')) ->findColumn('id'); $this->setNeedCompile($ids); } /** * @param catalog_persistentdocument_price $price */ public function setNeedCompileForPrice($price) { $product = $price->getProduct(); if ($product instanceof catalog_persistentdocument_product) { $this->updateCompiledProperty($product, false); } } /** * @param catalog_persistentdocument_product $document * @param boolean $compiled */ protected function updateCompiledProperty($document, $compiled) { $product = $document; if ($product !== null && $product->getCompiled() != $compiled) { if ($product->isModified()) { Framework::warn(__METHOD__ . $product->__toString() . ", $compiled : Is not possible on modified product"); return; } if (Framework::isInfoEnabled()) { Framework::info(__METHOD__ . ' ' . $product->__toString() . ($compiled ? ' is compiled':' to recompile')); } $product->setCompiled($compiled); $this->pp->updateDocument($product); f_DataCacheService::getInstance()->clearCacheByDocId($product->getId()); } } /** * @param integer $productId */ public function setCompiled($productId) { $product = $this->getDocumentInstance($productId, 'modules_catalog/product'); $product->getDocumentService()->updateCompiledProperty($product, true); } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_compiledproduct $compiledProduct */ public function updateCompiledProduct($product, $compiledProduct) { //TODO update compiledproduct properties if needed } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @param catalog_persistentdocument_billingarea $billingArea * @param integer[] $targetIds * @param Double $quantity * @return catalog_persistentdocument_price */ public function getPriceByTargetIds($product, $shop, $billingArea, $targetIds, $quantity = 1) { return catalog_PriceService::getInstance()->getPriceByTargetIds($product, $shop, $billingArea, $targetIds, $quantity); } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @param catalog_persistentdocument_billingarea $billingArea * @param integer[] $targetIds * @return catalog_persistentdocument_price[] */ public function getPricesByTargetIds($product, $shop, $billingArea, $targetIds) { return catalog_PriceService::getInstance()->getPricesByTargetIds($product, $shop, $billingArea, $targetIds); } /** * @param catalog_persistentdocument_product $product * @return array */ public function getPublicationInShopsInfos($product) { if (!$product->getCompiled()) { catalog_CompiledproductService::getInstance()->generateForProduct($product); } $query = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product.id', $product->getId())) ->add(Restrictions::eq('showInList', true)) ->addOrder(Order::asc('shopId')); $compiledByShopId = array(); foreach ($query->find() as $compiledProduct) { $shopId = $compiledProduct->getShopId(); if (!isset($compiledByShopId[$shopId])) { $compiledByShopId[$shopId] = array(); } $compiledByShopId[$shopId][] = $compiledProduct; } $ls = LocaleService::getInstance(); $formatter = array('ucf'); $result = array(); foreach ($compiledByShopId as $shopId => $compiledProducts) { $shopInfos = array(); $shop = catalog_persistentdocument_shop::getInstanceById($shopId); $billingArea = $shop->getDefaultBillingArea(); $shopInfos['shopLabel'] = $ls->transBO('m.catalog.bo.general.shop-in-website', $formatter, array('shop' => $shop->getLabel(), 'website' => $shop->getWebsite()->getLabel())); $shopInfos['products'] = array(); foreach ($compiledProducts as $compiledProduct) { $lang = $compiledProduct->getLang(); $publication = $ls->transBO('f.persistentdocument.status.'. strtolower($compiledProduct->getPublicationstatus()), $formatter); if ($compiledProduct->getPublicationStatus() === 'ACTIVE' && $compiledProduct->hasMeta('ActPubStatInf'.$lang)) { $publication .= ' (' . f_Locale::translateUI($compiledProduct->getMeta('ActPubStatInf'.$lang)) . ')'; } $shopInfos['products'][] = array( 'lang' => $lang, 'price' => $billingArea->formatPrice($compiledProduct->getPrice(), $lang), 'shelfLabel' => $compiledProduct->getShelf()->getLabel(), 'plublication' => $publication ); } $result[] = $shopInfos; } return $result; } /** * This method is called after à price has added on document * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_price $price */ public function priceAdded($product, $price) { // Nothing to do by default. } /** * This method is called before à price has added on document * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_price $price */ public function priceRemoved($product, $price) { // Nothing to do by default. } // Tweets handling. /** * @param catalog_persistentdocument_product $document or null * @param integer $websiteId * @return array */ public function getReplacementsForTweet($document, $websiteId) { $shop = catalog_ShopService::getInstance()->getDefaultByWebsiteId($websiteId); if ($shop === null) { return array(); } $ls = LocaleService::getInstance(); $label = array( 'name' => 'label', 'label' => $ls->transBO('m.catalog.document.product.label', array('ucf')), 'maxLength' => 80 ); $shortUrl = array( 'name' => 'shortUrl', 'label' => $ls->transBO('m.twitterconnect.bo.general.short-url', array('ucf')), 'maxLength' => 30 ); if ($document !== null) { $label['value'] = f_util_StringUtils::shortenString($document->getLabel(), 80); $shortUrl['value'] = website_ShortenUrlService::getInstance()->shortenUrl(LinkHelper::getDocumentUrl($document)); } $replacements = array($label, $shortUrl); if ($document !== null) { $billingArea = $shop->getDefaultBillingArea(); $price = $document->getPrice($shop, $billingArea, null); if ($price !== null) { $replacements[] = array( 'name' => 'price', 'value' => $billingArea->formatPrice($price->getValueWithTax()), 'label' => $ls->transBO('m.catalog.bo.general.price', array('ucf')), 'maxLength' => 10 ); } $brand = $document->getBrand(); if ($brand !== null) { $replacements[] = array( 'name' => 'brand', 'value' => f_util_StringUtils::shortenString($brand->getLabel()), 'label' => $ls->transBO('m.catalog.document.product.brand', array('ucf')), 'maxLength' => 40 ); } } else { $replacements[] = array( 'name' => 'price', 'label' => $ls->transBO('m.catalog.bo.general.price', array('ucf')), 'maxLength' => 10 ); $replacements[] = array( 'name' => 'brand', 'label' => $ls->transBO('m.catalog.document.product.brand', array('ucf')), 'maxLength' => 40 ); } return $replacements; } /** * @param catalog_persistentdocument_product $product * @return website_persistentdocument_website[] */ public function getWebsitesForTweets($product) { $websites = array(); $query = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product.id', $product->getId())) ->add(Restrictions::eq('primary', true)) ->setProjection(Projections::property('shopId'), Projections::property('publicationstatus')); foreach ($query->find() as $row) { $shop = DocumentHelper::getDocumentInstance($row['shopId'], 'modules_catalog/shop'); if ($shop->isPublished()) { $websites[] = $shop->getWebsite(); } } return $websites; } /** * @see twitterconnect_TweetService::setTweetOnPublishMeta() * @param catalog_persistentdocument_product $document * @param integer $websiteId */ public function setTweetOnPublishMeta($document, $websiteId) { $document->addMetaValue('modules.twitterconnect.tweetOnPublishForWebsite', $websiteId); $document->saveMeta(); $query = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product.id', $document->getId())) ->add(Restrictions::eq('websiteId', $websiteId)) ->add(Restrictions::eq('primary', true)); foreach ($query->find() as $compiledProduct) { $compiledProduct->setMeta('modules.twitterconnect.tweetOnPublish', $document->getId()); $compiledProduct->saveMeta(); } } /** * @see twitterconnect_TweetService::removeTweetOnPublishMeta() * @param catalog_persistentdocument_product $document * @param integer $websiteId */ public function removeTweetOnPublishMeta($document, $websiteId) { $document->removeMetaValue('modules.twitterconnect.tweetOnPublishForWebsite', $websiteId); $document->saveMeta(); $query = catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product.id', $document->getId())) ->add(Restrictions::eq('websiteId', $websiteId)) ->add(Restrictions::eq('primary', true)); foreach ($query->find() as $compiledProduct) { $compiledProduct->setMeta('modules.twitterconnect.tweetOnPublish', null); $compiledProduct->saveMeta(); } } /** * @param catalog_persistentdocument_product $document * @return f_persistentdocument_PersistentDocument[] */ public function getContainersForTweets($document) { $containers = array(); if (ModuleService::getInstance()->moduleExists('marketing')) { $containers = array_merge($containers, marketing_EditableanimService::getInstance()->getByContainedProduct($document)); } return $containers; } /** * @return integer[] */ public function getAlreadyTweetedPublishedProductIds() { $query = twitterconnect_TweetService::getInstance()->createQuery(); $query->createPropertyCriteria('relatedId', 'modules_catalog/product')->add(Restrictions::published()); $query->setProjection(Projections::property('relatedId')); return $query->findColumn('relatedId'); } /** * @param catalog_persistentdocument_product $document * @param integer $complementaryMaxCount * @param integer $similarMaxCount * @param integer $upsellMaxCount */ public function feedRelatedProducts($document) { $this->feedField($document, 'complementary'); $this->feedField($document, 'similar'); $this->feedField($document, 'upsell'); $document->save(); } /** * @param string $propertyName * @return string */ private function getAutoAddedMetaKey($propertyName) { return 'auto-added.' . strtolower($propertyName); } /** * @param string $propertyName * @return string */ private function getManuallyExcludedMetaKey($propertyName) { return 'manually-excluded.' . strtolower($propertyName); } /** * @param catalog_persistentdocument_product $document * @param string $propertyName */ private function feedField($document, $propertyName) { $ms = ModuleService::getInstance(); $feeder = $ms->getPreferenceValue('catalog', 'suggest' . ucfirst($propertyName) . 'FeederClass'); $maxCount = $ms->getPreferenceValue('catalog', 'autoFeed' . ucfirst($propertyName) . 'MaxCount'); if ($feeder && $feeder != 'none' && $maxCount > 0) { $metaAutoKey = $this->getAutoAddedMetaKey($propertyName); $metaExcludedKey = $this->getManuallyExcludedMetaKey($propertyName); $metaIds = $document->getMetaMultiple($metaAutoKey); $toRemove = $metaIds; $excludedIds = $document->getMetaMultiple($metaExcludedKey); $excludedIds[] = $document->getId(); $parameters = array('productId' => $document->getId(), 'excludedId' => $excludedIds, 'maxResults' => $maxCount); $products = f_util_ClassUtils::callMethod($feeder, 'getInstance')->getProductArray($parameters); foreach ($products as $row) { $product = $row[0]; $productId = $product->getId(); if (!in_array($productId, $metaIds) && !in_array($productId, $excludedIds)) { $document->{'add' . ucfirst($propertyName)}($product); $metaIds[] = $productId; } else { unset($toRemove[array_search($productId, $toRemove)]); } } foreach ($toRemove as $id) { $product = DocumentHelper::getDocumentInstance($id, 'modules_catalog/product'); $document->{'remove' . ucfirst($propertyName)}($product); unset($metaIds[array_search($id, $metaIds)]); } $value = array_values($metaIds); $document->setMetaMultiple($metaAutoKey, f_util_ArrayUtils::isEmpty($value) ? null : $value); } } /** * @param catalog_persistentdocument_product $document * @param string $propertyName */ private function updateRelatedProductsMetas($document, $propertyName) { if (!$document->isPropertyModified($propertyName)) { return; } $currentIds = DocumentHelper::getIdArrayFromDocumentArray($document->{'get' . ucfirst($propertyName) . 'Array'}()); $metaAutoKey = $this->getAutoAddedMetaKey($propertyName); $idsInMeta = $document->getMetaMultiple($metaAutoKey); $value = array_intersect($idsInMeta, $currentIds); $document->setMetaMultiple($metaAutoKey, f_util_ArrayUtils::isEmpty($value) ? null : $value); $metaExcludedKey = $this->getManuallyExcludedMetaKey($propertyName); $excludedIds = $document->getMetaMultiple($metaExcludedKey); $value = array_merge(array_diff($idsInMeta, $currentIds), array_diff($excludedIds, $currentIds)); $document->setMetaMultiple($metaExcludedKey, f_util_ArrayUtils::isEmpty($value) ? null : $value); } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop */ public function getShelfIdsByShop($product, $shop, $lang) { return catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product.id', $product->getId())) ->add(Restrictions::eq('shopId', $shop->getId())) ->add(Restrictions::eq('lang', $lang)) ->add(Restrictions::published()) ->setProjection(Projections::property('shelfId', 'shelfId'))->findColumn('shelfId'); } /** * @param catalog_persistentdocument_product $product * @param website_pesistentdocument_website $website * @return catalog_persistentdocument_shelf */ public function getBoPrimaryShelf($product) { return $product->getShelf(0); } /** * @param catalog_persistentdocument_product $product * @param website_pesistentdocument_website $website * @return catalog_persistentdocument_shelf */ public function getShopPrimaryShelf($product, $shop, $publlishedOnly = false) { $compiledProduct = $this->getPrimaryCompiledProductForShop($product, $shop); if ($compiledProduct !== null && (!$publlishedOnly || $compiledProduct->isPublished() || $compiledProduct->getPublicationCode() == 5)) { return DocumentHelper::getDocumentInstance($compiledProduct->getShelfId(), 'modules_catalog/shelf'); } return null; } /** * @param catalog_persistentdocument_product $product * @param catalog_persistentdocument_shop $shop * @return catalog_persistentdocument_compiledproduct */ public function getPrimaryCompiledProductForShop($product, $shop) { return catalog_CompiledproductService::getInstance()->createQuery() ->add(Restrictions::eq('product', $product)) ->add(Restrictions::eq('primary', true)) ->add(Restrictions::eq('shopId', $shop->getId())) ->add(Restrictions::eq('lang', RequestContext::getInstance()->getLang())) ->findUnique(); } /** * @param catalog_persistentdocument_product $product * @param double $quantity * @return double | null */ public function addStockQuantity($product, $quantity) { $oldQuantity = $product->getStockQuantity(); if ($oldQuantity !== null) { $newQuantity = $oldQuantity + $quantity; $product->setStockQuantity($newQuantity); if ($quantity < 0) { $theshold = $product->getStockAlertThreshold(); if ($theshold === null) { $theshold = intval(ModuleService::getInstance()->getPreferenceValue('catalog', 'stockAlertThreshold')); } $mustSend = ($oldQuantity > $theshold && $newQuantity <= $theshold); if ($mustSend) { $product->setMustSendStockAlert($mustSend); $product->setModificationdate(null); } } $this->updateStockLevel($product); if ($product->isModified()) { $product->save(); } return $newQuantity; } return $oldQuantity; } /** * @param catalog_persistentdocument_product $product */ protected function updateStockLevel($product) { $quantity = $product->getStockQuantity(); if ($quantity === null || $quantity >= 1) { $product->setStockLevel(catalog_StockService::LEVEL_AVAILABLE); } else { $product->setStockLevel(catalog_StockService::LEVEL_UNAVAILABLE); } } /** * @param catalog_persistentdocument_product $product * @return double | null */ public function getCurrentStockQuantity($product) { return $product->getStockQuantity(); } /** * @param catalog_persistentdocument_product $product * @return string [catalog_StockService::LEVEL_AVAILABLE] */ public function getCurrentStockLevel($product) { $lvl = $product->getStockLevel(); return $lvl === NULL ? catalog_StockService::LEVEL_AVAILABLE : $lvl; } /** * @param catalog_persistentdocument_product $product * @return boolean */ public function mustSendStockAlert($product) { return false; } /** * @param catalog_persistentdocument_product $product * @param string[] $propertiesNames * @param array $formProperties * @param integer $parentId */ public function addFormProperties($product, $propertiesNames, &$formProperties, $parentId = null) { $preferences = ModuleService::getInstance()->getPreferencesDocument('catalog'); if (in_array('complementary', $propertiesNames)) { $formProperties['suggestComplementaryFeederClass'] = $preferences->getSuggestComplementaryFeederClass(); $formProperties['suggestSimilarFeederClass'] = $preferences->getSuggestSimilarFeederClass(); $formProperties['suggestUpsellFeederClass'] = $preferences->getSuggestUpsellFeederClass(); } if (in_array('codeSKU', $propertiesNames)) { if ($product->getCodeSKU() === null) { $formProperties['codeSKU'] = $product->getId(); } } } /** * @param catalog_persistentdocument_product $product * @param string $moduleName * @param string $treeType * @param unknown_type $nodeAttributes */ public function addTreeAttributes($product, $moduleName, $treeType, &$nodeAttributes) { $detailVisual = $product->getDefaultVisual(); if ($detailVisual) { $nodeAttributes['hasPreviewImage'] = true; if ($treeType == 'wlist') { $nodeAttributes['thumbnailsrc'] = MediaHelper::getPublicFormatedUrl($detailVisual, "modules.uixul.backoffice/thumbnaillistitem"); } } } /** * @param catalog_persistentdocument_product $product * @return boolean */ public function isConfigurable($product) { return false; } /** * @param catalog_persistentdocument_product $document * @param catalog_persistentdocument_shop $shop * @return website_persistentdocument_page */ public function getConfigurationPage($document, $shop = null) { return null; } /** * Moves $document into the destination node identified by $destId. * * @param catalog_persistentdocument_product $document The document to move. * @param integer $destId ID of the destination node. * @param integer $beforeId * @param integer $afterId */ public function moveTo($document, $destId, $beforeId = null, $afterId = null) { $dest = DocumentHelper::getDocumentInstanceIfExists($destId); if (($dest instanceof catalog_persistentdocument_noshelfproductfolder) && ($document instanceof catalog_persistentdocument_product)) { if ($document->getShelfCount()) { $document->removeAllShelf(); $document->save(); } } else { parent::moveTo($document, $destId, $beforeId, $afterId); } } // Deprecated /** * @deprecated (will be removed in 4.0) use getBoPrimaryShelf or getShopPrimaryShelf instead */ public function getPrimaryShelf($product, $website = null, $publlishedOnly = false) { if ($website === null) { return $this->getBoPrimaryShelf($product); } else { $shop = catalog_ShopService::getInstance()->getDefaultByWebsite($website); return $this->getShopPrimaryShelf($product, $shop, $publlishedOnly); } } /** * @deprecated (will be removed in 4.0) use getPrimaryCompiledProductForShop instead */ public function getPrimaryCompiledProductForWebsite($product, $website) { $shop = catalog_ShopService::getInstance()->getDefaultByWebsite($website); return $this->getPrimaryCompiledProductForShop($product, $shop); } /** * @deprecated (will be removed in 4.0) use getPrimaryCompiledProductForShop instead */ public function generateUrlForShop($product, $shop, $lang = null, $parameters = array(), $useCache = true) { if (!$shop->getIsDefault()) { $parameters['catalogParam']['shopId'] = $shop->getId(); } return website_UrlRewritingService::getInstance()->getDocumentLinkForWebsite($product, $shop->getWebsite(), $lang, $parameters)->getUrl(); } /** * @deprecated use getDisplayableCrossSellingIds */ public function getDisplayableCrossSelling($document, $shop, $type = 'complementary', $sortBy = 'fieldorder') { // TODO: is there a more simple implementation? $methodName = 'getPublished'.ucfirst($type).'Array'; if (!f_util_ClassUtils::methodExists($document, $methodName)) { throw new Exception('Bad method name: '.$methodName); } $products = $document->{$methodName}(); if (count($products)) { $query = catalog_ProductService::getInstance()->createQuery() ->add(Restrictions::in('id', DocumentHelper::getIdArrayFromDocumentArray($products))); $query->createCriteria('compiledproduct') ->add(Restrictions::eq('shopId', $shop->getId())) ->add(Restrictions::eq('lang', RequestContext::getInstance()->getLang())) ->add(Restrictions::published()); $displayableProducts = $query->find(); } else { return array(); } if ($sortBy == 'random') { shuffle($displayableProducts); } else if ($sortBy == 'fieldorder') { $displayableIds = DocumentHelper::getIdArrayFromDocumentArray($displayableProducts); $displayableProducts = array(); foreach ($products as $product) { if (in_array($product->getId(), $displayableIds)) { $displayableProducts[] = $product; } } } return $displayableProducts; } /** * @deprecated use catalog_CompiledcrossitemService::getDisplayableLinkedIds() */ public function getDisplayableCrossSellingIds($document, $shop, $type = 'complementary') { $methodName = 'getPublished'.ucfirst($type).'Array'; if (!f_util_ClassUtils::methodExists($document, $methodName)) { throw new Exception('Bad method name: '.$methodName); } $productIds = array(); foreach ($document->{$methodName}() as $product) { $productIds[] = $product->getId(); } return $this->filterIdsForDisplay($productIds, $shop); } }
agpl-3.0
vroland/SimpleAnalyzer
doc/html/search/enums_0.js
153
var searchData= [ ['eventid',['EventID',['../simpleanalyzer-gui_2src_2GUI_2constants_8h.xhtml#ab25acc4990929d49b383f2b7c147f60f',1,'constants.h']]] ];
agpl-3.0
wadobo/congressus
congressus/tickets/apps.py
177
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class TicketsConfig(AppConfig): name = 'tickets' verbose_name = _('Tickets')
agpl-3.0
elastic-grid/Elastic-Grid
modules/elastic-grid-manager/src/test/java/com/elasticgrid/cluster/ClusterManagerMock.java
3825
/** * Elastic Grid * Copyright (C) 2008-2010 Elastic Grid, LLC. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.elasticgrid.cluster; import com.elasticgrid.model.*; import com.elasticgrid.model.ec2.EC2Node; import com.elasticgrid.model.ec2.EC2NodeType; import com.elasticgrid.model.ec2.impl.EC2ClusterImpl; import com.elasticgrid.model.ec2.impl.EC2NodeImpl; import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.RemoteException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.HashSet; /** * Mock for {@link ClusterManager}. */ public class ClusterManagerMock implements ClusterManager { private Map<String, Cluster> clusters = new HashMap<String, Cluster>(); public void startCluster(final String clusterName, List clusterTopology) throws ClusterException, ExecutionException, TimeoutException, InterruptedException, RemoteException { Cluster<EC2Node> cluster = new EC2ClusterImpl(); cluster.name(clusterName); for (int i = 0; i < clusterTopology.size(); i++) { NodeProfileInfo nodeProfileInfo = (NodeProfileInfo) clusterTopology.get(i); EC2NodeImpl node = new EC2NodeImpl(); node.instanceID(clusterName + Math.random()); node.setProfile(nodeProfileInfo.getNodeProfile()); node.setType((EC2NodeType) nodeProfileInfo.getNodeType()); try { node.address(InetAddress.getLocalHost()); } catch (UnknownHostException e) { e.printStackTrace(); } cluster.getNodes().add(node); } clusters.put(clusterName, cluster); } public void stopCluster(String clusterName) throws ClusterException, RemoteException { clusters.remove(clusterName); } public Set<Cluster> findClusters() throws ClusterException, RemoteException { return new HashSet<Cluster>(clusters.values()); } public Cluster cluster(String name) throws ClusterException, RemoteException { return clusters.get(name); } @SuppressWarnings("unchecked") public void resizeCluster(String clusterName, List clusterTopology) throws ClusterNotFoundException, ClusterException, ExecutionException, TimeoutException, InterruptedException, RemoteException { Cluster<EC2Node> cluster = clusters.get(clusterName); cluster.getNodes().clear(); for (int i = 0; i < clusterTopology.size(); i++) { NodeProfileInfo nodeProfileInfo = (NodeProfileInfo) clusterTopology.get(i); EC2NodeImpl node = new EC2NodeImpl(); node.instanceID(clusterName + '-' + Math.random()); node.setProfile(nodeProfileInfo.getNodeProfile()); node.setType((EC2NodeType) nodeProfileInfo.getNodeType()); try { node.address(InetAddress.getLocalHost()); } catch (UnknownHostException e) { e.printStackTrace(); } cluster.getNodes().add(node); } } }
agpl-3.0
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/tools/components/composite/CompositeToggleButton.java
3255
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.tools.components.composite; import javax.swing.*; import java.awt.*; /** * A {@link JToggleButton} that can be used to define <em>horizontal</em> composite elements such as * button groups or split buttons. * <p> * The button overrides the default paint methods to allow for a composition without gaps between * the individual button elements. As a consequence, {@code CompositeButton}s should never be used * as stand alone component. * <p> * Whether the {@code CompositeButton} is the left-most, a center, or the right-most element of the * composition can be specified in the constructors via the Swing constants * {@link SwingConstants#LEFT}, {@link SwingConstants#CENTER}, and {@link SwingConstants#RIGHT} * respectively. * * @author Michael Knopf * @since 7.0.0 */ class CompositeToggleButton extends JToggleButton { private static final long serialVersionUID = 1L; /** Paints the component background and border. */ private final CompositeButtonPainter painter; /** * Creates a new {@code CompositeToggleButton} with the given label to be used at the given * position. * * @param label the button label * @param position the position in the composite element ({@link SwingConstants#LEFT}, {@link SwingConstants#CENTER}, or {@link SwingConstants#RIGHT}) */ public CompositeToggleButton(String label, int position) { super(label); // the parent should never draw its background super.setContentAreaFilled(false); super.setBorderPainted(false); painter = new CompositeButtonPainter(this, position); } /** * Creates a new {@code CompositeToggleButton} with the given {@link Action} to be used at the * given position. * * @param action the button action * @param position the position in the composite element ({@link SwingConstants#LEFT}, {@link SwingConstants#CENTER}, or {@link SwingConstants#RIGHT}) */ public CompositeToggleButton(Action action, int position) { super(action); // the parent should never draw its background super.setContentAreaFilled(false); super.setBorderPainted(false); painter = new CompositeButtonPainter(this, position); } @Override protected void paintComponent(Graphics g) { painter.paintComponent(g); super.paintComponent(g); } @Override protected void paintBorder(Graphics g) { painter.paintBorder(g); } }
agpl-3.0
ZeeBeast/AeiaOTS
data/talkactions/scripts/afk.lua
1409
--[[ Talking Tp/signs/tiles for TFS 0.2+ 70%shawak,30%Damadgerz Idea by Damadgerz ]]-- local time = 5 -- 1 = 1 sec, 2 = 2 sec, ... local say_events = {} local function SayText(cid) if isPlayer(cid) == TRUE then if say_events[getPlayerGUID(cid)] ~= nil then if isPlayer(cid) == TRUE then doSendAnimatedText(getPlayerPosition(cid),"afk", math.random(01,255)) end say_events[getPlayerGUID(cid)] = addEvent(SayText, time * 1000 / 2, cid) end end return TRUE end function onSay(cid, words, param, channel) if(param == '') then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command param required.") return true end if param == "on" then if isPlayer(cid) == TRUE then doSendAnimatedText(getPlayerPosition(cid),"afk", math.random(01,255)) end say_events[getPlayerGUID(cid)] = addEvent(SayText, time * 1000, cid) doPlayerSendTextMessage(cid,MESSAGE_STATUS_WARNING,"You Now Stated you are (afk).") elseif param == "off" then stopEvent(say_events[getPlayerGUID(cid)]) say_events[getPlayerGUID(cid)] = nil doPlayerSendTextMessage(cid,MESSAGE_STATUS_WARNING,"You Now stated your are not (afk).") end return TRUE end
agpl-3.0
funkring/fdoo
addons-funkring/posix_log/__openerp__.py
1442
# -*- coding: utf-8 -*- ############################################################################# # # Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name" : "oerp.at POSIX Log", "description":""" oerp.at POSIX Log ================= * Displays log messages from the system """, "version" : "1.0", "author" : "funkring.net", "category" : "System", "depends" : ["posix", "mail"], "data" : ["wizard/posix_log_wizard.xml", "view/posix_log_view.xml", "data/log_facility.xml", "menu.xml", "security.xml" ], "auto_install" : False, "installable": True }
agpl-3.0
kaplanoah/wdiportal
db/migrate/20140208080528_create_projects.rb
229
class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :title t.string :url t.string :technology t.string :description t.timestamps end end end
agpl-3.0
gnosygnu/xowa_android
_140_dbs/src/main/java/gplx/dbs/qrys/Db_qry_delete.java
1083
package gplx.dbs.qrys; import gplx.*; import gplx.dbs.*; import gplx.core.criterias.*; import gplx.dbs.sqls.*; public class Db_qry_delete implements Db_qry { Db_qry_delete(String base_table, Criteria where) {this.base_table = base_table; this.where = where;} public int Tid() {return Db_qry_.Tid_delete;} public boolean Exec_is_rdr() {return Bool_.N;} public String Base_table() {return base_table;} private final String base_table; public String To_sql__exec(Sql_qry_wtr wtr) {return wtr.To_sql_str(this, false);} public Criteria Where() {return where;} private final Criteria where; public int Exec_qry(Db_conn conn) {return conn.Exec_qry(this);} public static Db_qry_delete new_all_(String tbl) {return new Db_qry_delete(tbl, Criteria_.All);} public static Db_qry_delete new_(String tbl, String... where) {return new Db_qry_delete(tbl, Db_crt_.eq_many_(where));} public static Db_qry_delete new_(String tbl, Criteria where) {return new Db_qry_delete(tbl, where);} public static final Criteria Where__null = null; }
agpl-3.0
splicemachine/spliceengine
db-testing/src/test/java/com/splicemachine/dbTesting/functionTests/tests/lang/AggregateClassLoadingTest.java
6642
/* * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. * * Some parts of this source code are based on Apache Derby, and the following notices apply to * Apache Derby: * * Apache Derby is a subproject of the Apache DB project, and is licensed under * the Apache License, Version 2.0 (the "License"); you may not use these files * except in compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Splice Machine, Inc. has modified the Apache Derby code in this file. * * All such Splice Machine modifications are Copyright 2012 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.dbTesting.functionTests.tests.lang; import java.net.URL; import java.net.URLClassLoader; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import junit.framework.TestSuite; import com.splicemachine.dbTesting.junit.BaseJDBCTestCase; import com.splicemachine.dbTesting.junit.CleanDatabaseTestSetup; import com.splicemachine.dbTesting.junit.JDBC; import com.splicemachine.dbTesting.junit.SecurityManagerSetup; /** * Test for ensuring the aggregate implementation classes are loaded correctly, * even when the context class loader loads Derby engine classes as well. This * is a typical situation we have seen with J2EE servers where Derby may be in * the application WAR and provided as a system service by the container. <BR> * Jira issue DERBY-997 <BR> * Assumes embedded and only needs to be run in embedded, since all class * loading happens on the engine side. */ public class AggregateClassLoadingTest extends BaseJDBCTestCase { /** * Basic constructor. */ public AggregateClassLoadingTest(String name) { super(name); } /** * Sets the auto commit to false. */ protected void initializeConnection(Connection conn) throws SQLException { conn.setAutoCommit(false); } /** * Returns the implemented tests. * * @return An instance of <code>Test</code> with the implemented tests to * run. */ public static Test suite() { /* this test creates a class loader, adding that permission to * derbyTesting.jar would mean that permission was granted all * the way up the stack to the db engine. Thus increasing * the chance that incorrectly a privileged block could be dropped * but the tests continue to pass. */ return SecurityManagerSetup.noSecurityManager( new CleanDatabaseTestSetup( new TestSuite(AggregateClassLoadingTest.class, "AggregateClassLoadingTest")) { /** * Save the class loader upon entry to the * suite, some JVM's install the main loader * as the context loader. */ private ClassLoader originalLoader; protected void setUp() throws Exception { originalLoader = Thread.currentThread().getContextClassLoader(); super.setUp(); } protected void tearDown() throws Exception { Thread.currentThread().setContextClassLoader(originalLoader); super.tearDown(); } /** * @see com.splicemachine.dbTesting.junit.CleanDatabaseTestSetup#decorateSQL(java.sql.Statement) */ protected void decorateSQL(Statement s) throws SQLException { s.execute("create table t (i int)"); s.execute("insert into t values 1,2,3,4,5,6,null,4,5,456,2,4,6,7,2144,44,2,-2,4"); /* * Find the location of the code for the Derby * connection. The rest of the engine will be at * the same location! */ URL derbyURL = s.getConnection().getClass().getProtectionDomain().getCodeSource() .getLocation(); /* * Create a new loader that loads from the same * location as the engine. Create it without a * parent, otherwise the parent will be the * class loader of this class which is most * likely the same as the engine. Since the * class loader delegates to its parent first * the bug would not show, as all the db * engine classes would be from a single loader. */ URLClassLoader cl = new URLClassLoader(new URL[] { derbyURL }, null); Thread.currentThread().setContextClassLoader(cl); super.decorateSQL(s); } }); } public void testAggregateMAX() throws SQLException { testAggregate("select MAX(i) from t"); } public void testAggregateMIN() throws SQLException { testAggregate("select MIN(i) from t"); } public void testAggregateAVG() throws SQLException { testAggregate("select AVG(i) from t"); } public void testAggregateCOUNT() throws SQLException { testAggregate("select COUNT(i) from t"); } public void testAggregateCOUNT2() throws SQLException { testAggregate("select COUNT(*) from t"); } /** * Just run and display the aggregates result. * * Test some aggregates, their generated class will attempt * to load the internal aggregate through the context loader * first, and then any remaining loader. */ private void testAggregate(String query) throws SQLException { Statement s = createStatement(); JDBC.assertDrainResults(s.executeQuery(query), 1); s.close(); } }
agpl-3.0
djoudi/otrs-gitimport-test
var/httpd/htdocs/js/Core.Agent.Dashboard.js
3808
// -- // Core.Agent.Dashboard.js - provides the special module functions for the dashboard // Copyright (C) 2001-2011 OTRS AG, http://otrs.org/ // -- // $Id: Core.Agent.Dashboard.js,v 1.5 2011-02-17 21:30:59 en Exp $ // -- // This software comes with ABSOLUTELY NO WARRANTY. For details, see // the enclosed file COPYING for license information (AGPL). If you // did not receive this file, see http://www.gnu.org/licenses/agpl.txt. // -- "use strict"; var Core = Core || {}; Core.Agent = Core.Agent || {}; /** * @namespace * @exports TargetNS as Core.Agent.Dashboard * @description * This namespace contains the special module functions for the Dashboard. */ Core.Agent.Dashboard = (function (TargetNS) { /** * @function * @return nothing * This function initializes the special module functions */ TargetNS.Init = function () { Core.UI.DnD.Sortable( $('.SidebarColumn'), { Handle: '.Header h2', Items: '.CanDrag', Placeholder: 'DropPlaceholder', Tolerance: 'pointer', Distance: 15, Opacity: 0.6, Update: function (event, ui) { var url = 'Action=' + Core.Config.Get('Action') + ';Subaction=UpdatePosition;'; $('.CanDrag').each( function (i) { url = url + ';Backend=' + $(this).attr('id'); } ); Core.AJAX.FunctionCall( Core.Config.Get('CGIHandle'), url, function () {} ); } } ); Core.UI.DnD.Sortable( $('.ContentColumn'), { Handle: '.Header h2', Items: '.CanDrag', Placeholder: 'DropPlaceholder', Tolerance: 'pointer', Distance: 15, Opacity: 0.6, Update: function (event, ui) { var url = 'Action=' + Core.Config.Get('Action') + ';Subaction=UpdatePosition;'; $('.CanDrag').each( function (i) { url = url + ';Backend=' + $(this).attr('id'); } ); Core.AJAX.FunctionCall( Core.Config.Get('CGIHandle'), url, function () {} ); } } ); }; /** * @function * @return nothing * This function binds a click event on an html element to update the preferences of the given dahsboard widget * @param {jQueryObject} $ClickedElement The jQuery object of the element(s) that get the event listener * @param {string} ElementID The ID of the element whose content should be updated with the server answer * @param {jQueryObject} $Form The jQuery object of the form with the data for the server request */ TargetNS.RegisterUpdatePreferences = function ($ClickedElement, ElementID, $Form) { if (isJQueryObject($ClickedElement) && $ClickedElement.length) { $ClickedElement.click(function () { var URL = Core.Config.Get('Baselink') + Core.AJAX.SerializeForm($Form); Core.AJAX.ContentUpdate($('#' + ElementID), URL, function () { Core.UI.ToggleTwoContainer($('#' + ElementID + '-setting'), $('#' + ElementID)); Core.UI.Table.InitCSSPseudoClasses(); }); return false; }); } }; return TargetNS; }(Core.Agent.Dashboard || {}));
agpl-3.0
gdi2290/rethinkdb
src/clustering/administration/jobs/manager.hpp
2297
// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef CLUSTERING_ADMINISTRATION_JOBS_MANAGER_HPP_ #define CLUSTERING_ADMINISTRATION_JOBS_MANAGER_HPP_ #include <string> #include <map> #include <set> #include "clustering/administration/jobs/report.hpp" #include "concurrency/one_per_thread.hpp" #include "containers/archive/stl_types.hpp" #include "containers/uuid.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/serialize_macros.hpp" class jobs_manager_business_card_t { public: typedef mailbox_t<void(std::vector<job_report_t>)> return_mailbox_t; typedef mailbox_t<void(return_mailbox_t::address_t)> get_job_reports_mailbox_t; typedef mailbox_t<void(uuid_u)> job_interrupt_mailbox_t; get_job_reports_mailbox_t::address_t get_job_reports_mailbox_address; job_interrupt_mailbox_t::address_t job_interrupt_mailbox_address; }; RDB_DECLARE_SERIALIZABLE(jobs_manager_business_card_t); class rdb_context_t; class reactor_driver_t; class jobs_manager_t { public: explicit jobs_manager_t(mailbox_manager_t *mailbox_manager, server_id_t const &server_id); typedef jobs_manager_business_card_t business_card_t; jobs_manager_business_card_t get_business_card(); // The `jobs_manager_t` object is constructed before either the `rdb_context_t` or // `reactor_driver_t` is constructed in `main/serve.cc`, thus the pointers to the // respective objects are set once they are constructed. void set_rdb_context(rdb_context_t *); void set_reactor_driver(reactor_driver_t *); private: static const uuid_u base_sindex_id; static const uuid_u base_disk_compaction_id; static const uuid_u base_backfill_id; void on_get_job_reports( UNUSED signal_t *interruptor, business_card_t::return_mailbox_t::address_t const &reply_address); void on_job_interrupt(UNUSED signal_t *interruptor, uuid_u const &id); mailbox_manager_t *mailbox_manager; business_card_t::get_job_reports_mailbox_t get_job_reports_mailbox; business_card_t::job_interrupt_mailbox_t job_interrupt_mailbox; server_id_t server_id; rdb_context_t *rdb_context; reactor_driver_t *reactor_driver; DISABLE_COPYING(jobs_manager_t); }; #endif /* CLUSTERING_ADMINISTRATION_JOBS_MANAGER_HPP_ */
agpl-3.0
arrivu/hiring-site
app/controllers/pseudonym_sessions_controller.rb
27576
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # class PseudonymSessionsController < ApplicationController protect_from_forgery :except => [:create, :destroy, :saml_consume, :oauth2_token] before_filter :forbid_on_files_domain, :except => [ :clear_file_session ] before_filter :require_password_session, :only => [ :otp_login, :disable_otp_login ] before_filter :require_user, :only => [ :otp_login ] def new if @current_user && !params[:re_login] && !params[:confirm] && !params[:expected_user_id] && !session[:used_remember_me_token] redirect_to dashboard_url return end if params[:needs_cookies] == '1' @needs_cookies = true return render(:template => 'shared/unauthorized', :layout => 'application', :status => :unauthorized) end session[:expected_user_id] = params[:expected_user_id].to_i if params[:expected_user_id] session[:confirm] = params[:confirm] if params[:confirm] session[:enrollment] = params[:enrollment] if params[:enrollment] if @current_pseudonym params[:pseudonym_session] ||= {} params[:pseudonym_session][:unique_id] ||= @current_pseudonym.unique_id end @pseudonym_session = PseudonymSession.new @headers = false @is_delegated = @domain_root_account.delegated_authentication? && !@domain_root_account.ldap_authentication? && !params[:canvas_login] @is_cas = @domain_root_account.cas_authentication? && @is_delegated @is_saml = @domain_root_account.saml_authentication? && @is_delegated if @is_cas && !params[:no_auto] if params[:ticket] # handle the callback from CAS logger.info "Attempting CAS login with ticket #{params[:ticket]} in account #{@domain_root_account.id}" st = CASClient::ServiceTicket.new(params[:ticket], cas_login_url) begin cas_client.validate_service_ticket(st) rescue => e logger.warn "Failed to validate CAS ticket: #{e.inspect}" flash[:delegated_message] = t 'errors.login_error', "There was a problem logging in at %{institution}", :institution => @domain_root_account.display_name redirect_to cas_login_url(:no_auto=>'true') return end if st.is_valid? @pseudonym = nil @pseudonym = @domain_root_account.pseudonyms.custom_find_by_unique_id(st.response.user) if @pseudonym # Successful login and we have a user @domain_root_account.pseudonym_sessions.create!(@pseudonym, false) session[:cas_login] = true @user = @pseudonym.login_assertions_for_user successful_login(@user, @pseudonym) return else logger.warn "Received CAS login for unknown user: #{st.response.user}" reset_session session[:delegated_message] = t 'errors.no_matching_user', "Canvas doesn't have an account for user: %{user}", :user => st.response.user redirect_to(cas_client.logout_url(cas_login_url :no_auto => true)) return end else logger.warn "Failed CAS login attempt." flash[:delegated_message] = t 'errors.login_error', "There was a problem logging in at %{institution}", :institution => @domain_root_account.display_name redirect_to cas_login_url(:no_auto=>'true') return end end initiate_cas_login(cas_client) elsif @is_saml && !params[:no_auto] if params[:account_authorization_config_id] if aac = @domain_root_account.account_authorization_configs.find_by_id(params[:account_authorization_config_id]) initiate_saml_login(request.host_with_port, aac) else message = t('errors.login_errors.no_config_for_id', "The Canvas account has no authentication configuration with that id") if @domain_root_account.auth_discovery_url redirect_to @domain_root_account.auth_discovery_url + "?message=#{URI.escape message}" else flash[:delegated_message] = message redirect_to login_url(:no_auto=>'true') end end else if @domain_root_account.auth_discovery_url redirect_to @domain_root_account.auth_discovery_url else initiate_saml_login(request.host_with_port) end end else flash[:delegated_message] = session.delete :delegated_message if session[:delegated_message] maybe_render_mobile_login end end def maybe_render_mobile_login(status = nil) if params[:mobile] || request.user_agent.to_s =~ /ipod|iphone|ipad|Android/i @login_handle_name = @domain_root_account.login_handle_name rescue AccountAuthorizationConfig.default_login_handle_name @login_handle_is_email = @login_handle_name == AccountAuthorizationConfig.default_login_handle_name @shared_js_vars = { :GOOGLE_ANALYTICS_KEY => Setting.get_cached('google_analytics_key', nil), :RESET_SENT => t("password_confirmation_sent", "Password confirmation sent. Make sure you check your spam box."), :RESET_ERROR => t("password_confirmation_error", "Error sending request.") } render :template => 'pseudonym_sessions/mobile_login', :layout => false, :status => status else @request = request render :action => 'new', :status => status end end def create # reset the session id cookie to prevent session fixation. reset_session_for_login # Try to use authlogic's built-in login approach first @pseudonym_session = @domain_root_account.pseudonym_sessions.new(params[:pseudonym_session]) @pseudonym_session.remote_ip = request.remote_ip found = @pseudonym_session.save # look for LDAP pseudonyms where we get the unique_id back from LDAP if !found && !@pseudonym_session.attempted_record @domain_root_account.account_authorization_configs.each do |aac| next unless aac.ldap_authentication? next unless aac.identifier_format.present? res = aac.ldap_bind_result(params[:pseudonym_session][:unique_id], params[:pseudonym_session][:password]) unique_id = res.first[aac.identifier_format].first if res if unique_id && pseudonym = @domain_root_account.pseudonyms.active.by_unique_id(unique_id).first pseudonym.instance_variable_set(:@ldap_result, res.first) @pseudonym_session = PseudonymSession.new(pseudonym, params[:pseudonym_session][:remember_me] == "1") found = @pseudonym_session.save break end end end if !found && params[:pseudonym_session] pseudonym = Pseudonym.authenticate(params[:pseudonym_session], @domain_root_account.trusted_account_ids, request.remote_ip) if pseudonym && pseudonym != :too_many_attempts @pseudonym_session = PseudonymSession.new(pseudonym, params[:pseudonym_session][:remember_me] == "1") found = @pseudonym_session.save end end if pseudonym == :too_many_attempts || @pseudonym_session.too_many_attempts? unsuccessful_login t('errors.max_attempts', "Too many failed login attempts. Please try again later or contact your system administrator."), true return end @pseudonym = @pseudonym_session && @pseudonym_session.record # If the user's account has been deleted, feel free to share that information if @pseudonym && (!@pseudonym.user || @pseudonym.user.unavailable?) unsuccessful_login t('errors.user_deleted', "That user account has been deleted. Please contact your system administrator to have your account re-activated."), true return end # If the user is registered and logged in, redirect them to their dashboard page if found # Call for some cleanups that should be run when a user logs in @user = @pseudonym.login_assertions_for_user successful_login(@user, @pseudonym) # Otherwise re-render the login page to show the error else unsuccessful_login t('errors.invalid_credentials', "Incorrect username and/or password") end end def destroy # the saml message has to survive a couple redirects and reset_session calls message = session[:delegated_message] @pseudonym_session.destroy rescue true if @domain_root_account.saml_authentication? and session[:saml_unique_id] # logout at the saml identity provider # once logged out it'll be redirected to here again if aac = @domain_root_account.account_authorization_configs.find_by_id(session[:saml_aac_id]) settings = aac.saml_settings(request.host_with_port) request = Onelogin::Saml::LogOutRequest.new(settings, session) forward_url = request.generate_request if aac.debugging? && aac.debug_get(:logged_in_user_id) == @current_user.id aac.debug_set(:logout_request_id, request.id) aac.debug_set(:logout_to_idp_url, forward_url) aac.debug_set(:logout_to_idp_xml, request.request_xml) aac.debug_set(:debugging, t('debug.logout_redirect', "LogoutRequest sent to IdP")) end reset_session session[:delegated_message] = message if message redirect_to(forward_url) return else reset_session flash[:message] = t('errors.logout_errors.no_idp_found', "Canvas was unable to log you out at your identity provider") end elsif @domain_root_account.cas_authentication? and session[:cas_login] reset_session session[:delegated_message] = message if message redirect_to(cas_client.logout_url(cas_login_url)) return else reset_session flash[:delegated_message] = message if message end flash[:logged_out] = true respond_to do |format| session.delete(:return_to) if @domain_root_account.delegated_authentication? && !@domain_root_account.ldap_authentication? format.html { redirect_to login_url(:no_auto=>'true') } else format.html { redirect_to login_url } end format.json { render :json => "OK".to_json, :status => :ok } end end def clear_file_session session.delete('file_access_user_id') session.delete('file_access_expiration') render :text => "ok" end def saml_consume if @domain_root_account.saml_authentication? && params[:SAMLResponse] # Break up the SAMLResponse into chunks for logging (a truncated version was probably already # logged with the request when using syslog) chunks = params[:SAMLResponse].scan(/.{1,1024}/) chunks.each_with_index do |chunk, idx| logger.info "SAMLResponse[#{idx+1}/#{chunks.length}] #{chunk}" end response = saml_response(params[:SAMLResponse]) if @domain_root_account.account_authorization_configs.count > 1 aac = @domain_root_account.account_authorization_configs.find_by_idp_entity_id(response.issuer) if aac.nil? logger.error "Attempted SAML login for #{response.issuer} on account without that IdP" @pseudonym_session.destroy rescue true reset_session if @domain_root_account.auth_discovery_url message = t('errors.login_errors.unrecognized_idp', "Canvas did not recognize your identity provider") redirect_to @domain_root_account.auth_discovery_url + "?message=#{URI.escape message}" else flash[:delegated_message] = t 'errors.login_errors.no_idp_set', "The institution you logged in from is not configured on this account." redirect_to login_url(:no_auto=>'true') end return end else aac = @domain_root_account.account_authorization_config end settings = aac.saml_settings(request.host_with_port) response.process(settings) unique_id = nil if aac.login_attribute == 'nameid' unique_id = response.name_id elsif aac.login_attribute == 'eduPersonPrincipalName' unique_id = response.saml_attributes["eduPersonPrincipalName"] elsif aac.login_attribute == 'eduPersonPrincipalName_stripped' unique_id = response.saml_attributes["eduPersonPrincipalName"] unique_id = unique_id.split('@', 2)[0] end logger.info "Attempting SAML login for #{aac.login_attribute} #{unique_id} in account #{@domain_root_account.id}" debugging = aac.debugging? && aac.debug_get(:request_id) == response.in_response_to if debugging aac.debug_set(:debugging, t('debug.redirect_from_idp', "Recieved LoginResponse from IdP")) aac.debug_set(:idp_response_encoded, params[:SAMLResponse]) aac.debug_set(:idp_response_xml_encrypted, response.xml) aac.debug_set(:idp_response_xml_decrypted, response.decrypted_document.to_s) aac.debug_set(:idp_in_response_to, response.in_response_to) aac.debug_set(:idp_login_destination, response.destination) aac.debug_set(:fingerprint_from_idp, response.fingerprint_from_idp) aac.debug_set(:login_to_canvas_success, 'false') end login_error_message = t 'errors.login_error', "There was a problem logging in at %{institution}", :institution => @domain_root_account.display_name if response.is_valid? aac.debug_set(:is_valid_login_response, 'true') if debugging if response.success_status? @pseudonym = @domain_root_account.pseudonyms.custom_find_by_unique_id(unique_id) if @pseudonym # We have to reset the session again here -- it's possible to do a # SAML login without hitting the #new action, depending on the # school's setup. reset_session_for_login #Successful login and we have a user @domain_root_account.pseudonym_sessions.create!(@pseudonym, false) @user = @pseudonym.login_assertions_for_user if debugging aac.debug_set(:login_to_canvas_success, 'true') aac.debug_set(:logged_in_user_id, @user.id) end session[:saml_unique_id] = unique_id session[:name_id] = response.name_id session[:name_qualifier] = response.name_qualifier session[:session_index] = response.session_index session[:return_to] = params[:RelayState] if params[:RelayState] && params[:RelayState] =~ /\A\/(\z|[^\/])/ session[:saml_aac_id] = aac.id successful_login(@user, @pseudonym) else message = "Received SAML login request for unknown user: #{unique_id}" logger.warn message aac.debug_set(:canvas_login_fail_message, message) if debugging # the saml message has to survive a couple redirects session[:delegated_message] = t 'errors.no_matching_user', "Canvas doesn't have an account for user: %{user}", :user => unique_id redirect_to :action => :destroy end elsif response.auth_failure? message = "Failed to log in correctly at IdP" logger.warn message aac.debug_set(:canvas_login_fail_message, message) if debugging flash[:delegated_message] = login_error_message redirect_to login_url(:no_auto=>'true') elsif response.no_authn_context? message = "Attempted SAML login for unsupported authn_context at IdP." logger.warn message aac.debug_set(:canvas_login_fail_message, message) if debugging flash[:delegated_message] = login_error_message redirect_to login_url(:no_auto=>'true') else message = "Unexpected SAML status code - status code: #{response.status_code rescue ""} - Status Message: #{response.status_message rescue ""}" logger.warn message aac.debug_set(:canvas_login_fail_message, message) if debugging redirect_to login_url(:no_auto=>'true') end else if debugging aac.debug_set(:is_valid_login_response, 'false') aac.debug_set(:login_response_validation_error, response.validation_error) end logger.error "Failed to verify SAML signature." @pseudonym_session.destroy rescue true reset_session flash[:delegated_message] = login_error_message redirect_to login_url(:no_auto=>'true') end elsif !params[:SAMLResponse] logger.error "saml_consume request with no SAMLResponse parameter" @pseudonym_session.destroy rescue true reset_session flash[:delegated_message] = login_error_message redirect_to login_url(:no_auto=>'true') else logger.error "Attempted SAML login on non-SAML enabled account." @pseudonym_session.destroy rescue true reset_session flash[:delegated_message] = login_error_message redirect_to login_url(:no_auto=>'true') end end def saml_logout if @domain_root_account.saml_authentication? && params[:SAMLResponse] response = saml_logout_response(params[:SAMLResponse]) if aac = @domain_root_account.account_authorization_configs.find_by_idp_entity_id(response.issuer) settings = aac.saml_settings(request.host_with_port) response.process(settings) if aac.debugging? && aac.debug_get(:logout_request_id) == response.in_response_to aac.debug_set(:idp_logout_response_encoded, params[:SAMLResponse]) aac.debug_set(:idp_logout_response_xml_encrypted, response.xml) aac.debug_set(:idp_logout_in_response_to, response.in_response_to) aac.debug_set(:idp_logout_destination, response.destination) aac.debug_set(:debugging, t('debug.logout_redirect_from_idp', "Received LogoutResponse from IdP")) end end end redirect_to :action => :destroy end def cas_client return @cas_client if @cas_client config = { :cas_base_url => @domain_root_account.account_authorization_config.auth_base } @cas_client = CASClient::Client.new(config) end def saml_response(raw_response, settings=nil) response = Onelogin::Saml::Response.new(raw_response, settings) response.logger = logger response end def saml_logout_response(raw_response, settings=nil) response = Onelogin::Saml::LogoutResponse.new(raw_response, settings) response.logger = logger response end def forbid_on_files_domain if HostUrl.is_file_host?(request.host_with_port) reset_session return redirect_to dashboard_url(:host => HostUrl.default_host) end true end def otp_remember_me_cookie_domain ActionController::Base.session_options[:domain] end def otp_login(send_otp = false) if !@current_user.otp_secret_key || request.method == :get session[:pending_otp_secret_key] ||= ROTP::Base32.random_base32 end if session[:pending_otp_secret_key] && params[:otp_login].try(:[], :otp_communication_channel_id) @cc = @current_user.communication_channels.sms.unretired.find(params[:otp_login][:otp_communication_channel_id]) session[:pending_otp_communication_channel_id] = @cc.id send_otp = true end if session[:pending_otp_secret_key] && params[:otp_login].try(:[], :phone_number) path = "#{params[:otp_login][:phone_number].gsub(/[^\d]/, '')}@#{params[:otp_login][:carrier]}" @cc = @current_user.communication_channels.sms.by_path(path).first @cc ||= @current_user.communication_channels.sms.create!(:path => path) if @cc.retired? @cc.workflow_state = 'unconfirmed' @cc.save! end session[:pending_otp_communication_channel_id] = @cc.id send_otp = true end secret_key = session[:pending_otp_secret_key] || @current_user.otp_secret_key if send_otp @cc ||= @current_user.otp_communication_channel @cc.try(:send_later_if_production_enqueue_args, :send_otp!, { :priority => Delayed::HIGH_PRIORITY, :max_attempts => 1 }, ROTP::TOTP.new(secret_key).now) end return render :action => 'otp_login' unless params[:otp_login].try(:[], :verification_code) drift = 30 # give them 5 minutes to enter an OTP sent via SMS drift = 300 if session[:pending_otp_communication_channel_id] || (!session[:pending_otp_secret_key] && @current_user.otp_communication_channel_id) if ROTP::TOTP.new(secret_key).verify_with_drift(params[:otp_login][:verification_code], drift) if session[:pending_otp_secret_key] @current_user.otp_secret_key = session.delete(:pending_otp_secret_key) @current_user.otp_communication_channel_id = session.delete(:pending_otp_communication_channel_id) @current_user.otp_communication_channel.try(:confirm) @current_user.save! end if params[:otp_login][:remember_me] == '1' now = Time.now.utc self.cookies['canvas_otp_remember_me'] = { :value => @current_user.otp_secret_key_remember_me_cookie(now), :expires => now + 30.days, :domain => otp_remember_me_cookie_domain, :httponly => true, :secure => ActionController::Base.session_options[:secure], :path => '/login' } end if session.delete(:pending_otp) successful_login(@current_user, @current_pseudonym, true) else flash[:notice] = t 'notices.mfa_complete', "Multi-factor authentication configured" redirect_to settings_profile_url end else @cc ||= @current_user.otp_communication_channel if !session[:pending_otp_secret_key] flash.now[:error] = t 'errors.invalid_otp', "Invalid verification code, please try again" end end def disable_otp_login if params[:user_id] == 'self' @user = @current_user else @user = User.find(params[:user_id]) return unless @user == @current_user || authorized_action(@user, @current_user, :manage_logins) end return render_unauthorized_action if @user == @current_user && @user.mfa_settings == :required @user.otp_secret_key = nil @user.otp_communication_channel = nil @user.save! render :json => {} end def successful_login(user, pseudonym, otp_passed = false) @current_user = user @current_pseudonym = pseudonym otp_passed ||= cookies['canvas_otp_remember_me'] && @current_user.validate_otp_secret_key_remember_me_cookie(cookies['canvas_otp_remember_me']) if !otp_passed mfa_settings = @current_pseudonym.mfa_settings if (@current_user.otp_secret_key && mfa_settings == :optional) || mfa_settings == :required session[:pending_otp] = true return otp_login(true) end end respond_to do |format| if session[:oauth2] return redirect_to(oauth2_auth_confirm_url) elsif session[:course_uuid] && user && (course = Course.find_by_uuid_and_workflow_state(session[:course_uuid], "created")) claim_session_course(course, user) format.html { redirect_to(course_url(course, :login_success => '1')) } elsif session[:confirm] format.html { redirect_to(registration_confirmation_path(session.delete(:confirm), :enrollment => session.delete(:enrollment), :login_success => 1, :confirm => (user.id == session.delete(:expected_user_id) ? 1 : nil))) } else # the URL to redirect back to is stored in the session, so it's # assumed that if that URL is found rather than using the default, # they must have cookies enabled and we don't need to worry about # adding the :login_success param to it. format.html { redirect_back_or_default(dashboard_url(:login_success => '1')) } end format.json { render :json => pseudonym.to_json(:methods => :user_code), :status => :ok } end end def unsuccessful_login(message, refresh = false) respond_to do |format| flash[:error] = message format.html do if refresh redirect_to login_url else @errored = true @pre_registered = @user if @user && !@user.registered? @headers = false maybe_render_mobile_login :bad_request end end format.json do @pseudonym_session.errors.add('base', message) render :json => @pseudonym_session.errors.to_json, :status => :bad_request end end end def oauth2_auth if params[:code] || params[:error] # hopefully the user never sees this, since it's an oob response and the # browser should be closed automatically. but we'll at least display # something basic. return render() end provider = Canvas::Oauth::Provider.new(params[:client_id], params[:redirect_uri]) return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key? return render(:status => 400, :json => { :message => "invalid redirect_uri" }) unless provider.has_valid_redirect? session[:oauth2] = provider.session_hash if @current_pseudonym redirect_to oauth2_auth_confirm_url else redirect_to login_url(:canvas_login => params[:canvas_login]) end end def oauth2_confirm @provider = Canvas::Oauth::Provider.new(session[:oauth2][:client_id]) end def oauth2_accept # now generate the temporary code, and respond/redirect code = Canvas::Oauth::Token.generate_code_for(@current_user.global_id, session[:oauth2][:client_id]) final_oauth2_redirect(session[:oauth2][:redirect_uri], :code => code) session.delete(:oauth2) end def oauth2_deny final_oauth2_redirect(session[:oauth2][:redirect_uri], :error => "access_denied") session.delete(:oauth2) end def oauth2_token basic_user, basic_pass = ActionController::HttpAuthentication::Basic.user_name_and_password(request) if ActionController::HttpAuthentication::Basic.authorization(request) client_id = params[:client_id].presence || basic_user secret = params[:client_secret].presence || basic_pass provider = Canvas::Oauth::Provider.new(client_id) return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key? return render(:status => 400, :json => { :message => "invalid client_secret" }) unless provider.is_authorized_by?(secret) token = provider.token_for(params[:code]) return render(:status => 400, :json => { :message => "invalid code" }) unless token.is_for_valid_code? render :json => token.to_json end def oauth2_logout return render :json => { :message => "can't delete OAuth access token when not using an OAuth access token" }, :status => 400 unless @access_token @access_token.destroy render :json => {} end def final_oauth2_redirect(redirect_uri, opts = {}) if Canvas::Oauth::Provider.is_oob?(redirect_uri) redirect_to oauth2_auth_url(opts) else has_params = redirect_uri =~ %r{\?} redirect_to(redirect_uri + (has_params ? "&" : "?") + opts.to_query) end end end
agpl-3.0
jzinedine/CMDBuild
cmdbuild/src/main/java/org/cmdbuild/services/soap/connector/DomainDirection.java
511
package org.cmdbuild.services.soap.connector; public enum DomainDirection { DIRECT("directed"), INVERSE("inverted"); private final String direction; DomainDirection(final String direction) { this.direction = direction; } public String getDirection() { return this.direction; } public static DomainDirection getDirection(final String action) { if (DomainDirection.DIRECT.getDirection().equals(action)) { return DomainDirection.DIRECT; } else { return DomainDirection.INVERSE; } } }
agpl-3.0
gfcapalbo/website_chd
website_ecommerce_extensions/controllers/__init__.py
55
#from . import controllers #from . import website_sale
agpl-3.0
asm-products/chartspree
charts/app.py
6962
import flask from flask import request, url_for, render_template, redirect, Response # from paste.util.multidict import MultiDict import json import settings import log import os import hashlib import urlparse import re import redis import pygal from pygal import style import loremdata TEMPPATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') CHARTCSS = { 'svg': os.path.join(TEMPPATH, 'chartbase-svg.css'), 'png': os.path.join(TEMPPATH, 'chartbase-png.css'), } REDIS = redis.Redis.from_url(settings.REDIS_URL) COUNTER_KEY = lambda x: 'charts_domain_counter_%s' % x CHART_KEY = lambda x: 'charts_chart_counter_%s' % x def _loads(val): ''' Loads a string and returns a python datastructure. It ultimately calls json.loads() but handles some exceptions: - [] aren't needed around lists - list items can use single quotes - unquoted list items that don't evaluate to json objects are first wrapped in quotes Doesn't attempt to do anything smart with nested data structures or dictionaries. ''' def _b(val): return u"["+val+u"]" try: return json.loads(val) except ValueError: # try converting quotes try: val = val.replace(u"'", u'"') return json.loads(val) except ValueError: # try brackets try: return json.loads(_b(val)) except ValueError: # try brackets and quoting elements try: parts = val.split(u",") if len(parts) > 1: testval = _b(u",".join([u'"'+p+u'"' for p in parts])) return json.loads(testval) return val except ValueError: return val def renderchart(kind, fmt='svg'): # get chart kind try: chartnames = [n.lower() for n in pygal.graph.CHARTS_NAMES] name_idx = chartnames.index(kind.lower()) except ValueError: name_idx = 0 chart_kind = getattr(pygal, pygal.graph.CHARTS_NAMES[name_idx], pygal.Line) # get arguments and series data configs = dict((key[1:],_loads(val)) for key,val in request.args.items() if key.startswith('_')) series = dict((key,val) for key,val in request.args.items() if not key.startswith('_')) # set configs if 'style' in configs: if configs['style'].lower() == "dark": configs['style'] = style.DefaultStyle else: try: styles = [n.lower() for n in dir(style) if n.endswith('Style')] style_idx = styles.index(configs['style'].lower()) configs['style'] = getattr(style, dir(style)[style_idx]) except ValueError: del configs['style'] if 'labels' in configs and not 'x_labels' in configs: if type(configs['labels']) == list: configs['x_labels'] = [unicode(x) for x in configs['labels']] if 'width' in configs and type(configs['width']) in [str, unicode]: try: configs['width'] = json.loads(configs['width'].replace(u'px', u'')) except: pass if 'height' in configs and type(configs['height']) in [str, unicode]: try: configs['height'] = json.loads(configs['height'].replace(u'px', u'')) except: pass custom_style = style.Style( background='transparent', plot_background='rgba(0,0,0,0)' if kind.lower() == 'sparkline' else 'rgba(0,0,0,0.05)', foreground='#000', foreground_light='#000', foreground_dark='#000', colors=( 'rgb(12,55,149)', 'rgb(117,38,65)', 'rgb(228,127,0)', 'rgb(159,170,0)', 'rgb(149,12,12)') ) params = { 'label_font_size':18, 'major_label_font_size':18, 'legend_font_size':24, 'title_font_size':24, 'show_y_guides':False, 'show_x_guides':False, 'print_values':False, 'y_labels_major_count':3, 'show_minor_y_labels':False, 'style':custom_style, } params.update(configs) config = pygal.Config(no_prefix=True, **params) config.css.append(CHARTCSS[fmt]) # write out chart chart = chart_kind(config) for key, val in series.items(): try: parsed = _loads(val) if type(parsed) in [str,unicode] and parsed.lower().startswith(u'lorem_'): chart.add(key, loremdata.loremdata(parsed)) else: chart.add(key, _loads(val)) except ValueError: pass if kind.lower() == 'sparkline': rendered = chart.render_sparkline() else: rendered = chart.render() if fmt.lower() == 'png': import cairosvg rendered = cairosvg.svg2png(bytestring=rendered, dpi=72) # tracking if request.referrer: try: rparse = urlparse.urlparse(request.referrer) rhost = re.sub(r"\W", "_", rparse.netloc) except: rhost = re.sub(r"\W", "_", request.referrer.split(u"://")[1]) REDIS.incr(COUNTER_KEY(rhost)) charturl = re.sub(r"\W", "_", request.url.split(u"://")[1]) REDIS.incr(CHART_KEY(charturl)) if fmt.lower() == 'png': return Response(rendered, mimetype='image/png') else: return Response(rendered, mimetype='image/svg+xml') def print_stats(): print("Domains ---------------") domains = [] for k in REDIS.keys(COUNTER_KEY(u'*')): if not k.startswith(COUNTER_KEY(u'reloaderdraft')): domains.append((k.replace(COUNTER_KEY(u''),u''), int(REDIS.get(k)))) for i, v in enumerate(sorted(domains, key=lambda x: x[1])): print("%4d: %s, %d" % (i, v[0].replace(u'_',u'.'), v[1])) # print("Charts ----------------") # charts = [] # for k in REDIS.keys(CHART_KEY(u'*')): # charts.append((k, int(REDIS.get(k)))) # for i, v in enumerate(sorted(charts, key=lambda x: x[1])): # print("%4d: %s, %d" % (i, v[0], v[1])) def index(): return flask.render_template('index.html', is_redirect=request.args.get('redirected')) def favicon(): return flask.redirect(url_for('static', filename='img/favicon.ico')) def configure_routes(app): app.add_url_rule('/', 'index', view_func=index, methods=['GET']) app.add_url_rule('/favicon.ico', view_func=favicon) app.add_url_rule('/<kind>.<fmt>', 'send', view_func=renderchart, methods=['GET']) def create_app(): app = flask.Flask(__name__) app.config.from_object(settings) configure_routes(app) @app.errorhandler(500) def internal_error(e): return render_template('500.html'), 500 @app.errorhandler(404) def page_not_found(e): return render_template('error.html', title='Oops, page not found'), 404 app.jinja_env.filters['nl2br'] = lambda val: val.replace('\n','<br>\n') return app
agpl-3.0
ubtue/ub_tools
cpp/cgi_progs/translator_statistics.cc
11693
/** \file translator_statistics.cc * \brief A CGI-tool for showing translator statistics. * \author andreas-ub */ /* Copyright (C) 2016-2021, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <set> #include <sstream> #include <string> #include "DbConnection.h" #include "DbResultSet.h" #include "DbRow.h" #include "EmailSender.h" #include "HtmlUtil.h" #include "IniFile.h" #include "StringUtil.h" #include "Template.h" #include "UBTools.h" #include "UrlUtil.h" #include "WebUtil.h" #include "util.h" namespace { const std::string CONF_FILE_PATH(UBTools::GetTuelibPath() + "translations.conf"); enum Category { VUFIND, KEYWORDS }; DbResultSet ExecSqlAndReturnResultsOrDie(const std::string &select_statement, DbConnection * const db_connection) { db_connection->queryOrDie(select_statement); return db_connection->getLastResultSet(); } void GetTranslatorFullNames(const IniFile &ini_file, std::vector<std::string> * const rows) { rows->clear(); std::map<std::string, std::set<std::string>> languages_to_translators; std::map<std::string, std::string> translator_ids_to_fullnames; std::string section_translator_languages = "TranslationLanguages"; std::string section_translator_full_names = "FullName"; std::vector<std::string> translator_ids = ini_file.getSectionEntryNames(section_translator_languages); std::vector<std::string> translator_fullname_ids = ini_file.getSectionEntryNames(section_translator_full_names); for (auto translator_fullname_id : translator_fullname_ids) translator_ids_to_fullnames.emplace(translator_fullname_id, ini_file.getString(section_translator_full_names, translator_fullname_id)); for (auto translator_id : translator_ids) { std::string translator_languages_value = ini_file.getString(section_translator_languages, translator_id); std::vector<std::string> translator_languages; StringUtil::SplitThenTrimWhite(translator_languages_value, ",", &translator_languages); std::string translator_id_and_name = translator_id; if (translator_ids_to_fullnames.find(translator_id) != translator_ids_to_fullnames.end()) translator_id_and_name += " (" + translator_ids_to_fullnames.find(translator_id)->second + ")"; for (auto translator_language : translator_languages) { if (languages_to_translators.find(translator_language) == languages_to_translators.end()) { std::set<std::string> set_translator_id_and_name = { translator_id_and_name }; languages_to_translators.emplace(translator_language, set_translator_id_and_name); } else languages_to_translators.find(translator_language)->second.emplace(translator_id_and_name); } } for (auto language_to_translator : languages_to_translators) rows->emplace_back("<tr><td>" + language_to_translator.first + "</td><td>" + StringUtil::Join(language_to_translator.second, ", ") + "</td></tr>"); } void GetSubsystemStatisticsAsHTMLRowsFromDatabase(DbConnection &db_connection, const std::string &target, std::vector<std::string> * const rows, const std::string &start_date, const std::string &end_date) { std::string id = (target == "vufind" ? "token" : "ppn"); std::string table_name = (target == "vufind" ? "vufind_translations" : "keyword_translations"); unsigned total_number; std::string query_total_number("SELECT COUNT(DISTINCT(" + id + ")) AS total_number FROM " + table_name + ";"); DbResultSet result_set_total_number(ExecSqlAndReturnResultsOrDie(query_total_number, &db_connection)); while (const auto db_row = result_set_total_number.getNextRow()) total_number = std::stoi(db_row["total_number"]); std::map<std::string, unsigned> map_translated; std::string query_translated("SELECT language_code,COUNT(DISTINCT(" + id + ")) AS translated_number FROM " + table_name + " GROUP BY language_code;"); DbResultSet result_set_translated(ExecSqlAndReturnResultsOrDie(query_translated, &db_connection)); while (const auto db_row = result_set_translated.getNextRow()) map_translated.emplace(db_row["language_code"], std::stoi(db_row["translated_number"])); rows->clear(); std::string query("SELECT language_code,COUNT(distinct " + id + ") AS number FROM " + table_name + " WHERE next_version_id IS NULL AND prev_version_id IS NOT NULL AND create_timestamp >= '" + start_date + "' AND create_timestamp <= '" + end_date + " 23:59:59" + "' GROUP BY language_code;"); DbResultSet result_set(ExecSqlAndReturnResultsOrDie(query, &db_connection)); while (const auto db_row = result_set.getNextRow()) { std::string language_code(db_row["language_code"]); std::string recently_number(db_row["number"]); std::string untranslated_number = "n.a."; auto elem = map_translated.find(language_code); if (elem != map_translated.end()) untranslated_number = std::to_string(total_number - elem->second); rows->emplace_back("<tr><td>" + language_code + "</td><td>" + recently_number + "</td><td>" + untranslated_number + "</td></tr>"); } } void GetVuFindStatisticsNewEntriesFromDatabase(DbConnection &db_connection, std::string * const number_new_entries, const std::string &start_date, const std::string &end_date) { std::string query("SELECT token FROM vufind_translations WHERE create_timestamp>='" + start_date + "' AND create_timestamp<='" + end_date + " 23:59:59" + "' AND token IN (SELECT token FROM vufind_translations GROUP BY token HAVING COUNT(*)=1);"); DbResultSet result_set(ExecSqlAndReturnResultsOrDie(query, &db_connection)); number_new_entries->clear(); unsigned counter(0); while (const auto db_row = result_set.getNextRow()) { // could use result_set.size(), but prob. more information requested in web gui std::string language_code(db_row["token"]); ++counter; } (*number_new_entries) = std::to_string(counter); } void GetKeyWordStatisticsNewEntriesFromDatabase(DbConnection &db_connection, std::string * const number_new_entries, const std::string &start_date, const std::string &end_date) { std::string query("SELECT ppn FROM keyword_translations WHERE create_timestamp>='" + start_date + "' AND create_timestamp<='" + end_date + " 23:59:59" + "' AND ppn IN (SELECT ppn FROM keyword_translations GROUP BY ppn HAVING COUNT(*)=1);"); DbResultSet result_set(ExecSqlAndReturnResultsOrDie(query, &db_connection)); number_new_entries->clear(); unsigned counter(0); while (const auto db_row = result_set.getNextRow()) { // could use result_set.size(), but prob. more information requested in web gui std::string language_code(db_row["ppn"]); ++counter; } (*number_new_entries) = std::to_string(counter); } void ShowFrontPage(DbConnection &db_connection, const IniFile &ini_file, const std::string &target, const std::string &start_date, const std::string &end_date) { Template::Map names_to_values_map; std::vector<std::string> vufind_rows; std::vector<std::string> keyword_rows; std::vector<std::string> assigned_translator_fullnames; std::string number_new_entries_vufind, number_new_entries_keyword; GetSubsystemStatisticsAsHTMLRowsFromDatabase(db_connection, "vufind", &vufind_rows, start_date, end_date); GetVuFindStatisticsNewEntriesFromDatabase(db_connection, &number_new_entries_vufind, start_date, end_date); GetSubsystemStatisticsAsHTMLRowsFromDatabase(db_connection, "keywords", &keyword_rows, start_date, end_date); GetKeyWordStatisticsNewEntriesFromDatabase(db_connection, &number_new_entries_keyword, start_date, end_date); GetTranslatorFullNames(ini_file, &assigned_translator_fullnames); names_to_values_map.insertArray("vufind_rows", vufind_rows); names_to_values_map.insertArray("keyword_rows", keyword_rows); names_to_values_map.insertScalar("target_translation_scope", target); names_to_values_map.insertScalar("number_new_entries_vufind", number_new_entries_vufind); names_to_values_map.insertScalar("number_new_entries_keyword", number_new_entries_keyword); names_to_values_map.insertScalar("start_date", start_date); names_to_values_map.insertScalar("end_date", end_date); names_to_values_map.insertArray("assigned_translator_fullnames", assigned_translator_fullnames); std::ifstream translator_statistics_html(UBTools::GetTuelibPath() + "translate_chainer/translator_statistics.html", std::ios::binary); Template::ExpandTemplate(translator_statistics_html, std::cout, names_to_values_map); } // \return the current day as a range endpoint inline std::string Now(unsigned negative_month_offset = 0) { unsigned year, month, day; TimeUtil::GetCurrentDate(&year, &month, &day); if (negative_month_offset > 0) { int signed_month = month - (negative_month_offset % 12); if (signed_month < 1) { year = year - ((negative_month_offset / 12) + 1); month = (signed_month + 12); } } return StringUtil::ToString(year, /* radix = */ 10, /* width = */ 4, /* padding_char = */ '0') + "-" + StringUtil::ToString(month, /* radix = */ 10, /* width = */ 2, /* padding_char = */ '0') + "-" + StringUtil::ToString(day, /* radix = */ 10, /* width = */ 2, /* padding_char = */ '0'); } } // unnamed namespace int Main(int argc, char *argv[]) { std::multimap<std::string, std::string> cgi_args; WebUtil::GetAllCgiArgs(&cgi_args, argc, argv); const IniFile ini_file(CONF_FILE_PATH); const std::string sql_database(ini_file.getString("Database", "sql_database")); const std::string sql_username(ini_file.getString("Database", "sql_username")); const std::string sql_password(ini_file.getString("Database", "sql_password")); DbConnection db_connection(DbConnection::MySQLFactory(sql_database, sql_username, sql_password)); const std::string translation_target(WebUtil::GetCGIParameterOrDefault(cgi_args, "target", "keywords")); std::string start_date(WebUtil::GetCGIParameterOrDefault(cgi_args, "start_date", Now(6))); if (start_date.empty()) start_date = Now(6); std::string end_date(WebUtil::GetCGIParameterOrDefault(cgi_args, "end_date", Now())); if (end_date.empty()) end_date = Now(); std::cout << "Content-Type: text/html; charset=utf-8\r\n\r\n"; ShowFrontPage(db_connection, ini_file, translation_target, start_date, end_date); return EXIT_SUCCESS; }
agpl-3.0
asrulhadi/wap
includes_wap/wap.php
315
<?php /* * @file : wap.php * @created : Apr 28, 2014 * @author : Ibéria Medeiros <ibemed at gmail.com> * @version : v1.0 * @license : GNU Public License v2.0 http://www.gnu.org/licenses/gpl-2.0.html * @desc : PHP WAP include file. */ include('wap_XSS.php'); include('wap_CodeInjection.php'); ?>
agpl-3.0
hsgr/medialibre
wp-content/plugins/wp-statistics/includes/functions/export.php
2723
<?php function wp_statistics_export_data() { global $WP_Statistics, $wpdb; if ( ! isset( $_POST['table-to-export'] ) or ! isset( $_POST['export-file-type'] ) ) { return; } $manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) ); if ( current_user_can( $manage_cap ) ) { $table = $_POST['table-to-export']; $type = $_POST['export-file-type']; // Validate the table name the user passed to us. if ( ! ( $table == "useronline" || $table == "visit" || $table == "visitor" || $table == "exclusions" || $table == "pages" || $table == "search" ) ) { $table = false; } // Validate the file type the user passed to us. if ( ! ( $type == "xml" || $type == "csv" || $type == "tsv" ) ) { $table = false; } if ( $table && $type ) { require( WP_Statistics::$reg['plugin-dir'] . 'includes/github/elidickinson/php-export-data/php-export-data.class.php' ); $file_name = 'wp-statistics' . '-' . $WP_Statistics->Current_Date( 'Y-m-d-H-i' ); switch ( $type ) { case 'xml': $exporter = new ExportDataExcel( 'browser', "{$file_name}.xml" ); break; case 'csv': $exporter = new ExportDataCSV( 'browser', "{$file_name}.csv" ); break; case 'tsv': $exporter = new ExportDataTSV( 'browser', "{$file_name}.tsv" ); break; } $exporter->initialize(); // We need to limit the number of results we retrieve to ensure we don't run out of memory $query_base = "SELECT * FROM {$wpdb->prefix}statistics_{$table}"; $query = $query_base . ' LIMIT 0,1000'; $i = 1; $more_results = true; $result = $wpdb->get_results( $query, ARRAY_A ); // If we didn't get any rows, don't output anything. if ( count( $result ) < 1 ) { echo "No data in table!"; exit; } if ( isset( $_POST['export-headers'] ) and $_POST['export-headers'] ) { foreach ( $result[0] as $key => $col ) { $columns[] = $key; } $exporter->addRow( $columns ); } while ( $more_results ) { foreach ( $result as $row ) { $exporter->addRow( $row ); // Make sure we've flushed the output buffer so we don't run out of memory on large exports. ob_flush(); flush(); } unset( $result ); $wpdb->flush(); $query = $query_base . ' LIMIT ' . ( $i * 1000 ) . ',1000'; $result = $wpdb->get_results( $query, ARRAY_A ); if ( count( $result ) == 0 ) { $more_results = false; } $i ++; } $exporter->finalize(); exit; } } }
agpl-3.0
opencadc/vos
cadc-vos-server/src/main/java/ca/nrc/cadc/uws/util/RestletWebUtil.java
4820
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2018. (c) 2018. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * ************************************************************************ */ package ca.nrc.cadc.uws.util; import org.restlet.Request; import org.restlet.data.Form; import org.restlet.data.Parameter; import ca.nrc.cadc.net.NetUtil; public class RestletWebUtil { /** * Restlet request constructor that taken a path override parameters. * <p> * * @param request The Request object. */ public static String getClientIP(final Request request) { final Form requestHeaders = (Form) request.getAttributes().get("org.restlet.http.headers"); final Parameter forwardedClientIP = (requestHeaders == null) ? null : requestHeaders.getFirst(NetUtil.FORWARDED_FOR_CLIENT_IP_HEADER); return (forwardedClientIP == null) ? request.getClientInfo().getAddress() : forwardedClientIP.getValue().split(",")[0]; } }
agpl-3.0
myplaceonline/myplaceonline_rails
db/migrate/20160316042105_add_category_filtertext_quests.rb
205
class AddCategoryFiltertextQuests < ActiveRecord::Migration def change Myp.migration_add_filtertext("quests", "learn education analysis exploration inquiry investigation probe experiment") end end
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
ejb-core/publication/src/main/java/com/stratelia/webactiv/util/publication/model/ValidationStep.java
2617
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.util.publication.model; import java.io.Serializable; import java.util.Date; public class ValidationStep implements Serializable { private static final long serialVersionUID = -5783286372913745898L; private int id = -1; private PublicationPK pubPK = null; private String userId = null; private Date validationDate = null; private String decision = null; private String userFullName = null; public ValidationStep() { } public ValidationStep(PublicationPK pubPK, String userId, String decision) { this.pubPK = pubPK; this.userId = userId; this.decision = decision; } public PublicationPK getPubPK() { return pubPK; } public void setPubPK(PublicationPK pubPK) { this.pubPK = pubPK; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getValidationDate() { return validationDate; } public void setValidationDate(Date validationDate) { this.validationDate = validationDate; } public String getUserFullName() { return userFullName; } public void setUserFullName(String userFullName) { this.userFullName = userFullName; } public String getDecision() { return decision; } public void setDecision(String decision) { this.decision = decision; } public int getId() { return id; } public void setId(int stepId) { this.id = stepId; } }
agpl-3.0
willprice/weboob
modules/boursorama/pages/investment.py
4506
# -*- coding: utf-8 -*- # Copyright(C) 2014 Simon Murail # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import re from lxml.etree import XPath from weboob.deprecated.browser import Page from weboob.capabilities.bank import Investment from weboob.browser.filters.standard import CleanDecimal Decimal = CleanDecimal(replace_dots=True).filter class AccountMarket(Page): def get_investment(self): for tr in self.document.xpath('//table[@id="liste-positions-engagements"]/tbody/tr'): cells = tr.xpath('./td') if len(cells) < 6: continue inv = Investment() inv.label = self.parser.tocleanstring(cells[0].xpath('.//a')[0]) isin_div = cells[0].xpath('.//div') if len(isin_div) > 0: inv.id = inv.code = self.parser.tocleanstring(isin_div[0]) inv.quantity = Decimal(cells[1]) # <td data-header="Cours">20,650<br>(<span class="varup">+0,54%</span>)</td> inv.unitprice = Decimal(cells[2].xpath('text()')[0]) inv.unitvalue = Decimal(cells[3]) inv.valuation = Decimal(cells[4]) inv.diff = Decimal(cells[5]) inv._detail_url = None yield inv _el_to_string = XPath('string()') def el_to_string(el): return unicode(_el_to_string(el)) class IsinMixin(object): def get_isin(self, s): mobj = self._re_isin.search(s) if mobj: return mobj.group(1) class AccountLifeInsurance(IsinMixin, Page): _re_isin = re.compile(r'isin=(\w+)') _tr_list = XPath('//div[@id="content-gauche"]//table[@class="list"]/tbody/tr') _td_list = XPath('./td') _link = XPath('./td[1]/a/@href') def get_investment(self): for tr in self._tr_list(self.document): cells = list(el_to_string(td) for td in self._td_list(tr)) link = unicode(self._link(tr)[0]) ''' Boursorama table cells ---------------------- 0. Fonds 1. Date de valeur 2. Valeur de part 3. Nombre de parts 4. Contre valeur 5. Prix revient 6. +/- value en €* 7. +/- value en %* Investment model ---------------- label = StringField('Label of stocks') code = StringField('Identifier of the stock (ISIN code)') description = StringField('Short description of the stock') quantity = IntField('Quantity of stocks') unitprice = DecimalField('Buy price of one stock') unitvalue = DecimalField('Current value of one stock') valuation = DecimalField('Total current valuation of the Investment') diff = DecimalField('Difference between the buy cost and the current valuation') ''' inv = Investment() isin = self.get_isin(link) if isin: inv.id = inv.code = isin inv.label = cells[0] inv.quantity = Decimal(cells[3]) inv.valuation = Decimal(cells[4]) inv.unitprice = Decimal(cells[5]) inv.unitvalue = Decimal(cells[2]) inv.diff = Decimal(cells[6]) inv._detail_url = link if '/cours.phtml' in link else None yield inv class InvestmentDetail(IsinMixin, Page): _re_isin = re.compile('(\w+)') _isin = XPath('//h2[@class and contains(concat(" ", normalize-space(@class), " "), " fv-isin ")]') _description = XPath('//p[@class="taj"] | //div[@class="taj"]') def get_investment_detail(self, inv): subtitle = el_to_string(self._isin(self.document)[0]) inv.id = inv.code = self.get_isin(subtitle) inv.description = el_to_string(self._description(self.document)[0]).strip()
agpl-3.0
codesy/codesy
auctions/utils.py
1642
import re from datetime import timedelta from django.utils import timezone from decouple import config from github import Github, UnknownObjectException from .models import Bid, Issue GITHUB_ISSUE_RE = re.compile('https://github.com/(.*)/issues/(\d+)') def github_client(): return Github(client_id=config('GITHUB_CLIENT_ID'), client_secret=config('GITHUB_CLIENT_SECRET')) def issue_state(url, gh_client): match = GITHUB_ISSUE_RE.match(url) if match: repo_name, issue_id = match.groups() try: repo = gh_client.get_repo(repo_name) issue = repo.get_issue(int(issue_id)) except UnknownObjectException: # TODO: log this exception somewhere pass else: return issue.state def update(instance, **kwargs): using = kwargs.pop('using', '') return instance._default_manager.filter(pk=instance.pk).using( using).update(**kwargs) def update_bid_issues(): for bid in Bid.objects.filter(issue=None): try: update(bid, issue=Issue.objects.get(url=bid.url)) except Issue.DoesNotExist: state = issue_state(bid.url) if state: update(bid, issue=Issue.objects.create(url=bid.url, state=state)) def update_issue_states(since=None): since = since or timezone.now() - timedelta(days=1) gh_client = github_client() for issue in Issue.objects.filter(last_fetched__lt=since): state = issue_state(issue.url, gh_client) if state: update(issue, last_fetched=timezone.now(), state=state)
agpl-3.0
gabrys/wikidot
php/modules/forum/sub/ForumThreadMoveModule.php
2316
<?php /** * Wikidot - free wiki collaboration software * Copyright (c) 2008, Wikidot Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * For more information about licensing visit: * http://www.wikidot.org/license * * @category Wikidot * @package Wikidot * @version $Id$ * @copyright Copyright (c) 2008, Wikidot Inc. * @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License */ class ForumThreadMoveModule extends SmartyModule { public function build($runData){ $pl = $runData->getParameterList(); $threadId = $pl->getParameterValue("threadId"); $site = $runData->getTemp("site"); $db = Database::connection(); $db->begin(); $thread = DB_ForumThreadPeer::instance()->selectByPrimaryKey($threadId); if($thread == null || $thread->getSiteId() !== $site->getSiteId()){ throw new ProcessException(_("No thread found... Is it deleted?"), "no_thread"); } $category = $thread->getForumCategory(); WDPermissionManager::instance()->hasForumPermission('moderate_forum', $runData->getUser(), $category); $runData->contextAdd("thread", $thread); $runData->contextAdd("category", $thread->getForumCategory()); // and select categories to move into too. $c = new Criteria(); $c->add("site_id", $site->getSiteId()); $c->addOrderDescending("visible"); $c->addOrderAscending("sort_index"); $groups = DB_ForumGroupPeer::instance()->select($c); $res = array(); foreach($groups as $g){ $c = new Criteria(); $c->add("group_id", $g->getGroupId()); $c->addOrderAscending("sort_index"); $categories = DB_ForumCategoryPeer::instance()->select($c); foreach($categories as $cat){ $res[] = array('group' => $g, 'category' => $cat); } } $runData->contextAdd("categories", $res); $db->commit(); } }
agpl-3.0
jesseh/dothis
volunteering/migrations/0059_auto_20150409_1457.py
731
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('volunteering', '0058_auto_20150126_2346'), ] operations = [ migrations.AlterField( model_name='volunteer', name='dear_name', field=models.CharField(help_text=b'Leave blank if same as first name', max_length=200, blank=True), preserve_default=True, ), migrations.AlterField( model_name='volunteer', name='external_id', field=models.CharField(default=0, unique=True, max_length=200), preserve_default=False, ), ]
agpl-3.0
kdhrubo/hoogly
product/src/main/java/com/effectiv/crm/domain/Product.java
2300
package com.effectiv.crm.domain; import java.util.Date; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import lombok.EqualsAndHashCode; @Entity @Table(name="T_PRODUCT") @Data @EqualsAndHashCode(callSuper=true) @JsonInclude(JsonInclude.Include.NON_NULL) public class Product extends BaseEntity{ @Column(name="NAME", nullable=true) private String name; @Column(name="OWNER", nullable=true) private String owner; @Column(name="PRODUCT_CODE", nullable=true) private String productCode; @Column(name="PART_NUMBER", nullable=true) private String partNumber; @Column(name="ACTIVE", nullable=true) private boolean active; @Column(name="VENDOR_ID", nullable=true) private String vendorId; @Column(name="PRODUCT_TYPE_ID", nullable=true) private String productTypeId; @Column(name="CURRENCY_ID", nullable=true) private String currencyId; @Column(name="PRODUCT_CATEGORY_ID", nullable=true) private String productCategory; @Column(name="SALES_START_DATE", nullable=true) private Date salesStartDate; @Column(name="SALES_END_DATE", nullable=true) private Date salesEndDate; @Column(name="COMMISSION_RATE", nullable=true) private double commissonRate; @Column(name="MANUFACTURER", nullable=true) private String manufacturer; @Column(name="UNIT_PRICE", nullable=true) private double unitPrice; @Column(name="TAXABLE", nullable=true) private boolean taxable; @Column(name="SUPPORT_START_DATE", nullable=true) private Date supportStartDate; @Column(name="SUPPORT_END_DATE", nullable=true) private Date supportEndDate; @Column(name="USAGE_UNIT_ID", nullable=true) private String usageUnitId; @Column(name="QTY_ORDERED", nullable=true) private int qtyOrdered; @Column(name="QTY_IN_STOCK", nullable=true) private int qtyInStock; @Column(name="REORDER_LEVEL", nullable=true) private int reorderLevel; @Column(name="HANDLER", nullable=true) private String handler; @Column(name="QTY_IN_DEMAND", nullable=true) private int qtyInDemand; @Column(name="DESCRIPTION", nullable=true) private String description; @Column(name="PRODUCT_URL", nullable=true) private String productUrl; //Product images @Column(name="ASSIGNED_USER_ID") private String assignedUserId; }
agpl-3.0