repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
magicnode/tpyouyou
online/htdocs/supplier/Lib/modules/cruise_orderModule.class.php
19926
<?php class cruise_orderModule extends AuthModule { function new_index() { $_REQUEST['is_new'] = 1; $this->index(); } function index() { $param = array(); //条件 $condition = " t.supplier_id = ".$this->supplier_id; //`order_confirm_type` tinyint(1) NOT NULL COMMENT '订单确认方式 1.付款后确认 2.确认后付款,3.自动确认', $condition .=" and (t.pay_status=1 or t.order_confirm_type = 2) and t.order_status <> 4 "; //order_status 订单状态(流程)1.新订单 2.已确认 3.已完成 4.作废 $is_new = intval($_REQUEST['is_new']); if(isset($_REQUEST['is_new']) && $is_new > 0){ $condition .=" and (t.refund_status = 1 or (t.order_confirm_type = 2 and t.order_status = 1) or (t.order_confirm_type = 1 and t.order_status = 1 and t.pay_status = 1) ) "; $param['is_new'] = 1; }else{ $param['is_new'] = 0; } //订单号 if(isset($_REQUEST['sn'])) $sn = strim($_REQUEST['sn']); else $sn = ""; $param['sn'] = $sn; if($sn!='') { $condition.=" and t.sn = '".$sn."' "; } //线路ID if(isset($_REQUEST['tourline_id'])) $tourline_id = strim($_REQUEST['tourline_id']); else $tourline_id = ""; $param['tourline_id'] = $tourline_id; if($tourline_id!='' && intval($tourline_id) > 0) { $condition.=" and t.tourline_id = ".intval($tourline_id)." "; } //预定人姓名 if(isset($_REQUEST['appoint_name'])) $appoint_name = strim($_REQUEST['appoint_name']); else $appoint_name = ""; $param['appoint_name'] = $appoint_name; if($appoint_name!='') { $condition.=" and t.appoint_name = '".$appoint_name."' "; } //预定人手机 if(isset($_REQUEST['appoint_mobile'])) $appoint_mobile = strim($_REQUEST['appoint_mobile']); else $appoint_mobile = ""; $param['appoint_mobile'] = $appoint_mobile; if($appoint_mobile!='') { $condition.=" and t.appoint_mobile = '".$appoint_mobile."' "; } //验证码 if(isset($_REQUEST['verify_code'])) $verify_code = strim($_REQUEST['verify_code']); else $verify_code = ""; $param['verify_code'] = $verify_code; if($verify_code!='') { $condition.=" and t.verify_code = '".$verify_code."' "; } //支付状态 $pay_status = -1; if(isset($_REQUEST['pay_status']) && strim($_REQUEST['pay_status'])!="") $pay_status = intval($_REQUEST['pay_status']); $param['pay_status'] = $pay_status; if($pay_status !=-1) { $condition .=" and t.pay_status=$pay_status "; } //退款状态 $refund_status = -1; if(isset($_REQUEST['refund_status']) && strim($_REQUEST['refund_status'])!="") $refund_status = intval($_REQUEST['refund_status']); $param['refund_status'] = $refund_status; if($refund_status !=-1) { $condition .=" and t.refund_status=$refund_status "; } //订单状态 $order_status = 0; if(isset($_REQUEST['order_status']) && strim($_REQUEST['order_status'])!="") $order_status = intval($_REQUEST['order_status']); $param['order_status'] = $order_status; if($order_status !=0) { $condition .=" and t.order_status=$order_status "; } //是否验证 $is_verify = intval($_REQUEST['is_verify']); if ($is_verify == 1){ $condition .=" and t.verify_time=0"; }else if ($is_verify == 2){ $condition .=" and t.verify_time>0"; } $param['is_verify'] = $is_verify; //下单时间 $create_time_begin = strim($_REQUEST['create_time_begin']); $param['create_time_begin'] = $create_time_begin; $create_time_end = strim($_REQUEST['create_time_end']); $param['create_time_end'] = $create_time_end; if(!empty($create_time_begin) && !empty($create_time_end)) { $condition.=" and t.create_time >= '".to_timespan($create_time_begin)."' and t.create_time <='". (to_timespan($create_time_end) + 3600 * 24 - 1)."' "; } //出发时间 $end_time_begin = strim($_REQUEST['end_time_begin']); $param['end_time_begin'] = $end_time_begin; $end_time_end = strim($_REQUEST['end_time_end']); $param['end_time_end'] = $end_time_end; if(!empty($end_time_begin) && !empty($end_time_end)) { $condition.=" and t.end_time >= '".$end_time_begin."' and t.end_time <='". $end_time_end."' "; } //分页 if(isset($_REQUEST['numPerPage'])) { $param['pageSize'] = intval($_REQUEST['numPerPage']); if($param['pageSize'] <=0||$param['pageSize'] >200) $param['pageSize'] = ADMIN_PAGE_SIZE; } else $param['pageSize'] = ADMIN_PAGE_SIZE; if(isset($_REQUEST['pageNum'])) $page = intval($_REQUEST['pageNum']); else $page = 0; if($page==0) $page = 1; $limit = (($page-1)*$param['pageSize']).",".$param['pageSize']; $param['pageNum'] = $page; //排序 if(isset($_REQUEST['orderField'])) $param['orderField'] = strim($_REQUEST['orderField']); else $param['orderField'] = "t.id"; if(isset($_REQUEST['orderDirection'])) $param['orderDirection'] = strim($_REQUEST['orderDirection'])=="asc"?"asc":"desc"; else $param['orderDirection'] = "desc"; $totalCount = $GLOBALS['db']->getOne("select count(id) from ".DB_PREFIX."tourline_order t where ".$condition); if($totalCount){ $sql = "select t.*,u.user_name,u.mobile,s.user_name as supplier_name from ".DB_PREFIX."tourline_order t left outer join ".DB_PREFIX."user u on u.id = t.user_id left outer join ".DB_PREFIX."supplier s on s.id = t.supplier_id where ".$condition." order by ".$param['orderField']." ".$param["orderDirection"]." limit ".$limit; $list = $GLOBALS['db']->getAll($sql); // 提取邮轮订单 foreach ($list as $key => $value) { $isC = $GLOBALS['db']->getOne("select is_cruise from ".DB_PREFIX."tourline where id =".$value['tourline_id']); if ($isC == 1) { $lists[] = $value; } } require_once APP_ROOT_PATH."system/libs/tourline.php"; foreach($lists as $k=>$v) { tourline_order_format($lists[$k]); } } /* 线路名称:tourline_name 订单号:sn 购买会员:user_name 下单时间:create_time 订单状态:order_status 支付状态:pay_status 订单金额:total_price 已付金额:pay_amount 已退金额:refund_amount */ $GLOBALS['tmpl']->assign('list',$lists); $GLOBALS['tmpl']->assign('totalCount',$totalCount); $GLOBALS['tmpl']->assign('param',$param); $GLOBALS['tmpl']->assign("formaction",admin_url("tourline_order")); $GLOBALS['tmpl']->assign("editurl",admin_url("tourline_order#order")); $GLOBALS['tmpl']->assign("exporturl",admin_url("tourline_order#export_csv")); $GLOBALS['tmpl']->display("core/tourline_order/index.html"); } public function export_csv($page = 1) { $param = array(); $condition = " t.supplier_id = ".$this->supplier_id; //`order_confirm_type` tinyint(1) NOT NULL COMMENT '订单确认方式 1.付款后确认 2.确认后付款,3.自动确认', $condition .=" and (t.pay_status=1 or t.order_confirm_type = 2) and t.order_status <> 4 "; //order_status 订单状态(流程)1.新订单 2.已确认 3.已完成 4.作废 $is_new = intval($_REQUEST['is_new']); if(isset($_REQUEST['is_new']) && $is_new > 0){ $condition .=" and (t.refund_status = 1 or (t.order_confirm_type = 2 and t.order_status = 1) or (t.order_confirm_type = 1 and t.order_status = 1 and t.pay_status = 1) ) "; $param['is_new'] = 1; }else{ $param['is_new'] = 0; } //订单号 if(isset($_REQUEST['sn'])) $sn = strim($_REQUEST['sn']); else $sn = ""; $param['sn'] = $sn; if($sn!='') { $condition.=" and t.sn = '".$sn."' "; } //线路ID if(isset($_REQUEST['tourline_id'])) $tourline_id = strim($_REQUEST['tourline_id']); else $tourline_id = ""; $param['tourline_id'] = $tourline_id; if($tourline_id!='' && intval($tourline_id) > 0) { $condition.=" and t.tourline_id = ".intval($tourline_id)." "; } //预定人姓名 if(isset($_REQUEST['appoint_name'])) $appoint_name = strim($_REQUEST['appoint_name']); else $appoint_name = ""; $param['appoint_name'] = $appoint_name; if($appoint_name!='') { $condition.=" and t.appoint_name = '".$appoint_name."' "; } //预定人手机 if(isset($_REQUEST['appoint_mobile'])) $appoint_mobile = strim($_REQUEST['appoint_mobile']); else $appoint_mobile = ""; $param['appoint_mobile'] = $appoint_mobile; if($appoint_mobile!='') { $condition.=" and t.appoint_mobile = '".$appoint_mobile."' "; } //验证码 if(isset($_REQUEST['verify_code'])) $verify_code = strim($_REQUEST['verify_code']); else $verify_code = ""; $param['verify_code'] = $verify_code; if($verify_code!='') { $condition.=" and t.verify_code = '".$verify_code."' "; } //支付状态 $pay_status = -1; if(isset($_REQUEST['pay_status']) && strim($_REQUEST['pay_status'])!="") $pay_status = intval($_REQUEST['pay_status']); $param['pay_status'] = $pay_status; if($pay_status !=-1) { $condition .=" and t.pay_status=$pay_status "; } //退款状态 $refund_status = -1; if(isset($_REQUEST['refund_status']) && strim($_REQUEST['refund_status'])!="") $refund_status = intval($_REQUEST['refund_status']); $param['refund_status'] = $refund_status; if($refund_status !=-1) { $condition .=" and t.refund_status=$refund_status "; } //订单状态 $order_status = 0; if(isset($_REQUEST['order_status']) && strim($_REQUEST['order_status'])!="") $order_status = intval($_REQUEST['order_status']); $param['order_status'] = $order_status; if($order_status !=0) { $condition .=" and t.order_status=$order_status "; } //是否验证 $is_verify = intval($_REQUEST['is_verify']); if ($is_verify == 1){ $condition .=" and t.verify_time=0"; }else if ($is_verify == 2){ $condition .=" and t.verify_time>0"; } $param['is_verify'] = $is_verify; //下单时间 $create_time_begin = strim($_REQUEST['create_time_begin']); $param['create_time_begin'] = $create_time_begin; $create_time_end = strim($_REQUEST['create_time_end']); $param['create_time_end'] = $create_time_end; if(!empty($create_time_begin) && !empty($create_time_end)) { $condition.=" and t.create_time >= '".to_timespan($create_time_begin)."' and t.create_time <='". (to_timespan($create_time_end) + 3600 * 24 - 1)."' "; } //出发时间 $end_time_begin = strim($_REQUEST['end_time_begin']); $param['end_time_begin'] = $end_time_begin; $end_time_end = strim($_REQUEST['end_time_end']); $param['end_time_end'] = $end_time_end; if(!empty($end_time_begin) && !empty($end_time_end)) { $condition.=" and t.end_time >= '".$end_time_begin."' and t.end_time <='". $end_time_end."' "; } $param['pageSize'] = 100; //分页 $limit = (($page-1)*$param['pageSize']).",".$param['pageSize']; $totalCount = $GLOBALS['db']->getOne("select count(id) from ".DB_PREFIX."tourline_order t where ".$condition); if($totalCount > 0){ $sql = "select t.*,u.user_name,u.mobile,s.user_name as supplier_name from ".DB_PREFIX."tourline_order t left outer join ".DB_PREFIX."user u on u.id = t.user_id left outer join ".DB_PREFIX."supplier s on s.id = t.supplier_id where ".$condition." limit ".$limit; //echo $sql; //die(); $list = $GLOBALS['db']->getAll($sql); require_once APP_ROOT_PATH."system/libs/tourline.php"; foreach($list as $k=>$v) { tourline_order_format($list[$k]); } if($page == 1) { $content = iconv("utf-8","gbk","订单ID,订单编号,门票名称,商家名称,购买会员,预定人姓名,预定人手机,出发日期,下单时间,订单金额,付款时间,已付金额,是否验证,支付状态,订单状态,退款状态,订单备注"); $content = $content . "\n"; } if($list) { register_shutdown_function(array(&$this, 'export_csv'), $page+1); foreach($list as $k=>$v) { $order_value = array(); $order_value['id'] = '"' . $v['id'] . '"'; $order_value['sn'] = '"' . $v['sn'] . '"'; $order_value['tourline_name'] = '"' . iconv('utf-8','gbk',$v['tourline_name']) . '"'; $order_value['supplier_name'] = '"' . iconv('utf-8','gbk',$v['supplier_name']) . '"'; $order_value['user_name'] = '"' .iconv('utf-8','gbk',$v['user_name']) . '"'; $order_value['appoint_name'] = '"' . iconv('utf-8','gbk',$v['appoint_name']) . '"'; $order_value['appoint_mobile'] = '"' . $v['appoint_mobile'] . '"'; $order_value['end_time'] = '"' . $v['end_time'] . '"'; $order_value['create_time_format'] = '"' . $v['create_time_format'] . '"'; $order_value['total_price_format'] = '"' . iconv('utf-8','gbk',$v['total_price_format']) . '"'; $order_value['pay_time_format'] = '"' . $v['pay_time_format'] . '"'; $order_value['pay_amount_format'] = '"' . iconv('utf-8','gbk',$v['pay_amount_format']) . '"'; $order_value['is_verify'] = '"' . iconv('utf-8','gbk',$v['is_verify']) . '"'; $order_value['pay_status_format'] = '"' . iconv('utf-8','gbk',$v['pay_status_format']) . '"'; $order_value['order_status_format'] = '"' . iconv('utf-8','gbk',$v['order_status_format']) . '"'; $order_value['refund_status_format'] = '"' . iconv('utf-8','gbk',$v['refund_status_format']) . '"'; $order_value['order_memo'] = '"' . iconv('utf-8','gbk',$v['order_memo']) . '"'; $content .= implode(",", $order_value) . "\n"; } } } header("Content-type:application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=tourline_order.csv"); echo $content; } public function order() { $ajax = intval($_REQUEST['ajax']); $id = intval($_REQUEST['id']); $sql = "select t.*,u.user_name,u.mobile,s.user_name as supplier_name from ".DB_PREFIX."tourline_order t left outer join ".DB_PREFIX."user u on u.id = t.user_id left outer join ".DB_PREFIX."supplier s on s.id = t.supplier_id where t.id = ".$id; $order = $GLOBALS['db']->getRow($sql);//"select * from ".DB_PREFIX."tourline_order where id = ".$id); if(empty($order)) { showErr("订单不存在",$ajax) ; } require_once APP_ROOT_PATH."system/libs/tourline.php"; tourline_order_format($order); $verify_time = intval($order['verify_time']); if ($verify_time == 0) $order['verify_code'] = '未验证'; //print_r($order); $GLOBALS['tmpl']->assign("order",$order); //参团人员; $namelist = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."tourline_order_namelist where tourline_order_id = ".intval($id)); foreach($namelist as $k=>$v) { //证件类型(1:身份证2:护照3:军官证4:港澳通行证5:台胎证6:其他) if ($v['paper_type'] == 1){ $namelist[$k]['paper_type_format'] = '身份证'; }else if ($v['paper_type'] == 2){ $namelist[$k]['paper_type_format'] = '护照'; }else if ($v['paper_type'] == 3){ $namelist[$k]['paper_type_format'] = '军官证'; }else if ($v['paper_type'] == 4){ $namelist[$k]['paper_type_format'] = '港澳通行证'; }else if ($v['paper_type'] == 5){ $namelist[$k]['paper_type_format'] = '台胎证'; }else if ($v['paper_type'] == 6){ $namelist[$k]['paper_type_format'] = '其他'; }else{ $namelist[$k]['paper_type_format'] = '其他'; } //是否有效 1是 0否 if ($v['status'] == 1){ $namelist[$k]['status_format'] = '是'; }else{ $namelist[$k]['status_format'] = '否'; } } $GLOBALS['tmpl']->assign('namelist',$namelist); $GLOBALS['tmpl']->assign("orderlogurl",admin_url("tourline_order#order_log",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->assign("pay_order_url",admin_url("tourline_order#pay_order",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->assign("order_status_url",admin_url("tourline_order#do_order_status",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->assign("refund_status_url",admin_url("tourline_order#do_refund_status",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->assign("use_verify_code_url",admin_url("tourline_order#use_verify_code",array("ajax"=>1,id=>$id,'verify_code'=>$order['verify_code']))); $GLOBALS['tmpl']->assign("refuse_refund_url",admin_url("tourline_order#refuse_refund",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->display("core/tourline_order/order.html"); } //确认订单,完成订单,订单作废 public function do_order_status() { $id = intval($_REQUEST['id']); $order_status = intval($_REQUEST['order_status']); $ajax = intval($_REQUEST['ajax']); require_once APP_ROOT_PATH."system/libs/tourline.php"; require_once APP_ROOT_PATH."system/libs/user.php"; if ($order_status == 2 || $order_status == 5){ //`order_status` tinyint(1) NOT NULL default '1' COMMENT '订单状态(流程)1.新订单 2.已确认 3.已完成 4.作废\r\n新订单:未确认(包含已付款)的都表示为新订单\r\n已确认:表示为商家或管理员查看,确认手动修改\r\n新订单、已确认均可申请退款,否则不可', tourline_order_confirm($id,$order_status,1); showSuccess('确认订单成功',$ajax,admin_url("tourline_order#order",array(id=>$id))); } } //退款 public function refuse_refund() { $id = intval($_REQUEST['id']); $ajax = intval($_REQUEST['ajax']); //refuse_reason $order = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."tourline_order where refund_status = 1 and id = ".$id." and supplier_id = ".$this->supplier_id); if(empty($order)) { showErr("用户未申请退款或退款单已被处理",$ajax) ; } require_once APP_ROOT_PATH."system/libs/tourline.php"; tourline_order_format($order); $GLOBALS['tmpl']->assign("order",$order); $GLOBALS['tmpl']->assign("id",$id); $GLOBALS['tmpl']->assign("refuse_reason",$order['refuse_reason']); $GLOBALS['tmpl']->assign("formaction",admin_url("tourline_order#do_refund_status",array("ajax"=>1,id=>$id))); $GLOBALS['tmpl']->assign("accounturl",admin_url("tourline_order#order",array("ajax"=>1,id=>$id))); //$GLOBALS['tmpl']->display("core/user/op_account.html"); $GLOBALS['tmpl']->display("core/tourline_order/refuse_refund.html"); } //确认退款,拒绝退款 public function do_refund_status() { $id = intval($_REQUEST['id']); $supplier_confirm = intval($_REQUEST['supplier_confirm']); $ajax = intval($_REQUEST['ajax']); $order = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."tourline_order where refund_status = 1 and id = ".$id." and supplier_id = ".$this->supplier_id); if(empty($order)) { showErr("用户未申请退款或退款单已被处理:".$id,$ajax,admin_url("tourline_order#order",array(id=>$id))) ; } require_once APP_ROOT_PATH."system/libs/tourline.php"; $refuse_reason = strim($_REQUEST['refuse_reason']); $GLOBALS['db']->query("update ".DB_PREFIX."tourline_order set supplier_confirm = $supplier_confirm, supplier_confirm_time = ".NOW_TIME.",refuse_reason='".$refuse_reason."' where refund_status = 1 and id = ".$id." ","SILENT"); if($GLOBALS['db']->affected_rows()>0){ save_tourline_order_log($id,'用户申请退款,商家确认',1); showSuccess('商家确认成功',$ajax,admin_url("tourline_order#order",array('id'=>$id))); }else{ showSuccess('商家确认失败',$ajax,admin_url("tourline_order#order",array('id'=>$id))); } } } ?>
gpl-3.0
nazariene/SpringTest
src/main/java/com/emc/spring/collections/InjectingCollectionsBean.java
1108
/* * Copyright (c) 2002-2016 EMC Corporation All Rights Reserved */ package com.emc.spring.collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class InjectingCollectionsBean { List<String> addressList; Set<String> addressSet; Map<String, String> addressMap; Properties addressProps; public List<String> getAddressList() { return addressList; } public void setAddressList(List<String> addressList) { this.addressList = addressList; } public Set<String> getAddressSet() { return addressSet; } public void setAddressSet(Set<String> addressSet) { this.addressSet = addressSet; } public Map<String, String> getAddressMap() { return addressMap; } public void setAddressMap(Map<String, String> addressMap) { this.addressMap = addressMap; } public Properties getAddressProps() { return addressProps; } public void setAddressProps(Properties addressProps) { this.addressProps = addressProps; } }
gpl-3.0
davideboehm/CryptoCore
CurrencyCore/Wallet/BitcoinStyleWallet/Script/Commands/FlowControl/If.cs
1950
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CurrencyCore.Wallet.BitcoinStyleWallet.Script.Data; namespace CurrencyCore.Wallet.BitcoinStyleWallet.Script.Commands.FlowControl { public class If : ScriptCommand { private readonly ScriptBranch trueBranch; private readonly ScriptBranch falseBranch; private readonly bool Negate; public If(ScriptBranch trueBranch, ScriptBranch falseBranch = null) : this(99, false, trueBranch, falseBranch) { } protected If(byte opCode, bool negate, ScriptBranch trueBranch, ScriptBranch falseBranch = null) : base(opCode, CombineBranchData(trueBranch, falseBranch)) { this.Negate = negate; this.trueBranch = trueBranch; this.falseBranch = falseBranch; } public override ScriptResult Execute(ScriptProgramStack currentState) { var value = currentState.Pop(); if(this.Negate ^ value.IsTrue()) { return trueBranch.Execute(currentState); } else if(falseBranch != null) { return falseBranch.Execute(currentState); } return ScriptResult.Success; } private static ScriptData CombineBranchData(ScriptBranch firstBranch, ScriptBranch secondBranch) { var size = firstBranch.Size + 1 + (secondBranch != null ? secondBranch.Size + 1 : 0); var buffer = new byte[size]; firstBranch.Serialize(buffer, 0); if (secondBranch != null) { //add else buffer[firstBranch.Size] = 103; secondBranch.Serialize(buffer, firstBranch.Size + 1); } //add endif buffer[size - 1] = 104; return new Bytes(buffer); } } }
gpl-3.0
maximumtech/Game
Game/src/Game/content/ItemAxe.java
696
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Game.content; import Game.base.IBreakable; import Game.base.World; /** * * @author maximumtech */ public class ItemAxe extends ItemTool { public ItemAxe(short id, ToolMaterial material) { super(id, material); } public float getHardnessModifier(World world, int x, int y, IBreakable block) { if ((block.getMaterial() == Material.WOOD || block.getMaterial() == Material.PLANT) && material.getTier() >= block.getTier()) { return material.getModifier() * (block.getMaterial() == Material.PLANT ? 0.5F : 1F); } return 1F; } }
gpl-3.0
fearless359/simpleinvoices
modules/billers/details.php
908
<?php /* * Script: details.php * Biller details page * * Authors: * Justin Kelly, Nicolas Ruflin * * Last edited: * 2007-07-19 * * License: * GPL v2 or above * * Website: * https://simpleinvoices.group */ global $smarty; //stop the direct browsing to this file - let index.php handle which files get displayed checkLogin(); //get the invoice id $biller_id = $_GET['id']; $biller = Biller::select($biller_id); // Drop down list code for invoice logo $files = getLogoList(); // end logo stuff $customFieldLabel = getCustomFieldLabels('',true); $smarty->assign('biller', $biller); $smarty->assign('files', $files); $smarty->assign('customFieldLabel', $customFieldLabel); $smarty->assign('pageActive', 'biller'); $subPageActive = $_GET['action'] =="view" ? "biller_view" : "biller_edit" ; $smarty->assign('subPageActive', $subPageActive); $smarty->assign('active_tab', '#people');
gpl-3.0
RodrigodosSantosFelix/projetosSistemas
CodeJava/CrinicaMedica/src/clinicamedica/BD.java
1952
package clinicamedica; import javax.swing.JOptionPane; import java.sql.*; public class BD { static final String banco = "jdbc:mysql://localhost:3306/crinicamedica"; Connection connection = null; Statement query = null; ResultSet results = null; PreparedStatement myinclude = null; public void include (int crm, String nomemed, String especialidademed) { try { connection = DriverManager.getConnection(banco,"root",""); query = connection.createStatement(); results = query.executeQuery("SELECT * FROM medicos"); ResultSetMetaData column = results.getMetaData(); int numberColumn = column.getColumnCount(); System.out.println ("Informações do Banco de Dados CrinicaMedica"); myinclude = connection.prepareStatement("INSERT INTO medicos(crm,nomemed,especialidadeMed) VALUES (?,?,?)"); myinclude.setInt(1, crm); myinclude.setString(2, nomemed); myinclude.setString(3, especialidademed); myinclude.executeUpdate(); for (int i = 1; i <= numberColumn; i++) System.out.println(column.getColumnName(i)); while (results.next()) { for (int i = 1; i <= numberColumn; i++) System.out.println("Dados " + results.getObject(i)); System.out.println(); } } catch (SQLException error) { error.printStackTrace(); } finally { try { results.close(); query.close(); connection.close(); } catch (Exception newerror) { newerror.printStackTrace(); } } } }
gpl-3.0
caw/mb
old/mb_simulation.js
13980
/** * Created by chriswri on 18/03/15. */ ; (function () { const SECONDS_IN_MINUTE = 60; let running = true; // remember - the flows are converted to liters/sec let circ = { fa: 5.0 / SECONDS_IN_MINUTE, fv: 5.0 / SECONDS_IN_MINUTE, fc: 5.0 / SECONDS_IN_MINUTE, va: 0.85, vv: 3.25, vra: 0.1, ca: 0.00355, cv: 0.0825, cra: 0.005, ra: 19.34 * SECONDS_IN_MINUTE, rv: 0.74 * SECONDS_IN_MINUTE, pa: 100, pv: 3.7, pra: 0.0, dva: 0.0, dvv: 0.0, dvra: 0.0, vao: 0.495, vvo: 2.95, vrao: 0.1, vae: 0.355, vve: 0.3, vrae: 0.0, pga: 96.3, pgv: 3.7, fan: 5.0 * SECONDS_IN_MINUTE, hs: 1.0, dt: 0.05, pms: 7.1, starling: function (pra) { let r2 = 6 * (pra + 4); let r3 = Math.pow(r2, 2.5); let r4 = (r3 / (5000 + r3)) * 13 + 0.5; return r4 / SECONDS_IN_MINUTE; }, iterate: function (n) { for (let i = 0; i < n; i++) { this.vrae = this.vra - this.vrao; this.pra = this.vrae / this.cra; this.fan = this.starling(this.pra); this.fa = this.fan * this.hs; this.dva = this.fa - this.fc; this.vae = this.va - this.vao; this.pa = this.vae / this.ca; this.pga = this.pa - this.pv; this.fc = this.pga / this.ra; this.dvv = this.fc - this.fv; this.vve = this.vv - this.vvo; this.pv = this.vve / this.cv; this.pgv = this.pv - this.pra; this.fv = this.pgv / this.rv; this.dvra = this.fv - this.fa; this.va = this.va + this.dva * this.dt; this.vv = this.vv + this.dvv * this.dt; this.vra = this.vra + this.dvra * this.dt; this.pms = (this.vrae + this.vae + this.vve) / (this.cra + this.ca + this.cv); } } } let canvas = new fabric.Canvas('c'); canvas.backgroundColor = "#cccccc"; canvas.on('mouse:down', function (options) { if (options.target) { if (options.target.id) { (deltaFunctions[options.target.id])(); }; }; }); var deltaFunctions = { ra_dec: function () { if (circ.ra > 1) { circ.ra -= 30; }; canvas.renderAll(); }, ra_inc: function () { if (circ.ra < 3000) { circ.ra += 30; }; canvas.renderAll(); }, rv_dec: function () { if (circ.rv > 10) { circ.rv -= 2; }; canvas.renderAll(); }, rv_inc: function () { if (circ.rv < 3000) { circ.rv += 2; }; canvas.renderAll(); }, vvo_dec: function () { console.log('vvo_dec'); if (circ.vvo > 1) { circ.vvo -= 0.05; }; canvas.renderAll() }, vvo_inc: function () { console.log('vvo_inc'); if (circ.vvo < 6.0) { circ.vvo += 0.05; }; canvas.renderAll(); }, cv_dec: function () { console.log('cv_dec'); if (circ.cv > 0.001) { circ.cv -= 0.001; }; canvas.renderAll() }, cv_inc: function () { console.log('cv_inc'); if (circ.cv < 1.20) { circ.cv += 0.001; }; canvas.renderAll(); }, ca_dec: function () { console.log('cv_dec'); if (circ.ca > 0.0001) { circ.ca -= 0.0005; }; canvas.renderAll() }, ca_inc: function () { console.log('cv_inc'); if (circ.ca < 1.20) { circ.ca += 0.0005; }; canvas.renderAll(); }, hs_dec: function () { if (circ.hs > 0) { circ.hs -= 0.05; }; if (circ.hs <= 0) { circ.hs = 0; }; canvas.renderAll(); }, hs_inc: function () { if (circ.hs < 3.0) { circ.hs += 0.05; }; canvas.renderAll(); }, run_toggle: function () { if (running) { console.log('pausing'); running = false; run.set({ text: "Resume" }); } else { console.log('resuming'); running = true; run.set({ text: "Pause" }); }; canvas.renderAll(); } }; fabric.Image.fromURL('images/circulation.png', function (circ_image) { var scale = 1.0; circ_image.set({ left: (canvas.width - scale * circ_image.width) / 2, top: (canvas.height - scale * circ_image.height) / 2 - 50, scaleX: scale, scaleY: scale, selectable: false }); canvas.add(circ_image); canvas.sendToBack(circ_image); canvas.calcOffset(); canvas.renderAll(); }); var ra = new fabric.Text("Ra: " + (circ.ra / SECONDS_IN_MINUTE).toFixed(0), { left: 700, top: 520, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var ra_inc = new fabric.Text("+", { left: 785, top: 550, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "ra_inc" }); var ra_dec = new fabric.Text("_", { left: 700, top: 535, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "ra_dec" }); var rv = new fabric.Text("Rv: " + (circ.rv / SECONDS_IN_MINUTE).toFixed(2), { left: 100, top: 520, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var rv_inc = new fabric.Text("+", { left: 220, top: 550, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "rv_inc" }); var rv_dec = new fabric.Text("_", { left: 100, top: 535, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "rv_dec" }); var cv = new fabric.Text("Cv: " + circ.cv.toFixed(4), { left: 100, top: 280, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var cv_inc = new fabric.Text("+", { left: 260, top: 310, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "cv_inc" }); var cv_dec = new fabric.Text("_", { left: 100, top: 295, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "cv_dec" }); var ca = new fabric.Text("Ca: " + circ.ca.toFixed(4), { left: 700, top: 280, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var ca_inc = new fabric.Text("+", { left: 860, top: 310, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "ca_inc" }); var ca_dec = new fabric.Text("_", { left: 700, top: 295, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "ca_dec" }); var vrae = new fabric.Text(circ.vrae.toFixed(1), { left: 100, top: 100, fontFamily: 'Verdana' }); var vra = new fabric.Text(circ.vra.toFixed(1), { left: 100, top: 100, fontFamily: 'Verdana' }); var pra = new fabric.Text("Pra: " + circ.pra.toFixed(1), { left: 300, top: 80, fontSize: 32, fontFamily: 'Verdana', fill: '#777777', selectable: false }); var pms = new fabric.Text("Pms: " + circ.pms.toFixed(1), { left: 10, top: 620, fontSize: 32, fontFamily: 'Verdana', fill: '#777777', selectable: false }); var fa = new fabric.Text("fa: " + (circ.fa * 60).toFixed(1), { left: 700, top: 120, fontSize: 32, fontFamily: 'Verdana', fill: '#777777', selectable: false }); var fv = new fabric.Text("fv: " + (circ.fv * 60).toFixed(1), { left: 100, top: 120, fontSize: 32, fontFamily: 'Verdana', fill: '#777777', selectable: false }); var vae = new fabric.Text("Vae: " + circ.vve.toFixed(2), { left: 700, top: 440, fontFamily: 'Verdana', fill: '#777777', fontSize: 32, selectable: false }); var vve = new fabric.Text("Vve: " + circ.vve.toFixed(2), { left: 100, top: 440, fontFamily: 'Verdana', fill: '#777777', fontSize: 32, selectable: false }); var va = new fabric.Text(circ.va.toFixed(1), { left: 100, top: 80, fontFamily: 'Verdana' }); var pa = new fabric.Text("Pa: " + circ.pa.toFixed(0), { left: 700, top: 200, fontFamily: 'Verdana', fontSize: 32, fill: '#ff0000', selectable: false }); var vao = new fabric.Text("Va0: " + circ.vao.toFixed(2), { left: 700, top: 360, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var vvo = new fabric.Text("Vv0: " + circ.vvo.toFixed(2), { left: 100, top: 360, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var vvo_dec = new fabric.Text("_", { left: 100, top: 370, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "vvo_dec" }); var vvo_inc = new fabric.Text("+", { left: 235, top: 385, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "vvo_inc" }); var hs = new fabric.Text("HS: " + circ.hs.toFixed(2), { left: 415, top: 200, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', }); var hs_dec = new fabric.Text("_", { left: 415, top: 210, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: '#ffffff', id: "hs_dec" }); var hs_inc = new fabric.Text("+", { left: 535, top: 225, fontFamily: 'Verdana', fontSize: 32, selectable: false, fill: "#ffffff", id: "hs_inc" }); var vv = new fabric.Text(circ.vv.toFixed(1), { left: 100, top: 100, fontFamily: 'Verdana', fontSize: 32, fill: '#0000FF', selectable: false }); var pv = new fabric.Text("Pv: " + circ.pv.toFixed(1), { left: 100, top: 200, fontFamily: 'Verdana', fontSize: 32, fill: '#777777', selectable: false }); var run = new fabric.Text("Pause", { left: 800, top: 620, fontFamily: 'Verdana', fontsize: 32, fill: '#ffffff', selectable: false, id: "run_toggle" }); // not displaying venous return = fv here canvas.add(rv, rv_inc, rv_dec, ca, ca_dec, ca_inc, fv, pms, ra, pra, fa, pa, vvo, vao, pv, cv, cv_inc, cv_dec, hs, ra_inc, ra_dec, vvo_inc, vvo_dec, vae, vve, hs_inc, hs_dec, run); canvas.bringToFront(fa); var update_display = function () { fa.set({ text: "fa: " + (circ.fa * 60).toFixed((1)) }); fv.set({ text: "fv: " + (circ.fv * 60).toFixed((1)) }); pms.set({ text: "Pms: " + circ.pms.toFixed(1) }); vra.set({ text: "Vra: " + circ.vra.toFixed(1) }); ra.set({ text: "Ra: " + (circ.ra / SECONDS_IN_MINUTE).toFixed(0) }); rv.set({ text: "Rv: " + (circ.rv / SECONDS_IN_MINUTE).toFixed(2) }); pra.set({ text: "Pra: " + circ.pra.toFixed(1) }); pa.set({ text: "Pa: " + circ.pa.toFixed(0) }); cv.set({ text: "Cv: " + circ.cv.toFixed(4) }); ca.set({ text: "Ca: " + circ.ca.toFixed(4) }); pv.set({ text: "Pv: " + circ.pv.toFixed(1) }); hs.set({ text: "HS: " + circ.hs.toFixed(2) }); vvo.set({ text: "Vv0: " + circ.vvo.toFixed(2) }); vao.set({ text: "Va0: " + circ.vao.toFixed(2) }); vve.set({ text: "Vve: " + circ.vve.toFixed(2) }); vae.set({ text: "Vae: " + circ.vae.toFixed(2) }); canvas.renderAll(); }; var iterations = 0; // every second, call circ.iterate(20) - that's one sec. worth of iteration setInterval(function () { if (running) { circ.iterate(20); } update_display(); }, 1000) })();
gpl-3.0
alexanderbailey/FISOFS
read_file.cpp
4223
////////////////////////////////////////////////////////////////////////////// // // // read_file.cpp is part of 'FISOFS' // // Copyright (C) 2014 Alex Bailey // // // // Licensing information can be found in the README file // // // ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <cstdlib> #include <sstream> #include <string> #include <stdio.h> #include <string.h> #include <math.h> using namespace std; // Function to print the set of gaps of a semigroup void print_semigroup(const char *V, char n) { for (int i=0;i<=n-1;i++) { cout << "[ "; for (int j=1;j<=*(V+i*(2*n));j++) { cout << *(V+i*(2*n)+j)+1 << " "; } cout << "]"; } cout << endl; } // Function to encode a word in the free semigroup to its shortlex position inline unsigned long long shortlex_encode(const char *V, int r) { unsigned long long s=0; if (r==1) { return (*V-1); } else { for (int i=1;i<=*V;i++) { s=s+*(V+i)*pow(r,*V-i); } return(s+(pow(r,*V)-r)/(r-1)); } } // Function to decode a word from its shortlex position inline void shortlex_decode(unsigned long long x, int r, char *V) { if (r==1) { *V=x+1; for (int i=1;i<=x+1;i++) *(V+i)=0; } else { int m=floor(log((r-1)*(x+2))/log(r)+0.00000000001); *V=m; if(m==1) { *(V+1)=x; } else { unsigned long long t=x+1-(pow(r,m)-1)/(r-1); for (int i=1;i<=m-1;i++) { *(V+i)=floor(t/pow(r,m-i)); t=t-pow(r,m-i)*(*(V+i)); } *(V+m)=t; } } } // Main function begins here int main(int c, char *a[]) { // Retrieving command line parameters // n = index, k = support, i = size of orbit, p = number of chunks to split file, q = which chunk to read static int n=atoi(a[1]); static int k=atoi(a[2]); long i=atol(a[3]); long p=atol(a[4]); long q=atol(a[5]); stringstream stream_folder_name; stream_folder_name << "subsgps/n-" << n << "/"; string folder_name=stream_folder_name.str(); // Calculating bitrate of file int bit; char largest_frob[2*n]; largest_frob[0]=2*n-1; for (int j=1;j<=2*n-1;j++) largest_frob[j]=k-1; bit=8*ceil((floor(log(shortlex_encode(&largest_frob[0],k))/log(2))+1)/8); // Declaring variables char temp_semigroup[2*n*n]; temp_semigroup[0]=1; temp_semigroup[1]=0; unsigned long long encoded_word; // Calcuating which part of the file to read size_t file_size; stringstream stream_file_name; stream_file_name << folder_name << "n-" << n << "-k-" << k << "-i-" << i << ".bit" << bit; string file_name=stream_file_name.str(); ifstream file(file_name.c_str(),ios::in|ios::binary|ios::ate); file_size=file.tellg(); unsigned long long m; m=file_size/(bit/8)/(n-1); unsigned long long pStart=ceil(((q-1)*m)/p); unsigned long long pEnd=ceil((q*m)/p); unsigned long long bStart=pStart*(bit/8)*(n-1); unsigned long long bEnd=pEnd*(bit/8)*(n-1); cout << "File: " << file_name << ", filesize = " << file_size << ", number of semigroups = " << file_size/(bit/8)/(n-1) << endl; cout << "Reading chunk " << q << " of " << p << endl; cout << "Reading semigroups "; if (pEnd==0) cout << "0"; else cout << pStart; cout << " to " << pEnd << ", "; cout << "from byte " << bStart << " to " << bEnd << endl; // Reading in q-th chunk of file char *data_stream=new char[bEnd-bStart]; file.seekg(bStart,ios::beg); file.read(data_stream,bEnd-bStart); file.close(); for (int j=0;j<pEnd-pStart;j++) { cout << "0 "; for (int l=0;l<n-1;l++) { encoded_word=0; memcpy(&encoded_word,&data_stream[(bit/8)*((n-1)*j+l)],bit/8); cout << encoded_word << " "; shortlex_decode(encoded_word,k,&(temp_semigroup[(2*n)*(l+1)])); } // Printing gaps of semigroup with both shortlex encoding and without print_semigroup(&temp_semigroup[0],n); } delete[] data_stream; return(0); }
gpl-3.0
RemiDeltombe/repnet
assets/js/input/mouse.js
1187
/** * @class Mouse Manage user mouse, Singleton * @memberOf RepNet.Input * @constructor */ var Mouse = function Mouse() { if (typeof Mouse._instance == 'undefined') { Mouse._instance = this; this.emitters = new Map(MouseEmitter) MouseEmitter.call(this, window); } return Mouse._instance; }; Tools.extend(Mouse, MouseEmitter); /** * Register mouse event on a dom element * @param {string} eventName event name * @param {Function} callback callback triggered by event * @param {DOMElement} dom Dom to register, default as window * @return {void} */ Mouse.prototype.on = function(eventName, callback, dom) { if (typeof dom == 'undefined') { return MouseEmitter.prototype.on.call(this, eventName, callback); } else { return this.emitter(dom).on(eventName, callback); } } /** * Return a dom emitter * @param {DOMElement} dom DOM * @return {MouseEmitter} emitter */ Mouse.prototype.emitter = function(dom) { var e; if (typeof dom.uuid == 'undefined') dom.uuid = Tools.generateUUID(); if (!this.emitters.exist(dom.uuid)) { e = new MouseEmitter(dom); this.emitters.set(dom.uuid, e); } return this.emitters.get(dom.uuid); }
gpl-3.0
pingwindyktator/ptest
additionals.hpp
1010
#ifndef PLIB_PTEST_ADDITIONALS_HPP #define PLIB_PTEST_ADDITIONALS_HPP #include <chrono> #include <thread> #include <vector> namespace ptest { class timeout_exception : public std::exception { virtual const char *what () const throw(); }; template <typename func_t, typename ... Args> std::chrono::microseconds measure_execution_time (func_t &&func, Args &&... args) { auto start = std::chrono::high_resolution_clock::now(); func(std::forward<Args>(args)...); auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>(end - start); } template <typename func_t, typename ... Args> void call_test (size_t threads_number, func_t &&func, Args &&... args) { std::vector<std::thread> threads; threads.reserve(threads_number); for (size_t i = 0; i < threads_number; ++i) threads.emplace_back(func, std::forward<Args>(args)...); for (auto &t : threads) t.join(); } } #endif //PLIB_PTEST_ADDITIONALS_HPP
gpl-3.0
rhomicom-systems-tech-gh/Rhomicom-ERP-Desktop
RhomicomERP/Person/Dialogs/addAttchmntDiag.cs
2704
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using BasicPersonData.Classes; namespace BasicPersonData.Dialogs { public partial class addAttchmntDiag : Form { public addAttchmntDiag() { InitializeComponent(); } public long batchID = -1; private void baseDirButton_Click(object sender, EventArgs e) { this.fileNmTextBox.Text = Global.mnFrm.cmCde.pickAFile(); } private void OKButton_Click(object sender, EventArgs e) { if (this.attchmntNmTextBox.Text == "") { Global.mnFrm.cmCde.showMsg("Please provide a name/description for the File!", 0); return; } if (this.fileNmTextBox.Text == "") { Global.mnFrm.cmCde.showMsg("Please select the File to Add!", 0); return; } if (Global.mnFrm.cmCde.myComputer.FileSystem.FileExists(this.fileNmTextBox.Text) == false) { Global.mnFrm.cmCde.showMsg("Please select a valid File!", 0); return; } long oldattchID = Global.getAttchmntID(this.attchmntNmTextBox.Text, this.batchID); if (oldattchID > 0 && this.attchmntIDTextBox.Text == "-1") { Global.mnFrm.cmCde.showMsg("Attachment Name is already in use in this Batch!", 0); return; } else if (oldattchID > 0 && oldattchID.ToString() != this.attchmntIDTextBox.Text) { Global.mnFrm.cmCde.showMsg("New Attachment Name is already in use in this Batch!", 0); return; } this.DialogResult = DialogResult.OK; this.Close(); } private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } private void addAttchmntDiag_Load(object sender, EventArgs e) { Color[] clrs = Global.mnFrm.cmCde.getColors(); this.BackColor = clrs[0]; } private void docCtgryButton_Click(object sender, EventArgs e) { //Attachment Document Categories int[] selVals = new int[1]; selVals[0] = Global.mnFrm.cmCde.getPssblValID(this.attchmntNmTextBox.Text, Global.mnFrm.cmCde.getLovID("Attachment Document Categories")); DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag( Global.mnFrm.cmCde.getLovID("Attachment Document Categories"), ref selVals, true, true, "%", "Both", true); if (dgRes == DialogResult.OK) { for (int i = 0; i < selVals.Length; i++) { this.attchmntNmTextBox.Text = Global.mnFrm.cmCde.getPssblValNm(selVals[i]); } } } } }
gpl-3.0
traintoproclaim/ttp-web
htdocs/administrator/components/com_acymailing/views/data/tmpl/vemod.php
474
<?php /** * @package AcyMailing for Joomla! * @version 4.5.1 * @author acyba.com * @copyright (C) 2009-2013 ACYBA S.A.R.L. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php $db = JFactory::getDBO(); $db->setQuery('SELECT count(*) FROM `#__vemod_news_mailer_users`'); $resultUsers = $db->loadResult(); echo JText::sprintf('USERS_IN_COMP',$resultUsers,'Vemod News Mailer');
gpl-3.0
watsalya/sentora
modules/sentoraconfig/code/controller.ext.php
6520
<?php /** * * Sentora - A Cross-Platform Open-Source Web Hosting Control panel. * * @package ZPanel * @version $Id$ * @author Bobby Allen - ballen@bobbyallen.me * @copyright (c) 2008-2014 ZPanel Group - http://www.zpanelcp.com/ * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3 * * This program (Sentora) 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/>. * */ class module_controller extends ctrl_module { static $ok; static function getConfig() { global $zdbh; $currentuser = ctrl_users::GetUserDetail(); $sql = "SELECT * FROM x_settings WHERE so_module_vc=:module AND so_usereditable_en = 'true' ORDER BY so_cleanname_vc"; $module = ui_module::GetModuleName(); $numrows = $zdbh->prepare($sql); $numrows->bindParam(':module', $module); $numrows->execute(); if ($numrows->fetchColumn() <> 0) { $sql = $zdbh->prepare($sql); $sql->bindParam(':module', $module); $res = array(); $sql->execute(); while ($rowsettings = $sql->fetch()) { if (ctrl_options::CheckForPredefinedOptions($rowsettings['so_defvalues_tx'])) { $fieldhtml = ctrl_options::OuputSettingMenuField($rowsettings['so_name_vc'], $rowsettings['so_defvalues_tx'], $rowsettings['so_value_tx']); } else { $fieldhtml = ctrl_options::OutputSettingTextArea($rowsettings['so_name_vc'], $rowsettings['so_value_tx']); } array_push($res, array('cleanname' => ui_language::translate($rowsettings['so_cleanname_vc']), 'name' => $rowsettings['so_name_vc'], 'description' => ui_language::translate($rowsettings['so_desc_tx']), 'value' => $rowsettings['so_value_tx'], 'fieldhtml' => $fieldhtml)); } return $res; } else { return false; } } static function getLastRunTime() { $time = ctrl_options::GetSystemOption('daemon_lastrun'); if ($time != '0') { return date(ctrl_options::GetSystemOption('sentora_df'), $time); } else { return false; } } static function getNextRunTime() { if (ctrl_options::GetSystemOption('daemon_lastrun') > 0) { $new_time = ctrl_options::GetSystemOption('daemon_lastrun') + ctrl_options::GetSystemOption('daemon_run_interval'); return date(ctrl_options::GetSystemOption('sentora_df'), $new_time); } else { // The default cron is set to run every 5 minutes on the 5 minute mark! return date(ctrl_options::GetSystemOption('sentora_df'), ceil(time() / 300) * 300); } } static function getLastDayRunTime() { $time = ctrl_options::GetSystemOption('daemon_dayrun'); if ($time != '0') { return date(ctrl_options::GetSystemOption('sentora_df'), $time); } else { return false; } } static function getLastWeekRunTime() { $time = ctrl_options::GetSystemOption('daemon_weekrun'); if ($time != '0') { return date(ctrl_options::GetSystemOption('sentora_df'), $time); } else { return false; } } static function getLastMonthRunTime() { $time = ctrl_options::GetSystemOption('daemon_monthrun'); if ($time != '0') { return date(ctrl_options::GetSystemOption('sentora_df'), $time); } else { return false; } } static function doUpdateConfig() { global $zdbh; global $controller; runtime_csfr::Protect(); $sql = "SELECT * FROM x_settings WHERE so_module_vc=:module AND so_usereditable_en = 'true'"; $module = ui_module::GetModuleName(); $numrows = $zdbh->prepare($sql); $numrows->bindParam(':module', $module); $numrows->execute(); if ($numrows->fetchColumn() <> 0) { $sql = $zdbh->prepare($sql); $sql->bindParam(':module', $module); $sql->execute(); while ($row = $sql->fetch()) { if (!fs_director::CheckForEmptyValue($controller->GetControllerRequest('FORM', $row['so_name_vc']))) { $updatesql = $zdbh->prepare("UPDATE x_settings SET so_value_tx = :value WHERE so_name_vc = :so_name_vc"); $value = $controller->GetControllerRequest('FORM', $row['so_name_vc']); $updatesql->bindParam(':value', $value); $updatesql->bindParam(':so_name_vc', $row['so_name_vc']); $updatesql->execute(); } } } self::$ok = true; } static function doForceDaemon() { global $zdbh; global $controller; runtime_csfr::Protect(); $formvars = $controller->GetAllControllerRequests('FORM'); if (isset($formvars['inForceFull'])) { $sql = $zdbh->prepare("UPDATE x_settings set so_value_tx = '0' WHERE so_name_vc = 'daemon_lastrun'"); $sql->execute(); $sql = $zdbh->prepare("UPDATE x_settings set so_value_tx = '0' WHERE so_name_vc = 'daemon_dayrun'"); $sql->execute(); $sql = $zdbh->prepare("UPDATE x_settings set so_value_tx = '0' WHERE so_name_vc = 'daemon_weekrun'"); $sql->execute(); $sql = $zdbh->prepare("UPDATE x_settings set so_value_tx = '0' WHERE so_name_vc = 'daemon_monthrun'"); $sql->execute(); } self::$ok = true; } static function getResult() { if (!fs_director::CheckForEmptyValue(self::$ok)) { return ui_sysmessage::shout(ui_language::translate("Changes to your settings have been saved successfully!")); } return; } }
gpl-3.0
WP-Mozart/mozart
libraries/Component/Widget/Sidebar/Customizer/customsidebars.php
2577
<?php /* * This file is part of the Mozart library. * * (c) Alexandru Furculita <alex@rhetina.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ /* Copyright Incsub (http://incsub.com) Author - Javier Marquez (http://arqex.com/) Contributor - Philipp Stracker (Incsub) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (Version 2 - GPLv2) as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* This plugin was originally developed by Javier Marquez. http://arqex.com/ */ if (!class_exists('CustomSidebars')) { // used for more readable i18n functions: __( 'text', CSB_LANG ); define('CSB_LANG', 'custom-sidebars'); $plugin_dir = dirname(__FILE__); $plugin_dir_rel = dirname(plugin_basename(__FILE__)); $plugin_url = plugin_dir_url(__FILE__); define('CSB_LANG_DIR', $plugin_dir_rel.'/lang/'); define('CSB_VIEWS_DIR', $plugin_dir.'/views/'); define('CSB_INC_DIR', $plugin_dir.'/inc/'); define('CSB_JS_URL', $plugin_url.'js/'); define('CSB_CSS_URL', $plugin_url.'css/'); // Load the actual core. require_once 'inc/class-custom-sidebars.php'; } // Include function library if (file_exists(CSB_INC_DIR.'external/wpmu-lib/core.php')) { require_once CSB_INC_DIR.'external/wpmu-lib/core.php'; } // Initialize the plugin add_action('set_current_user', array('CustomSidebars', 'instance')); if (!class_exists('CustomSidebarsEmptyPlugin')) { class CustomSidebarsEmptyPlugin extends WP_Widget { public function CustomSidebarsEmptyPlugin() { parent::WP_Widget(false, $name = 'CustomSidebarsEmptyPlugin'); } public function form($instance) { //Nothing, just a dummy plugin to display nothing } public function update($new_instance, $old_instance) { //Nothing, just a dummy plugin to display nothing } public function widget($args, $instance) { echo ''; } } //end class } //end if class exists
gpl-3.0
masadeus/second-home
includes/functions.php
7508
<?php /** * functions.php * * Second Home * * Helper functions. */ require_once("constants.php"); /** * Apologizes to user with message. */ function apologize($message) { render("apology.php", ["message" => $message]); exit; } /** * Facilitates debugging by dumping contents of variable * to browser. */ function dump($variable) { require("../templates/dump.php"); exit; } /** * Logs out current user, if any. Based on Example #1 at * http://us.php.net/manual/en/function.session-destroy.php. */ function logout() { // unset any session variables $_SESSION = []; // expire cookie if (!empty($_COOKIE[session_name()])) { setcookie(session_name(), "", time() - 42000); } // destroy session session_destroy(); } /** * Returns a stock by symbol (case-insensitively) else false if not found. */ function lookup($symbol) { // reject symbols that start with ^ if (preg_match("/^\^/", $symbol)) { return false; } // reject symbols that contain commas if (preg_match("/,/", $symbol)) { return false; } // headers for proxy servers $headers = [ "Accept" => "*/*", "Connection" => "Keep-Alive", "User-Agent" => sprintf("curl/%s", curl_version()["version"]) ]; // open connection to Yahoo $context = stream_context_create([ "http" => [ "header" => implode(array_map(function($value, $key) { return sprintf("%s: %s\r\n", $key, $value); }, $headers, array_keys($headers))), "method" => "GET" ] ]); $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={$symbol}", "r", false, $context); if ($handle === false) { // trigger (big, orange) error trigger_error("Could not connect to Yahoo!", E_USER_ERROR); exit; } // download first line of CSV file $data = fgetcsv($handle); if ($data === false || count($data) == 1) { return false; } // close connection to Yahoo fclose($handle); // ensure symbol was found if ($data[2] === "N/A" || $data[2] === "0.00") { return false; } // return stock as an associative array return [ "symbol" => $data[0], "name" => $data[1], "price" => floatval($data[2]) ]; } /** * Executes SQL statement, possibly with parameters, returning * an array of all rows in result set or false on (non-fatal) error. */ function query(/* $sql [, ... ] */) { // SQL statement $sql = func_get_arg(0); cleanInput($sql); // parameters, if any $parameters = array_slice(func_get_args(), 1); // try to connect to database static $handle; if (!isset($handle)) { try { // connect to database // ";charset=utf8" for diacrítics $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER . ";charset=utf8", USERNAME, PASSWORD); // ensure that PDO::prepare returns false when passed invalid SQL $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch (Exception $e) { // trigger (big, orange) error trigger_error($e->getMessage(), E_USER_ERROR); exit; } } // prepare SQL statement $statement = $handle->prepare($sql); if ($statement === false) { // trigger (big, orange) error trigger_error($handle->errorInfo()[2], E_USER_ERROR); exit; } // execute SQL statement $results = $statement->execute($parameters); // return result set's rows, if any if ($results !== false) { return $statement->fetchAll(PDO::FETCH_ASSOC); } else { return false; } } /** * Redirects user to destination, which can be * a URL or a relative path on the local host. * * Because this function outputs an HTTP header, it * must be called before caller outputs any HTML. */ function redirect($destination) { // handle URL if (preg_match("/^https?:\/\//", $destination)) { header("Location: " . $destination); } // handle absolute path else if (preg_match("/^\//", $destination)) { $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http"; $host = $_SERVER["HTTP_HOST"]; header("Location: $protocol://$host$destination"); } // handle relative path else { // adapted from http://www.php.net/header $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http"; $host = $_SERVER["HTTP_HOST"]; $path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\"); header("Location: $protocol://$host$path/$destination"); } // exit immediately since we're redirecting anyway exit; } /** * Renders template, passing in values. */ function render ($template, $values = []) { // if template exists, render it if (file_exists("../templates/$template")) { // extract variables into local scope extract($values); // render header require("../templates/header.php"); // render template require("../templates/$template"); // render footer require("../templates/footer.php"); } // else err else { trigger_error("Invalid template: $template", E_USER_ERROR); } } /** * Renders only for portfolio, or other sections that need the $cathegories variable. */ function render_categories ($template, $values = [], $categories) { // if template exists, render it if (file_exists("../templates/$template")) { // extract variables into local scope extract($values); extract($categories); // render header require("../templates/header.php"); // render template require("../templates/$template"); // render footer require("../templates/footer.php"); } // else err else { trigger_error("Invalid template: $template", E_USER_ERROR); } } /** * Cleans out malicious bits */ function cleanInput($input) { $search = array( '@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments ); $output = preg_replace($search, '', $input); return $output; $message = $output; apologize(); } ?>
gpl-3.0
ivelinahristova/ChooseWise
user/management/commands/newsletter.py
696
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from datetime import datetime from django.utils import timezone from dateutil.parser import parse from datetime import date, timedelta from django.core.mail import send_mail class Command(BaseCommand): help = 'Closes the specified poll for voting' def handle(self, *args, **options): users = User.objects.filter(last_login__lte = date.today() - timedelta(days = 3)) for user in users: self.stdout.write(('Successfully "%s"' % user.email)) send_mail('Hello', 'World', 'iv4etoxx@gmail.com', [user.email, 'iv4eto_xx@abv.bg'])
gpl-3.0
DrummingFish/GielinorCraft
src/main/java/com/drummingfish/gielinorcraft/GielinorCraft.java
6116
package com.drummingfish.gielinorcraft; import com.drummingfish.gielinorcraft.block.BlocksGC; import com.drummingfish.gielinorcraft.config.ConfigHandler; import com.drummingfish.gielinorcraft.gui.GuiHandler; import com.drummingfish.gielinorcraft.item.ItemsGC; import com.drummingfish.gielinorcraft.proxy.ClientProxy; import com.drummingfish.gielinorcraft.utilities.LogHelper; import com.drummingfish.gielinorcraft.world.WorldProviderGielinor; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; import net.minecraftforge.common.DimensionManager; @Mod(modid = ModInfo.ID, name = ModInfo.NAME, version = ModInfo.VERSION) public class GielinorCraft { @Mod.Instance(ModInfo.ID) public static GielinorCraft instance; @SidedProxy(clientSide = "com.drummingfish.gielinorcraft.proxy.ClientProxy", serverSide = "com.drummingfish.gielinorcraft.proxy.CommonProxy") public static ClientProxy proxy; public static int dimensionId = 8; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { ConfigHandler.init(event.getSuggestedConfigurationFile()); FMLCommonHandler.instance().bus().register(new ConfigHandler()); ItemsGC.init(); BlocksGC.init(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); proxy.initArmourRenderer("BRONZE"); proxy.initArmourRenderer("IRON"); proxy.initArmourRenderer("STEEL"); proxy.initArmourRenderer("INITIATE"); proxy.initArmourRenderer("BLACK"); proxy.initArmourRenderer("WHITE"); proxy.initArmourRenderer("MITHRIL"); proxy.initArmourRenderer("PROSELYTE"); proxy.initArmourRenderer("ELITEBLACK"); proxy.initArmourRenderer("ADAMANT"); proxy.initArmourRenderer("RUNE"); proxy.initArmourRenderer("DRAGONSTONE"); proxy.initArmourRenderer("ROCKSHELL"); proxy.initArmourRenderer("GRANITE"); proxy.initArmourRenderer("CORRUPTDRAGON"); proxy.initArmourRenderer("DRAGON"); proxy.initArmourRenderer("OBSIDIAN"); proxy.initArmourRenderer("TAWARRIOR"); proxy.initArmourRenderer("BARROWS"); proxy.initArmourRenderer("BANDOS"); proxy.initArmourRenderer("TORVA"); proxy.initArmourRenderer("TETSU"); proxy.initArmourRenderer("BATTLEMAGE"); proxy.initArmourRenderer("VANGUARD"); proxy.initArmourRenderer("MALEVOLENT"); proxy.initArmourRenderer("SOFTLEATHER"); proxy.initArmourRenderer("HARDLEATHER"); proxy.initArmourRenderer("STUDDEDLEATHER"); proxy.initArmourRenderer("FROGLEATHER"); proxy.initArmourRenderer("CARAPACE"); proxy.initArmourRenderer("SNAKESKIN"); proxy.initArmourRenderer("GREENDRAGONHIDE"); proxy.initArmourRenderer("VOIDKNIGHTRANGED"); proxy.initArmourRenderer("SPINED"); proxy.initArmourRenderer("SACREDCLAYRANGED"); proxy.initArmourRenderer("BLUEDRAGONHIDE"); proxy.initArmourRenderer("REDDRAGONHIDE"); proxy.initArmourRenderer("BLACKDRAGONHIDE"); proxy.initArmourRenderer("BLESSEDDRAGONHIDE"); proxy.initArmourRenderer("DEMONSLAYER"); proxy.initArmourRenderer("ROYALDRAGONHIDE"); proxy.initArmourRenderer("TARANGER"); proxy.initArmourRenderer("KARIL"); proxy.initArmourRenderer("ARMADYL"); proxy.initArmourRenderer("MORRIGAN"); proxy.initArmourRenderer("PERNIX"); proxy.initArmourRenderer("DEATHLOTUS"); proxy.initArmourRenderer("SIRENIC"); proxy.initArmourRenderer("FIRSTTOWER"); proxy.initArmourRenderer("ELEMENTAL"); proxy.initArmourRenderer("WIZARD"); proxy.initArmourRenderer("MIND"); proxy.initArmourRenderer("MYCELIUM"); proxy.initArmourRenderer("IMPHIDE"); proxy.initArmourRenderer("HEXCREST"); proxy.initArmourRenderer("COMBATROBES"); proxy.initArmourRenderer("DRUIDICMMAGE"); proxy.initArmourRenderer("SPIDERSILK"); proxy.initArmourRenderer("FUNGAL"); proxy.initArmourRenderer("MYSTIC"); proxy.initArmourRenderer("BODY"); proxy.initArmourRenderer("COSMIC"); proxy.initArmourRenderer("ENCHANTED"); proxy.initArmourRenderer("DAGONHAI"); proxy.initArmourRenderer("NECROMANCER"); proxy.initArmourRenderer("SPLITBARK"); proxy.initArmourRenderer("VOIDKNIGHTMAGE"); proxy.initArmourRenderer("CHAOS"); proxy.initArmourRenderer("SKELETAL"); proxy.initArmourRenderer("BATWING"); proxy.initArmourRenderer("SACREDCLAYMAGE"); proxy.initArmourRenderer("INFINITY"); proxy.initArmourRenderer("DRAGONBONE"); proxy.initArmourRenderer("BATTLE"); proxy.initArmourRenderer("GRIFOLIC"); proxy.initArmourRenderer("GOD"); proxy.initArmourRenderer("LUNAR"); proxy.initArmourRenderer("TAMAGE"); proxy.initArmourRenderer("AHRIM"); proxy.initArmourRenderer("SUBJUGATION"); proxy.initArmourRenderer("GANODERMIC"); proxy.initArmourRenderer("ZURIEL"); proxy.initArmourRenderer("VIRTUS"); proxy.initArmourRenderer("HYBRID"); proxy.initArmourRenderer("SEASINGER"); proxy.initArmourRenderer("TECTONIC"); LogHelper.info("Pre-Initialization Complete!"); } @Mod.EventHandler public void load(FMLInitializationEvent event) { //DimensionManager.registerProviderType(dimensionId, WorldProviderGielinor.class, false); //DimensionManager.registerDimension(dimensionId, dimensionId); LogHelper.info("Initialization Complete!"); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { LogHelper.info("Post-Initialization Complete!"); } }
gpl-3.0
lotaris/rox-center
spec/support/helpers.rb
906
# Copyright (c) 2012-2014 Lotaris SA # # This file is part of ROX Center. # # ROX Center 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. # # ROX Center 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 ROX Center. If not, see <http://www.gnu.org/licenses/>. module SpecHelpers def test_password "$2a$12$QPPUK39lqu68/rOZEL2N0Obwee2gI1uEffdnogGncY8tyGL3Umrcy" end def translate *args I18n.translate *args end alias_method :t, :translate end
gpl-3.0
CassandraProject/JCALCView
Source/Instruction_LAC.java
2204
/* * CALCView is a Java based Calc Block Editor * Copyright (C) 2003 * * Created by Tod Baudais * * This file is part of CALCView. * * CALCView is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * CALCView 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 CALCView. If not, see <http://www.gnu.org/licenses/>. */ // // File: Instruction_LAC.java // /* LAC Mxx (Load Accumulator) LAC Mxx loads the accumulator with contents of memory location xx, where xx is a one or two digit number, between 01 and 24 (or 1 and 24), that specifies the specific memory register whose contents are to be loaded into the accumulator. sptr(after) = sptr(before) + 1. CHECKED: March 28, 2003 */ class Instruction_LAC implements Instruction_Interface { Instruction_LAC() { } public void Run (Steps_Table_Model steps, Stack_Table_Model stack, Machine reg) { Mem_Step s = steps.Get_Current_Step (); try { float r = (float) reg.Index_To_Memory(s.Get_Register1()).Get_Value(); stack.Push(r); } catch (Exception_Stack_Overflow e) { if (reg.Index_To_Memory(Constants.PERROR).Get_Value() == 0.0F) reg.Index_To_Memory(Constants.PERROR).Set_Value(5); // error code throw e; } finally { steps.Increment_Step(); } } public void Update_Register_Use (Mem_Step s, Registers_Table_Model reg) { reg.Use_Register (Constants.PERROR); if (s.Register_1()) reg.Use_Register (s.Get_Register1()); if (s.Register_2()) reg.Use_Register (s.Get_Register2()); } public boolean Check (Mem_Step s, Machine mem) { return s.Mxx_1() && s.Empty_2(); } }
gpl-3.0
bgrainger/MySql.Data
src/MySqlConnector/Authentication/IAuthenticationPlugin.cs
827
namespace MySqlConnector.Authentication; /// <summary> /// The primary interface implemented by an authentication plugin. /// </summary> public interface IAuthenticationPlugin { /// <summary> /// The authentication plugin name. /// </summary> string Name { get; } /// <summary> /// Creates the authentication response. /// </summary> /// <param name="password">The client's password.</param> /// <param name="authenticationData">The authentication data supplied by the server; this is the <code>auth method data</code> /// from the <a href="https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest">Authentication /// Method Switch Request Packet</a>.</param> /// <returns></returns> byte[] CreateResponse(string password, ReadOnlySpan<byte> authenticationData); }
gpl-3.0
wireapp/wire-android-sync-engine
zmessaging/src/main/scala/com/waz/bitmap/BitmapDecoder.scala
2914
/* * Wire * Copyright (C) 2016 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.waz.bitmap import java.io.{File, InputStream} import android.graphics.BitmapFactory.Options import android.graphics.BitmapFactory import com.waz.log.BasicLogging.LogTag.DerivedLogTag import com.waz.log.LogSE._ import com.waz.threading.{CancellableFuture, Threading} import com.waz.utils._ import com.waz.utils.wrappers.Bitmap import com.waz.utils.wrappers class BitmapDecoder extends DerivedLogTag { private implicit lazy val dispatcher = Threading.ImageDispatcher def factoryOptions(sampleSize: Int) = returning(new Options) { opts => opts.inSampleSize = sampleSize opts.inScaled = false } private def nextPowerOfTwo(i : Int) = 1 << (32 - Integer.numberOfLeadingZeros(i)) def withFixedOrientation(bitmap: Bitmap, orientation: Int): Bitmap = if (bitmap == null || bitmap.isEmpty) wrappers.EmptyBitmap else BitmapUtils.fixOrientation(bitmap, orientation) def retryOnError(sampleSize: Int, maxSampleSize: Int = 8)(loader: Int => Bitmap): Bitmap = { try { loader(sampleSize) } catch { case e: OutOfMemoryError if sampleSize < maxSampleSize => warn(l"decoding failed for sampleSize: $sampleSize", e) retryOnError(nextPowerOfTwo(sampleSize), maxSampleSize)(loader) } } def apply(file: File, inSampleSize: Int, orientation: Int): CancellableFuture[Bitmap] = dispatcher { retryOnError(inSampleSize, inSampleSize * 3) { sampleSize => withFixedOrientation(BitmapFactory.decodeFile(file.getAbsolutePath, factoryOptions(sampleSize)), orientation) } } def apply(data: Array[Byte], inSampleSize: Int, orientation: Int): CancellableFuture[Bitmap] = dispatcher { retryOnError(inSampleSize, inSampleSize * 3) { sampleSize => withFixedOrientation(BitmapFactory.decodeByteArray(data, 0, data.length, factoryOptions(sampleSize)), orientation) } } def apply(stream: () => InputStream, inSampleSize: Int, orientation: Int): CancellableFuture[Bitmap] = dispatcher { retryOnError(inSampleSize, inSampleSize * 3) { sampleSize => IoUtils.withResource(stream()) { in => withFixedOrientation(BitmapFactory.decodeStream(in, null, factoryOptions(sampleSize)), orientation) } } } }
gpl-3.0
DennisWeyrauch/MetaLanguageParser
MetaLanguageParser/lang/java/§readLine.java
32
$$args$$ = System.in.readln()
gpl-3.0
Lester-Dowling/studies
Android/BoostExploration/app/src/main/cpp/library-static/explore-06-signals-and-slots/src/hello-world-slot.cpp
720
/** * @file hello-world-slot.cpp * @date Started Fri 13 Apr 2018 04:44:38 PM AEST * @brief Copied from: * $HOME/oss/boost_1_66_0/libs/signals2/example/hello_world_slot.cpp */ #include "pch.hpp" #include <boost/signals2/signal.hpp> #include "formatted/formatted.hpp" #include "hello-world-slot.hpp" namespace { struct HelloWorld { void operator()() const { std::cout << "Hello, World!" << std::endl; } }; } namespace explore_06_signals_and_slots { extern void hello_world_slot() { formatted::title_function_name("Hello world slot"); boost::signals2::signal<void()> sig; // Connect a HelloWorld slot HelloWorld hello; sig.connect(hello); // Call all of the slots sig(); } }
gpl-3.0
SirSengir/Starliners
Starliners.Game/Gui/Interface/ContainerHud.cs
2059
/* * Copyright (c) 2014 SirSengir * Starliners (http://github.com/SirSengir/Starliners) * * This file is part of Starliners. * * Starliners 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. * * Starliners 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 Starliners. If not, see <http://www.gnu.org/licenses/>. */ using System; using BLibrary.Gui.Data; using Starliners.Game; using Starliners.Gui; using System.Linq; namespace Starliners.Gui.Interface { sealed class ContainerHud : Container { Player _player; public ContainerHud (Player player) : base ((ushort)GuiIds.Hud) { Precedence = KeysPrecedents.HUD; Tags.Add (TAG_MENUBAR); _player = player; UpdateFragment (KeysFragments.PLAYER_NAME, _player.Name); Subscribe (_player.Bookkeeping); Subscribe (_player.HighScore); OnChanged (); } protected override void Refresh (object sender, EventArgs e) { base.Refresh (sender, e); UpdateFragment (KeysFragments.PLAYER_FUNDS, _player.Bookkeeping.Funds); UpdateFragment (KeysFragments.PLAYER_FUNDS_TRANSACTIONS, _player.Bookkeeping.Records.Where (p => p.Signal && p.TimeStamp > _player.Access.Clock.Ticks - GameClock.TICKS_PER_ROTATION).ToList ()); UpdateFragment (KeysFragments.PLAYER_SCORE, _player.HighScore.Score); UpdateFragment (KeysFragments.PLAYER_SCORE_TRANSACTIONS, _player.HighScore.Records.Where (p => p.TimeStamp > _player.Access.Clock.Ticks - GameClock.TICKS_PER_ROTATION).ToList ()); } } }
gpl-3.0
VivienGaluchot/Harmony
src/harmony/processcore/data/DataTypes.java
1310
// Harmony : procedural sound waves generator // Copyright (C) 2017 Vivien Galuchot // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package harmony.processcore.data; import harmony.math.Vector2D; public class DataTypes { // Base types public final static DataType Double = new SimpleDataType(Double.class, new Double(0.0)); public final static DataType Integer = new SimpleDataType(Integer.class, new Integer(0)); public final static DataType Boolean = new SimpleDataType(Boolean.class, new Boolean(false)); // Math public final static DataType Vector2D = new SimpleDataType(Vector2D.class, new Vector2D()); // List public final static DataType[] dataTypes = {Double, Integer}; }
gpl-3.0
mark-burnett/filament-dynamics
unit_tests/numerical/test_interpolation.py
3377
# Copyright (C) 2010 Mark Burnett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest from actin_dynamics.numerical import interpolation class TestLinearProject(unittest.TestCase): def test_linear_project(self): test_data = [({'x1': 2, 'x2': 3, 'x3': 5, 'y1': 6, 'y2': 7}, 9), ({'x1': 2, 'x2': 3, 'x3': 1, 'y1': 6, 'y2': 7}, 5), ({'x1': 2, 'x2': 3, 'x3': 5, 'y1': 1, 'y2': 5}, 13), ({'x1': 2, 'x2': 3, 'x3': 1, 'y1': 1, 'y2': 5}, -3), ({'x1': 1, 'x2': 3, 'x3': 2, 'y1': 1, 'y2': 5}, 3)] for kwargs, result in test_data: self.assertEqual(result, interpolation.linear_project(**kwargs)) class TestInterp1D(unittest.TestCase): def setUp(self): self.x_mesh = [2*i for i in xrange(10)] self.y_mesh = [4*i for i in xrange(10)] self.linterp = interpolation.interp1d(self.x_mesh, self.y_mesh) def test_middle(self): test_data = [(1, 2), (2, 4)] for x, y in test_data: self.assertEqual(y, self.linterp(x)) def test_start(self): self.assertRaises(IndexError, self.linterp, 0) def test_before_start(self): self.assertRaises(IndexError, self.linterp, -1) def test_end(self): self.assertEqual(self.y_mesh[-1], self.linterp(self.x_mesh[-1])) self.assertEqual(34, self.linterp(17)) def test_after_end(self): self.assertRaises(IndexError, self.linterp, self.x_mesh[-1] + 1) class TestLineaerResample(unittest.TestCase): def setUp(self): self.x_mesh = [2*i for i in xrange(10)] self.y_mesh = [3, 7, 5, 1, 3, 1, 7, 9, 11, 5] self.measurement = (self.x_mesh, self.y_mesh) def test_middle(self): new_x = [2*i + 1 for i in xrange(9)] new_y = map(float, [5, 6, 3, 2, 2, 4, 8, 10, 8]) results = (new_x, new_y) self.assertEqual(results, interpolation.linear_resample(self.measurement, new_x)) def test_before_start(self): new_x = range(-3, 0) + range(0, 3) new_y = [-3.0, -1.0, 1.0, 3.0, 5.0, 7.0] results = (new_x, new_y) self.assertEqual(results, interpolation.linear_resample(self.measurement, new_x)) def test_after_end(self): new_x = [15 + i for i in xrange(7)] new_y = [10.0, 11.0, 8.0, 5.0, 2.0, -1.0, -4.0] results = (new_x, new_y) self.assertEqual(results, interpolation.linear_resample(self.measurement, new_x)) if '__main__' == __name__: unittest.main()
gpl-3.0
HAMcast/HAMcast
modules/mcpo/mcpo-0.5.1/source/mcpo/messages/MCPOMemberMessage.cc
3074
// [License] // The Ariba-Underlay Copyright // // Copyright (c) 2008-2009, Institute of Telematics, Karlsruhe Institute of Technology (KIT) // // Institute of Telematics // Karlsruhe Institute of Technology (KIT) // Zirkel 2, 76128 Karlsruhe // Germany // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OF TELEMATICS OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation // are those of the authors and should not be interpreted as representing // official policies, either expressed or implied, of the Institute of // Telematics. // [License] #include "MCPOMemberMessage.h" namespace ariba { namespace services { namespace mcpo { vsznDefault(MCPOMemberMsg); /****************************************************************************** * Constructor *****************************************************************************/ MCPOMemberMsg::MCPOMemberMsg() { } // MCPOMemberMsg /****************************************************************************** * Destructor *****************************************************************************/ MCPOMemberMsg::~MCPOMemberMsg(){ } // ~MCPOMemberMsg /****************************************************************************** * Inserts neighbor NodeID into vector * @param neighbor NodeID of neighbor in cluster *****************************************************************************/ void MCPOMemberMsg::insert( NodeID* member ){ members.push_back( member ); } // insert /****************************************************************************** * Returns list of neighbors as vector * @return Vector of neighbor NodeIDs *****************************************************************************/ MCPOMemberMsg::MemberList MCPOMemberMsg::getList() { return members; } // getList }}} // spovnet::services::ariba
gpl-3.0
odedlaz/intro_to_ds
lab9_lab10/src/consts.py
80
BOOLEAN = 'boolean' TF = 'tf' TFIDF = 'tfidf' BOOLEAN_TYPE = 1 TFIDF_TYPE = 2
gpl-3.0
boompieman/iim_project
nxt_1.4.4/src/net/sourceforge/nite/tools/dacoder/DACoder.java
20137
package net.sourceforge.nite.tools.dacoder; import net.sourceforge.nite.gui.transcriptionviewer.*; import net.sourceforge.nite.gui.textviewer.*; import net.sourceforge.nite.gui.util.*; import net.sourceforge.nite.util.Debug; import net.sourceforge.nite.nxt.*; import net.sourceforge.nite.nom.*; import net.sourceforge.nite.nom.link.*; import net.sourceforge.nite.nom.nomwrite.*; import net.sourceforge.nite.meta.*; import net.sourceforge.nite.nom.nomwrite.impl.*; import net.sourceforge.nite.gui.mediaviewer.*; import net.sourceforge.nite.query.*; import net.sourceforge.nite.tools.linker.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.tree.*; import javax.swing.event.*; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.Iterator; import java.util.logging.*; import java.io.*; /** * Dialogue Act Annotation Tool * * This tool extends the AbstractCallableTool, offering functionality * for annotating dialogue acts and relations between them on a * transcribed corpus. A lot of the most important functionality is * derived directly from the * {@link net.sourceforge.nite.gui.util.AbstractCallableTool * superclass}, so don't forget to read that documentation! * Documentation on the additions in this tool will be added in due * time... whenever I find the time, basically. * @author Dennis Reidsma, UTwente * **/ public class DACoder extends AbstractCallableTool implements NOMView { /*================================================================================== CONSTRUCTION ==================================================================================*/ protected void initConfig() { config = new DACoderConfig(); } /** * The main method for a subclassing tool is probably always the same: simply call * the constructor and pass any arguments. */ public static void main(String[] args) { DACoder mainProg = new DACoder(args); } /** * Call this superclass-constructor if you make an extension of the DACoder; * then choose your own initialization inspired by what is in the other constructor of DACoder */ public DACoder() { } /** * This method starts with parsing the arguments passed to this tool, after which it calls * all those useful methods from the superclass that make development of a new tool such an * easy process. */ public DACoder(String[] args) { /* mostly necessary: */ parseArguments(args); //AbstractCallableTool.parseArguments parses the usual arguments: corpus, observation, annotator, usecvs. initConfig(); //cfreate the tool specific configuration class initLnF(); // Look and feel. Can be ignored/left out if you happen to like the default metal look-and-feel initializeCorpus(getCorpusName(),getObservationName()); //initialize the corpus, given the settings passed as arguments setupMainFrame(getConfig().getApplicationName()); //setup a main frame setupDesktop(); //setup a desktop on which all the windows (media viewer, transcription view, etc) are added //* pretty much optional: * setupLog(Logger.global, 10, 615, 500, 90); //a logging window, useful for giving feedback to the user setupMediaPlayer(695,15,380,180); //a mediaplayer: necessary if you want video or audio players synchronized to the transcription view setupTranscriptionView(10,10,500,600); //one of the most important elements for many tools: a view of the transcription. Highly customizable in the methods initTranscriptionView and refreshTranscriptionView. setupSearch(); //search functinoality can be included by default in all subclassing tools. Search results can be highlighted in the transcription view. setupActions(); setupMenus(); setupDACodingGui(); //ook uitsplitsen in tweeen en aanroepen met de coordinaten als parameter (en de NTV, corpus,. cofig) getNTV().gotoDocumentStart(); Logger.global.info("DACoder Initialization complete"); } /** * In the DACoder the following codings are loaded as annotator specific: * the codings containing the dialogue act elements, the adjacency pair elements. * <br> * The following methods are available to use here: * <br><b>nom.forceAnnotatorCoding(annotatorname, {name of coding})</b>: * The given coding MUST be loaded annotator specific. If it doesn't exist for this annotator, don't * load data for this coding. * <br><b>nom.preferAnnotatorCoding(annotatorname, {name of coding})</b>: * The given coding will preferably be loaded annotator specific. If it doesn't exist for this annotator, * load the 'main' data for this coding. * <br><b>nom.setDefaultAnnotator(annotatorname)</b>: Prefer the given anntoator for all codings, unless * overridden by one of the above methods. * */ protected void initNomAnnotatorSpecificLoads(NOMWriteCorpus nom) throws NOMException { if (getAnnotatorName()!=null) { Set specificCodings = new HashSet(); //collect in a set, because they may be stored in the same coding DACoderConfig cfg = (DACoderConfig)getConfig(); NElement dael = nom.getMetaData().getElementByName(cfg.getDAElementName()); if (dael != null) { specificCodings.add(dael.getLayer().getContainer()); } NElement apel = nom.getMetaData().getElementByName(cfg.getAPElementName()); if (apel != null) { specificCodings.add(apel.getLayer().getContainer()); } Iterator it = specificCodings.iterator(); while (it.hasNext()) { nom.forceAnnotatorCoding(getAnnotatorName(), ((NCoding)it.next()).getName()); } } } protected void setupDACodingGui() { setupEditorModules(); setupInputMaps(); } //===================== NOMSHARED INTERFACING =================================== /** * The DACoder should be a NOMView, to be able to lock the corpus and notify changes. * * AT THE MOMENT IT DOES NOT DO ANYTHING WHEN IT RECEIVES AN EDIT */ public void handleChange(NOMEdit change) { System.out.println("External change: " + change); } //===================== NEW GLOBAL ACTIONS =================================== /** * Not operational yet */ public static final String SETUP_KEYS_ACTION = "Change key settings"; /** * New actions: none */ protected void setupActions() { super.setupActions(); ActionMap actMap = getActionMap(); Action act = null; NTranscriptionView ntv = getNTV(); //no extension } /** * No new menu options in fileM */ protected void setupMenus() { super.setupMenus(); Map menus = getMenuMap(); JMenu fileM = (JMenu)menus.get("File"); } //======================== special view =========================== public void initTranscriptionViewSettings() { super.initTranscriptionViewSettings(); StringInsertDisplayStrategy ds=new StringInsertDisplayStrategy(getNTV()) { protected String formStartString(NOMElement element) { return getNTV().getSegmentText(element) + ": "; } }; ds.setEndString(""); getNTV().setDisplayStrategy(((DACoderConfig)config).getSegmentationElementName(),ds); //display: how to visualize dialogue acts: //blue letters, some extra spacing, slightly larger font and dialog act type Style style = getNTV().addStyle("dact-style",null); StyleConstants.setForeground(style,Color.blue); StringInsertDisplayStrategy ds2=new StringInsertDisplayStrategy(getNTV(), style) { protected String formStartString(NOMElement element) { // adding check if segmentation and dact element are the same // - concatenate start string - not ideal really! JK 7.8.8 String inittext=""; if (((DACoderConfig)config).getSegmentationElementName().equals(((DACoderConfig)getConfig()).getDAElementName())) { inittext = getNTV().getSegmentText(element) + ": "; } //show type of da... String text = "Dialogue-act"; String dat = ((DACoderConfig)getConfig()).getDAAttributeName(); if (dat==null || dat.length()==0) { List tl = element.getPointers(); if (tl != null) { Iterator tlIt = tl.iterator(); while (tlIt.hasNext()) { NOMPointer p2 = (NOMPointer)tlIt.next(); if (p2.getRole().equals(((DACoderConfig)getConfig()).getDATypeRole())) { text = ((String)p2.getToElement().getAttributeComparableValue(((DACoderConfig)getConfig()).getDAAGloss())); } } } } else { text = (String)element.getAttributeComparableValue(dat); } String comm = element.getComment(); if (comm == null) { comm = ""; } else if (!comm.equals("")) { comm="***"; } return " " +comm+ " " + inittext + text + ": <"; } }; ds2.setEndString("> "); getNTV().setDisplayStrategy(((DACoderConfig)getConfig()).getDAElementName(),ds2); //selection: set of annotation element types that can be selected Set s = new HashSet(); s.add(((DACoderConfig)getConfig()).getDAElementName()); getNTV().setSelectableAnnotationTypes(s); } //public Logger performancelogger; protected void setupLog(Logger log, int x, int y, int w, int h) { super.setupLog(log,x,y,w,h); //performancelogger = Logger.getLogger("performance"); /*String path = getMetaData().getCodingPath(); String name="log"; long postfix = System.currentTimeMillis(); try { FileHandler fh = new FileHandler(path+"/"+name+postfix); performancelogger.addHandler(fh); } catch (IOException ex) { }*/ //performancelogger.info("Logging started"); } /*================================================================================== SETUP METHODS ==================================================================================*/ /** * Initialize editor modules and put them on screen. */ private void setupEditorModules(){ daPane= new DAEditorModule(this); NITEMediaPlayer niteplayer = getMediaPlayer(); if ((niteplayer != null) && (niteplayer instanceof NMediaPlayer)) { NMediaPlayer player = (NMediaPlayer)niteplayer; player.addSignalListener(daPane); } // Set up two display elements to pass to the linker // modules. This just makes it easier to avoid passing lots of // parameters. DACoderConfig daconf = (DACoderConfig)getConfig(); AbstractDisplayElement daElement = new ConcreteDisplayElement(daconf.getDAElementName(), null, daconf.getDATypeDefault(), daconf.getDATypeRoot(), daconf.getDATypeRole(), daconf.getDAAGloss(), "Dialogue Act", "DA"); AbstractDisplayElement apElement = new ConcreteDisplayElement(daconf.getAPElementName(), null, daconf.getDefaultAPType(), daconf.getAPTypeRoot(), daconf.getNXTConfig().getCorpusSettingValue("aptyperole"), daconf.getAPGloss(), "Adjacency Pair", "AP"); String apsr=daconf.getNXTConfig().getCorpusSettingValue("apsourcerole"); String aptr=daconf.getNXTConfig().getCorpusSettingValue("aptargetrole"); // jonathan 16.12.04 - make adjacency pairs optional if (daconf.showAdjacencyPairWindows()) { // we're linking two daElements together with an apElement.. apPane= new LinkEditorModule(this, apElement, daElement, daElement, apsr, aptr); apPane.setDefaultType(getCorpus().getElementByID(daconf.getDefaultAPType())); } JInternalFrame daModFrame = new JInternalFrame ("Edit Dialogue Acts", true, false, true, true); SwingUtils.getResourceIcon(daModFrame, "/eclipseicons/eview16/editor_view.gif",getClass()); daModFrame.getContentPane().add(daPane.getPanel()); daModFrame.setSize(460,260); daModFrame.setLocation(520,460); daModFrame.setVisible(true); getDesktop().add(daModFrame); // jonathan 16.12.04 - make adjacency pairs optional if (((DACoderConfig)getConfig()).showAdjacencyPairWindows()) { JInternalFrame apModFrame = new JInternalFrame ("Edit Adjacency Pairs", true, false, true, true); SwingUtils.getResourceIcon(apModFrame, "/eclipseicons/eview16/editor_view.gif",getClass()); apModFrame.getContentPane().add(apPane.getPanel()); apModFrame.setSize(460,250); apModFrame.setLocation(520,10); apModFrame.setVisible(true); getDesktop().add(apModFrame); apDisplayPane= new LinkDisplayModule(this, apElement, daElement, daElement, apsr, aptr); JInternalFrame apDisplayFrame = new JInternalFrame ("Adjacency Pairs", true, false, true, true); SwingUtils.getResourceIcon(apDisplayFrame, "/net/sourceforge/nite/icons/logo/graph16.gif",getClass()); apDisplayFrame.getContentPane().add(apDisplayPane.getPanel()); apDisplayFrame.setSize(460,200); apDisplayFrame.setLocation(520,260); apDisplayFrame.setVisible(true); apPane.addLinkChangeListener(apDisplayPane); getDesktop().add(apDisplayFrame); } } protected InputMap globalImap; protected ActionMap globalAmap; protected InputMap getglobalImap(){ return globalImap; } protected ActionMap getglobalAmap(){ return globalAmap; } /** * This method should be diffferent for every tool version. * Get relevant actions from relevant editor modules, put them in central action map, create appropriate inputmaps... */ protected void setupInputMaps() { ActionMap amapDAMod = getdaPane().getActionMap(); ActionMap amapAPMod = null; // jonathan 16.12.04 - make adjacency pairs optional if (((DACoderConfig)getConfig()).showAdjacencyPairWindows()) { amapAPMod = getapPane().getActionMap(); } globalImap = new ComponentInputMap(getNTV()); globalAmap = new ActionMap(); globalAmap.put(daPane.CHANGE_DA_RANGE_ACTION, amapDAMod.get(daPane.CHANGE_DA_RANGE_ACTION)); globalImap.put(KeyStroke.getKeyStroke("typed r"), daPane.CHANGE_DA_RANGE_ACTION); globalImap.put(KeyStroke.getKeyStroke("typed R"), daPane.CHANGE_DA_RANGE_ACTION); globalAmap.put(daPane.NEW_DA_ACTION, amapDAMod.get(daPane.NEW_DA_ACTION)); globalImap.put(KeyStroke.getKeyStroke("typed d"), daPane.NEW_DA_ACTION); globalImap.put(KeyStroke.getKeyStroke("typed D"), daPane.NEW_DA_ACTION); globalAmap.put(daPane.DELETE_DA_ACTION, amapDAMod.get(daPane.DELETE_DA_ACTION)); globalImap.put(KeyStroke.getKeyStroke("DELETE"), daPane.DELETE_DA_ACTION); globalAmap.put(daPane.DELETE_DA_ACTION_NO_CONFIRM, amapDAMod.get(daPane.DELETE_DA_ACTION_NO_CONFIRM)); globalImap.put(KeyStroke.getKeyStroke("shift DELETE"), daPane.DELETE_DA_ACTION_NO_CONFIRM); // jonathan 16.12.04 - make adjacency pairs optional if (((DACoderConfig)getConfig()).showAdjacencyPairWindows()) { globalAmap.put(apPane.NEW_LINK_ACTION, amapAPMod.get(apPane.NEW_LINK_ACTION)); globalImap.put(KeyStroke.getKeyStroke("typed a"), apPane.NEW_LINK_ACTION); globalImap.put(KeyStroke.getKeyStroke("typed A"), apPane.NEW_LINK_ACTION); globalAmap.put(apPane.CHANGE_LINK_SOURCE_ACTION, amapAPMod.get(apPane.CHANGE_LINK_SOURCE_ACTION)); globalImap.put(KeyStroke.getKeyStroke("typed s"), apPane.CHANGE_LINK_SOURCE_ACTION); globalImap.put(KeyStroke.getKeyStroke("typed S"), apPane.CHANGE_LINK_SOURCE_ACTION); globalAmap.put(apPane.CHANGE_LINK_TARGET_ACTION, amapAPMod.get(apPane.CHANGE_LINK_TARGET_ACTION)); globalImap.put(KeyStroke.getKeyStroke("typed t"), apPane.CHANGE_LINK_TARGET_ACTION); globalImap.put(KeyStroke.getKeyStroke("typed T"), apPane.CHANGE_LINK_TARGET_ACTION); globalAmap.put(apPane.CANCEL_ACTION, amapAPMod.get(apPane.CANCEL_ACTION)); globalImap.put(KeyStroke.getKeyStroke("ESCAPE"), apPane.CANCEL_ACTION); } getDesktop().setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,globalImap); getDesktop().setActionMap(globalAmap); getNTV().setInputMap(JComponent.WHEN_FOCUSED,globalImap); getNTV().setActionMap(globalAmap); getdaPane().getPanel().setInputMap(JComponent.WHEN_FOCUSED,globalImap); getdaPane().getPanel().setActionMap(globalAmap); // jonathan 16.12.04 - make adjacency pairs optional if (((DACoderConfig)getConfig()).showAdjacencyPairWindows()) { getapPane().getPanel().setInputMap(JComponent.WHEN_FOCUSED,globalImap); getapPane().getPanel().setActionMap(globalAmap); } logFrame.setInputMap(JComponent.WHEN_FOCUSED,globalImap); logFrame.setActionMap(globalAmap); } /*======================= variables and accessors =======================*/ /** * The DAElementPane will be made private, and available through an accessor. * This makes it easier to avoid initialization problems. If you use an accessor, the pane * doesn't have to be initialized before you create e.g. the delete action. */ DAEditorModule daPane;//[DR: naming! /** * See {@link project.ami.textlabeler.DAAnnotationTool#ntv ntv} attribute. */ public DAEditorModule getdaPane() { return daPane; } /** * The APElementPane will be made private, and available through an accessor. * This makes it easier to avoid initialization problems. If you use an accessor, the pane * doesn't have to be initialized before you create e.g. the delete action. */ LinkEditorModule apPane; /** * See {@link project.ami.textlabeler.DAAnnotationTool#ntv ntv} attribute. */ public LinkEditorModule getapPane() { return apPane; } /** * The APDisplayPane will be made private, and available through an accessor. * This makes it easier to avoid initialization problems. If you use an accessor, the pane * doesn't have to be initialized before you create e.g. the delete action. */ LinkDisplayModule apDisplayPane; /** * See {@link project.ami.textlabeler.DAAnnotationTool#ntv ntv} attribute. */ public LinkDisplayModule getapDisplayPane() { return apDisplayPane; } /*======================== Pointless utility methods which are better off forgotten... ========================*/ /** * Extremely dependent on a particular corpus structure... */ protected NOMElement getPersonForAgentName(String agentName) { //Iterator i = search("($h person)(exists $p participant):($p@"+getMetaData().getObservationAttributeName() +"==\"" + getObservationName() + "\") && ($p>$h) && ($p@"+getMetaData().getAgentAttributeName() +"==\"" + agentName + "\")").iterator(); //if (i.hasNext()) { // i.next(); //} NOMElement result = null; //if (i.hasNext()) { // result = (NOMElement)((List)i.next()).get(0); //} return result; } /* allows sub-components to search */ public List search(String s) { return super.search(s); } }
gpl-3.0
Shebella/HIPPO
clc/modules/core/src/main/java/edu/ucsb/eucalyptus/cloud/VolumeAlreadyExistsException.java
3928
/******************************************************************************* *Copyright (c) 2009 Eucalyptus Systems, Inc. * * 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, only version 3 of the License. * * * This file 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/>. * * Please contact Eucalyptus Systems, Inc., 130 Castilian * Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/> * if you need additional information or have any questions. * * This file may incorporate work covered under the following copyright and * permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF * THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE * LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS * SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA * BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN * THE REGENTS DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT * OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR * WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH * ANY SUCH LICENSES OR RIGHTS. *******************************************************************************/ /* * * Author: Sunil Soman sunils@cs.ucsb.edu */ package edu.ucsb.eucalyptus.cloud; import com.eucalyptus.util.EucalyptusCloudException; public class VolumeAlreadyExistsException extends EucalyptusCloudException { String volume; public VolumeAlreadyExistsException() { super( "Already Exists" ); } public VolumeAlreadyExistsException(String volume) { super(volume); this.volume = volume; } public String getVolumeName() { return volume; } public VolumeAlreadyExistsException(Throwable ex) { super("Already Exists", ex); } public VolumeAlreadyExistsException(String message, Throwable ex) { super(message,ex); } }
gpl-3.0
mrtnkg/vtcpp
public_scripts/logout.php
103
<?php include('init.php'); unset($_SESSION); session_destroy(); header('Location: '.$base_url); ?>
gpl-3.0
ovh/ip-reputation-monitoring
reputation/reporting/reporter.py
4649
# -*- coding: utf-8 -*- # # Copyright (C) 2016, OVH SAS # # This file is part of ip-reputation-monitoring. # # ip-reputation-monitoring 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/>. """ Reporting module """ import smtplib from email.mime.text import MIMEText from config import settings from mongo import mongo from utils import utils from utils.logger import LOGGER MAIL_CATEGORY = 'SPAM' class Reporter(object): """ Class used to send an e-mail notification for each IP ranked as having the worst reputation. """ def __init__(self): pass def send_reports(self): """ The only public method used to run the process of email sending. """ with mongo.Mongo() as database: for entry in database.find_highest_scores(): subject = self._prepare_subject(entry['_id'], entry['value']) raw = self._prepare_raw(database, entry['_id']) body = self._prepare_body(entry['_id'], entry['value'], raw) self._send_mail(subject, body) def _send_mail(self, subject, body): """ Send a simple text e-mail. Settings are used to get the recipient. :param str subject: Subject of the email :param str body: Body content of the email """ try: msg = MIMEText(body) msg['Subject'] = subject msg['From'] = settings.SCORING_EMAIL['reporting']['from'] msg['To'] = settings.SCORING_EMAIL['reporting']['to'] smtp = smtplib.SMTP_SSL(settings.SCORING_EMAIL['host']) smtp.sendmail(msg['From'], msg['To'], msg.as_string()) smtp.quit() except Exception as ex: LOGGER.error('Something went wrong when sending the email: %s', ex) def _prepare_raw(self, database, addr): """ Retrieve raw data that triggered new event to be attached to this ip addr (it can take the form of a csv line or an email). :param Mongo database: `Mongo` instance :param str addr: Related IP address :rtype array: :return: Array of raw data for each event entry """ results = [] for entry in database.find_all_event_data_for_ip(addr): line = "Raised by {} with a weight of {}.".format(entry['source'], str(entry['weight'])) # Emails are encoded as b64 to avoid any side effects. if not utils.is_base64_encoded(entry['data']): line = "{} Raw data:\n{}".format(line, entry['data']) else: line = "{} This is an e-mail and it won't be displayed in this report.".format(line) results.append(line) return results def _prepare_subject(self, addr, score): """ Format email subject """ return "{} [score={}]".format(addr, str(score)) def _prepare_body(self, addr, score, raw): """ Format email body """ lines = [] lines.append(' '.join(['IP:', addr])) lines.append(' '.join(['Category:', MAIL_CATEGORY])) lines.append(' '.join(['Score:', str(score), '(', self._get_grade(score), ')'])) lines.append('') lines.append('') if len(raw) > 250: lines.append(' '.join(['Find below 250 of the', str(len(raw)), 'entries for this IP:'])) lines.extend(raw[:250]) else: lines.append(' '.join(['Find below the', str(len(raw)), 'entries for this IP:'])) lines.extend(raw) return '\n'.join(lines) def _get_grade(self, score): """ Associate a label to a score """ if score > 10000: return 'APOCALYPSE' elif score > 5000: return 'ABSOLUTELY CRITICAL' elif score > 2000: return 'CRITICAL' elif score > 500: return 'MAJOR' elif score > 250: return 'MINOR' elif score > 0: return 'NOT RELEVANT' else: return 'NOP'
gpl-3.0
shomy4/SuperKamp
money/forms.py
4200
# -*- coding: utf-8 -*- from django import forms from django.forms import ModelForm from parameters.models import ParLine from parameters import system_tables as ptables #from django.forms.widgets import SelectDateWidget #from datetimewidget.widgets import DateWidget, DateInput from . import messages as msg from .models import Exchange_Rate class CreateExchangeRateForm(ModelForm): """ Form for Exchange Rate """ currency_date = forms.DateField(widget=forms.TextInput(attrs={'class':'form_input', 'required':'true'}),required=True, error_messages={'required': msg.required_date}) value = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form_input', 'required':'true'}), required=True, error_messages={'required': msg.required_price}) currency = forms.ModelChoiceField(queryset=ParLine.objects.filter(table_no=ptables.PT_6, line_num4=1).order_by('line_num2'),to_field_name="line_no",label="Currency",required=True, error_messages={'required': msg.required_currency}, empty_label=None) currency_ref = forms.ModelChoiceField(queryset=ParLine.objects.filter(table_no=ptables.PT_6, line_num4=1).order_by('line_num1'),to_field_name="line_no",label="Currency",required=True, error_messages={'required': msg.required_currency_ref}, empty_label=None) last_user = forms.IntegerField(required=False) user_created = forms.IntegerField(required=False) class Meta: model = Exchange_Rate fields = ['currency_date', 'value', 'currency', 'currency_ref', 'last_user', 'user_created'] def __init__(self, *args, **kwargs): self.last_user = kwargs.pop("last_user") self.user_created = kwargs.pop("user_created") #self.currency = kwargs.pop("currency") #self.currency_ref = kwargs.pop("currency_ref") #self.date = kwargs.pop("date") super(self.__class__, self).__init__(*args, **kwargs) self.fields['last_user'].initial = self.last_user self.fields['user_created'].initial = self.user_created #self.fields['currency'].initial = self.currency #self.fields['currency_ref'].initial = self.currency_ref #self.fields['date'].initial = self.date def clean_last_user(self): last_user = self.cleaned_data['last_user'] if last_user is None: last_user = self.last_user return last_user def clean_user_created(self): user_created = self.cleaned_data['user_created'] if user_created is None: user_created = self.last_user return user_created def clean_currency(self): currency = self.cleaned_data['currency'] if currency == None: return None currency_line_no = ParLine.objects.filter(table_no=ptables.PT_6, line_desc = currency)[0].line_no return currency_line_no def clean_currency_ref(self): currency_ref = self.cleaned_data['currency_ref'] if currency_ref == None: return None currency_ref_line_no = ParLine.objects.filter(table_no=ptables.PT_6, line_desc = currency_ref)[0].line_no return currency_ref_line_no def clean_currency_date(self): currency_date = self.cleaned_data['currency_date'] if currency_date is None: currency_date = self.currency_date return currency_date class ExchangesAdvanceSearchParameters(forms.Form): #currency = forms.ModelChoiceField(queryset=ParLine.objects.filter(table_no=ptables.PT_6).order_by('line_num2'), to_field_name="line_no", label="Currency",required=True, error_messages={'required': msg.required_currency}, empty_label=None) currency = forms.ModelChoiceField(queryset=ParLine.objects.filter(table_no=ptables.PT_6, line_num4=1).order_by('line_num2'), to_field_name="line_no", label="Currency", widget=forms.Select(attrs={'class':'form-control choice_field'}),required=False) currency_date = forms.DateField( widget=forms.TextInput(attrs={'class': 'form-control choice_field', 'id': 'id_currency_date'}), required=False)
gpl-3.0
dqtien/cms
resources/views/backend/article/tag/index.blade.php
404
@extends('backend.layouts.dashboard') @section('css') <!-- css link here --> @stop @section('content') <div class="box box-primary"> <div class="box-header with-border"> </div> <div class="box-body table-responsive"> </div> <div class="box-footer clearfix"> </div> </div> @stop @section('javascript') <!-- js link here --> @stop
gpl-3.0
smulholland2/BrickApp
src/BrickApp/Models/Bricks/Post.cs
561
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BrickApp.Models.Bricks { public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public string Tags { get; set;} public DateTime DateCreated { get; set; } public DateTime LastUpdated { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } public Status Status { get; set; } } }
gpl-3.0
gmardau/gmd-tree-library
src/binary_tree/streap.hpp
11134
// gmd-tree-library - C++ - Streap tree // Copyright (C) 2017 Gustavo Martins // This file is part of the gmd-tree-library. This library 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 library. If not, see <http://www.gnu.org/licenses/>. #ifndef _GMD_BINARY_TREE_STREAP_ #define _GMD_BINARY_TREE_STREAP_ template <typename Key, typename Value, typename Info, bool SetMap, bool Threaded> struct binary_tree_node<tree_streap, Key, Value, Info, SetMap, Threaded> : public binary_tree_node_base<binary_tree_node<tree_streap, Key, Value, Info, SetMap, Threaded>, Key, Value, Info, SetMap, Threaded> { template <typename, bool, typename, typename> friend struct binary_tree_base; template <binary_tree_type, typename, bool, typename, typename> friend struct binary_tree_subbase; template <typename, typename, typename, typename, bool> friend struct binary_tree_node_superbase; template <binary_tree_type, typename, typename, typename, bool, bool> friend struct binary_tree_node; template <bool, typename, bool> friend struct binary_tree_traversor; friend struct binary_tree_iteration; private: using _Node = binary_tree_node<tree_streap, Key, Value, Info, SetMap, Threaded>; using _Base = binary_tree_node_base<_Node, Key, Value, Info, SetMap, Threaded>; using _Key = Key; using _Value = Value; using _Info = Info; static constexpr binary_tree_type _Tree = tree_streap; static constexpr bool _SetMap = SetMap, _Threaded = Threaded; /* === Variables === */ private: ::__gnu_cxx::__aligned_membuf<Info> _info; size_t _key = 0; /* === Variables === */ /* === Constructor & Destructor === */ private: binary_tree_node (_Base *up) : _Base(up) {} template <bool _ = Threaded, typename = ::std::enable_if_t<_>> binary_tree_node (_Base *up, _Base *prev, _Base *next) : _Base(up, prev, next) {} template <typename Node_Other, typename =::std::enable_if_t<_Tree == Node_Other::_Tree>> binary_tree_node (_Base *up, Node_Other *other) : _Base(up), _key(other->_key) {} template <typename Node_Other, typename =::std::enable_if_t<_Tree != Node_Other::_Tree>, typename = void> binary_tree_node (_Base *up, Node_Other *) : _Base(up) {} /* === Constructor & Destructor === */ /* === Reset === */ private: inline void reset () {} /* === Reset === */ /* === Print === */ private: inline void print () const { printf("\x1B[37m%lu\x1B[0m ", _key); } /* === Print === */ }; template <typename Node, bool Multi, typename Comparator, typename Allocator> struct binary_tree_subbase<tree_streap, Node, Multi, Comparator, Allocator> : public binary_tree_base<Node, Multi, Comparator, Allocator> { template <typename, bool, typename, typename> friend struct binary_tree_base; private: using _Node = typename Node::_Base; using _Base = binary_tree_base<Node, Multi, Comparator, Allocator>; using _Iteration = binary_tree_iteration; public: using _Base::_Base; using _Base::operator=; /* ##################################################################### */ /* ##################### Constructor & Destructor ###################### */ /* === Range === */ public: template <typename T1, typename T2> binary_tree_subbase (const T1 &first, const T2 &last, const Comparator &c = Comparator(), const Allocator &a = Allocator()) : _Base(c, a) { _Base::insert(first, last); } template <typename T1, typename T2> binary_tree_subbase (const T1 &first, const T2 &last, const Allocator &a) : _Base( a) { _Base::insert(first, last); } /* === Range === */ /* === Initializer List === */ public: binary_tree_subbase (const ::std::initializer_list<typename Node::_Info> &il, const Comparator &c = Comparator(), const Allocator &a = Allocator()) : _Base(c, a) { _Base::insert(il); } binary_tree_subbase (const ::std::initializer_list<typename Node::_Info> &il, const Allocator &a) : _Base( a) { _Base::insert(il); } /* === Initializer List === */ /* ##################### Constructor & Destructor ###################### */ /* ##################################################################### */ /* === Helpers === */ private: static inline size_t &_key (_Node *node) { return node->cast()->_key; } /* === Helpers === */ /* ##################################################################### */ /* ######################### Lookup (override) ######################### */ /* === Count (override) === */ public: template <typename Key> ::std::enable_if_t<::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>, size_t> count (const Key &key) { if(!Multi) { _Node *node = _Base::_find(key); if(node != &(_Base::_head)) { ++_key(node); _sift_up(node); return 1; } return 0; } else { size_t count = 0; _Node *lower = _Base::_lower_bound(key), *upper = _Base::_upper_bound(key); for( ; lower != upper; lower = _Iteration::_<1>(lower), ++count) { ++_key(lower); _sift_up(lower); } return count; } } /* === Count (override) === */ /* === Contains (override) === */ public: template <typename Key> inline ::std::enable_if_t<::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>, bool> contains (const Key &key) { _Node *node = _Base::_find(key); if(node != &(_Base::_head)) { { ++_key(node); _sift_up(node); } return true; } return false; } /* === Contains (override) === */ /* === Find (override) === */ public: template <typename T = typename _Base::_Traversor, typename Key> inline ::std::enable_if_t<(::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>) && _Base::template _is_traversor_v<T>, T> find (const Key &key) { _Node *node = _Base::_find(key); if(node != &(_Base::_head)) { ++_key(node); _sift_up(node); } return T(node); } /* === Find (override) === */ /* === Find short (override) === */ public: template <typename T = typename _Base::_Traversor, typename Key> inline ::std::enable_if_t<(::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>) && _Base::template _is_traversor_v<T>, T> find_short (const Key &key) { _Node *node = _Base::_find_short(key); if(node != &(_Base::_head)) { ++_key(node); _sift_up(node); } return T(node); } /* === Find short (override) === */ /* === Lower bound (override) === */ public: template <typename T = typename _Base::_Traversor, typename Key> inline ::std::enable_if_t<(::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>) && _Base::template _is_traversor_v<T>, T> lower_bound (const Key &key) { _Node *node = _Base::_lower_bound(key); if(node != &(_Base::_head)) { ++_key(node); _sift_up(node); } return T(node); } /* === Lower bound (override) === */ /* === Upper bound (override) === */ public: template <typename T = typename _Base::_Traversor, typename Key> inline ::std::enable_if_t<(::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>) && _Base::template _is_traversor_v<T>, T> upper_bound (const Key &key) { _Node *node = _Base::_upper_bound(key); if(node != &(_Base::_head)) { ++_key(node); _sift_up(node); } return T(node); } /* === Upper bound (override) === */ /* === Equal range (override) === */ public: template <typename T = typename _Base::_Traversor, typename Key> ::std::enable_if_t<(::std::is_same_v<typename Node::_Key, Key> || _is_transparent_v<Comparator, Key>) && _Base::template _is_traversor_v<T>, ::std::pair<T, T>> equal_range (const Key &key) { _Node* lower = _Base::_lower_bound(key); if(lower == &(_Base::_head) || _Base::_comparator(key, **lower)) return ::std::pair<T, T>(T(lower), T(lower)); if(!Multi) return ::std::pair<T, T>(T(lower), T(_Iteration::_<1>(lower))); _Node *upper = _Base::_upper_bound(key); for(_Node *node = lower; node != upper; node = _Iteration::_<1>(node)) { ++_key(node); _sift_up(node); } return ::std::pair<T, T>(T(lower), T(upper)); } /* === Equal range (override) === */ /* ######################### Lookup (override) ######################### */ /* ##################################################################### */ /* ##################################################################### */ /* ############################# Modifiers ############################# */ /* === Insert === */ private: template <typename Arg> ::std::pair<_Node *, bool> _insert_ (Arg &&info) { ::std::pair<_Node *, bool> result = _Base::_insert_bottom(::std::forward<Arg>(info)); ++_key(result.first); _sift_up(result.first); return result; } private: template <typename Arg> ::std::pair<_Node *, bool> _insert_hint_ (_Node *hint, Arg &&info) { ::std::pair<_Node *, bool> result = _Base::_insert_hint_bottom(hint, ::std::forward<Arg>(info)); ++_key(result.first); _sift_up(result.first); return result; } /* === Insert === */ /* === Emplace === */ private: ::std::pair<_Node *, bool> _emplace_ (_Node *node) { ::std::pair<_Node *, bool> result = _Base::_emplace_bottom(node); ++_key(result.first); _sift_up(result.first); return result; } private: ::std::pair<_Node *, bool> _emplace_hint_ (_Node *hint, _Node *node) { ::std::pair<_Node *, bool> result = _Base::_emplace_hint_bottom(hint, node); ++_key(result.first); _sift_up(result.first); return result; } /* === Emplace === */ /* === Erase === */ private: void _erase_ (_Node *node, const bool del) { if(_sift_down(node) == 0) _Base::_remove_node(node, node->_down[0], del); else _Base::_remove_node(node, node->_down[1], del); } /* === Erase === */ /* ############################# Modifiers ############################# */ /* ##################################################################### */ /* === Sift === */ private: void _sift_up (_Node *node) { for(_Node *parent = node->_up; parent != &(_Base::_head) && _key(parent) <= _key(node); parent = node->_up) { if(node == parent->_down[0]) _Base::_rotate_right(parent, node); else _Base::_rotate_left (parent, node); } } private: bool _sift_down (_Node *node) { while(node->_down[0] != nullptr) { if(node->_down[1] != nullptr) { if(_key(node->_down[0]) > _key(node->_down[1])) _Base::_rotate_right(node, node->_down[0]); else _Base::_rotate_left (node, node->_down[1]); } else return 0; } return 1; } /* === Sift === */ }; #endif
gpl-3.0
JTeamDevelop/CPXUtilities
dev/incomplete/user.js
11384
/////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.vue.AU = new Vue({ el: '#title', data: { ready:false, _id: "", name: "", HP : 0, maxHP: 0, XP:0, XPFree: 0, AP:0, coin: 0, location:[] }, computed:{ AUdata: function() { var realmName = '<h2 class="center header">'+CPXDB[this.location[0]].name+'</h2>'; var unitdata = '<h3 class="center header">'+this.name+" HP "+this.HP+" AP "+Math.floor(this.AP)+'</h3>'; return realmName+unitdata; } }, methods: { showVue: function(unit) { for (var x in CPX.hero.model){ if(objExists(this[x])){ if(x=="location") {this[x] = unit[x].concat([]); } else {this[x] = unit[x]; } } } this.ready = true; } } }) /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.user.addRealm = function (realmid) { if(!objExists(USER[realmid])) { USER[realmid] = {}; CPX.save.user(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit = function (opts) { var uobj = { class : ["unit"] } } CPX.unit.array = function () { var A = []; for(var x in CPXUNITS){ A.push(CPXUNITS[x]); } return A; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.actions = function (type,unit) { var actions = []; if(type=="fight"){ if(unit.class.includes('hero')){ var weapon = unit.inventory.find(function (el){ return el.equipped && el.class.includes('weapon'); }) if(objExists(weapon)) { if(weapon.class.includes('ranged')){actions.push("shoot"); } actions.push("fight"); } } else if (unit.class.includes('minion')){ actions.push("fight"); if(unit.special.includes('Shoot')) { actions.push('Shoot'); } } actions.push('defend','wait'); } return actions; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.move = function (unit,to) { //update the unit location unit.location = to.concat([]); CPX.save.unit(unit); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.minionSkills = function (base,rank) { var skills = {}; for (var x in base.skills){ skills[x] = base.skills[x]+rank; if(skills[x]<0) { skills[x] = 0} } return skills; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.buy = function (unit,cost,type) { //reduce coin unit.coin-=cost; var item={}; if(type=="store"){ for(var x in CPXTEMP.store){ if(CPXTEMP.store[x].qty>0){ if(objExists(GEAR[CPXTEMP.store[x].id])){ item = objCopy(GEAR[CPXTEMP.store[x].id]); item.template=item.id; item.name=item.id; delete item.id; item.qty = CPXTEMP.store[x].qty; item.equipped = false; unit.inventory.push(item); } } } } else if(type="recruit"){ //new recruits for(var x in CPXTEMP.recruit){ CPX.unit.addRecruit(unit,CPXTEMP.recruit[x]); } } CPX.save.unit(unit); }; /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.addRecruit = function (unit,recruit){ //only if qty is greater than 0 if(recruit.qty>0){ //if the recruit exists in the minions list if(objExists(MINIONS[recruit.id])){ //copy the object to mod var item = objCopy(MINIONS[recruit.id]); //set the template & name equals the id, remove id item.template=item.id; item.name=item.id; item.id = ''; //set skills item.rank = recruit.rank; item.skills = CPX.unit.minionSkills(MINIONS[recruit.id],recruit.rank); //add minion class item.class.push('minion'); //set HP - 1 for a minion item.maxHP = 1; item.HP = 1; //initially not independent from hero. No conditions item.independent = false; item.conditions = []; //set the quantity - total qty will be pushed to the array item.qty = 1; for(var i=0;i<recruit.qty;i++) { unit.recruits.push(item); } } CPX.save.unit(unit); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.refreshAP = function (unit){ if(unit.AP<30) { unit.AP+=30; } unit.recruits.forEach(function(el){ if(el.independent) { if(el.AP<30) {el.AP+=30; } } }) CPX.save.unit(unit); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.fullHP = function (unit){ unit.HP=unit.maxHP; CPX.save.unit(unit); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.newHD = function (unit){ var nmax = 6+CPXC.rpg((unit.HD-1)+'d6', {sum: true})+unit.HD*CPX.unit.skillVal(unit,'Physique'); if(nmax > unit.maxHP) { unit.maxHP = nmax; } return } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.moveSpeed = function (unit){ var speed = unit.speed; //find the slowest speed of the party unit.recruits.forEach(function(el){ if(!el.independent){} }); return speed; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// //changes is an object full of keys to modify CPX.unit.change = function (unit,changes){ for (var x in changes){ unit[x] += changes[x]; if(unit.HP<0) { //kill hero } } //only save heroes; if(unit.class.includes('hero')) { CPX.save.unit(unit); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.damage = function (unit){ var might = (objExists(unit.skills.Might)) ? unit.skills.Might-1 : 0; var d=[], weapon={dmg:['1d4'],class:[]}; if(unit.class.findOne(['hero','foe'])){ unit.inventory.forEach(function (el){ if(el.equipped && el.class.includes('weapon')) { weapon = objCopy(el); } }) if(unit.class.includes('foe')){ var fdmg = []; weapon.dmg.forEach(function(el){ fdmg = fdmg.concat(DIERANKS[el]); }) weapon.dmg = fdmg; } } //if minion calculate differently else if (unit.class.includes('minion')){ unit.inventory.forEach(function(el){ if(objExists(GEAR[el])) { if(GEAR[el].class.includes('weapon')) { weapon=GEAR[el]; } } }) } if(weapon.class.includes('ranged')) { d = weapon.dmg; } else { d = [].concat(DIERANKS[might],weapon.dmg); } return d; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.parry = function (unit){ var fight = (objExists(unit.skills.Fight)) ? unit.skills.Fight : 1; var p = 3+fight; return p; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.dodge = function (unit){ var athletics = (objExists(unit.skills.Athletics)) ? unit.skills.Athletics : 1; var a = 3+athletics; return a; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.armor = function (unit){ var fort = (objExists(unit.skills.Fortitude)) ? unit.skills.Fortitude : 1; var f=3+fort, armor={armor:0}; if(unit.class.findOne(['hero','foe'])){ unit.inventory.forEach(function (el){ if(el.equipped && el.class.includes('armor')) { armor = el; } }) } //if minion calculate differently else if (unit.class.includes('minion')){ unit.inventory.forEach(function(el){ if(objExists(GEAR[el])) { if(GEAR[el].class.includes('armor')) { armor = GEAR[el]; } } }) } return {f:f,arm:armor.armor}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.unit.skillVal = function (unit,skill){ var v=0, fight = CPX.vue.fight.show; function recruitBonus(){ unit.recruits.forEach(function(el){ //if the recruit has the skill - the unit gets a bonus if(objExists(el.skills[skill])) { //if the recruit rank is greater than the hero's use the minions' if(el.skills[skill]>=v) { v=el.skills[skill]+1; } //otherwise increas the hero value by one else { v++; } } }) } //skills - go backwards for vue use - epic,legendary,master,expert,professional,trained,untrianed,liability if(objExists(unit.skills[skill])) { v= unit.skills[skill]; } //if foe check for qty if (unit.class.includes('foe')){ if(unit.qty>1) { if(unit.qty >4) {v+=4;} else {v+=unit.qty;} } } //check if there are recruits to support the unit if (!fight) { recruitBonus(); } return v; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.hero = function (opts) { var hero = objCopy(CPX.hero.model); hero._id = CPXC.guid(); hero.class = ["hero","unit"]; hero.skills = {Athletics:1,Lore:1,Physique:1,Will:1}; hero.HP = 3; hero.maxHP = 3; hero.XP = -50; hero.XPFree = 50; hero.AP = 30; hero.coin = 50; hero.speed=30; CPXUNITS[hero._id] = hero; CPX.save.unit(hero); return CPXUNITS[hero._id]; } CPX.hero.model = { _id: "", class: [], name: "", speed:0, HP : 0, maxHP : 0, XP:0, XPFree:0, AP:0, coin: 0, conditions:[], recruits: [], inventory: [], location : [], aspects : [], skills : {}, stunts : [] } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.optionList = function (list) { var R = ""; list.forEach(function (L) { R+=CPX.option(L); }); return R; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// CPX.clearAllData = function (event) { var content = '<div data-role="header"><h1>Destroy All Data</h1></div>'; content += "<div class=content>This will delete all the data! You will have to start over. Are you sure?</div>"; var buttons = [ {text:"Yes",id:"destroyAll",classes:["red"],style:"inline"}, {text:"No",classes:["green","closeDialog"],data:[["id","confirm"]],style:"inline"} ] content += '<div class=center>'+CPX.optionList(buttons)+'</div>'; $("#confirm").html(content); $("#confirm").enhanceWithin(); $( "#confirm" ).popup(); $( "#confirm" ).popup("open",{positionTo: "window"} ); $('#destroyAll').on('click',function() { localStorage.clear(); $( "#confirm" ).popup( "destroy" ); }); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
gpl-3.0
data-tsunami/museo-cachi
cachi/migrations/0010_auto__chg_field_fragmento_numero_inventario.py
15801
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Fragmento.numero_inventario' db.alter_column(u'cachi_fragmento', 'numero_inventario', self.gf('django.db.models.fields.PositiveIntegerField')(null=True)) def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'Fragmento.numero_inventario' raise RuntimeError("Cannot reverse this migration. 'Fragmento.numero_inventario' and its values cannot be restored.") # The following code is provided here to aid in writing a correct migration # Changing field 'Fragmento.numero_inventario' db.alter_column(u'cachi_fragmento', 'numero_inventario', self.gf('django.db.models.fields.PositiveIntegerField')()) models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'cachi.adjunto': { 'Meta': {'object_name': 'Adjunto'}, 'adjunto': ('django.db.models.fields.files.FileField', [], {'max_length': '768'}), 'content_type': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'ficha_relevamiento_sitio': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.FichaRelevamientoSitio']", 'null': 'True', 'blank': 'True'}), 'ficha_tecnica': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'adjunto_ficha_tecnica'", 'null': 'True', 'to': u"orm['cachi.FichaTecnica']"}), 'fragmento': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'adjunto_fragmento'", 'null': 'True', 'to': u"orm['cachi.Fragmento']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'informe_campo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.InformeCampo']", 'null': 'True', 'blank': 'True'}), 'nombre_archivo': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'pieza_conjunto': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'adjunto_pieza_conjunto'", 'null': 'True', 'to': u"orm['cachi.PiezaConjunto']"}), 'size': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'tipo': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'cachi.ficharelevamientositio': { 'Meta': {'object_name': 'FichaRelevamientoSitio'}, 'adjuntos': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Adjunto']", 'null': 'True', 'blank': 'True'}), 'autor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Persona']"}), 'fecha': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'cachi.fichatecnica': { 'Meta': {'object_name': 'FichaTecnica'}, 'alto': ('django.db.models.fields.PositiveIntegerField', [], {}), 'autor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Persona']", 'null': 'True', 'blank': 'True'}), 'color': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'decoracion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'desperfectos': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'desperfectos_fabricacion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'diagnostico_estado': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'diametro_max': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'diametro_min': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'espesor': ('django.db.models.fields.PositiveIntegerField', [], {}), 'fecha': ('django.db.models.fields.DateField', [], {}), 'fragmento': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'fichas_tecnicas'", 'to': u"orm['cachi.Fragmento']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inscripciones_marcas': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'observacion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'otras_caracteristicas_distintivas': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'peso': ('django.db.models.fields.PositiveIntegerField', [], {}), 'razon_actualizacion': ('django.db.models.fields.PositiveIntegerField', [], {}), 'reparaciones': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'tratamiento': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'usuario': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}) }, u'cachi.fragmento': { 'Meta': {'object_name': 'Fragmento'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'numero_inventario': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'pieza_conjunto': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'fragmentos_pieza_conjunto'", 'to': u"orm['cachi.PiezaConjunto']"}), 'ultima_version': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'ultima_version'", 'null': 'True', 'to': u"orm['cachi.FichaTecnica']"}) }, u'cachi.informecampo': { 'Meta': {'object_name': 'InformeCampo'}, 'adjuntos': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Adjunto']", 'null': 'True', 'blank': 'True'}), 'autor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Persona']"}), 'fecha': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sitio_aqueologico': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.SitioArqueologico']", 'null': 'True', 'blank': 'True'}) }, u'cachi.modificacion': { 'Meta': {'object_name': 'Modificacion'}, 'atributo': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'fecha': ('django.db.models.fields.DateField', [], {}), 'ficha_tecnica': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.FichaTecnica']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'pieza_conjunto': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.PiezaConjunto']", 'null': 'True', 'blank': 'True'}), 'sitio_aqueologico': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.SitioArqueologico']", 'null': 'True', 'blank': 'True'}), 'valor_nuevo': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'valor_viejo': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, u'cachi.naturaleza': { 'Meta': {'object_name': 'Naturaleza'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'cachi.persona': { 'Meta': {'object_name': 'Persona'}, 'apellido': ('django.db.models.fields.CharField', [], {'max_length': '64'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True'}) }, u'cachi.piezaconjunto': { 'Meta': {'object_name': 'PiezaConjunto'}, 'cantidad_fragmentos': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'condicion_hallazgo': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'fecha_hallazgo': ('django.db.models.fields.DateField', [], {}), 'forma': ('django.db.models.fields.TextField', [], {'max_length': '128'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'naturaleza': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Naturaleza']"}), 'nombre_descriptivo': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'persona_colectora': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Persona']", 'null': 'True', 'blank': 'True'}), 'tecnica_manufactura': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'tipo_adquisicion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.TipoAdquisicion']", 'null': 'True', 'blank': 'True'}), 'tipo_condicion_hallazgo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.TipoCondicionHallazgo']", 'null': 'True', 'blank': 'True'}), 'ubicacion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.Ubicacion']", 'null': 'True', 'blank': 'True'}) }, u'cachi.procedencia': { 'Meta': {'object_name': 'Procedencia'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'otra': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'pieza_conjunto': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'procedencia'", 'unique': 'True', 'to': u"orm['cachi.PiezaConjunto']"}), 'sitio_arqueologico': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.SitioArqueologico']", 'null': 'True', 'blank': 'True'}), 'ubicacion_geografica': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.UbicacionGeografica']", 'null': 'True', 'blank': 'True'}) }, u'cachi.sitioarqueologico': { 'Meta': {'object_name': 'SitioArqueologico'}, 'coordenada_x': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'coordenada_y': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'ubicacion_geografica': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.UbicacionGeografica']"}) }, u'cachi.tipoadquisicion': { 'Meta': {'object_name': 'TipoAdquisicion'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'cachi.tipocondicionhallazgo': { 'Meta': {'object_name': 'TipoCondicionHallazgo'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'cachi.ubicacion': { 'Meta': {'object_name': 'Ubicacion'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'cachi.ubicaciongeografica': { 'Meta': {'object_name': 'UbicacionGeografica'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'padre': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cachi.UbicacionGeografica']", 'null': 'True', 'blank': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['cachi']
gpl-3.0
nunux-keeper/keeper-core-api
src/dao/mongodb/client.dao.js
241
'use strict' const AbstractMongodbDao = require('./abstract') /** * Client DAO. * @module client.dao */ class ClientDao extends AbstractMongodbDao { constructor (client) { super(client, 'client') } } module.exports = ClientDao
gpl-3.0
antonio-peyrano/micrositio
v1.1.0/php/frontend/programa/catPrograma.php
8697
<?php /* * Micrositio-Phoenix v1.0 Software para gestion de la planeación operativa. * PHP v5 * Autor: Prof. Jesus Antonio Peyrano Luna <antonio.peyrano@live.com.mx> * Nota aclaratoria: Este programa se distribuye bajo los terminos y disposiciones * definidos en la GPL v3.0, debidamente incluidos en el repositorio original. * Cualquier copia y/o redistribucion del presente, debe hacerse con una copia * adjunta de la licencia en todo momento. * Licencia: http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ header('Content-Type: text/html; charset=iso-8859-1'); //Forzar la codificación a ISO-8859-1. session_start(); include_once ($_SERVER['DOCUMENT_ROOT']."/phoenix/php/backend/dal/conectividad.class.php"); //Se carga la referencia a la clase de conectividad. include_once ($_SERVER['DOCUMENT_ROOT']."/phoenix/php/backend/config.php"); //Se carga la referencia de los atributos de configuración. include_once ($_SERVER['DOCUMENT_ROOT']."/phoenix/php/backend/dal/grid.class.php"); //Se carga la referencia a la clase para manejo de rejillas de datos. global $username, $password, $servername, $dbname; $condicionales = ''; //Variable de control de condiciones de clausula select. $sufijo= "prg_"; //Variable de control de sufijo de identificadores. $Inicio = 0; $Pagina = 0; $DisplayRow = 10; if(isset($_GET['pagina'])) { //Se proporciona referencia de pagina a mostrar. $Pagina = $_GET['pagina']; $Inicio = ($Pagina-1)*$DisplayRow; } else { //En caso de no ser proporcionada la pagina. $Inicio = 0; $Pagina = 1; } if(isset($_GET['nomprograma'])) { /* * Si el archivo ha sido llamado como una referencia con parametros. */ $condicionales= 'Programa LIKE \'%'.$_GET['nomprograma'].'%\''; } if(isset($_GET['nomidentidad'])) { /* * Si el archivo ha sido llamado como una referencia con parametros. */ if($_GET['nomidentidad']!="-1") { if($condicionales!='') { //Si la variable de condicionales no esta vacia. $condicionales= $condicionales.' AND '; } $condicionales= $condicionales.'opProgramas.idEntidad LIKE \'%'.$_GET['nomidentidad'].'%\''; } } $objConexion= new mySQL_conexion($username, $password, $servername, $dbname); //Se crea el objeto de la clase a instanciar. if($_SESSION['idEmpleado']!=0) { /* * En el caso que el usuario que inicio sesion, sea un empleado registrado, * las consultas sobre programas solo podran desplegar aquellos programas * en los que el usuario aparezca como responsable o auxiliar. */ if($_SESSION['nivel'] == 'Administrador') { /* * En caso que el usuario sea un administrador asociado a un empleado registrado * en el sistema. */ if($condicionales=="") { //Cargar la cadena de consulta por default. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } else { //En caso de contar con el criterio de filtrado. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 AND " .$condicionales. " ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } } else { /* * En el caso de tratarse de un usuario sin perfil de administrador. */ if($condicionales=="") { //Cargar la cadena de consulta por default. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 AND (idResponsable=".$_SESSION['idEmpleado']." OR idSubalterno=".$_SESSION['idEmpleado'].") ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } else { //En caso de contar con el criterio de filtrado. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 AND " .$condicionales. " AND (idResponsable=".$_SESSION['idEmpleado']." OR idSubalterno=".$_SESSION['idEmpleado'].") ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } } } else { /* * Considerando que el usuario no sea un empleado registrado, se establece la carga * convencional de los programas. Tomando anticipado que se trata de un administrador. */ if($_SESSION['nivel'] == 'Administrador') { if($condicionales=="") { //Cargar la cadena de consulta por default. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } else { //En caso de contar con el criterio de filtrado. $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=0 AND " .$condicionales. " ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } } else { $consulta= "SELECT idPrograma, Nomenclatura, Programa, Entidad, opProgramas.Status FROM (opProgramas INNER JOIN catEntidades ON catEntidades.idEntidad = opProgramas.idEntidad) WHERE opProgramas.Status=-1 ORDER BY idPrograma"." limit ".$Inicio.",".$DisplayRow; //Se establece el modelo de consulta de datos. } } $dataset = $objConexion -> conectar($consulta); //Se ejecuta la consulta. $column_names= ""; //Variable de control para los nombres de columnas a mostrarse en el grid. function constructor($dataset,$sufijo) { /* Esta función se encarga de crear el contenido HTML de la pagina * tal como lo visualizara el usuario en el navegador. */ $objGrid = new myGrid($dataset, 'Catalogo de Programas', $sufijo, 'idPrograma'); echo' <html> <link rel= "stylesheet" href= "./css/dgstyle.css"></style> <head> </head> <body>'; echo $objGrid->headerTable(); echo $objGrid->bodyTable(); echo' </body> </html> '; } constructor($dataset,$sufijo); //Llamada a la funcion principal de la pagina. ?>
gpl-3.0
hollys-home-kitchen/cookmomcooks
client/src/app/recipe-form/recipe-form.component.ts
843
import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Recipe } from '../recipe'; import { RecipeService } from '../recipe.service' @Component({ moduleId: module.id, selector: 'app-recipe-form', templateUrl: 'recipe-form.component.html', styleUrls: ['recipe-form.component.css'], providers: [RecipeService] }) export class RecipeFormComponent implements OnInit { @Input() id; recipe = new Recipe(); constructor(private recipeService: RecipeService, private router: Router) {} ngOnInit() { if (this.id) { this.recipeService .get(this.id) .subscribe(response => this.recipe = response.json()); } } onSubmit() { this.recipeService .save(this.recipe) .subscribe(response => this.router.navigate(['/recipe-list'])); } }
gpl-3.0
lostjared/Acid.Cam.v2.Qt
src/plugin.cpp
3150
/* * Acid Cam v2 - Qt/OpenCV Edition * written by Jared Bruni ( http://lostsidedead.com ) * (C) 2017 GPL */ #include "plugin.h" PluginList plugins; void add_directory(QDir &cdir, std::vector<std::string> &files) { cdir.setFilter(QDir::Files | QDir::Dirs); QFileInfoList list = cdir.entryInfoList(); int pos = 0; QString platform; #if defined(__linux__) platform = ".so"; #elif defined(__APPLE__) platform = ".dylib"; #else platform = ".dll"; #endif while(pos < list.size()) { QFileInfo info = list.at(pos); if(info.isDir() && info.fileName() != "." && info.fileName() != "..") { QDir cdir = info.dir(); cdir.cd(info.fileName()); add_directory(cdir, files); ++pos; continue; } else if(info.isFile() && info.fileName() != "." && info.fileName() != ".." && info.fileName().contains(platform)) { files.push_back(info.filePath().toStdString()); } ++pos; } } void init_plugins() { std::vector<std::string> files; QDir d("plugins"); add_directory(d, files); if(files.size()>0) { for(unsigned int i = 0; i < files.size(); ++i) { Plugin *p = new Plugin(); if(p->loadPlugin(files[i])) plugins.plugin_list.push_back(p); } } } void draw_plugin(cv::Mat &frame, int filter) { for(int z = 0; z < frame.rows; ++z) { for(int i = 0; i < frame.cols; ++i) { unsigned char rgb[3]; cv::Vec3b &cpixel = frame.at<cv::Vec3b>(z, i); rgb[0] = cpixel[0]; rgb[1] = cpixel[1]; rgb[2] = cpixel[2]; plugins.plugin_list[filter]->call_Pixel(i, z, rgb); cpixel[0] = rgb[0]; cpixel[1] = rgb[1]; cpixel[2] = rgb[2]; } } plugins.plugin_list[filter]->call_Complete(); } void plugin_callback(cv::Mat &) { } Plugin::Plugin() { library = 0; } Plugin::~Plugin() { if(library) delete library; } bool Plugin::loadPlugin(const std::string &text) { library = new QLibrary(text.c_str()); if(!library) { QMessageBox::information(0, QObject::tr("Could not load Library"), text.c_str()); return false; } pixel_function = (pixel) library->resolve("pixel"); if(!pixel_function) { QMessageBox::information(0, text.c_str(), "Could not find pixel function"); return false; } complete_function = (complete) library->resolve("complete"); if(!complete_function) { QMessageBox::information(0, text.c_str(), "Could not find complete function"); return false; } mod_name = text; return true; } void Plugin::call_Pixel(int x, int y, unsigned char *rgb) { if(pixel_function) pixel_function(x, y, rgb); } void Plugin::call_Complete() { if(complete_function) complete_function(); } PluginList::PluginList() { } PluginList::~PluginList() { if(plugin_list.size() == 0) return; for(auto i = plugin_list.begin(); i != plugin_list.end(); ++i) delete *i; }
gpl-3.0
ArrayZone/ArrayUniverse
src/xgp3.0.0/upload/application/core/Objects.php
3003
<?php /** * @project XG Proyect * @version 3.x.x build 0000 * @copyright Copyright (C) 2008 - 2014 */ if ( ! defined ( 'INSIDE' ) ) { die ( header ( 'location:../../' ) ) ; } class Objects { private $_objects; private $_relations; private $_price; private $_combat_specs; private $_production; private $_objects_list; /** * __construct() */ public function __construct() { // REQUIRE THIS DAMN FILE require ( XGP_ROOT . 'application/core/objects_collection.php' ); // SET THE ARRAY ELEMENTS TO A PARTICULAR PROPERTY $this->_objects = $resource; $this->_relations = $requeriments; $this->_price = $pricelist; $this->_combat_specs = $CombatCaps; $this->_production = $ProdGrid; $this->_objects_list = $reslist; } /** * method get_objects * param $object_id * return one particular object or everything */ public function get_objects ( $object_id = NULL ) { if ( ! empty ( $object_id ) ) { return $this->_objects[$object_id]; } else { return $this->_objects; } } /** * method get_relations * param $object_id * return one particular object relations or everything */ public function get_relations ( $object_id = NULL ) { if ( ! empty ( $object_id ) ) { return $this->_relations[$object_id]; } else { return $this->_relations; } } /** * method get_price * param $object_id * param $resource * return one particular object relations or everything */ public function get_price ( $object_id = NULL , $resource = '' ) { if ( ! empty ( $object_id ) ) { if ( empty ( $resource ) ) { return $this->_price[$object_id]; } else { return $this->_price[$object_id][$resource]; } } else { return $this->_price; } } /** * method get_combat_specs * param $object_id * param $type * return one particular object combat specs or everything */ public function get_combat_specs ( $object_id = NULL , $type = '' ) { if ( ! empty ( $object_id ) ) { if ( empty ( $type ) ) { return $this->_combat_specs[$object_id]; } else { return $this->_combat_specs[$object_id][$type]; } } else { return $this->_combat_specs; } } /** * method get_production * param $object_id * return one particular object relations or everything */ public function get_production ( $object_id = NULL ) { if ( ! empty ( $object_id ) ) { return $this->_production[$object_id]; } else { return $this->_production; } } /** * method get_objects_list * param $object_id * return one particular object list or everything */ public function get_objects_list ( $object_id = NULL ) { if ( ! empty ( $object_id ) ) { return $this->_objects_list[$object_id]; } else { return $this->_objects_list; } } } /* end of Objects.php */
gpl-3.0
uliss/pddoc
pddoc/pd/comment.py
2993
#!/usr/bin/env python # coding=utf-8 # Copyright (C) 2014 by Serge Poltavski # # serge.poltavski@gmail.com # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/> # __author__ = 'Serge Poltavski' from .baseobject import * from .abstractvisitor import AbstractVisitor from .obj import PdObject class Comment(BaseObject): def __init__(self, x, y, args, width=0): super(Comment, self).__init__(x, y, 0, 0) self.args = [] self._line_width = width for a in args: if a: self.args.append(a.strip()) @staticmethod def unescape(s): return s.strip() \ .replace(chr(13), "") \ .replace(chr(10), "") \ .replace("\\;", ";") \ .replace("\\,", ",") @staticmethod def escape(s): res = "" for c in s: if c == ';': res += " \\; " elif c == ',': res += " \\, " elif c in (chr(10), chr(13)): continue else: res += c return res def text(self): res = "" for a in self.args: a = self.unescape(a) if a == ",": res += "," elif a == ";": res += ";" else: res += " " + a res = res.strip() return res def __str__(self): res = "# %-39s {x:%i,y:%i}, f %i" % (self.text(), self._x, self._y, self._line_width) return res def draw(self, painter): painter.draw_comment(self) def traverse(self, visitor): assert isinstance(visitor, AbstractVisitor) if visitor.skip_comment(self): return visitor.visit_comment(self) def calc_brect(self): brect = PdObject.brect_calc().comment_brect(self) self._width = brect[2] self._height = brect[3] def line_width(self): return self._line_width
gpl-3.0
malkiah/bdkanvas
client/js/UIPropertySectionTab.js
1316
'use strict'; class UIPropertySectionTab { constructor(bundle, lines) { this.bundle = bundle; this.lines = lines; this.createDiv(); } createDiv(){ this.div = document.createElement("div"); this.div.className = "sectiontabtable"; var columns = Math.ceil(Object.keys(this.bundle.properties).length / this.lines); var column = 0; var line = 0; var rowDiv = null; for (var name in this.bundle.properties) { if (this.bundle.properties.hasOwnProperty(name)) { var property = this.bundle.properties[name]; if (column === 0) { rowDiv = document.createElement("div"); rowDiv.className = "sectiontabrow"; this.div.appendChild(rowDiv); } var descCell = document.createElement("div"); descCell.className = "sectiontabcell_l"; descCell.appendChild(document.createTextNode(property.data.desc + ": ")); rowDiv.appendChild(descCell); var ctrlCell = document.createElement("div"); ctrlCell.className = "sectiontabcell_r"; ctrlCell.appendChild(property.getControl()); rowDiv.appendChild(ctrlCell); column++; if (column === columns){ line++; column = 0; } } } } getDiv() { return this.div; } }
gpl-3.0
lveci/nest
nest-reader-dem/src/main/java/org/esa/nest/dataio/dem/ElevationTile.java
960
/* * Copyright (C) 2013 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.nest.dataio.dem; /** Interface for Elevation tiles */ public interface ElevationTile { public void dispose(); public float getSample(int pixelX, int pixelY) throws Exception; public void clearCache(); }
gpl-3.0
robertbaker/SevenUpdate
Externals/SevenSoftware.Windows/VirtualizingCollection.cs
19558
// <copyright file="VirtualizingCollection.cs" project="SevenSoftware.Windows">Paul McClean</copyright> // <license href="http://www.gnu.org/licenses/gpl-3.0.txt" name="GNU General Public License 3" /> using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace SevenSoftware.Windows { /// <summary> /// Specialized list implementation that provides data virtualization. The collection is divided up into pages, /// and pages are dynamically fetched from the IItemsProvider when required. Stale pages are removed after a /// configurable period of time. /// Intended for use with large collections on a network or disk resource that cannot be instantiated locally /// due to memory consumption or fetch latency. /// </summary> /// <remarks> /// The IList implmentation is not fully complete, but should be sufficient for use as read only collection /// data bound to a suitable ItemsControl. /// </remarks> /// <typeparam name="T">The IList collection.</typeparam> public class VirtualizingCollection<T> : IList<T>, IList { /// <summary> /// The items provider. /// </summary> readonly IItemsProvider<T> itemsProvider; /// <summary> /// Gets the size of the page. /// </summary> readonly int pageSize = 100; /// <summary> /// Gets the page timeout. /// </summary> readonly long pageTimeout = 10000; /// <summary> /// The times when the page was last updated. /// </summary> readonly Dictionary<int, DateTime> pageTouchTimes = new Dictionary<int, DateTime>(); /// <summary> /// The collection of pages. /// </summary> readonly Dictionary<int, IList<T>> pages = new Dictionary<int, IList<T>>(); /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> int count = -1; /// <summary> /// Initializes a new instance of the <see cref="VirtualizingCollection&lt;T&gt;"/> class. /// </summary> /// <param name="itemsProvider">The items provider.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="pageTimeout">The page timeout.</param> protected VirtualizingCollection(IItemsProvider<T> itemsProvider, int pageSize, int pageTimeout) { this.itemsProvider = itemsProvider; this.pageSize = pageSize; this.pageTimeout = pageTimeout; } /// <summary> /// Initializes a new instance of the <see cref="VirtualizingCollection&lt;T&gt;"/> class. /// </summary> /// <param name="itemsProvider">The items provider.</param> /// <param name="pageSize">Size of the page.</param> protected VirtualizingCollection(IItemsProvider<T> itemsProvider, int pageSize) { this.itemsProvider = itemsProvider; this.pageSize = pageSize; } /// <summary> /// Initializes a new instance of the <see cref="VirtualizingCollection&lt;T&gt;"/> class. /// </summary> /// <param name="itemsProvider">The items provider.</param> protected VirtualizingCollection(IItemsProvider<T> itemsProvider) { this.itemsProvider = itemsProvider; } /// <summary> /// Gets or sets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// The first time this property is accessed, it will fetch the count from the IItemsProvider. /// </summary> /// <value></value> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public virtual int Count { get { if (count == -1) { LoadCount(); } return count; } protected set { count = value; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size. /// </summary> /// <value></value> /// <returns>Always false. /// </returns> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <value></value> /// <returns>Always true. /// </returns> public bool IsReadOnly { get { return true; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe). /// </summary> /// <value></value> /// <returns>Always false. /// </returns> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <value></value> /// <returns> /// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </returns> public object SyncRoot { get { return this; } } /// <summary> /// Gets the items provider. /// </summary> /// <value>The items provider.</value> IItemsProvider<T> ItemsProvider { get { return itemsProvider; } } /// <summary> /// Gets the size of the page. /// </summary> /// <value>The size of the page.</value> int PageSize { get { return pageSize; } } /// <summary> /// Gets the page timeout. /// </summary> /// <value>The page timeout.</value> long PageTimeout { get { return pageTimeout; } } /// <summary> /// Gets the item at the specified index. This property will fetch /// the corresponding page from the IItemsProvider if required. /// </summary> /// <param name="index">The index of the page you retrieve.</param> /// <returns>The page in the collection.</returns> public T this[int index] { get { // determine which page and offset within page int pageIndex = index / PageSize; int pageOffset = index % PageSize; // request primary page RequestPage(pageIndex); // if accessing upper 50% then request next page if (pageOffset > PageSize / 2 && pageIndex < Count / PageSize) { RequestPage(pageIndex + 1); } // if accessing lower 50% then request prev page if (pageOffset < PageSize / 2 && pageIndex > 0) { RequestPage(pageIndex - 1); } // remove stale pages CleanUpPages(); // defensive check in case of async load if (pages[pageIndex] == null) { return default(T); } // return requested item return pages[pageIndex][pageOffset]; } set { throw new NotSupportedException(); } } /// <summary> /// Gets item in the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns>The item from the collection.</returns> object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } /// <summary> /// Not supported. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public void Add(T item) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public void Clear() { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// Always false. /// </returns> public bool Contains(T item) { return false; } /// <summary> /// Not supported. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="arrayIndex"/> is less than 0. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>. /// -or- /// Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. /// </exception> public void CopyTo(T[] array, int arrayIndex) { throw new NotSupportedException(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <remarks> /// This method should be avoided on large collections due to poor performance. /// </remarks> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } /// <summary> /// Not supported /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// Always -1. /// </returns> public int IndexOf(T item) { return -1; } /// <summary> /// Not supported. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public void Insert(int index, T item) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public bool Remove(T item) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public void RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="value">The object to be added at the end of the List.</param> /// <returns>Not Supported.</returns> int IList.Add(object value) { throw new NotSupportedException(); } /// <summary> /// Determines whether the item is in the list. /// </summary> /// <param name="value">The object to locate in the List</param> /// <returns>true if the object is in the list; otherwise false.</returns> bool IList.Contains(object value) { return Contains((T)value); } /// <summary> /// Not supported. /// </summary> /// <param name="array">The array to copy.</param> /// <param name="index">The zero-based index at which the copy begins.</param> void ICollection.CopyTo(Array array, int index) { throw new NotSupportedException(); } /// <summary> /// Searches for the specified object and returns the zero-based index of the first occurrence within the entire List /// </summary> /// <param name="value">The object to locate in the List</param> /// <returns>The zero-based index of the first occurrence within the List.</returns> int IList.IndexOf(object value) { return IndexOf((T)value); } /// <summary> /// Inserts an element into the List at the specified index. /// </summary> /// <param name="index">The zero-based index at which the item should be inserted.</param> /// <param name="value">The object to insert.</param> void IList.Insert(int index, object value) { Insert(index, (T)value); } /// <summary> /// Not supported. /// </summary> /// <param name="value">The object to remove from the list.</param> void IList.Remove(object value) { throw new NotSupportedException(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Fetches the count of itmes from the IItemsProvider. /// </summary> /// <returns>The number of items from the collection</returns> protected int FetchCount() { return ItemsProvider.Count; } /// <summary> /// Fetches the requested page from the IItemsProvider. /// </summary> /// <param name="pageIndex">Index of the page.</param> /// <returns>The page from the index.</returns> protected IList<T> FetchPage(int pageIndex) { return ItemsProvider.FetchRange(pageIndex * PageSize, PageSize); } /// <summary> /// Loads the count of items. /// </summary> protected virtual void LoadCount() { Count = FetchCount(); } /// <summary> /// Loads the page of items. /// </summary> /// <param name="pageIndex">Index of the page.</param> protected virtual void LoadPage(int pageIndex) { PopulatePage(pageIndex, FetchPage(pageIndex)); } /// <summary> /// Populates the page within the dictionary. /// </summary> /// <param name="pageIndex">Index of the page.</param> /// <param name="page">The page.</param> protected virtual void PopulatePage(int pageIndex, IList<T> page) { Trace.WriteLine("Page populated: " + pageIndex); if (pages.ContainsKey(pageIndex)) { pages[pageIndex] = page; } } /// <summary> /// Makes a request for the specified page, creating the necessary slots in the dictionary, /// and updating the page touch time. /// </summary> /// <param name="pageIndex">Index of the page.</param> protected virtual void RequestPage(int pageIndex) { if (!pages.ContainsKey(pageIndex)) { pages.Add(pageIndex, null); pageTouchTimes.Add(pageIndex, DateTime.Now); Trace.WriteLine("Added page: " + pageIndex); LoadPage(pageIndex); } else { pageTouchTimes[pageIndex] = DateTime.Now; } } /// <summary> /// Cleans up any stale pages that have not been accessed in the period dictated by PageTimeout. /// </summary> void CleanUpPages() { var keys = new List<int>(pageTouchTimes.Keys); foreach (int key in keys) { // page 0 is a special case, since WPF ItemsControl access the first item frequently if (key != 0 && (DateTime.Now - pageTouchTimes[key]).TotalMilliseconds > PageTimeout) { pages.Remove(key); pageTouchTimes.Remove(key); Trace.WriteLine("Removed Page: " + key); } } } } }
gpl-3.0
IDS-UK/genderhub
wp-content/plugins/search-filter-pro/public/includes/class-search-filter-config.php
6361
<?php /** * Search & Filter Pro * * @package Search_Filter_Post_Data * @author Ross Morsali * @link http://www.designsandcode.com/ * @copyright 2015 Designs & Code */ class Search_Filter_Config { private $plugin_slug = ''; private $form_data = array(); private $count_table; private $cache; public $query; public $current_query; private $sfid = 0; function __construct($plugin_slug, $sfid) { $this->plugin_slug = $plugin_slug; $this->init($sfid); } public function init($sfid) { if($this->sfid == 0 ) { $this->sfid = $sfid; $this->init_settings($sfid); if(!isset($this->query)) { $this->query = new Search_Filter_Query($this->sfid, $this->form_data['settings'], $this->form_data['fields_assoc'], $this->get_filters()); $this->current_query = new Search_Filter_Active_Query($this->plugin_slug, $this->sfid, $this->form_data['settings'], $this->form_data['fields_assoc']); } } } public function query() { return($this->query); } public function current_query() { return $this->current_query; } public function get_field_by_key($key) { if(isset($this->form_data['fields_assoc'][$key])) { return $this->form_data['fields_assoc'][$key]; } else { return false; } } public function set_count_table($count_table) { $this->count_table = $count_table; } public function get_count_table() { return $this->count_table; } public function get_count_var($field_name, $term_name) { if(isset($this->count_table[$field_name])) { if(isset($this->count_table[$field_name][$term_name])) { return $this->count_table[$field_name][$term_name]; } } return 0; } public function init_settings($postid = '') { $form_id = $postid; $this->form_data['settings'] = Search_Filter_Helper::get_settings_meta($form_id); $this->form_data['fields'] = Search_Filter_Helper::get_fields_meta($form_id); $this->form_data['fields_assoc'] = array(); $this->form_data['fields_taxonomies'] = array(); if(($this->form_data['settings'])&&($this->form_data['fields'])) { $this->form_data['id'] = $form_id; $this->form_data['postid'] = $postid; $this->form_data['idref'] = $postid; //$fieldswkeys = array(); foreach ($this->form_data['fields'] as $field) { if($field['type']=="post_meta") { $meta_key = $field['meta_key']; if(isset($field['meta_key_manual_toggle'])) { if($field['meta_key_manual_toggle']==1) { $meta_key = $field['meta_key_manual']; } } $this->form_data['fields_assoc'][SF_META_PRE.$meta_key] = $field; //make fields accessible by key } else if($field['type']=="taxonomy") { $taxonomy_name = $field['taxonomy_name']; $this->form_data['fields_assoc'][SF_TAX_PRE.$taxonomy_name] = $field; //make fields accessible by key array_push($this->form_data['fields_taxonomies'], $taxonomy_name); } else if(($field['type']=="tag")||($field['type']=="category")) { $taxonomy_name = $field['taxonomy_name']; $this->form_data['fields_assoc'][SF_TAX_PRE.$taxonomy_name] = $field; //make fields accessible by key /*if($this->is_using_custom_template()) {//if we're using a custom template, treat tag and cat as normal taxonomies $this->form_data['fields_assoc'][SF_TAX_PRE.$taxonomy_name] = $field; //make fields accessible by key } else {//else make them special ;) $this->form_data['fields_assoc'][$field['type']] = $field; //make fields accessible by key }*/ array_push($this->form_data['fields_taxonomies'], $taxonomy_name); } else { $this->form_data['fields_assoc'][$field['type']] = $field; //make fields accessible by key } } } } public function get_filters() { $filters = array(); //var_dump($this->get_fields()); if(!empty($this->form_data['fields'])) { foreach($this->form_data['fields'] as $key => $field) { $valid_filter_types = array("tag", "category", "taxonomy", "post_meta"); if(in_array($field['type'], $valid_filter_types)) { if(($field['type']=="tag")||($field['type']=="category")||($field['type']=="taxonomy")) { array_push($filters, "_sft_".$field['taxonomy_name']); } else if($field['type']=="post_meta") { array_push($filters, "_sfm_".$field['meta_key']); } } } } return $filters; } public function get_fields() { $fields = array(); foreach ($this->form_data['fields_taxonomies'] as $tax_field) { array_push($fields, "_sft_".$tax_field); } return $fields; } public function get_fields_taxonomies() { return $this->form_data['fields_taxonomies']; } function data($index = '') { if(isset($this->form_data[$index])) { return $this->form_data[$index]; } return false; } public function settings($index) { if(isset($this->form_data['settings'])) { if(isset($this->form_data['settings'][$index])) { return $this->form_data['settings'][$index]; } } return false; } public function get_template_name() { if(isset($this->form_data['settings'])) { if(isset($this->form_data['settings']['use_template_manual_toggle'])) { if($this->form_data['settings']['use_template_manual_toggle']==1) {//then a template option has been selected if(isset($this->form_data['settings']['template_name_manual'])) { return $this->form_data['settings']['template_name_manual']; } } } } return false; } public function is_valid_form() { if(isset($this->form_data['id'])) { if($this->form_data['id']!=0) { return true; } } return false; } public function form_id() { if(isset($this->form_data['id'])) { if($this->form_data['id']!=0) { return $this->form_data['id']; } } return false; } /*public function is_using_custom_template() { if(isset($this->form_data['settings'])) { if(isset($this->form_data['settings']['use_template_manual_toggle'])) { if($this->form_data['settings']['use_template_manual_toggle']==1) { return true; } } } return false; }*/ public function return_data() { return $this->form_data; } } ?>
gpl-3.0
arun06eee/ZydeFood
admin/controllers/Loyalty.php
12427
<?php if ( ! defined('BASEPATH')) exit('No direct access allowed'); class Loyalty extends Admin_Controller { public function __construct() { parent::__construct(); // calls the constructor $this->user->restrict('Admin.Loyalty'); $this->load->model('Loyalty_model'); $this->load->library('pagination'); $this->lang->load('loyalty_lang'); } public function index() { $url = '?'; $filter = array(); if ($this->input->get('page')) { $filter['page'] = (int) $this->input->get('page'); } else { $filter['page'] = ''; } if ($this->config->item('page_limit')) { $filter['limit'] = $this->config->item('page_limit'); } if ($this->input->get('filter_search')) { $filter['filter_search'] = $data['filter_search'] = $this->input->get('filter_search'); $url .= 'filter_search='.$filter['filter_search'].'&'; } else { $data['filter_search'] = ''; } if (is_numeric($this->input->get('filter_status'))) { $filter['filter_status'] = $data['filter_status'] = $this->input->get('filter_status'); $url .= 'filter_status='.$filter['filter_status'].'&'; } else { $filter['filter_status'] = $data['filter_status'] = ''; } if ($this->input->get('sort_by')) { $filter['sort_by'] = $data['sort_by'] = $this->input->get('sort_by'); } else { $filter['sort_by'] = $data['sort_by'] = 'loyalty_id'; } if ($this->input->get('order_by')) { $filter['order_by'] = $data['order_by'] = $this->input->get('order_by'); $data['order_by_active'] = $this->input->get('order_by') .' active'; } else { $filter['order_by'] = $data['order_by'] = 'DESC'; $data['order_by_active'] = 'DESC'; } $this->template->setTitle($this->lang->line('text_title')); $this->template->setHeading($this->lang->line('text_heading')); $this->template->setButton($this->lang->line('button_new'), array('class' => 'btn btn-primary', 'href' => page_url() .'/edit')); $this->template->setButton($this->lang->line('button_delete'), array('class' => 'btn btn-danger', 'onclick' => 'confirmDelete();')); if ($this->input->post('delete') AND $this->_deleteLoyalty() === TRUE) { redirect('loyalty'); } $order_by = (isset($filter['order_by']) AND $filter['order_by'] == 'ASC') ? 'DESC' : 'ASC'; $data['sort_name'] = site_url('loyalty'.$url.'sort_by=name&order_by='.$order_by); $data['sort_min_range'] = site_url('loyalty'.$url.'sort_by=min_range&order_by='.$order_by); $data['sort_max_range'] = site_url('loyalty'.$url.'sort_by=max_range&order_by='.$order_by); $data['sort_status'] = site_url('loyalty'.$url.'sort_by=status&order_by='.$order_by); $data['sort_points'] = site_url('loyalty'.$url.'sort_by=status&order_by='.$order_by); $data['loyalties'] = array(); $results = $this->Loyalty_model->getList($filter); foreach ($results as $result) { $data['loyalties'][] = array( 'loyalty_id' => $result['loyalty_id'], 'name' => $result['name'], 'min_range' => $result['min_range'], 'max_range' => $result['max_range'], 'points' => $result['points'], 'status' => ($result['status'] === '1') ? $this->lang->line('text_enabled') : $this->lang->line('text_disabled'), 'edit' => site_url('loyalty/edit?id=' . $result['loyalty_id']) ); } if ($this->input->get('sort_by') AND $this->input->get('order_by')) { $url .= 'sort_by='.$filter['sort_by'].'&'; $url .= 'order_by='.$filter['order_by'].'&'; } $config['base_url'] = site_url('loyalty'.$url); $config['total_rows'] = $this->Loyalty_model->getCount($filter); $config['per_page'] = $filter['limit']; $this->pagination->initialize($config); $data['pagination'] = array( 'info' => $this->pagination->create_infos(), 'links' => $this->pagination->create_links() ); $this->template->render('loyalty', $data); } public function edit() { //edit loyalty method $loyalty_info = $this->Loyalty_model->getEditLoyalty((int) $this->input->get('id')); if ($loyalty_info) { $loyalty_id = $loyalty_info['loyalty_id']; $data['_action'] = site_url('loyalty/edit?id='. $loyalty_id); } else { $loyalty_id = 0; $data['_action'] = site_url('loyalty/edit'); } if ($this->input->post('validity')) { $validity = $this->input->post('validity'); } else if (!empty($loyalty_info['validity'])) { $validity = $loyalty_info['validity']; } else { $validity = 'forever'; } $title = (isset($loyalty_info['name'])) ? $loyalty_info['name'] : $this->lang->line('text_new'); $this->template->setTitle(sprintf($this->lang->line('text_edit_heading'), $title)); $this->template->setHeading(sprintf($this->lang->line('text_edit_heading'), $title)); $this->template->setButton($this->lang->line('button_save'), array('class' => 'btn btn-primary', 'onclick' => '$(\'#edit-form\').submit();')); $this->template->setButton($this->lang->line('button_save_close'), array('class' => 'btn btn-default', 'onclick' => 'saveClose();')); $this->template->setButton($this->lang->line('button_icon_back'), array('class' => 'btn btn-default', 'href' => site_url('loyalty'))); $this->template->setStyleTag(assets_url('js/datepicker/datepicker.css'), 'datepicker-css'); $this->template->setScriptTag(assets_url("js/datepicker/bootstrap-datepicker.js"), 'bootstrap-datepicker-js'); $this->template->setStyleTag(assets_url('js/datepicker/bootstrap-timepicker.css'), 'bootstrap-timepicker-css'); $this->template->setScriptTag(assets_url("js/datepicker/bootstrap-timepicker.js"), 'bootstrap-timepicker-js'); if ($this->input->post() AND $coupon_id = $this->_saveLoyalty()) { if ($this->input->post('save_close') === '1') { redirect('loyalty'); } redirect('loyalty/edit?id='. $coupon_id); } //edit loyalty info $data['loyalty_id'] = $loyalty_info['loyalty_id']; $data['name'] = $loyalty_info['name']; $data['min_range'] = $loyalty_info['min_range']; $data['max_range'] = $loyalty_info['max_range']; $data['description'] = $loyalty_info['description']; $data['points'] = $loyalty_info['points']; $data['validity'] = $validity; $data['fixed_date'] = (empty($loyalty_info['fixed_date']) OR $loyalty_info['fixed_date'] === '0000-00-00') ? '' : mdate('%d-%m-%Y', strtotime($loyalty_info['fixed_date'])); $data['fixed_from_time'] = (empty($loyalty_info['fixed_from_time']) OR $loyalty_info['fixed_from_time'] === '00:00:00') ? '' : mdate('%h:%i %a', strtotime($loyalty_info['fixed_from_time'])); $data['fixed_to_time'] = (empty($loyalty_info['fixed_to_time']) OR $loyalty_info['fixed_to_time'] === '00:00:00') ? '' : mdate('%h:%i %a', strtotime($loyalty_info['fixed_to_time'])); $data['period_start_date'] = (empty($loyalty_info['period_start_date']) OR $loyalty_info['period_start_date'] === '0000-00-00') ? '' : mdate('%d-%m-%Y', strtotime($loyalty_info['period_start_date'])); $data['period_end_date'] = (empty($loyalty_info['period_end_date']) OR $loyalty_info['period_end_date'] === '0000-00-00') ? '' : mdate('%d-%m-%Y', strtotime($loyalty_info['period_end_date'])); $data['recurring_every'] = (empty($loyalty_info['recurring_every'])) ? array() : explode(', ', $loyalty_info['recurring_every']); $data['recurring_from_time'] = (empty($loyalty_info['recurring_from_time']) OR $loyalty_info['recurring_from_time'] === '00:00:00') ? '' : mdate('%h:%i %a', strtotime($loyalty_info['recurring_from_time'])); $data['recurring_to_time'] = (empty($loyalty_info['recurring_to_time']) OR $loyalty_info['recurring_to_time'] === '00:00:00') ? '' : mdate('%h:%i %a', strtotime($loyalty_info['recurring_to_time'])); $data['date_added'] = $loyalty_info['date_added']; $data['status'] = $loyalty_info['status']; $data['weekdays'] = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); $data['fixed_time'] = $this->lang->line('text_24_hour'); if (isset($loyalty_info['fixed_from_time'], $loyalty_info['fixed_to_time']) AND ($loyalty_info['fixed_from_time'] !== '00:00:00' OR $loyalty_info['fixed_to_time'] !== '23:59:00')) { $data['fixed_time'] = $this->lang->line('text_custom'); } $data['recurring_time'] = $this->lang->line('text_24_hour'); if (isset($loyalty_info['recurring_from_time'], $loyalty_info['recurring_to_time']) AND ($loyalty_info['recurring_from_time'] !== '00:00:00' OR $loyalty_info['recurring_to_time'] !== '23:59:00')) { $data['recurring_time'] = $this->lang->line('text_custom'); } $this->template->render('Loyalty_edit', $data); } public function _saveLoyalty() { //save loyalty method if ($this->validateForm() === TRUE) { $save_type = ( ! is_numeric($this->input->get('id'))) ? $this->lang->line('text_added') : $this->lang->line('text_updated'); if ($new_Loyalty = $this->Loyalty_model->Save_Loyalty($this->input->get('id'), $this->input->post())) { //goes to loyalty model Save_Loyalty $this->alert->set('success', sprintf($this->lang->line('alert_success'), 'loyalty'.$save_type)); } else { redirect('loyalty'); } return $new_Loyalty; } } public function _deleteLoyalty() { //loyalty delete method if ($this->input->post('delete')) { $deleted_rows = $this->Loyalty_model->deleteLoyalty($this->input->post('delete')); //goes to delete loyalty model method deleteLoyalty if ($deleted_rows > 0) { $prefix = ($deleted_rows > 1) ? '['.$deleted_rows.'] Loyalties': 'loyalty'; $this->alert->set('success', sprintf($this->lang->line('alert_success'), $prefix.' '.$this->lang->line('text_deleted'))); } else { $this->alert->set('warning', sprintf($this->lang->line('alert_error_nothing'), $this->lang->line('text_deleted'))); } return TRUE; } } private function validateForm() { //loyalty form validation $this->form_validation->set_rules('name', 'lang:label_name', 'xss_clean|trim|required|min_length[2]|max_length[128]'); $this->form_validation->set_rules('description', 'lang:label_description', 'xss_clean|trim|min_length[2]|max_length[1028]'); $this->form_validation->set_rules('validity', 'lang:label_validity', 'xss_clean|trim|required'); if ($this->input->post('validity') === 'fixed') { $this->form_validation->set_rules('validity_times[fixed_date]', 'lang:label_fixed_date', 'xss_clean|trim|required|valid_date'); $this->form_validation->set_rules('fixed_time', 'lang:label_fixed_time', 'xss_clean|trim|required'); if ($this->input->post('fixed_time') !== '24hours') { $this->form_validation->set_rules('validity_times[fixed_from_time]', 'lang:label_fixed_from_time', 'xss_clean|trim|required|valid_time'); $this->form_validation->set_rules('validity_times[fixed_to_time]', 'lang:label_fixed_to_time', 'xss_clean|trim|required|valid_time'); } } else if ($this->input->post('validity') === 'period') { $this->form_validation->set_rules('validity_times[period_start_date]', 'lang:label_period_start_date', 'xss_clean|trim|required|valid_date'); $this->form_validation->set_rules('validity_times[period_end_date]', 'lang:label_period_end_date', 'xss_clean|trim|required|valid_date'); } else if ($this->input->post('validity') === 'recurring') { $this->form_validation->set_rules('validity_times[recurring_every]', 'lang:label_recurring_every', 'xss_clean|trim|required'); if (isset($_POST['validity_times']['recurring_every'])) { foreach ($_POST['validity_times']['recurring_every'] as $key => $value) { $this->form_validation->set_rules('validity_times[recurring_every]['.$key.']', 'lang:label_recurring_every', 'xss_clean|required'); } } $this->form_validation->set_rules('recurring_time', 'lang:label_recurring_time', 'xss_clean|trim|required'); if ($this->input->post('recurring_time') !== '24hours') { $this->form_validation->set_rules('validity_times[recurring_from_time]', 'lang:label_recurring_from_time', 'xss_clean|trim|required|valid_time'); $this->form_validation->set_rules('validity_times[recurring_to_time]', 'lang:label_recurring_to_time', 'xss_clean|trim|required|valid_time'); } } $this->form_validation->set_rules('status', 'lang:label_status', 'xss_clean|trim|required|integer'); if ($this->form_validation->run() === TRUE) { return TRUE; } else { return FALSE; } } }
gpl-3.0
SwamiRama/diablo_browser
app/controllers/chatrooms_controller.rb
1119
class ChatroomsController < ApplicationController before_action :authenticate_user! def index @chatroom = Chatroom.new @chatrooms = Chatroom.all end def new flash[:notice] = nil if request.referrer.split('/').last == 'chatrooms' @chatroom = Chatroom.new end def edit @chatroom = Chatroom.find_by(slug: params[:slug]) end def create @chatroom = Chatroom.new(chatroom_params) if @chatroom.save respond_to do |format| format.html { redirect_to @chatroom } format.js end else respond_to do |format| flash[:notice] = { error: ['a chatroom with this topic already exists'] } format.html { redirect_to new_chatroom_path } format.js { render template: 'chatrooms/chatroom_error.js.erb' } end end end def update chatroom = Chatroom.find(params[:slug]) chatroom.update(chatroom_params) redirect_to chatroom end def show @chatroom = Chatroom.find(params[:slug]) @message = Message.new end private def chatroom_params params.require(:chatroom).permit(:topic) end end
gpl-3.0
mwilbers/mw-repo
modules/core/src/main/java/de/mw/mwdata/core/Identifiable.java
416
package de.mw.mwdata.core; /** * Common interface for applying application wide unique identifiers to * arbitrary java objects. * * @author WilbersM * */ public interface Identifiable { /** * Creates unique identifier by concatenating the given token to an prefix that * forms an application wide unique id * * @param token * @return */ public String createIdentifier(final String token); }
gpl-3.0
gentlecolts/White-Gloves-Willy
Assets/scripts/UI/AudienceMeter.cs
3053
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AudienceMeter : MonoBehaviour { const float happyMax=100; public float cheerTimer; [Space(10)] public float heartLifeTime; public GameObject thrownHeart; public Transform heartSpawnRegion; private EnemySpawner[] spawnRegions; private GameObject player; [Space(10)] public EnemyMovement thrownEnemy; static AudienceMeter instance; public static AudienceMeter Instance { get {return instance; } } private float happyLevel; public float HappyLevel { get {return happyLevel; } } [Space(10)] public Image audiencefill; public float delayUntilCheer; public AudioSource bigCheerNoise; public AudioSource smallCheerNoise; public AudioSource booNoise; [Range(0,happyMax)] public float startValue,unhappyLevel,smallCheerAmount,bigCheerAmount,drainPerSec; private bool isHappy=true, booing=false; void Start () { instance=this; happyLevel=startValue; spawnRegions=FindObjectsOfType<EnemySpawner>(); player=GameObject.FindGameObjectWithTag("Player"); StartCoroutine(CheerLoop()); if(heartSpawnRegion) { heartSpawnRegion.gameObject.SetActive(false); } } IEnumerator CheerLoop() { while(true) { yield return new WaitForSeconds(cheerTimer); Vector3 spawnPoint=heartSpawnRegion.position +new Vector3( heartSpawnRegion.localScale.x*Random.Range(-.5f,.5f), heartSpawnRegion.localScale.y*Random.Range(-.5f,.5f), 0 ); if(happyLevel>happyMax/2) { if(heartSpawnRegion==null) { Debug.Log("Audience would have spawned something good, but heartSpawnRegion was null"); }else { Debug.Log("Spawning happy item"); Destroy(Instantiate(thrownHeart,spawnPoint,Quaternion.identity),heartLifeTime); } }else { if(spawnRegions.Length>0) { Debug.Log("Spawning unhappy item"); //spawnRegions[Random.Range(0,spawnRegions.Length)].maxEnemyCount++; Instantiate(thrownEnemy,spawnPoint,Quaternion.identity); }else { Debug.Log("Audience would have done something nasty, but no spawn regions"); } } } } void Update () { happyLevel=Mathf.Clamp(happyLevel-drainPerSec*Time.deltaTime,0,happyMax); audiencefill.fillAmount = happyLevel/happyMax; if (HappyLevel < unhappyLevel) { isHappy = false; if (!booing) { StartCoroutine (NotHappy ()); booing = true; } }else { isHappy= true; } } //possibly have audience react to these public void smallCheer() { Debug.Log("small cheer!"); if (isHappy) { StartCoroutine (MakeNoise (smallCheerNoise)); } happyLevel+=smallCheerAmount; } public void bigCheer() { Debug.Log("big cheer!"); if (isHappy) { StartCoroutine (MakeNoise (bigCheerNoise)); } happyLevel+=bigCheerAmount; } IEnumerator MakeNoise(AudioSource noise) { yield return new WaitForSeconds (delayUntilCheer); noise.Play (); } IEnumerator NotHappy() { while (!isHappy) { booNoise.Play (); yield return new WaitForSeconds (8f); } } }
gpl-3.0
Konstantin-Surzhin/letsgo
jhipster-blog/src/main/java/org/letsgo/config/LoggingAspectConfiguration.java
482
package org.letsgo.config; import org.letsgo.aop.logging.LoggingAspect; import io.github.jhipster.config.JHipsterConstants; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; @Configuration @EnableAspectJAutoProxy public class LoggingAspectConfiguration { @Bean @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public LoggingAspect loggingAspect(Environment env) { return new LoggingAspect(env); } }
gpl-3.0
keenbaffling/djd-login-request
includes/class-djd-login-request-i18n.php
980
<?php /** * Define the internationalization functionality * * Loads and defines the internationalization files for this plugin * so that it is ready for translation. * * @link https://ph.linkedin.com/in/klinton-ballecer-45294811b * @since 1.0.0 * * @package Djd_Login_Request * @subpackage Djd_Login_Request/includes */ /** * Define the internationalization functionality. * * Loads and defines the internationalization files for this plugin * so that it is ready for translation. * * @since 1.0.0 * @package Djd_Login_Request * @subpackage Djd_Login_Request/includes * @author Klinton Ballecer <klinton.ballecer@gmail.com> */ class Djd_Login_Request_i18n { /** * Load the plugin text domain for translation. * * @since 1.0.0 */ public function load_plugin_textdomain() { load_plugin_textdomain( 'djd-login-request', false, dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/' ); } }
gpl-3.0
drostie/adso
ciphers.py
3594
# -*- coding: utf-8 -*- # This file is a part of adso, which uses PySkein, which is licensed under the # GPL. As far as I can understand, this means that this code must also be # released under the GPL. Since I don't believe in the value of copyright, I # would like apologize to later users for that fact. Nonetheless: # # Copyright 2010 Chris Drost # # adso is free software: it can be redistributed and modified under the # terms of the GNU General Public License, version 3, as published by the # Free Software Foundation. adso is distributed WITHOUT ANY WARRANTIES; # this includes the implied warranties of MERCHANTABILITY and FITNESS FOR A # PARTICULAR PURPOSE. See the license for more details. You should have # received a copy of the license text along with adso, in a text document # named 'COPYING'. If you have not, visit http://www.gnu.org/licenses/ . import skein from array import array supported = [] encryptors = {} decryptors = {} def encrypt(cipher, key, iv, data): "Encrypts a string of data according to the cipher." if cipher in supported: return encryptors[cipher](key, iv, data) else: raise ValueError('Cipher "%s" is not supported by this adso instance.' \ % cipher) def decrypt(cipher, key, iv, data): "Decrypts a string of data according to the cipher." if cipher in supported: return decryptors[cipher](key, iv, data) else: raise ValueError('Cipher "%s" is not supported by this adso instance.' \ % cipher) # Cipher names in 'supported' should contain a namespace and a cipher specification. # They should _bytes = lambda x: x.encode('utf-8') if type(x) == str else x def register(name, enc, dec): supported.append(name) encryptors[name] = lambda key, iv, data: enc(_bytes(key), _bytes(iv), _bytes(data)) decryptors[name] = lambda key, iv, data: dec(_bytes(key), _bytes(iv), _bytes(data)) def derive_key(key, message, length): "Hashes a message with a key to produce a <length>-bit derived key. This function is adso-specific." s = skein.skein512(digest_bits=length, mac=key, pers=b'20100914 spam@drostie.org adso/key_derivation') s.update(message); return s.digest() __little_endian = not array("L", [1]).tostring()[0] def _tf_tweak_ctr(i): # tweak counter goes 0, 1, 2, ..., not 0, 64. 128, ... arr = array('L', [0, i >> 6]) if not __little_endian: arr.byteswap() return arr.tostring() def _tf_encrypt(key, iv, data): # adso always uses JSON, so we pad the message with JSON whitespace. while len(data) % 64 != 0: data += b' ' cipher = skein.threefish(derive_key(key, iv, 512), _tf_tweak_ctr(0)) output = b'' for k in range(0, len(data), 64): cipher.tweak = _tf_tweak_ctr(k) output += cipher.encrypt_block(data[k : k + 64]) return output def _tf_decrypt(key, iv, data): cipher = skein.threefish(derive_key(key, iv, 512), _tf_tweak_ctr(0)) output = b'' for k in range(0, len(data), 64): cipher.tweak = _tf_tweak_ctr(k) output += cipher.decrypt_block(data[k : k + 64]) return output.strip() register('adso-threefish512/tctr', _tf_encrypt, _tf_decrypt) def _skein512stream(key, iv, data): stream = array('B', skein.skein512(digest_bits=8 * len(data), mac=key, nonce=iv).digest()) for i in range(0, len(data)): stream[i] ^= data[i] return stream.tostring() # I would label this as stream-skein512, but the above breaks the spec in a # subtle way: in the Skein spec, digest_bits should be set to a special value, # since you don't always know the length of the message in advance. register('adso-skein512', _skein512stream, _skein512stream)
gpl-3.0
GhettoGirl/pFinanceKeeper
dialogs/prefsdialog.hpp
1920
#ifndef PREFSDIALOG_HPP #define PREFSDIALOG_HPP #include <QListWidget> #include <dialogs/materialdialog.hpp> #include <core/databasemanager.hpp> class PrefsDialog : public MaterialDialog { Q_OBJECT public: explicit PrefsDialog(QWidget *parent = 0); ~PrefsDialog(); protected: void keyPressEvent(QKeyEvent *event); void keyReleaseEvent(QKeyEvent *event); bool eventFilter(QObject *obj, QEvent *event); private slots: void updateEarningCategories(); void updateExpenseCategories(); void updateCategoriesAbstract(DatabaseManager::EntryType); void addEarningCategory(); void addExpenseCategory(); void addCategoryAbstract(DatabaseManager::EntryType); void removeEarningCategory(); void removeExpenseCategory(); void removeCategoryAbstract(DatabaseManager::EntryType); private: QVBoxLayout *m_layout; void buildCategoryLists(); void buildCategoryList(DatabaseManager::EntryType); QFont *font_category; QFont *font_default; QFont *font_defaultBold; QFrame *ui_categoryEditor_field; QLabel *ui_categoryEditor_field_title; QListWidget *ui_categoryEditor_earnings; QListWidget *ui_categoryEditor_expenses; QLabel *ui_categoryEditor_earnings_label; QLabel *ui_categoryEditor_expenses_label; QGridLayout *ui_categoryEditor_layout; MaterialButton *ui_categoryEditor_earning_addCatBtn; MaterialButton *ui_categoryEditor_expense_addCatBtn; void ui_categoryEditor_createAddButton(MaterialButton *btn, const QString &tooltip); MaterialButton *ui_categoryEditor_earning_removeCatBtn; MaterialButton *ui_categoryEditor_expense_removeCatBtn; void ui_categoryEditor_createRemoveButton(MaterialButton *btn, const QString &tooltip); void ui_categoryEditor_createAbstractButton(MaterialButton *btn, const QString &tooltip); }; extern PrefsDialog *prefsDialog; #endif // PREFSDIALOG_HPP
gpl-3.0
RomanKorchmenko/BowlingFX
BowlingFX/Assets/Daikon Forge/DFGUI/Scripts/Rich Text/dfMarkupParser.cs
8140
using System; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; /**************************************************************************** * PLEASE NOTE: The code in this file is under extremely active development * and is likely to change quite frequently. It is not recommended to modify * the code in this file, as your changes are likely to be overwritten by * the next product update when it is published. * **************************************************************************/ /* * INTERESTING LINKS: * * Fully managed HTML engine: http://htmlrenderer.codeplex.com/ * Visual formatting model: http://www.w3.org/TR/CSS21/visuren.html * CSS blocks spec: http://www.w3.org/TR/CSS21/syndata.html#block * Default style sheet for HTML4: http://www.w3.org/TR/CSS21/sample.html * Anonymous inline boxes: http://www.w3.org/TR/CSS21/visuren.html#anonymous * Table height layout: http://www.w3.org/TR/CSS21/tables.html#height-layout * CSS length units: http://www.w3.org/TR/CSS21/syndata.html#length-units * CSS font element: http://www.w3.org/TR/CSS21/fonts.html#font-shorthand * Font metrics: http://msdn.microsoft.com/en-us/library/xwf9s90b(VS.71).aspx * */ /// <summary> /// Parses pseudo-HTML markup into a list of dfMarkupElement instances /// </summary> public class dfMarkupParser { #region Static variables private static Regex TAG_PATTERN = null; private static Regex ATTR_PATTERN = null; private static Regex STYLE_PATTERN = null; private static Dictionary<string, Type> tagTypes = null; private static dfMarkupParser parserInstance = new dfMarkupParser(); #endregion #region Static class constructor static dfMarkupParser() { var options = RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant; TAG_PATTERN = new Regex( @"(\<\/?)(?<tag>[a-zA-Z0-9$_]+)(\s(?<attr>.+?))?([\/]*\>)", options ); ATTR_PATTERN = new Regex( @"(?<key>[a-zA-Z0-9$_]+)=(?<value>(""((\\"")|\\\\|[^""\n])*"")|('((\\')|\\\\|[^'\n])*')|\d+|\w+)", options ); STYLE_PATTERN = new Regex( @"(?<key>[a-zA-Z0-9\-]+)(\s*\:\s*)(?<value>[^;]+)", options ); } #endregion #region Static methods /// <summary> /// Parses pseudo-HTML markup into a list of dfMarkupElement instances /// </summary> public static dfList<dfMarkupElement> Parse( dfRichTextLabel owner, string source ) { try { //@Profiler.BeginSample( "Parse markup" ); parserInstance.owner = owner; var result = parserInstance.parseMarkup( source ); return result; } finally { //@Profiler.EndSample(); } } #endregion #region Private variables private dfRichTextLabel owner = null; #endregion #region Private utility methods private dfList<dfMarkupElement> parseMarkup( string source ) { //@Profiler.BeginSample( "Parse markup: Tokenize" ); var tokens = new Queue<dfMarkupElement>(); var matches = TAG_PATTERN.Matches( source ); var index = 0; for( int i = 0; i < matches.Count; i++ ) { var match = matches[ i ]; if( match.Index > index ) { var text = source.Substring( index, match.Index - index ); var textElement = new dfMarkupString( text ); tokens.Enqueue( textElement ); } index = match.Index + match.Length; tokens.Enqueue( parseTag( match ) ); } if( index < source.Length ) { var text = source.Substring( index ); var textElement = new dfMarkupString( text ); tokens.Enqueue( textElement ); } //@Profiler.EndSample(); return processTokens( tokens ); } private dfList<dfMarkupElement> processTokens( Queue<dfMarkupElement> tokens ) { //@Profiler.BeginSample( "Parse markup: Process tokens" ); var elements = dfList<dfMarkupElement>.Obtain(); while( tokens.Count > 0 ) { elements.Add( parseElement( tokens ) ); } for( int i = 0; i < elements.Count; i++ ) { if( elements[ i ] is dfMarkupTag ) { ( (dfMarkupTag)elements[ i ] ).Owner = this.owner; } } //@Profiler.EndSample(); return elements; } private dfMarkupElement parseElement( Queue<dfMarkupElement> tokens ) { var token = tokens.Dequeue(); if( token is dfMarkupString ) return ( (dfMarkupString)token ).SplitWords(); var tag = (dfMarkupTag)token; if( tag.IsClosedTag || tag.IsEndTag ) { return refineTag( tag ); } while( tokens.Count > 0 ) { var child = parseElement( tokens ); if( child is dfMarkupTag ) { var childTag = (dfMarkupTag)child; if( childTag.IsEndTag ) { if( childTag.TagName == tag.TagName ) break; return refineTag( tag ); } } tag.AddChildNode( child ); } return refineTag( tag ); } /// <summary> /// Refines a generic dfMarkupTag instance into a more specific /// derived class instance, if one can be determined /// </summary> /// <param name="original"></param> /// <returns></returns> private dfMarkupTag refineTag( dfMarkupTag original ) { // Don't bother refining end tags, they only exist to indicate // when we are done parsing/processing a tag that has child // elements. if( original.IsEndTag ) return original; if( tagTypes == null ) { tagTypes = new Dictionary<string, Type>(); var assemblyTypes = getAssemblyTypes(); for( int i = 0; i < assemblyTypes.Length; i++ ) { var type = assemblyTypes[ i ]; if( !typeof( dfMarkupTag ).IsAssignableFrom( type ) ) { continue; } var attributes = type.GetCustomAttributes( typeof( dfMarkupTagInfoAttribute ), true ); if( attributes == null || attributes.Length == 0 ) continue; for( int x = 0; x < attributes.Length; x++ ) { var tagName = ( (dfMarkupTagInfoAttribute)attributes[ x ] ).TagName; tagTypes[ tagName ] = type; } } } if( tagTypes.ContainsKey( original.TagName ) ) { var tagType = tagTypes[original.TagName]; return (dfMarkupTag)Activator.CreateInstance( tagType, original ); } return original; } private Type[] getAssemblyTypes() { #if !UNITY_EDITOR && UNITY_METRO return typeof( dfMarkupParser ).GetTypeInfo().Assembly.ExportedTypes.ToArray(); #else return Assembly.GetExecutingAssembly().GetExportedTypes(); #endif } private dfMarkupElement parseTag( System.Text.RegularExpressions.Match tag ) { var tagName = tag.Groups[ "tag" ].Value.ToLowerInvariant(); if( tag.Value.StartsWith( "</" ) ) { return new dfMarkupTag( tagName ) { IsEndTag = true }; } var element = new dfMarkupTag( tagName ); var attributes = tag.Groups[ "attr" ].Value; var matches = ATTR_PATTERN.Matches( attributes ); for( int i = 0; i < matches.Count; i++ ) { var attrMatch = matches[ i ]; var key = attrMatch.Groups[ "key" ].Value; var value = dfMarkupEntity.Replace( attrMatch.Groups[ "value" ].Value ); if( value.StartsWith( "\"" ) ) value = value.Trim( '"' ); else if( value.StartsWith( "'" ) ) value = value.Trim( '\'' ); if( string.IsNullOrEmpty( value ) ) continue; if( key == "style" ) { parseStyleAttribute( element, value ); } else { element.Attributes.Add( new dfMarkupAttribute( key, value ) ); } } if( tag.Value.EndsWith( "/>" ) || tagName == "br" || tagName == "img" ) { element.IsClosedTag = true; } return element; } private void parseStyleAttribute( dfMarkupTag element, string text ) { var matches = STYLE_PATTERN.Matches( text ); for( int i = 0; i < matches.Count; i++ ) { var match = matches[ i ]; var key = match.Groups[ "key" ].Value.ToLowerInvariant(); var value = match.Groups[ "value" ].Value; element.Attributes.Add( new dfMarkupAttribute( key, value ) ); } } #endregion }
gpl-3.0
cedrick-f/pyxorga
src/Images.py
3349
from wx.lib.embeddedimage import PyEmbeddedImage #---------------------------------------------------------------------- LogoXMind = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAACoAAAAqCAYAAADFw8lbAAAAAXNSR0IArs4c6QAAAARnQU1B" "AACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5F" "VCB2My41LjExR/NCNwAAB2tJREFUWEe9mG2IVGUUx1eDIKKCxNZ0nbl3VvfOTCWRaBQZgghC" "RUF+aAlEQoQiEqSQzCgqNNgoKsSi8INfBIUKRAo/ROk6uurO3Nm11cx822xTM1/Wl113p6fz" "e+5z996ZuTOzrtscOOzu7L3n/J9zzv+c80xDvSXT1HRHdsaUyW5LzM6n7Hn5tL3YTdsru9LN" "yzvTTTPMY/UVt7HxTgC5KetRAOXS9qv5dKItm7S/7UhaHZmk1ZNxrJOivXsdq1ue+fRAInGP" "eX18ZUtDw23tzqS7iFI2HUvnU4kFRAennSlr676ktQsQAGp3rDPtTrx/lxMfFpBqr2hnKqE6" "kraSz4Z41k3aLcb02AVQmXTTvRjLOfH5Ep3WrnRiVVeq+ct9yfjP4jgngI7udqw+A2ioPQQI" "zaYTyhWVd4sUsHuS1iHsGnc1ZcKWdMPtRKnTmT61K9k8O5eKPyf1tFocrPfThlFSJoDOC6AB" "HxAOqwHqeqC5TPmcd7Anv7caHOVClDpb7FluOr5Ipy2VWKvT5liZIG3x8+0tsSsCqkDafEA+" "qDAYNApQNcUGPsT3GjJnoAVCoevUCahQ2i6RtnAdVYpSlNOxKLbJjGRuI53BwAuEoifkRKpa" "2qKMj6fig/Kh1iGmgRcIJyClAKwXqCjFL9mDkJShgRcIzbbdiV3wgUYZqYfim4xSfnDFwAvE" "dexnIAsP1QQqJ87PnK5c+37lxu5TrjUl+rnRqLGVS0xV+ZaY/oxgwREh1AoDLxB6omY2L5YA" "xYDbPE3lrEaVmz5ZdT+cVD3zH1NHX1ysTryyTP2+5AUlfbTonUiVZ3xb+oCi3bNa1OGFT6oj" "zz+tfnn8EQ3cML9fcLQJtAkeQiMU7v6UtU3INAyBfMP8xBCA+j76UJ3fulld2ZtRA78dUYWB" "AYUUrl3VzxCZImBhFVuA+vWpherEipe1rX+++0bbGjxxXA33X9Z/81xWDkO3ySftTWWjlHnM" "CTgJJ8I4Jz+97n1tRBUKGlQlwTHRLgOIYk8ixSE5VCVbg72ndKbyM5oM82WUyo5gIAbCssAc" "9gkF0L8+/9iYqS5E+ODcWdpJFFDqGaDV5EZfn444fjXzpRTp7wZeIGw2QqhjIy1KUsmLfopr" "yblNG7UTnxRhpR5PrlppnoyWq25WlwfvgwEsjG0DL5Bsiz2HU3AaTSgDtu+TNmOqtpz5aoMm" "GxHkXZ/RlMWZDZ+Zp6Kld/Ub3nviF6Bk1zB/oofQiMz1OBOB+tBAJRJ+dM5+/YUxV1uITO/b" "b+psQLLjy5d69RmVGalXyATIcCY082UA6YlZOkr5IJeyN8O4EeajAJfI4Pz6oR7j4dbkyv4O" "fXg6AOmmZPDj+8Q/4/xA0t4euURzgjDzR1T+Ji30uj/efUtdO9it/h0cNG5vXohgbtoklW28" "O7Kmyai3nVkdkVcT1jumgk+oMgMSWf/0NHwIRFu5aZGU9+/eqU69/ppX00y3kD98MyXZd7lT" "GXiBcIVgztYapUTBj8if694z3scm1PQp6Qg6awQB+/K7YX6vm7JfMvAC4b7D5jLC/BKARJJR" "enD2g3paXdzxvdfEx0GIMKOUEsOXN0pjF1jgDbxA2PIPONaOMPO1yu+0GQqfGiUKpULd0sqI" "DjV4+oN31IXt27zJNkoZ+vucJhilYAill2iuRQaiJ4xSNn0eGCGUAXls2RINJkqY00RZLy5S" "EvRNfuddxiK1PNrBwcFYdPBJwAgc9zYD0RPuKWJ8FfcWagSgvEBrqsRyxieE0OPTP5yvZMYQ" "kEiNNrrXDx/SB8/Iu5Ri5BItKW+liAFKCohktVbENNLRCwMsVbIiUaYkai04vnCwPXJAyM2+" "bOAFQjugLfiEgjDVRI8+w9Zqqvul2Lz804/mzepCOQGUdknbFGjFuylLNI12d3OT6n5ibtU+" "CePpp6Q3ClypspzQO6MEWzfOntWlBAnJJLspt2GYX0YomM8XDDsT0woA9euKnxghwpADVgNS" "gyitzUoqEWW6EVXG8cUdP+hRSieBQPyPyHNwfhrmD/H9QtQonSgPrNdLwUMz9clYLI48u0gz" "WPdSmC11Gbl/1lAAsLv2zJvj1W7Yltguelb+r5dox8qUMR+B+VIb5yAUrNd9TepFp7jE2FhU" "R020li2AwpWKS7R/K6008+ul+DbX52ORzOdLsaIlOsLI/634DQHt5apk4AVCPejvoeoA1Afk" "KwQikygghUyDNP3I5YRRGrlE34JGAWJM+4AICsRhfDMZiaJ81sOtg/YUeSOlZ/FPeljZEj0K" "rQYINYAGWdJp6EwfouaBsjeK7zXybivDh8WZ72kNtHIh1NWW6FJAqA8oHCUBVKDVcVmDFNS+" "BpS0N8k7bQJqhegCVky+COFKFPndaCXhSypOisNSQKVRgnSlaWMMM+HYfrjiQAaYS5shjaaB" "F4/FsQgnhFDifDgCEGm7FE6bBuSlba0cZiRtADI3yeJr73gJDiRy60kVEdKASJuAh2gAojyI" "PGsYnaJsHtdLWFAA46eN/gogDlF/UA0N/wHsGWxDpTsXyAAAAABJRU5ErkJggg==") getLogoXMindData = LogoXMind.GetData getLogoXMindImage = LogoXMind.GetImage getLogoXMindBitmap = LogoXMind.GetBitmap getLogoXMindIcon = LogoXMind.GetIcon
gpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-Konschtat/mobs/Hexenpilz.lua
1152
----------------------------------- -- Area: Abyssea - Konschtat (15) -- Mob: Hexenpilz ----------------------------------- package.loaded["scripts/globals/abyssea"] = nil; ----------------------------------- require("scripts/zones/Abyssea-Konschtat/textIDs"); require("scripts/globals/abyssea"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) -- local result = DoCruor(killer,result); -- DoExp(killer,bonus); -- DoLights(mob,killer); -- PyxisSpawn(mob,killer,npc); -- player:messageSpecial(CRUOR_OBTAINED,result); end;
gpl-3.0
FlightControl-Master/DCS-API
DCSZone.lua
194
------------------------------------------------------------------------------- -- @module DCSZone --- -- @type Zone -- @field DCSVec3#Vec3 point -- @field #number radius Zone = {}
gpl-3.0
PascalSteger/NNfunclass
Visualization.java
6000
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.geom.Path2D; import javax.swing.JFrame; import javax.swing.JPanel; /** * Visualization: graphical output of Input and LinSup evaluated, with formula * draw Input in normalized mode, fits as well! give formula in original mode * * @author psteger * @date Aug 1, 2010 * @copyright GPL v3.0 */ public class Visualization extends JPanel { private static final long serialVersionUID = 1L; private final Input in_; private final Fitter fit_; private final Vec winsize_; private final int border_; private final int size_; /** * default constructor * * @param in Input, normalized * @param fit Fitter object for normalized data */ Visualization(final Input in, final Fitter fit) { border_ = 50; size_ = 250; in_ = in; in_.normalize(); System.out.println( in_ ); final Vec s = in_.getS(); double sx = 1 / s.getX(); double sy = 1 / s.getY(); sy = sy / sx * size_ + 2 * border_ + 80;// 80 for title // bar sx = size_ + 2 * border_; // winsize_ = new Vec( sx, sy ); winsize_ = new Vec( size_ + 2 * border_, size_ + 2 * border_ + 80 ); System.out.println( "winsize_ = " + winsize_ ); fit_ = fit; } /** * subroutine to draw an ellipse with semimajor axes a=b=r * * @param g Graphics2D * @param x position of center, x coordinate * @param y position of center, y coordinate * @param r radius */ static void drawCircle( final Graphics2D g, final int x, final int y, final int r ) { g.fillOval( x - r / 2, y - r / 2, 2 * r, 2 * r ); } /** * draw all points with error bars * * @param g2d Graphics2D, plotting area */ void drawInput( final Graphics2D g2d ) { final int r = 5; // final Vec s = new Vec( in_.getS() ); final double sx = size_;// 1 / s.getX(); final double sy = size_;// 1 / s.getY(); // draw error bars g2d.setColor( new Color( 202, 0, 0 ) ); for ( int i = 0; i < in_.getN(); ++i ) { final Vec p = new Vec( in_.getPos( i ) ); final Vec e = new Vec( in_.getErr( i ) ); final int x = (int) (p.getX() * sx) + border_; final int y = (int) ((1 - p.getY()) * sy) + border_; final int ex = (int) (e.getX() * sx); final int ey = (int) (e.getY() * sy); final Polygon px = new Polygon(); px.addPoint( x - ex, y ); px.addPoint( x - ex, y - r / 2 ); px.addPoint( x - ex, y + r / 2 ); px.addPoint( x - ex, y ); px.addPoint( x + ex, y ); px.addPoint( x + ex, y - r / 2 ); px.addPoint( x + ex, y + r / 2 ); px.addPoint( x + ex, y ); final Polygon py = new Polygon(); py.addPoint( x, y - ey ); py.addPoint( x - r / 2, y - ey ); py.addPoint( x + r / 2, y - ey ); py.addPoint( x, y - ey ); py.addPoint( x, y + ey ); py.addPoint( x - r / 2, y + ey ); py.addPoint( x + r / 2, y + ey ); py.addPoint( x, y + ey ); g2d.drawPolygon( px ); g2d.drawPolygon( py ); } // draw data points g2d.setColor( new Color( 0, 0, 112 ) ); for ( int i = 0; i < in_.getN(); ++i ) { final Vec v = new Vec( in_.getPos( i ) ); // System.out.println( v.getX() ); final int x = (int) (v.getX() * sx) + border_; // System.out.println( x ); final int y = (int) ((1 - v.getY()) * sy) + border_; drawCircle( g2d, x - r / 2, y - r / 2, r ); } } /** * draw fitting formula * * @param g2d Graphics2D object to be drawn to */ void drawFit( final Graphics2D g2d ) { g2d.setColor( new Color( 0, 90, 0 ) ); // get x,y values // assumption: one FForm in LinSup // TODO: generalize later on // TODO: change coordinate system, x to right, y up // we plot in normalized mode, so plotting area is [0,1]x[0,1] // add together to Path2D final double sx = size_; final double sy = size_; final Path2D p = new Path2D.Double(); System.out.println( "Path2D: " ); final int startx = border_; final int starty = (int) (sy * (1 - fit_.getLs().eval( 0 )) + border_); p.moveTo( startx, starty ); final double step = 0.1; for ( double i = step; i <= 1.0; i += step ) { final int x = (int) (sx * i) + border_; final int y = (int) (sy * (1 - fit_.getLs().eval( i )) + border_); System.out.println( "(" + x + "," + y + ")" ); p.lineTo( x, y ); } // actually draw function g2d.setColor( new Color( 0, 200, 10 ) ); g2d.draw( p ); } void drawFunction( Graphics2D g2d ) { g2d.setColor( new Color( 10, 10, 10 ) ); int x = border_; int y = size_ + 2 * border_; g2d.drawString( "f(x)=0.00+1.00*(x*1.00+0.00)^2", x, y ); } /* * (non-Javadoc) * * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ @Override public void paintComponent( final Graphics g ) { super.paintComponent( g ); final Graphics2D g2d = (Graphics2D) g; g2d.setBackground( new Color( 250, 250, 200 ) ); g2d.setColor( new Color( 100, 100, 100 ) ); g2d.drawRect( border_, border_, size_, size_ ); drawInput( g2d ); drawFit( g2d ); drawFunction( g2d ); } /** * basic routine to open frame, show it * * @param vis */ public void show( final Visualization vis ) { final JFrame frame = new JFrame( "Visualization" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.add( vis ); frame.setSize( (int) winsize_.getX(), (int) winsize_.getY() ); frame.setLocationRelativeTo( null ); frame.setVisible( true ); } /** * test program * * @param args none */ public static void main( final String[] args ) { System.out.println( "Input:" ); final Input in = new Input( 10, 1, 2 ); System.out.println( in ); System.out.println( "Fitter with given function:" ); final Fitter fit = new Fitter(); System.out.println( "* SFunction: " ); final SFunction sf = new SFunction( 1, 2 ); System.out.println( sf ); System.out.println( "* LinSup:" ); final LinSup ls = new LinSup( sf ); System.out.println( ls ); fit.setLs( ls ); final Visualization vis = new Visualization( in, fit ); vis.show( vis ); } }
gpl-3.0
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/lib/tool_shed/scripts/check_s3_for_empty_tool_dependency_installation_paths.py
7921
import argparse import os import sys new_path = [ os.path.join( os.getcwd(), "lib" ) ] new_path.extend( sys.path[1:] ) sys.path = new_path from galaxy.util import asbool from galaxy import eggs eggs.require( 'boto' ) import boto from tool_shed.util.basic_util import INSTALLATION_LOG class BucketList( object ): def __init__( self, amazon_id, amazon_secret, bucket ): # Connect to S3 using the provided Amazon access key and secret identifier. self.s3 = boto.connect_s3( amazon_id, amazon_secret ) self.bucket_name = bucket # Connect to S3 using the received bucket name. self.bucket = boto.s3.bucket.Bucket( self.s3, bucket ) self.install_dirs = self.get_tool_dependency_install_paths() self.empty_installation_paths = self.check_for_empty_tool_dependency_installation_paths() def display_empty_installation_paths( self ): for empty_installation_path in self.empty_installation_paths: print empty_installation_path def delete_empty_installation_paths( self ): print 'Deleting empty installation paths.' for empty_installation_path in self.empty_installation_paths: # Get all keys in the S3 bucket that start with the installation path, and delete each one. for path_to_delete in self.bucket.list( prefix=empty_installation_path ): self.bucket.delete_key( path_to_delete.key ) print 'Deleted empty path %s' % str( empty_installation_path ) def get_tool_dependency_install_paths( self ): found_paths = [] for item in self.bucket.list(): name = str( item.name ) # Skip environment_settings and __virtualenv_src, since these directories do not contain package tool dependencies. if name.startswith( 'environment_settings' ) or name.startswith( '__virtualenv_src' ): continue paths = name.rstrip('/').split( '/' ) # Paths are in the format name/version/owner/repository/changeset_revision. If the changeset revision is # present, we need to check the contents of that path. If not, then the tool dependency was completely # uninstalled. if len( paths ) >= 5: td_install_dir = '/'.join( paths[ :5 ] ) + '/' if td_install_dir not in found_paths: found_paths.append( name ) return found_paths def check_for_empty_tool_dependency_installation_paths( self ): empty_directories = [] for item in self.install_dirs: # Get all entries under the path for this tool dependency. contents = self.bucket.list( prefix=item ) tool_dependency_path_contents = [] # Find out if there are two or less items in the path. The first entry will be the installation path itself. # If only one other item exists, and the full path ends with the installation log, this is an incorrectly installed # tool dependency. for item in contents: tool_dependency_path_contents.append( item ) # If there are more than two items in the path, we cannot safely assume that the dependency failed to # install correctly. if len( tool_dependency_path_contents ) > 2: break # If the root directory is the only entry in the path, we have an empty tool dependency installation path. if len( tool_dependency_path_contents ) == 1: empty_directories.append( tool_dependency_path_contents[ 0 ] ) # Otherwise, if the only other entry is the installation log, we have an installation path that should be deleted. # This would not be the case in a Galaxy instance, since the Galaxy admin will need to verify the contents of # the installation path in order to determine which action should be taken. elif len( tool_dependency_path_contents ) == 2 and \ tool_dependency_path_contents[1].name.endswith( INSTALLATION_LOG ): empty_directories.append( tool_dependency_path_contents[ 0 ] ) return [ item.name for item in empty_directories ] def main( args ): ''' Amazon credentials can be provided in one of three ways: 1. By specifying them on the command line with the --id and --secret arguments. 2. By specifying a path to a file that contains the credentials in the form ACCESS_KEY:SECRET_KEY using the --s3passwd argument. 3. By specifying the above path in the 's3passwd' environment variable. Each listed option will override the ones below it, if present. ''' if None in [ args.id, args.secret ]: if args.s3passwd is None: args.s3passwd = os.environ.get( 's3passwd', None ) if args.s3passwd is not None and os.path.exists( args.s3passwd ): awsid, secret = file( args.s3passwd, 'r' ).read().rstrip( '\n' ).split( ':' ) else: print 'Amazon ID and secret not provided, and no s3passwd file found.' return 1 else: awsid = args.id secret = args.secret dependency_cleaner = BucketList( awsid, secret, args.bucket ) if len( dependency_cleaner.empty_installation_paths ) == 0: print 'No empty installation paths found, exiting.' return 0 print 'The following %d tool dependency installation paths were found to be empty or contain only the file %s.' % \ ( len( dependency_cleaner.empty_installation_paths ), INSTALLATION_LOG ) if asbool( args.delete ): dependency_cleaner.delete_empty_installation_paths() else: for empty_installation_path in dependency_cleaner.empty_installation_paths: print empty_installation_path return 0 if __name__ == '__main__': description = 'Determine if there are any tool dependency installation paths that should be removed. Remove them if ' description += 'the --delete command line argument is provided with a true value.' parser = argparse.ArgumentParser( description=description ) parser.add_argument( '--delete', dest='delete', required=True, action='store', default=False, type=asbool, help='Whether to delete empty folders or list them on exit.' ) parser.add_argument( '--bucket', dest='bucket', required=True, action='store', metavar='name', help='The S3 bucket where tool dependencies are installed.' ) parser.add_argument( '--id', dest='id', required=False, action='store', default=None, metavar='ACCESS_KEY', help='The identifier for an amazon account that has read access to the bucket.' ) parser.add_argument( '--secret', dest='secret', required=False, action='store', default=None, metavar='SECRET_KEY', help='The secret key for an amazon account that has upload/delete access to the bucket.' ) parser.add_argument( '--s3passwd', dest='s3passwd', required=False, action='store', default=None, metavar='path/file', help='The path to a file containing Amazon access credentials, in the format KEY:SECRET.' ) args = parser.parse_args() sys.exit( main( args ) )
gpl-3.0
cjaymes/pyscap
src/scap/model/oval_5/defs/windows/FileAuditedpermissionsObjectElement.py
1374
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.defs.windows.ObjectType import ObjectType logger = logging.getLogger(__name__) class FileAuditedpermissionsObjectElement(ObjectType): MODEL_MAP = { 'tag_name': 'fileauditedpermissions_object', 'elements': [ {'tag_name': 'behaviors', 'class': 'FileAuditPermissionsBehaviors', 'min': 0}, {'tag_name': 'path', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0}, {'tag_name': 'filename', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'nillable': True, 'min': 0}, {'tag_name': 'trustee_name', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0}, ], }
gpl-3.0
luqmanarifin/ngobrol
ngobrol-server/src/com/ngobrol/server/group/Group.java
707
package com.ngobrol.server.group; /** * Created by luqmanarifin on 01/11/16. */ public class Group { private long id; private String name; private String adminUsername; public Group(long id, String name, String adminUsername) { this.id = id; this.name = name; this.adminUsername = adminUsername; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAdminUsername() { return adminUsername; } public void setAdminUsername(String adminUsername) { this.adminUsername = adminUsername; } }
gpl-3.0
herpingdo/Hakkit
net/minecraft/src/ContainerRepairINNER2.java
3804
package net.minecraft.src; class ContainerRepairINNER2 extends Slot { final World field_135071_a; final int field_135069_b; final int field_135070_c; final int field_135067_d; final ContainerRepair field_135068_e; ContainerRepairINNER2(ContainerRepair par1ContainerRepair, IInventory par2IInventory, int par3, int par4, int par5, World par6World, int par7, int par8, int par9) { super(par2IInventory, par3, par4, par5); this.field_135068_e = par1ContainerRepair; this.field_135071_a = par6World; this.field_135069_b = par7; this.field_135070_c = par8; this.field_135067_d = par9; } /** * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ public boolean isItemValid(ItemStack par1ItemStack) { return false; } /** * Return whether this slot's stack can be taken from this slot. */ public boolean canTakeStack(EntityPlayer par1EntityPlayer) { return (par1EntityPlayer.capabilities.isCreativeMode || par1EntityPlayer.experienceLevel >= this.field_135068_e.maximumCost) && this.field_135068_e.maximumCost > 0 && this.getHasStack(); } public void onPickupFromSlot(EntityPlayer par1EntityPlayer, ItemStack par2ItemStack) { if (!par1EntityPlayer.capabilities.isCreativeMode) { par1EntityPlayer.addExperienceLevel(-this.field_135068_e.maximumCost); } ContainerRepair.getRepairInputInventory(this.field_135068_e).setInventorySlotContents(0, (ItemStack)null); if (ContainerRepair.getStackSizeUsedInRepair(this.field_135068_e) > 0) { ItemStack var3 = ContainerRepair.getRepairInputInventory(this.field_135068_e).getStackInSlot(1); if (var3 != null && var3.stackSize > ContainerRepair.getStackSizeUsedInRepair(this.field_135068_e)) { var3.stackSize -= ContainerRepair.getStackSizeUsedInRepair(this.field_135068_e); ContainerRepair.getRepairInputInventory(this.field_135068_e).setInventorySlotContents(1, var3); } else { ContainerRepair.getRepairInputInventory(this.field_135068_e).setInventorySlotContents(1, (ItemStack)null); } } else { ContainerRepair.getRepairInputInventory(this.field_135068_e).setInventorySlotContents(1, (ItemStack)null); } this.field_135068_e.maximumCost = 0; if (!par1EntityPlayer.capabilities.isCreativeMode && !this.field_135071_a.isRemote && this.field_135071_a.getBlockId(this.field_135069_b, this.field_135070_c, this.field_135067_d) == Block.anvil.blockID && par1EntityPlayer.getRNG().nextFloat() < 0.12F) { int var6 = this.field_135071_a.getBlockMetadata(this.field_135069_b, this.field_135070_c, this.field_135067_d); int var4 = var6 & 3; int var5 = var6 >> 2; ++var5; if (var5 > 2) { this.field_135071_a.setBlockToAir(this.field_135069_b, this.field_135070_c, this.field_135067_d); this.field_135071_a.playAuxSFX(1020, this.field_135069_b, this.field_135070_c, this.field_135067_d, 0); } else { this.field_135071_a.setBlockMetadata(this.field_135069_b, this.field_135070_c, this.field_135067_d, var4 | var5 << 2, 2); this.field_135071_a.playAuxSFX(1021, this.field_135069_b, this.field_135070_c, this.field_135067_d, 0); } } else if (!this.field_135071_a.isRemote) { this.field_135071_a.playAuxSFX(1021, this.field_135069_b, this.field_135070_c, this.field_135067_d, 0); } } }
gpl-3.0
miaojiaxiaodai/ssdianzi
manage.py
251
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ssdianzi.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
gpl-3.0
java-decompiler/jd-gui
app/src/main/java/org/jd/gui/view/OpenTypeView.java
11472
/* * Copyright (c) 2008-2019 Emmanuel Dupuy. * This project is distributed under the GPLv3 license. * This is a Copyleft license that gives the user the right to use, * copy and modify the code freely for non-commercial purposes. */ package org.jd.gui.view; import org.jd.gui.api.API; import org.jd.gui.api.model.Container; import org.jd.gui.api.model.Type; import org.jd.gui.util.exception.ExceptionUtil; import org.jd.gui.util.function.TriConsumer; import org.jd.gui.util.swing.SwingUtil; import org.jd.gui.view.bean.OpenTypeListCellBean; import org.jd.gui.view.renderer.OpenTypeListCellRenderer; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.function.Consumer; public class OpenTypeView { protected static final int MAX_LINE_COUNT = 80; protected static final TypeNameComparator TYPE_NAME_COMPARATOR = new TypeNameComparator(); protected API api; protected JDialog openTypeDialog; protected JTextField openTypeEnterTextField; protected JLabel openTypeMatchLabel; protected JList openTypeList; @SuppressWarnings("unchecked") public OpenTypeView(API api, JFrame mainFrame, Consumer<String> changedPatternCallback, TriConsumer<Point, Collection<Container.Entry>, String> selectedTypeCallback) { this.api = api; // Build GUI SwingUtil.invokeLater(() -> { openTypeDialog = new JDialog(mainFrame, "Open Type", false); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); panel.setLayout(new BorderLayout()); openTypeDialog.add(panel); // Box for "Select a type to open" Box vbox = Box.createVerticalBox(); panel.add(vbox, BorderLayout.NORTH); Box hbox = Box.createHorizontalBox(); hbox.add(new JLabel("Select a type to open (* = any string, ? = any character, TZ = TimeZone):")); hbox.add(Box.createHorizontalGlue()); vbox.add(hbox); vbox.add(Box.createVerticalStrut(10)); // Text field vbox.add(openTypeEnterTextField = new JTextField(30)); openTypeEnterTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { switch (e.getKeyChar()) { case '=': case '(': case ')': case '{': case '}': case '[': case ']': e.consume(); break; default: if (Character.isDigit(e.getKeyChar()) && (openTypeEnterTextField.getText().length() == 0)) { // First character can not be a digit e.consume(); } break; } } @Override public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_DOWN) && (openTypeList.getModel().getSize() > 0)) { openTypeList.setSelectedIndex(0); openTypeList.requestFocus(); e.consume(); } } }); openTypeEnterTextField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { openTypeList.clearSelection(); } @Override public void focusLost(FocusEvent e) {} }); openTypeEnterTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { call(e); } @Override public void removeUpdate(DocumentEvent e) { call(e); } @Override public void changedUpdate(DocumentEvent e) { call(e); } protected void call(DocumentEvent e) { try { changedPatternCallback.accept(e.getDocument().getText(0, e.getDocument().getLength())); } catch (BadLocationException ex) { assert ExceptionUtil.printStackTrace(ex); } } }); vbox.add(Box.createVerticalStrut(10)); hbox = Box.createHorizontalBox(); hbox.add(openTypeMatchLabel = new JLabel("Matching types:")); hbox.add(Box.createHorizontalGlue()); vbox.add(hbox); vbox.add(Box.createVerticalStrut(10)); // List of types JScrollPane scrollPane = new JScrollPane(openTypeList = new JList()); openTypeList.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_UP) && (openTypeList.getSelectedIndex() == 0)) { openTypeEnterTextField.requestFocus(); e.consume(); } } }); openTypeList.setModel(new DefaultListModel<OpenTypeListCellBean>()); openTypeList.setCellRenderer(new OpenTypeListCellRenderer()); openTypeList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { onTypeSelected(selectedTypeCallback); } } }); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setPreferredSize(new Dimension(400, 150)); panel.add(scrollPane, BorderLayout.CENTER); // Buttons "Open" and "Cancel" vbox = Box.createVerticalBox(); panel.add(vbox, BorderLayout.SOUTH); vbox.add(Box.createVerticalStrut(25)); vbox.add(hbox = Box.createHorizontalBox()); hbox.add(Box.createHorizontalGlue()); JButton openTypeOpenButton = new JButton("Open"); hbox.add(openTypeOpenButton); openTypeOpenButton.setEnabled(false); openTypeOpenButton.addActionListener(e -> onTypeSelected(selectedTypeCallback)); hbox.add(Box.createHorizontalStrut(5)); JButton openTypeCancelButton = new JButton("Cancel"); hbox.add(openTypeCancelButton); Action openTypeCancelActionListener = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { openTypeDialog.setVisible(false); } }; openTypeCancelButton.addActionListener(openTypeCancelActionListener); // Last setup JRootPane rootPane = openTypeDialog.getRootPane(); rootPane.setDefaultButton(openTypeOpenButton); rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "OpenTypeView.cancel"); rootPane.getActionMap().put("OpenTypeView.cancel", openTypeCancelActionListener); openTypeList.addListSelectionListener(e -> openTypeOpenButton.setEnabled(openTypeList.getSelectedValue() != null)); openTypeDialog.setMinimumSize(openTypeDialog.getSize()); // Prepare to display openTypeDialog.pack(); openTypeDialog.setLocationRelativeTo(mainFrame); }); } public void show() { SwingUtil.invokeLater(() -> { // Init openTypeEnterTextField.selectAll(); // Show openTypeDialog.setVisible(true); openTypeEnterTextField.requestFocus(); }); } public boolean isVisible() { return openTypeDialog.isVisible(); } public String getPattern() { return openTypeEnterTextField.getText(); } public void showWaitCursor() { SwingUtil.invokeLater(() -> openTypeDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR))); } public void hideWaitCursor() { SwingUtil.invokeLater(() -> openTypeDialog.setCursor(Cursor.getDefaultCursor())); } @SuppressWarnings("unchecked") public void updateList(Map<String, Collection<Container.Entry>> map) { SwingUtil.invokeLater(() -> { DefaultListModel model = (DefaultListModel)openTypeList.getModel(); ArrayList<String> typeNames = new ArrayList<>(map.keySet()); int index = 0; typeNames.sort(TYPE_NAME_COMPARATOR); model.removeAllElements(); for (String typeName : typeNames) { if (index < MAX_LINE_COUNT) { Collection<Container.Entry> entries = map.get(typeName); Container.Entry firstEntry = entries.iterator().next(); Type type = api.getTypeFactory(firstEntry).make(api, firstEntry, typeName); if (type != null) { model.addElement(new OpenTypeListCellBean(type.getDisplayTypeName(), type.getDisplayPackageName(), type.getIcon(), entries, typeName)); } else { model.addElement(new OpenTypeListCellBean(typeName, entries, typeName)); } } else if (index == MAX_LINE_COUNT) { model.addElement(null); } } int count = typeNames.size(); switch (count) { case 0: openTypeMatchLabel.setText("Matching types:"); break; case 1: openTypeMatchLabel.setText("1 matching type:"); break; default: openTypeMatchLabel.setText(count + " matching types:"); } }); } public void focus() { SwingUtil.invokeLater(() -> { openTypeList.requestFocus(); }); } protected void onTypeSelected(TriConsumer<Point, Collection<Container.Entry>, String> selectedTypeCallback) { SwingUtil.invokeLater(() -> { int index = openTypeList.getSelectedIndex(); if (index != -1) { OpenTypeListCellBean selectedCellBean = (OpenTypeListCellBean)openTypeList.getModel().getElementAt(index); Point listLocation = openTypeList.getLocationOnScreen(); Rectangle cellBound = openTypeList.getCellBounds(index, index); Point leftBottom = new Point(listLocation.x + cellBound.x, listLocation.y + cellBound.y + cellBound.height); selectedTypeCallback.accept(leftBottom, selectedCellBean.entries, selectedCellBean.typeName); } }); } protected static class TypeNameComparator implements Comparator<String> { @Override public int compare(String tn1, String tn2) { int lasPackageSeparatorIndex = tn1.lastIndexOf('/'); String shortName1 = tn1.substring(lasPackageSeparatorIndex+1); lasPackageSeparatorIndex = tn2.lastIndexOf('/'); String shortName2 = tn2.substring(lasPackageSeparatorIndex+1); return shortName1.compareTo(shortName2); } } }
gpl-3.0
wp-plugins/woocommerce-germanized
includes/class-wc-gzd-emails.php
8769
<?php /** * Attaches legal relevant Pages to WooCommerce Emails if has been set by WooCommerce Germanized Options * * @class WC_GZD_Emails * @version 1.0.0 * @author Vendidero */ class WC_GZD_Emails { /** * contains options and page ids * @var array */ private $footer_attachments = array(); /** * Adds legal page ids to different options and adds a hook to the email footer */ public function __construct() { // Order attachments $attachment_order = wc_gzd_get_email_attachment_order(); $this->footer_attachments = array(); foreach ( $attachment_order as $key => $order ) $this->footer_attachments[ 'woocommerce_gzd_mail_attach_' . $key ] = $key; add_action( 'woocommerce_email', array( $this, 'email_hooks' ), 0, 1 ); } public function email_hooks( $mailer ) { // Add new customer activation if ( get_option( 'woocommerce_gzd_customer_activation' ) == 'yes' ) { remove_action( 'woocommerce_created_customer_notification', array( $mailer, 'customer_new_account' ), 10 ); add_action( 'woocommerce_created_customer_notification', array( $this, 'customer_new_account_activation' ), 9, 3 ); } // Hook before WooCommerce Footer is applied remove_action( 'woocommerce_email_footer', array( $mailer, 'email_footer' ) ); add_action( 'woocommerce_email_footer', array( $this, 'add_template_footers' ), 0 ); add_action( 'woocommerce_email_footer', array( $mailer, 'email_footer' ), 1 ); add_filter( 'woocommerce_email_footer_text', array( $this, 'email_footer_plain' ), 0 ); add_filter( 'woocommerce_email_styles', array( $this, 'styles' ) ); $mails = $mailer->get_emails(); if ( ! empty( $mails ) ) { foreach ( $mails as $mail ) add_action( 'woocommerce_germanized_email_footer_' . $mail->id, array( $this, 'hook_mail_footer' ), 10, 1 ); } add_filter( 'woocommerce_order_item_product', array( $this, 'set_order_email_filters' ), 0, 1 ); // Pay now button add_action( 'woocommerce_email_before_order_table', array( $this, 'email_pay_now_button' ), 0, 1 ); add_action( 'woocommerce_email_after_order_table', array( $this, 'email_digital_revocation_notice' ), 0, 3 ); } public function email_digital_revocation_notice( $order, $sent_to_admin, $plain_text ) { if ( get_option( 'woocommerce_gzd_checkout_legal_digital_checkbox' ) !== 'yes' ) return; $type = $this->get_current_email_object(); if ( $type && $type->id == 'customer_processing_order' ) { // Check if order contains digital products $items = $order->get_items(); $is_downloadable = false; if ( ! empty( $items ) ) { foreach ( $items as $item ) { $_product = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item ); if ( $_product->is_downloadable() || apply_filters( 'woocommerce_gzd_product_is_revocation_exception', false, $_product ) ) $is_downloadable = true; } } if ( $is_downloadable && $text = wc_gzd_get_legal_text_digital_email_notice() ) echo wpautop( apply_filters( 'woocommerce_gzd_order_confirmation_digital_notice', '<div class="gzd-digital-notice-text">' . $text . '</div>', $order ) ); } } public function email_pay_now_button( $order ) { $type = $this->get_current_email_object(); if ( $type && $type->id == 'customer_processing_order' ) WC_GZD_Checkout::instance()->add_payment_link( $order->id ); } public function email_footer_plain( $text ) { $type = $this->get_current_email_object(); if ( $type && $type->get_email_type() == 'plain' ) $this->add_template_footers(); return $text; } public function get_email_instance_by_id( $id ) { $mailer = WC()->mailer(); $mails = $mailer->get_emails(); foreach ( $mails as $mail ) { if ( $id === $mail->id ) return $mail; } return false; } public function set_order_email_filters( $product ) { if ( is_wc_endpoint_url() || is_admin() ) return $product; // Add order item name actions add_action( 'woocommerce_order_item_name', 'wc_gzd_cart_product_delivery_time', wc_gzd_get_hook_priority( 'email_product_delivery_time' ), 2 ); add_action( 'woocommerce_order_item_name', 'wc_gzd_cart_product_item_desc', wc_gzd_get_hook_priority( 'email_product_item_desc' ), 2 ); add_filter( 'woocommerce_order_formatted_line_subtotal', 'wc_gzd_cart_product_unit_price', wc_gzd_get_hook_priority( 'email_product_unit_price' ), 2 ); return $product; } /** * Add email styles * * @param string $css * @return string */ public function styles( $css ) { return $css .= ' .unit-price-cart { display: block; font-size: 0.9em; } .gzd-digital-notice-text { margin-top: 16px; } '; } /** * Customer new account activation email. * * @param int $customer_id * @param array $new_customer_data */ public function customer_new_account_activation( $customer_id, $new_customer_data = array(), $password_generated = false ) { global $wp_hasher; if ( ! $customer_id ) return; $user_pass = ! empty( $new_customer_data['user_pass'] ) ? $new_customer_data['user_pass'] : ''; if ( empty( $wp_hasher ) ) { require_once ABSPATH . WPINC . '/class-phpass.php'; $wp_hasher = new PasswordHash( 8, true ); } $user_activation = $wp_hasher->HashPassword( wp_generate_password( 20 ) ); $user_activation_url = apply_filters( 'woocommerce_gzd_customer_activation_url', add_query_arg( 'activate', $user_activation, get_permalink( wc_get_page_id( 'myaccount' ) ) ) ); add_user_meta( $customer_id, '_woocommerce_activation', $user_activation ); if ( $email = $this->get_email_instance_by_id( 'customer_new_account_activation' ) ) $email->trigger( $customer_id, $user_activation, $user_activation_url, $user_pass, $password_generated ); } /** * Hook into Email Footer and attach legal page content if necessary * * @param object $mail */ public function hook_mail_footer( $mail ) { if ( ! empty( $this->footer_attachments ) ) { foreach ( $this->footer_attachments as $option_key => $page_option ) { $option = woocommerce_get_page_id ( $page_option ); if ( $option == -1 || ! get_option( $option_key ) ) continue; if ( in_array( $mail->id, get_option( $option_key ) ) && apply_filters( 'woocommerce_gzd_attach_email_footer', true, $mail, $page_option ) ) { $this->attach_page_content( $option, $mail->get_email_type() ); } } } } /** * Add global footer Hooks to Email templates */ public function add_template_footers() { $type = $this->get_current_email_object(); if ( $type ) do_action( 'woocommerce_germanized_email_footer_' . $type->id, $type ); } public function get_current_email_object() { if ( isset( $GLOBALS[ 'wc_gzd_template_name' ] ) && ! empty( $GLOBALS[ 'wc_gzd_template_name' ] ) ) { $object = $this->get_email_instance_by_tpl( $GLOBALS[ 'wc_gzd_template_name' ] ); if ( is_object( $object ) ) return $object; } return false; } /** * Returns Email Object by examining the template file * * @param string $tpl * @return mixed */ private function get_email_instance_by_tpl( $tpls = array() ) { $found_mails = array(); foreach ( $tpls as $tpl ) { $tpl = apply_filters( 'woocommerce_germanized_email_template_name', str_replace( array( 'admin-', '-' ), array( '', '_' ), basename( $tpl, '.php' ) ), $tpl ); $mails = WC()->mailer()->get_emails(); if ( ! empty( $mails ) ) { foreach ( $mails as $mail ) { if ( $mail->id == $tpl ) array_push( $found_mails, $mail ); } } } if ( ! empty( $found_mails ) ) return $found_mails[ sizeof( $found_mails ) - 1 ]; return null; } /** * Attach page content by ID. Removes revocation_form shortcut to not show the form within the Email footer. * * @param integer $page_id */ public function attach_page_content( $page_id, $email_type = 'html' ) { remove_shortcode( 'revocation_form' ); add_shortcode( 'revocation_form', array( $this, 'revocation_form_replacement' ) ); $template = 'emails/email-footer-attachment.php'; if ( $email_type == 'plain' ) $template = 'emails/plain/email-footer-attachment.php'; wc_get_template( $template, array( 'post_attach' => get_post( $page_id ), ) ); add_shortcode( 'revocation_form', 'WC_GZD_Shortcodes::revocation_form' ); } /** * Replaces revocation_form shortcut with a link to the revocation form * * @param array $atts * @return string */ public function revocation_form_replacement( $atts ) { return '<a href="' . esc_url( get_permalink( wc_get_page_id( 'revocation' ) ) ) . '">' . _x( 'Forward your Revocation online', 'revocation-form', 'woocommerce-germanized' ) . '</a>'; } }
gpl-3.0
phtb233/super-blood-busters
core/src/com/phtb/superbloodbusters/accessors/SpriteAccessor.java
2511
package com.phtb.superbloodbusters.accessors; import aurelienribon.tweenengine.TweenAccessor; import com.badlogic.gdx.graphics.g2d.Sprite; /** * Created by stephen on 31/10/16. * * Tween Accessor for Sprites. */ public class SpriteAccessor implements TweenAccessor<Sprite> { public static final int POSITION_X = 1; public static final int POSITION_Y = 2; public static final int POSITION_XY = 3; public static final int ALPHA = 4; public static final int SCALE_X = 5; public static final int SCALE_Y = 6; public static final int SCALE_XY = 7; public static final int SCALE = 8; // Redundant @Override public int getValues(Sprite target, int tweenType, float[] returnValues) { switch (tweenType){ case POSITION_X: returnValues[0] = target.getX(); return 1; case POSITION_Y: returnValues[0] = target.getY(); return 1; case POSITION_XY: returnValues[0] = target.getX(); returnValues[1] = target.getY(); return 2; case ALPHA: returnValues[0] = target.getColor().a; return 1; case SCALE_X: returnValues[0] = target.getScaleX(); return 1; case SCALE_Y: returnValues[0] = target.getScaleY(); return 1; case SCALE_XY: returnValues[0] = target.getScaleX(); returnValues[1] = target.getScaleY(); return 2; case SCALE: returnValues[0] = target.getScaleX(); return 1; default: assert false; return -1; } } @Override public void setValues(Sprite target, int tweenType, float[] newValues) { switch (tweenType){ case POSITION_X: target.setX(newValues[0]); break; case POSITION_Y: target.setY(newValues[0]); break; case POSITION_XY: target.setPosition(newValues[0], newValues[1]); break; case ALPHA: target.setAlpha(newValues[0]); break; case SCALE_X: target.setScale(newValues[0], target.getScaleY()); break; case SCALE_Y: target.setScale(target.getScaleX(), newValues[0]); break; case SCALE_XY: target.setScale(newValues[0], newValues[1]); break; case SCALE: target.setScale(newValues[0]); break; default: assert false; } } }
gpl-3.0
elfinlazz/melia
src/Shared/Data/MeliaData.cs
708
// Copyright (c) Aura development team - Licensed under GNU GPL // For more information, see license file in the main folder using Melia.Shared.Data.Database; namespace Melia.Shared.Data { /// <summary> /// Wrapper for all file databases. /// </summary> public class MeliaData { public BarrackDb BarrackDb = new BarrackDb(); public DialogDb DialogDb = new DialogDb(); public ExpDb ExpDb = new ExpDb(); public ItemDb ItemDb = new ItemDb(); public JobDb JobDb = new JobDb(); public MapDb MapDb = new MapDb(); public MonsterDb MonsterDb = new MonsterDb(); public ServerDb ServerDb = new ServerDb(); public ShopDb ShopDb = new ShopDb(); public SkillDb SkillDb = new SkillDb(); } }
gpl-3.0
PatrykHajzer/C-
Zad10/zad10.cpp
369
#include <stdio.h> #include <math.h> #include <iostream> #define PI 3.14159265 using namespace std; double w1; double w2; float i; int main () { for( i=(-3.14159265); i<=(3.14159265); i=i+0.2) { w1 = sin(i); cout<< w1<<" dla kąta "<< i*180/PI <<endl; w2 = sin(i*i); cout<< w2<<" dla kwadratu kąta "<< sqrt(i*180/PI) <<endl; } return 0; }
gpl-3.0
kevoree-modeling/framework
microframework/src/test/java/org/kevoree/modeling/util/maths/matrix/solvers/decomposition/QrHelperFunctions_D64.java
11152
package org.kevoree.modeling.util.maths.matrix.solvers.decomposition; import org.kevoree.modeling.util.maths.matrix.DenseMatrix64F; import org.kevoree.modeling.util.maths.structure.KArray2D; public class QrHelperFunctions_D64 { public static double findMax( double[] u, int startU , int length ) { double max = -1; int index = startU; int stopIndex = startU + length; for( ; index < stopIndex; index++ ) { double val = u[index]; val = (val < 0.0D) ? -val : val; if( val > max ) max = val; } return max; } public static double findMaxArray(KArray2D u, int col, int startU , int length ) { double max = -1; int index = startU; int stopIndex = startU + length; for( ; index < stopIndex; index++ ) { double val = u.get(index,col); val = (val < 0.0D) ? -val : val; if( val > max ) max = val; } return max; } public static void divideElements4arg(final int j, final int numRows , final double[] u, final double u_0 ) { // double div_u = 1.0/u_0; // // if( Double.isInfinite(div_u)) { for( int i = j; i < numRows; i++ ) { u[i] /= u_0; } // } else { // for( int i = j; i < getNumRows; i++ ) { // u[i] *= div_u; // } // } } public static void divideElements4argArray(final int j, final int numRows , KArray2D u, int col, final double u_0 ) { // double div_u = 1.0/u_0; // // if( Double.isInfinite(div_u)) { for( int i = j; i < numRows; i++ ) { u.set(i,col,u.get(i,col)/ u_0); } // } else { // for( int i = j; i < getNumRows; i++ ) { // u[i] *= div_u; // } // } } public static void divideElements(int j, int numRows , double[] u, int startU , double u_0 ) { // double div_u = 1.0/u_0; // // if( Double.isInfinite(div_u)) { for( int i = j; i < numRows; i++ ) { u[i+startU] /= u_0; } // } else { // for( int i = j; i < getNumRows; i++ ) { // u[i+startU] *= div_u; // } // } } public static void divideElements_Brow(int j, int numRows , double[] u, double b[] , int startB , double u_0 ) { // double div_u = 1.0/u_0; // // if( Double.isInfinite(div_u)) { for( int i = j; i < numRows; i++ ) { u[i] = b[i+startB] /= u_0; } // } else { // for( int i = j; i < getNumRows; i++ ) { // u[i] = b[i+startB] *= div_u; // } // } } public static void divideElements_Bcol(int j, int numRows , int numCols , double[] u, double b[] , int startB , double u_0 ) { // double div_u = 1.0/u_0; // // if( Double.isInfinite(div_u)) { int indexB = j*numCols+startB; for( int i = j; i < numRows; i++) { b[indexB] = u[i] /= u_0; indexB += numCols; } // } else { // int indexB = j*getNumCols+startB; // for( int i = j; i < getNumRows; i++ , indexB += getNumCols ) { // b[indexB] = u[i] *= div_u; // } // } } public static double computeTauAndDivide(int j, int numRows , double[] u, int startU , double max) { // compute the norm2 of the matrix, with each element // normalized by the max value to avoid overflow problems double tau = 0; // double div_max = 1.0/max; // if( Double.isInfinite(div_max)) { // more accurate for( int i = j; i < numRows; i++ ) { double d = u[startU+i] /= max; tau += d*d; } // } else { // // faster // for( int i = j; i < getNumRows; i++ ) { // double d = u[startU+i] *= div_max; // tau += d*d; // } // } tau = Math.sqrt(tau); if( u[startU+j] < 0 ) tau = -tau; return tau; } public static double computeTauAndDivide4arg(final int j, final int numRows , final double[] u , final double max) { double tau = 0; // double div_max = 1.0/max; // if( Double.isInfinite(div_max)) { for( int i = j; i < numRows; i++ ) { double d = u[i] /= max; tau += d*d; } // } else { // for( int i = j; i < getNumRows; i++ ) { // double d = u[i] *= div_max; // tau += d*d; // } // } tau = Math.sqrt(tau); if( u[j] < 0 ) tau = -tau; return tau; } public static double computeTauAndDivide4argArray(final int j, final int numRows , KArray2D u , int col, final double max) { double tau = 0; // double div_max = 1.0/max; // if( Double.isInfinite(div_max)) { for( int i = j; i < numRows; i++ ) { u.set(i,col,u.get(i,col)/max); double d = u.get(i,col); tau += d*d; } // } else { // for( int i = j; i < getNumRows; i++ ) { // double d = u[i] *= div_max; // tau += d*d; // } // } tau = Math.sqrt(tau); if( u.get(j,col) < 0 ) tau = -tau; return tau; } public static void rank1UpdateMultR( DenseMatrix64F A , double u[] , double gamma , int colA0, int w0, int w1 , double _temp[] ) { // for( int i = colA0; i < A.getNumCols; i++ ) { // double val = 0; // // for( int k = w0; k < w1; k++ ) { // val += u[k]*A.data[k*A.getNumCols +i]; // } // _temp[i] = gamma*val; // } // reordered to reduce cpu cache issues for( int i = colA0; i < A.numCols; i++ ) { _temp[i] = u[w0]*A.data[w0 *A.numCols +i]; } for( int k = w0+1; k < w1; k++ ) { int indexA = k*A.numCols + colA0; double valU = u[k]; for( int i = colA0; i < A.numCols; i++ ) { _temp[i] += valU*A.data[indexA++]; } } for( int i = colA0; i < A.numCols; i++ ) { _temp[i] *= gamma; } // end of reorder for( int i = w0; i < w1; i++ ) { double valU = u[i]; int indexA = i*A.numCols + colA0; for( int j = colA0; j < A.numCols; j++ ) { A.data[indexA++] -= valU*_temp[j]; } } } public static void rank1UpdateMultRArray( DenseMatrix64F A , KArray2D u , int col, double gamma , int colA0, int w0, int w1 , double _temp[] ) { // for( int i = colA0; i < A.getNumCols; i++ ) { // double val = 0; // // for( int k = w0; k < w1; k++ ) { // val += u[k]*A.data[k*A.getNumCols +i]; // } // _temp[i] = gamma*val; // } // reordered to reduce cpu cache issues for( int i = colA0; i < A.numCols; i++ ) { _temp[i] = u.get(w0,col)*A.data[w0 *A.numCols +i]; } for( int k = w0+1; k < w1; k++ ) { int indexA = k*A.numCols + colA0; double valU = u.get(k,col); for( int i = colA0; i < A.numCols; i++ ) { _temp[i] += valU*A.data[indexA++]; } } for( int i = colA0; i < A.numCols; i++ ) { _temp[i] *= gamma; } // end of reorder for( int i = w0; i < w1; i++ ) { double valU = u.get(i,col); int indexA = i*A.numCols + colA0; for( int j = colA0; j < A.numCols; j++ ) { A.data[indexA++] -= valU*_temp[j]; } } } public static void rank1UpdateMultR8param(DenseMatrix64F A, double u[], int offsetU, double gamma, int colA0, int w0, int w1, double _temp[]) { // for( int i = colA0; i < A.getNumCols; i++ ) { // double val = 0; // // for( int k = w0; k < w1; k++ ) { // val += u[k+offsetU]*A.data[k*A.getNumCols +i]; // } // _temp[i] = gamma*val; // } // reordered to reduce cpu cache issues for( int i = colA0; i < A.numCols; i++ ) { _temp[i] = u[w0+offsetU]*A.data[w0 *A.numCols +i]; } for( int k = w0+1; k < w1; k++ ) { int indexA = k*A.numCols + colA0; double valU = u[k+offsetU]; for( int i = colA0; i < A.numCols; i++ ) { _temp[i] += valU*A.data[indexA++]; } } for( int i = colA0; i < A.numCols; i++ ) { _temp[i] *= gamma; } // end of reorder for( int i = w0; i < w1; i++ ) { double valU = u[i+offsetU]; int indexA = i*A.numCols + colA0; for( int j = colA0; j < A.numCols; j++ ) { A.data[indexA++] -= valU*_temp[j]; } } } /** * <p> * Performs a rank-1 update operation on the submatrix specified by w with the multiply on the left.<br> * <br> * A = A(I - &gamma;*u*u<sup>T</sup>)<br> * </p> * <p> * The order that matrix multiplies are performed has been carefully selected * to minimize the number of operations. * </p> * * <p> * Before this can become a truly generic operation the submatrix specification needs * to be made more generic. * </p> */ public static void rank1UpdateMultL( DenseMatrix64F A , double u[] , double gamma , int colA0, int w0 , int w1 ) { for( int i = colA0; i < A.numRows; i++ ) { int startIndex = i*A.numCols+w0; double sum = 0; int rowIndex = startIndex; for( int j = w0; j < w1; j++ ) { sum += A.data[rowIndex++]*u[j]; } sum = -gamma*sum; rowIndex = startIndex; for( int j = w0; j < w1; j++ ) { A.data[rowIndex++] += sum*u[j]; } } } }
gpl-3.0
PonteIneptique/collatinus-python
pycollatinus/__init__.py
36
from .lemmatiseur import Lemmatiseur
gpl-3.0
MizarWeb/Mizar
examples/getting-started-version.js
84
document.getElementById("version").innerHTML = "Mizar version : V" + Mizar.VERSION;
gpl-3.0
kevinhikali/px_kevin
src/data_struct/thread.cpp
507
#include <iostream> #include <string> // about multi thread #include <thread> #include <mutex> #include <atomic> #include <future> #include <chrono> using namespace std; mutex m; void thread_func1(int a, char b) { m.lock(); cout<<b; m.unlock(); return; } void thread_func2(int a, char b) { m.lock(); cout<<b; m.unlock(); return; } int main() { thread t1(thread_func1, 1, 'k'); thread t2(thread_func2, 1, 'e'); t1.join(); t2.join(); return 0; }
gpl-3.0
victor-david/panama
src/Panama/ViewModel/Windows/AlertWindowViewModel.cs
5110
/* * Copyright 2019 Victor D. Sandiego * This file is part of Panama. * Panama is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 * Panama is distributed in the hope that it will be useful, but without warranty of any kind. */ using Restless.App.Panama.Database.Tables; using Restless.App.Panama.Resources; using Restless.Tools.Controls; using Restless.Tools.Utility; using System; using System.Collections.ObjectModel; using System.ComponentModel; namespace Restless.App.Panama.ViewModel { /// <summary> /// Provides the view model logic for the <see cref="View.AboutWindow"/>. /// </summary> public class AlertWindowViewModel : WindowViewModel { #region Private private AlertTable.RowObject selectedAlert; #endregion /************************************************************************/ #region Public properties /// <summary> /// Gets a list of row objects that represents current alerts /// </summary> public ObservableCollection<AlertTable.RowObject> Alerts { get; } /// <summary> /// Gets or sets the selected alert object. /// </summary> public AlertTable.RowObject SelectedAlert { get => selectedAlert; set { if (SetProperty(ref selectedAlert, value)) { } } } ///// <summary> ///// Gets the data grid columns. ///// </summary> //public DataGridColumnCollection Columns //{ // get; //} ///// <summary> ///// Gets the collection of menu items. The view binds to this collection so that VMs can manipulate menu items programatically ///// </summary> //public MenuItemCollection MenuItems //{ // get; //} #endregion /************************************************************************/ #region Constructor /// <summary> /// Initializes a new instance of the <see cref="AlertWindowViewModel"/> class. /// </summary> /// <param name="alerts">The alerts</param> public AlertWindowViewModel(ObservableCollection<AlertTable.RowObject> alerts) { Alerts = alerts ?? throw new ArgumentNullException(nameof(alerts)); //Columns = new DataGridColumnCollection(); var col = Columns.Create("Date", nameof(AlertTable.RowObject.Date)).MakeDate(); Columns.SetDefaultSort(col, ListSortDirection.Ascending); Columns.Create("Title", nameof(AlertTable.RowObject.Title)); Columns.Create("Url", nameof(AlertTable.RowObject.Url)); Commands.Add("OpenUrl", OpenUrl, HasUrl); Commands.Add("Postpone1", Postpone1, IsAlertSelected); Commands.Add("Postpone3", Postpone3, IsAlertSelected); Commands.Add("Postpone5", Postpone5, IsAlertSelected); Commands.Add("Postpone7", Postpone7, IsAlertSelected); Commands.Add("Postpone10", Postpone10, IsAlertSelected); Commands.Add("Dismiss", Dismiss, IsAlertSelected); //MenuItems = new MenuItemCollection(); MenuItems.AddItem(Strings.CommandBrowseToUrlOrClick, Commands["OpenUrl"]).AddImageResource("ImageBrowseToUrlMenu"); } #endregion /************************************************************************/ #region Private methods private bool IsAlertSelected(object parm) { return SelectedAlert != null; } private bool HasUrl(object parm) { return SelectedAlert != null && SelectedAlert.HasUrl; } private void OpenUrl(object parm) { if (SelectedAlert != null && !string.IsNullOrEmpty(SelectedAlert.Url)) { OpenHelper.OpenWebSite(null, SelectedAlert.Url); } } private void Postpone1(object parm) { Postpone(1); } private void Postpone3(object parm) { Postpone(3); } private void Postpone5(object parm) { Postpone(5); } private void Postpone7(object parm) { Postpone(7); } private void Postpone10(object parm) { Postpone(10); } private void Postpone(int days) { if (SelectedAlert != null) { DateTime utc = DateTime.UtcNow.AddDays(days); SelectedAlert.Date = new DateTime(utc.Year, utc.Month, utc.Day); Alerts.Remove(SelectedAlert); } } private void Dismiss(object parm) { if (SelectedAlert != null) { SelectedAlert.Enabled = false; Alerts.Remove(SelectedAlert); } } #endregion } }
gpl-3.0
Tyler-Gauch/MedievalMayhem
Assets/Scripts/References/Events/TriggerEventsExample.cs
434
using UnityEngine; using System.Collections; using MedievalMayhem.Utilities.Event; namespace MedievalMayhem.References.Events { public class TriggerEventsExample : MonoBehaviour { // Update is called once per frame void Update () { if (Input.GetKeyDown ("q")) { EventManager.TriggerEvent ("eventsExample1"); } else if (Input.GetKeyDown ("w")) { EventManager.TriggerEvent ("eventsExample2"); } } } }
gpl-3.0
ujjwalagrawal17/open-event-orga-app
app/src/main/java/org/fossasia/openevent/app/module/event/list/contract/IEventsView.java
544
package org.fossasia.openevent.app.module.event.list.contract; import org.fossasia.openevent.app.common.app.lifecycle.contract.view.Emptiable; import org.fossasia.openevent.app.common.app.lifecycle.contract.view.Erroneous; import org.fossasia.openevent.app.common.app.lifecycle.contract.view.Progressive; import org.fossasia.openevent.app.common.app.lifecycle.contract.view.Refreshable; import org.fossasia.openevent.app.common.data.models.Event; public interface IEventsView extends Progressive, Erroneous, Refreshable, Emptiable<Event> { }
gpl-3.0
Edholm/dat255-bearded-octo-lama
tests/src/it/chalmers/dat255_bearded_octo_lama/test/TestDays.java
3957
/** * Copyright (C) 2012 Emil Edholm, Emil Johansson, Johan Andersson, Johan Gustafsson * * This file is part of dat255-bearded-octo-lama * * dat255-bearded-octo-lama 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. * * dat255-bearded-octo-lama 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 dat255-bearded-octo-lama. If not, see <http://www.gnu.org/licenses/>. * */ package it.chalmers.dat255_bearded_octo_lama.test; import it.chalmers.dat255_bearded_octo_lama.utilities.Days; import it.chalmers.dat255_bearded_octo_lama.utilities.Weekday; import java.util.Calendar; import java.util.EnumSet; import junit.framework.Assert; import junit.framework.TestCase; /** * Unit test for the {@link it.chalmers.dat255_bearded_octo_lama.utilities.Days} class. * @author Emil Edholm * @date 20 okt 2012 */ public class TestDays extends TestCase { private Days noDays; private Days allDays; private Days weekdays, weekend; @Override public final void setUp() { noDays = new Days(); allDays = new Days(EnumSet.allOf(Weekday.class)); weekdays = new Days(Weekday.MONDAY, Weekday.FRIDAY); weekend = new Days(Weekday.SATURDAY, Weekday.SUNDAY); } /** * Test method for {@link it.chalmers.dat255_bearded_octo_lama.utilities.Days#decode(int)} * and * {@link it.chalmers.dat255_bearded_octo_lama.utilities.Days#encode()}. */ public final void testEncodeDecode() { // Assert correct encoding/decoding if no days have been added. Days decodedValue = Days.decode(noDays.encode()); Assert.assertTrue(noDays.equals(decodedValue)); // Assert correct encoding/decoding if all days were added. decodedValue = Days.decode(allDays.encode()); Assert.assertTrue(allDays.equals(decodedValue)); // Assert correct encoding/decoding if only a subset of days were added. decodedValue = Days.decode(weekdays.encode()); Assert.assertTrue(weekdays.equals(decodedValue)); // More of the same. decodedValue = Days.decode(weekend.encode()); Assert.assertTrue(weekend.equals(decodedValue)); } public final void testInitDaysConstructor() { Days d = new Days(Weekday.WEDNESDAY); Assert.assertEquals(1, d.size()); Assert.assertTrue(d.contains(Weekday.WEDNESDAY)); } public final void testStartEndConstructor() { int daysInWeekend = 2; Assert.assertEquals(daysInWeekend, weekend.size()); Assert.assertTrue(weekend.contains(Weekday.SATURDAY)); Assert.assertTrue(weekend.contains(Weekday.SUNDAY)); } public final void testBaseUponConstructor() { EnumSet<Weekday> base = EnumSet.of(Weekday.TUESDAY); Days d = new Days(base); Assert.assertEquals(base.size(), d.size()); Assert.assertTrue(d.contains(Weekday.TUESDAY)); } public final void testEquals() { Days d1 = new Days(Weekday.MONDAY); Days d2 = new Days(Weekday.TUESDAY); d1.add(Weekday.TUESDAY); d2.add(Weekday.MONDAY); Assert.assertTrue(d1.equals(d2)); d2.add(Weekday.WEDNESDAY); Assert.assertFalse(d1.equals(d2)); } public final void testDaysLeft() { Calendar cal = Calendar.getInstance(); Days d = new Days(Weekday.WEDNESDAY); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Assert.assertEquals(2, d.daysLeft(cal)); cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY); Assert.assertEquals(0, d.daysLeft(cal)); cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY); Assert.assertEquals(6, d.daysLeft(cal)); d = new Days(); Assert.assertTrue(d.isEmpty()); Assert.assertEquals(-1, d.daysLeft()); } }
gpl-3.0
Kittychanley/TFCraft
src/Common/com/bioxx/tfc/Entities/Mobs/EntityPheasantTFC.java
3227
package com.bioxx.tfc.Entities.Mobs; import java.util.ArrayList; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIEatGrass; import net.minecraft.init.Items; import net.minecraft.world.World; import com.bioxx.tfc.TFCItems; import com.bioxx.tfc.Core.TFC_Core; import com.bioxx.tfc.Core.TFC_Sounds; import com.bioxx.tfc.api.Entities.IAnimal; import com.bioxx.tfc.api.Util.Helper; public class EntityPheasantTFC extends EntityChickenTFC { private final EntityAIEatGrass aiEatGrass = new EntityAIEatGrass(this); public EntityPheasantTFC(World par1World) { super(par1World); } public EntityPheasantTFC(World world, IAnimal mother, ArrayList<Float> data) { super(world, mother, data); } @Override public void addAI() { } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(50);//MaxHealth } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ @Override public void onLivingUpdate() { timeUntilNextEgg = 10000; super.onLivingUpdate(); } /** * Returns the sound this mob makes while it's alive. */ @Override protected String getLivingSound () { return isChild() ? TFC_Sounds.PHAESANTCHICKSAY : TFC_Sounds.PHAESANTSAY; } /** * Returns the sound this mob makes when it is hurt. */ @Override protected String getHurtSound () { return isChild() ? null : TFC_Sounds.PHAESANTHURT; } /** * Returns the sound this mob makes on death. */ @Override protected String getDeathSound () { return isChild() ? null : TFC_Sounds.PHAESANTDEATH; } @Override public void roosterCrow() { //Nulled so that pheasant dont crow since they extend chickens } /** * Drop 0-2 items of this living's type */ @Override protected void dropFewItems(boolean par1, int par2) { float ageMod = TFC_Core.getPercentGrown(this); this.dropItem(Items.feather, (int)(ageMod * this.size_mod * (5 + this.rand.nextInt(10)))); if(isAdult()) { float foodWeight = ageMod * (this.size_mod * 40);//528 oz (33lbs) is the average yield of lamb after slaughter and processing TFC_Core.animalDropMeat(this, TFCItems.chickenRaw, foodWeight); this.dropItem(Items.bone, rand.nextInt(2) + 1); } } @Override public EntityPheasantTFC createChild(EntityAgeable entityageable) { ArrayList<Float> data = new ArrayList<Float>(); data.add(mateSizeMod); return new EntityPheasantTFC(worldObj, this, data); } @Override public boolean canMateWith(IAnimal animal) { return false; } @Override public EntityAgeable createChildTFC(EntityAgeable entityageable) { ArrayList<Float> data = new ArrayList<Float>(); data.add(entityageable.getEntityData().getFloat("MateSize")); return new EntityPheasantTFC(worldObj, this, data); } @Override public int getAnimalTypeID() { return Helper.stringToInt("pheasant"); } }
gpl-3.0
fpellanda/libisi
lib/ordered_hash.rb
4985
# AUTHOR # jan molic /mig/at/1984/dot/cz/ # # DESCRIPTION # Hash with preserved order and some array-like extensions # Public domain. # # THANKS # Andrew Johnson for his suggestions and fixes of Hash[], # merge, to_a, inspect and shift class OrderedHash < ::Hash attr_accessor :order class << self def [] *args hsh = OrderedHash.new if Hash === args[0] hsh.replace args[0] elsif (args.size % 2) != 0 raise ArgumentError, "odd number of elements for Hash" else 0.step(args.size - 1, 2) do |a| b = a + 1 hsh[args[a]] = args[b] end end hsh end end def initialize(*a, &b) super @order = [] end def store_only a,b store a,b end alias orig_store store def store(a,b,key_lookup = true) @order.push a if !key_lookup or !has_key?(a) super a,b end alias []= store def == hsh2 return false if @order != hsh2.order super hsh2 end def clear @order = [] super end def delete key @order.delete key super end def each_key @order.each { |k| yield k } self end def each_value @order.each { |k| yield self[k] } self end def each @order.each { |k| yield k,self[k] } self end alias each_pair each def delete_if @order.clone.each { |k| delete k if yield(k) } self end def values ary = [] @order.each { |k| ary.push self[k] } ary end def keys @order end def first {@order.first => self[@order.first]} end def last {@order.last => self[@order.last]} end def invert hsh2 = Hash.new @order.each { |k| hsh2[self[k]] = k } hsh2 end def reject &block self.dup.delete_if &block end def reject! &block hsh2 = reject &block self == hsh2 ? nil : hsh2 end def replace hsh2 @order = hsh2.keys super hsh2 end def shift key = @order.first key ? [key,delete(key)] : super end def unshift k,v unless self.include? k @order.unshift k orig_store(k,v) true else false end end def push k,v unless self.include? k @order.push k orig_store(k,v) true else false end end def pop key = @order.last key ? [key,delete(key)] : nil end def to_a ary = [] each { |k,v| ary << [k,v] } ary end def to_s self.to_a.to_s end def inspect ary = [] each {|k,v| ary << k.inspect + "=>" + v.inspect} '{' + ary.join(", ") + '}' end def update hsh2 hsh2.each { |k,v| self[k] = v } self end alias :merge! update def merge hsh2 self.dup update(hsh2) end def select ary = [] each { |k,v| ary << [k,v] if yield k,v } ary end def class Hash end def __class__ OrderedHash end attr_accessor "to_yaml_style" def yaml_inline= bool if respond_to?("to_yaml_style") self.to_yaml_style = :inline else unless defined? @__yaml_inline_meth @__yaml_inline_meth = lambda {|opts| YAML::quick_emit(object_id, opts) {|emitter| emitter << '{ ' << map{|kv| kv.join ': '}.join(', ') << ' }' } } class << self def to_yaml opts = {} begin @__yaml_inline ? @__yaml_inline_meth[ opts ] : super rescue @to_yaml_style = :inline super end end end end end @__yaml_inline = bool end def yaml_inline!() self.yaml_inline = true end def each_with_index @order.each_with_index { |k, index| yield k, self[k], index } self end end # class OrderedHash def OrderedHash(*a, &b) OrderedHash.new(*a, &b) end # array extension class Array def can_be_a_hash? self.select {|e| e.class == Array and e.length == 2}.length == self.length end def to_hash(depth = false) # array must have the form [[key, value], [key, value]] raise "Dont know how to convert array to hash (not all elements ar 2-dim arrays)" unless can_be_a_hash? new_hash = OrderedHash.new order = [] self.each {|key,value| order << key if depth and value.class == Array and value.can_be_a_hash? then new_hash.store(key, value.to_hash(true),false) else new_hash.store(key, value,false) end } new_hash.order = order new_hash end end
gpl-3.0
Zapuss/ZapekFapeCore
src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp
27690
/* * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.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/>. */ /* ScriptData SDName: trial_of_the_crusader SD%Complete: ??% SDComment: based on /dev/rsa SDCategory: Crusader Coliseum EndScriptData */ // Known bugs: // - They should be floating but they aren't respecting the floor =( // - Hardcoded bullets spawner #include "ScriptPCH.h" #include "trial_of_the_crusader.h" enum Yells { SAY_AGGRO = -1649040, SAY_DEATH = -1649041, SAY_BERSERK = -1649042, EMOTE_SHIELD = -1649043, SAY_SHIELD = -1649044, SAY_KILL1 = -1649045, SAY_KILL2 = -1649046, EMOTE_LIGHT_VORTEX = -1649047, SAY_LIGHT_VORTEX = -1649048, EMOTE_DARK_VORTEX = -1649049, SAY_DARK_VORTEX = -1649050, }; enum Equipment { EQUIP_MAIN_1 = 9423, EQUIP_MAIN_2 = 37377, }; enum Summons { NPC_BULLET_CONTROLLER = 34743, NPC_BULLET_DARK = 34628, NPC_BULLET_LIGHT = 34630, }; enum BossSpells { SPELL_LIGHT_TWIN_SPIKE = 66075, SPELL_LIGHT_SURGE = 65766, SPELL_LIGHT_SHIELD = 65858, SPELL_LIGHT_TWIN_PACT = 65876, SPELL_LIGHT_VORTEX = 66046, SPELL_LIGHT_TOUCH = 67297, SPELL_LIGHT_ESSENCE = 65686, SPELL_EMPOWERED_LIGHT = 65748, SPELL_TWIN_EMPATHY_LIGHT = 66133, SPELL_UNLEASHED_LIGHT = 65795, SPELL_DARK_TWIN_SPIKE = 66069, SPELL_DARK_SURGE = 65768, SPELL_DARK_SHIELD = 65874, SPELL_DARK_TWIN_PACT = 65875, SPELL_DARK_VORTEX = 66058, SPELL_DARK_TOUCH = 67282, SPELL_DARK_ESSENCE = 65684, SPELL_EMPOWERED_DARK = 65724, SPELL_TWIN_EMPATHY_DARK = 66132, SPELL_UNLEASHED_DARK = 65808, SPELL_CONTROLLER_PERIODIC = 66149, SPELL_POWER_TWINS = 65879, SPELL_BERSERK = 64238, SPELL_POWERING_UP = 67590, SPELL_SURGE_OF_SPEED = 65828, }; #define SPELL_DARK_ESSENCE_HELPER RAID_MODE<uint32>(65684, 67176, 67177, 67178) #define SPELL_LIGHT_ESSENCE_HELPER RAID_MODE<uint32>(65686, 67222, 67223, 67224) #define SPELL_POWERING_UP_HELPER RAID_MODE<uint32>(67590, 67602, 67603, 67604) #define SPELL_UNLEASHED_DARK_HELPER RAID_MODE<uint32>(65808, 67172, 67173, 67174) #define SPELL_UNLEASHED_LIGHT_HELPER RAID_MODE<uint32>(65795, 67238, 67239, 67240) enum Actions { ACTION_VORTEX, ACTION_PACT }; /*###### ## boss_twin_base ######*/ class OrbsDespawner : public BasicEvent { public: explicit OrbsDespawner(Creature* creature) : _creature(creature) { } bool Execute(uint64 /*currTime*/, uint32 /*diff*/) { Trinity::CreatureWorker<OrbsDespawner> worker(_creature, *this); _creature->VisitNearbyGridObject(5000.0f, worker); return true; } void operator()(Creature* creature) const { switch (creature->GetEntry()) { case NPC_BULLET_DARK: case NPC_BULLET_LIGHT: creature->DespawnOrUnsummon(); return; default: return; } } private: Creature* _creature; }; struct boss_twin_baseAI : public ScriptedAI { boss_twin_baseAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; SummonList Summons; AuraStateType m_uiAuraState; uint8 m_uiStage; bool m_bIsBerserk; uint32 m_uiWeapon; uint32 m_uiSpecialAbilityTimer; uint32 m_uiSpikeTimer; uint32 m_uiTouchTimer; uint32 m_uiBerserkTimer; int32 m_uiVortexSay; int32 m_uiVortexEmote; uint32 m_uiSisterNpcId; uint32 m_uiMyEmphatySpellId; uint32 m_uiOtherEssenceSpellId; uint32 m_uiSurgeSpellId; uint32 m_uiVortexSpellId; uint32 m_uiShieldSpellId; uint32 m_uiTwinPactSpellId; uint32 m_uiSpikeSpellId; uint32 m_uiTouchSpellId; void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->ModifyAuraState(m_uiAuraState, true); /* Uncomment this once that they are flying above the ground me->SetLevitate(true); me->SetFlying(true); */ m_bIsBerserk = false; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; m_uiSpikeTimer = 20*IN_MILLISECONDS; m_uiTouchTimer = urand(10, 15)*IN_MILLISECONDS; m_uiBerserkTimer = IsHeroic() ? 6*MINUTE*IN_MILLISECONDS : 10*MINUTE*IN_MILLISECONDS; Summons.DespawnAll(); } void JustReachedHome() { if (m_pInstance) m_pInstance->SetData(TYPE_VALKIRIES, FAIL); Summons.DespawnAll(); me->DespawnOrUnsummon(); } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 1: m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_AGGRESSIVE); break; } } void KilledUnit(Unit* who) { if (who->GetTypeId() == TYPEID_PLAYER) { DoScriptText(urand(0, 1) ? SAY_KILL1 : SAY_KILL2, me); if (m_pInstance) m_pInstance->SetData(DATA_TRIBUTE_TO_IMMORTALITY_ELEGIBLE, 0); } } void JustSummoned(Creature* summoned) { Summons.Summon(summoned); } void SummonedCreatureDespawn(Creature* summoned) { switch (summoned->GetEntry()) { case NPC_LIGHT_ESSENCE: m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_LIGHT_ESSENCE_HELPER); m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_POWERING_UP_HELPER); break; case NPC_DARK_ESSENCE: m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_DARK_ESSENCE_HELPER); m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_POWERING_UP_HELPER); break; case NPC_BULLET_CONTROLLER: me->_Events.AddEvent(new OrbsDespawner(me), me->_Events.CalculateTime(100)); break; } Summons.Despawn(summoned); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (m_pInstance) { if (Creature* pSister = GetSister()) { if (!pSister->isAlive()) { me->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); pSister->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); m_pInstance->SetData(TYPE_VALKIRIES, DONE); Summons.DespawnAll(); } else { me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); m_pInstance->SetData(TYPE_VALKIRIES, SPECIAL); } } } Summons.DespawnAll(); } // Called when sister pointer needed Creature* GetSister() { return Unit::GetCreature((*me), m_pInstance->GetData64(m_uiSisterNpcId)); } void EnterCombat(Unit* /*who*/) { me->SetInCombatWithZone(); if (m_pInstance) { if (Creature* pSister = GetSister()) { me->AddAura(m_uiMyEmphatySpellId, pSister); pSister->SetInCombatWithZone(); } m_pInstance->SetData(TYPE_VALKIRIES, IN_PROGRESS); } DoScriptText(SAY_AGGRO, me); DoCast(me, m_uiSurgeSpellId); } void DoAction(const int32 action) { switch (action) { case ACTION_VORTEX: m_uiStage = me->GetEntry() == NPC_LIGHTBANE ? 2 : 1; break; case ACTION_PACT: m_uiStage = me->GetEntry() == NPC_LIGHTBANE ? 1 : 2; break; } } void EnableDualWield(bool mode = true) { SetEquipmentSlots(false, m_uiWeapon, mode ? m_uiWeapon : EQUIP_UNEQUIP, EQUIP_UNEQUIP); me->SetCanDualWield(mode); me->UpdateDamagePhysical(mode ? OFF_ATTACK : BASE_ATTACK); } void UpdateAI(const uint32 uiDiff) { if (!m_pInstance || !UpdateVictim()) return; switch (m_uiStage) { case 0: break; case 1: // Vortex if (m_uiSpecialAbilityTimer <= uiDiff) { if (Creature* pSister = GetSister()) pSister->AI()->DoAction(ACTION_VORTEX); DoScriptText(m_uiVortexEmote, me); DoScriptText(m_uiVortexSay, me); DoCastAOE(m_uiVortexSpellId); m_uiStage = 0; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; } else m_uiSpecialAbilityTimer -= uiDiff; break; case 2: // Shield+Pact if (m_uiSpecialAbilityTimer <= uiDiff) { DoScriptText(EMOTE_SHIELD, me); DoScriptText(SAY_SHIELD, me); if (Creature* pSister = GetSister()) { pSister->AI()->DoAction(ACTION_PACT); pSister->CastSpell(pSister, SPELL_POWER_TWINS, false); } DoCast(me, m_uiShieldSpellId); DoCast(me, m_uiTwinPactSpellId); m_uiStage = 0; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; } else m_uiSpecialAbilityTimer -= uiDiff; break; default: break; } if (m_uiSpikeTimer <= uiDiff) { DoCastVictim(m_uiSpikeSpellId); m_uiSpikeTimer = 20*IN_MILLISECONDS; } else m_uiSpikeTimer -= uiDiff; if (IsHeroic() && m_uiTouchTimer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 200, true, m_uiOtherEssenceSpellId)) me->CastCustomSpell(m_uiTouchSpellId, SPELLVALUE_MAX_TARGETS, 1, target, false); m_uiTouchTimer = urand(10, 15)*IN_MILLISECONDS; } else m_uiTouchTimer -= uiDiff; if (!m_bIsBerserk && m_uiBerserkTimer <= uiDiff) { DoCast(me, SPELL_BERSERK); DoScriptText(SAY_BERSERK, me); m_bIsBerserk = true; } else m_uiBerserkTimer -= uiDiff; DoMeleeAttackIfReady(); } }; /*###### ## boss_fjola ######*/ class boss_fjola : public CreatureScript { public: boss_fjola() : CreatureScript("boss_fjola") { } CreatureAI* GetAI(Creature* creature) const { return new boss_fjolaAI(creature); } struct boss_fjolaAI : public boss_twin_baseAI { boss_fjolaAI(Creature* creature) : boss_twin_baseAI(creature) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; void Reset() { boss_twin_baseAI::Reset(); SetEquipmentSlots(false, EQUIP_MAIN_1, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); m_uiStage = 0; m_uiWeapon = EQUIP_MAIN_1; m_uiAuraState = AURA_STATE_UNKNOWN22; m_uiVortexEmote = EMOTE_LIGHT_VORTEX; m_uiVortexSay = SAY_LIGHT_VORTEX; m_uiSisterNpcId = NPC_DARKBANE; m_uiMyEmphatySpellId = SPELL_TWIN_EMPATHY_DARK; m_uiOtherEssenceSpellId = SPELL_DARK_ESSENCE_HELPER; m_uiSurgeSpellId = SPELL_LIGHT_SURGE; m_uiVortexSpellId = SPELL_LIGHT_VORTEX; m_uiShieldSpellId = SPELL_LIGHT_SHIELD; m_uiTwinPactSpellId = SPELL_LIGHT_TWIN_PACT; m_uiTouchSpellId = SPELL_LIGHT_TOUCH; m_uiSpikeSpellId = SPELL_LIGHT_TWIN_SPIKE; if (m_pInstance) { m_pInstance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_START_TWINS_FIGHT); } } void EnterCombat(Unit* who) { if (m_pInstance) { m_pInstance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_START_TWINS_FIGHT); } me->SummonCreature(NPC_BULLET_CONTROLLER, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 0.0f, TEMPSUMMON_MANUAL_DESPAWN); boss_twin_baseAI::EnterCombat(who); } void EnterEvadeMode() { m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); boss_twin_baseAI::EnterEvadeMode(); } void JustReachedHome() { if (m_pInstance) m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); boss_twin_baseAI::JustReachedHome(); } }; }; /*###### ## boss_eydis ######*/ class boss_eydis : public CreatureScript { public: boss_eydis() : CreatureScript("boss_eydis") { } CreatureAI* GetAI(Creature* creature) const { return new boss_eydisAI(creature); } struct boss_eydisAI : public boss_twin_baseAI { boss_eydisAI(Creature* creature) : boss_twin_baseAI(creature) {} void Reset() { boss_twin_baseAI::Reset(); SetEquipmentSlots(false, EQUIP_MAIN_2, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); m_uiStage = 1; m_uiWeapon = EQUIP_MAIN_2; m_uiAuraState = AURA_STATE_UNKNOWN19; m_uiVortexEmote = EMOTE_DARK_VORTEX; m_uiVortexSay = SAY_DARK_VORTEX; m_uiSisterNpcId = NPC_LIGHTBANE; m_uiMyEmphatySpellId = SPELL_TWIN_EMPATHY_LIGHT; m_uiOtherEssenceSpellId = SPELL_LIGHT_ESSENCE_HELPER; m_uiSurgeSpellId = SPELL_DARK_SURGE; m_uiVortexSpellId = SPELL_DARK_VORTEX; m_uiShieldSpellId = SPELL_DARK_SHIELD; m_uiTwinPactSpellId = SPELL_DARK_TWIN_PACT; m_uiTouchSpellId = SPELL_DARK_TOUCH; m_uiSpikeSpellId = SPELL_DARK_TWIN_SPIKE; } }; }; #define ESSENCE_REMOVE 0 #define ESSENCE_APPLY 1 class mob_essence_of_twin : public CreatureScript { public: mob_essence_of_twin() : CreatureScript("mob_essence_of_twin") { } struct mob_essence_of_twinAI : public ScriptedAI { mob_essence_of_twinAI(Creature* creature) : ScriptedAI(creature) { } uint32 GetData(uint32 data) { uint32 spellReturned = 0; switch (me->GetEntry()) { case NPC_LIGHT_ESSENCE: spellReturned = data == ESSENCE_REMOVE? SPELL_DARK_ESSENCE_HELPER : SPELL_LIGHT_ESSENCE_HELPER; break; case NPC_DARK_ESSENCE: spellReturned = data == ESSENCE_REMOVE? SPELL_LIGHT_ESSENCE_HELPER : SPELL_DARK_ESSENCE_HELPER; break; default: break; } return spellReturned; } }; CreatureAI* GetAI(Creature* creature) const { return new mob_essence_of_twinAI(creature); }; bool OnGossipHello(Player* player, Creature* creature) { player->RemoveAurasDueToSpell(creature->GetAI()->GetData(ESSENCE_REMOVE)); player->CastSpell(player, creature->GetAI()->GetData(ESSENCE_APPLY), true); player->CLOSE_GOSSIP_MENU(); return true; } }; struct mob_unleashed_ballAI : public ScriptedAI { mob_unleashed_ballAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiRangeCheckTimer; void MoveToNextPoint() { float x0 = ToCCommonLoc[1].GetPositionX(), y0 = ToCCommonLoc[1].GetPositionY(), r = 47.0f; float y = y0; float x = frand(x0 - r, x0 + r); float sq = pow(r, 2) - pow(x - x0, 2); float rt = sqrtf(fabs(sq)); if (urand(0, 1)) y = y0 + rt; else y = y0 - rt; me->GetMotionMaster()->MovePoint(0, x, y, me->GetPositionZ()); } void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->SetLevitate(true); me->SetFlying(true); SetCombatMovement(false); MoveToNextPoint(); m_uiRangeCheckTimer = IN_MILLISECONDS; } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 0: if (urand(0, 3) == 0) MoveToNextPoint(); else me->DisappearAndDie(); break; } } }; class mob_unleashed_dark : public CreatureScript { public: mob_unleashed_dark() : CreatureScript("mob_unleashed_dark") { } CreatureAI* GetAI(Creature* creature) const { return new mob_unleashed_darkAI(creature); } struct mob_unleashed_darkAI : public mob_unleashed_ballAI { mob_unleashed_darkAI(Creature* creature) : mob_unleashed_ballAI(creature) {} void UpdateAI(const uint32 uiDiff) { if (m_uiRangeCheckTimer < uiDiff) { if (Unit* target = me->SelectNearestTarget(2.0f)) if (target->GetTypeId() == TYPEID_PLAYER && target->isAlive()) { DoCastAOE(SPELL_UNLEASHED_DARK); me->GetMotionMaster()->MoveIdle(); me->DespawnOrUnsummon(500); } m_uiRangeCheckTimer = IN_MILLISECONDS; } else m_uiRangeCheckTimer -= uiDiff; } void SpellHitTarget(Unit* who, SpellInfo const* spell) { if (spell->Id == SPELL_UNLEASHED_DARK_HELPER) { if (who->HasAura(SPELL_DARK_ESSENCE_HELPER)) who->CastSpell(who, SPELL_POWERING_UP, true); } } }; }; class mob_unleashed_light : public CreatureScript { public: mob_unleashed_light() : CreatureScript("mob_unleashed_light") { } CreatureAI* GetAI(Creature* creature) const { return new mob_unleashed_lightAI(creature); } struct mob_unleashed_lightAI : public mob_unleashed_ballAI { mob_unleashed_lightAI(Creature* creature) : mob_unleashed_ballAI(creature) {} void UpdateAI(const uint32 uiDiff) { if (m_uiRangeCheckTimer < uiDiff) { if (Unit* target = me->SelectNearestTarget(2.0f)) if (target->GetTypeId() == TYPEID_PLAYER && target->isAlive()) { DoCastAOE(SPELL_UNLEASHED_LIGHT); me->GetMotionMaster()->MoveIdle(); me->DespawnOrUnsummon(500); } m_uiRangeCheckTimer = IN_MILLISECONDS; } else m_uiRangeCheckTimer -= uiDiff; } void SpellHitTarget(Unit* who, SpellInfo const* spell) { if (spell->Id == SPELL_UNLEASHED_LIGHT_HELPER) { if (who->HasAura(SPELL_LIGHT_ESSENCE_HELPER)) who->CastSpell(who, SPELL_POWERING_UP, true); } } }; }; class mob_bullet_controller : public CreatureScript { public: mob_bullet_controller() : CreatureScript("mob_bullet_controller") { } CreatureAI* GetAI(Creature* creature) const { return new mob_bullet_controllerAI(creature); } struct mob_bullet_controllerAI : public Scripted_NoMovementAI { mob_bullet_controllerAI(Creature* creature) : Scripted_NoMovementAI(creature) { Reset(); } void Reset() { DoCastAOE(SPELL_CONTROLLER_PERIODIC); } void UpdateAI(const uint32 /*uiDiff*/) { UpdateVictim(); } }; }; class spell_powering_up : public SpellScriptLoader { public: spell_powering_up() : SpellScriptLoader("spell_powering_up") { } class spell_powering_up_AuraScript : public AuraScript { PrepareAuraScript(spell_powering_up_AuraScript); void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Unit* target = GetTarget()) { if (Aura* pAura = target->GetAura(GetId())) { if (pAura->GetStackAmount() == 100) { if (target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2206, EFFECT_1)) target->CastSpell(target, SPELL_EMPOWERED_DARK, true); if (target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2845, EFFECT_1)) target->CastSpell(target, SPELL_EMPOWERED_LIGHT, true); target->RemoveAurasDueToSpell(GetId()); } } } } void Register() { OnEffectApply += AuraEffectApplyFn(spell_powering_up_AuraScript::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_powering_up_AuraScript(); } class spell_powering_up_SpellScript : public SpellScript { public: PrepareSpellScript(spell_powering_up_SpellScript) uint32 spellId; bool Validate(SpellEntry const* /*spellEntry*/) { spellId = sSpellMgr->GetSpellIdForDifficulty(SPELL_SURGE_OF_SPEED, GetCaster()); if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { if (Unit* target = GetTargetUnit()) if (urand(0, 99) < 15) target->CastSpell(target, spellId, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_powering_up_SpellScript::HandleScriptEffect, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_powering_up_SpellScript(); } }; class spell_valkyr_essences : public SpellScriptLoader { public: spell_valkyr_essences() : SpellScriptLoader("spell_valkyr_essences") { } class spell_valkyr_essences_AuraScript : public AuraScript { PrepareAuraScript(spell_valkyr_essences_AuraScript); uint32 spellId; bool Load() { spellId = sSpellMgr->GetSpellIdForDifficulty(SPELL_SURGE_OF_SPEED, GetCaster()); if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void Absorb(AuraEffect* /*aurEff*/, DamageInfo & /*dmgInfo*/, uint32 & /*absorbAmount*/) { if (urand(0, 99) < 5) GetTarget()->CastSpell(GetTarget(), spellId, true); } void Register() { OnEffectAbsorb += AuraEffectAbsorbFn(spell_valkyr_essences_AuraScript::Absorb, EFFECT_0); } }; AuraScript* GetAuraScript() const { return new spell_valkyr_essences_AuraScript(); } }; class spell_power_of_the_twins : public SpellScriptLoader { public: spell_power_of_the_twins() : SpellScriptLoader("spell_power_of_the_twins") { } class spell_power_of_the_twins_AuraScript : public AuraScript { PrepareAuraScript(spell_power_of_the_twins_AuraScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_UNIT; } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) { if (Creature* Valk = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(GetCaster()->GetEntry()))) CAST_AI(boss_twin_baseAI, Valk->AI())->EnableDualWield(true); } } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) { if (Creature* Valk = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(GetCaster()->GetEntry()))) CAST_AI(boss_twin_baseAI, Valk->AI())->EnableDualWield(false); } } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_power_of_the_twins_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_power_of_the_twins_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } }; AuraScript* GetAuraScript() const { return new spell_power_of_the_twins_AuraScript(); } }; void AddSC_boss_twin_valkyr() { new boss_fjola(); new boss_eydis(); new mob_unleashed_light(); new mob_unleashed_dark(); new mob_essence_of_twin(); new mob_bullet_controller(); new spell_powering_up(); new spell_valkyr_essences(); new spell_power_of_the_twins(); }
gpl-3.0
OpenFOAM/OpenFOAM-dev
applications/solvers/multiphase/multiphaseEulerFoam/phaseSystems/populationBalanceModel/coalescenceModels/BrownianCollisions/BrownianCollisions.H
4487
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2019-2021 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::diameterModels::coalescenceModels::BrownianCollisions Description Model describing coagulation due to Brownian motion. Utilises collisional diameters and the Cunningham slip correction. The slip correction coefficient is implemented in the following form: \f[ C_{c_i} = 1 + \lambda [A_1 + A_2 \exp(-A_3 d_i/\lambda)]/d_i\,. \f] The coefficients default to the values proposed by Davis (1945). The mean free path is computed by \f[ \lambda = \frac{kT}{\sqrt{2} \pi p \sigma^{2}}\,. \f] \vartable A_1 | Coefficient [-] A_2 | Coefficient [-] A_3 | Coefficient [-] \sigma | Lennard-Jones parameter [m] \endvartable Reference: \verbatim Davies, C. N. (1945). Definitive equations for the fluid resistance of spheres. Proceedings of the Physical Society, 57(4), 259. \endverbatim Usage \table Property | Description | Required | Default value A1 | Coefficient A1 | no | 2.514 A2 | Coefficient A2 | no | 0.8 A3 | Coefficient A2 | no | 0.55 sigma | Lennard-Jones parameter | yes | none \endtable SourceFiles BrownianCollisions.C \*---------------------------------------------------------------------------*/ #ifndef BrownianCollisions_H #define BrownianCollisions_H #include "coalescenceModel.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { namespace diameterModels { namespace coalescenceModels { /*---------------------------------------------------------------------------*\ Class BrownianCollisions Declaration \*---------------------------------------------------------------------------*/ class BrownianCollisions : public coalescenceModel { // Private Data //- Cunningham slip correction coefficient A1 const dimensionedScalar A1_; //- Cunningham slip correction coefficient A2 const dimensionedScalar A2_; //- Cunningham slip correction coefficient A3 const dimensionedScalar A3_; //- Lennard-Jones sigma parameter const dimensionedScalar sigma_; //- Mean free path volScalarField lambda_; public: //- Runtime type information TypeName("BrownianCollisions"); // Constructor BrownianCollisions ( const populationBalanceModel& popBal, const dictionary& dict ); //- Destructor virtual ~BrownianCollisions() {} // Member Functions //- Precompute diameter independent expressions virtual void precompute(); //- Add to coalescenceRate virtual void addToCoalescenceRate ( volScalarField& coalescenceRate, const label i, const label j ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace coalescenceModels } // End namespace diameterModels } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
gpl-3.0
lukedirtwalker/musikloud2
app/src/maemo5/plugins/pluginsearchdialog.cpp
3709
/* * Copyright (C) 2015 Stuart Howarth <showarth@marxoft.co.uk> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pluginsearchdialog.h" #include "mainwindow.h" #include "pluginsearchtypemodel.h" #include "searchhistorydialog.h" #include "settings.h" #include "valueselector.h" #include <QLineEdit> #include <QDialogButtonBox> #include <QPushButton> #include <QGridLayout> PluginSearchDialog::PluginSearchDialog(const QString &service, QWidget *parent) : Dialog(parent), m_typeModel(new PluginSearchTypeModel(this)), m_typeSelector(new ValueSelector(tr("Search for"), this)), m_searchEdit(new QLineEdit(this)), m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Cancel, Qt::Vertical, this)), m_historyButton(new QPushButton(tr("History"), this)), m_searchButton(new QPushButton(tr("Done"), this)), m_layout(new QGridLayout(this)) { setWindowTitle(tr("Search")); m_typeModel->setService(service); m_typeSelector->setModel(m_typeModel); m_typeSelector->setCurrentIndex(qMax(0, m_typeModel->match("name", Settings::instance()->defaultSearchType(service)))); m_searchEdit->setPlaceholderText(tr("Search")); m_searchEdit->setFocus(Qt::OtherFocusReason); m_searchButton->setDefault(true); m_searchButton->setEnabled(false); m_buttonBox->addButton(m_historyButton, QDialogButtonBox::ActionRole); m_buttonBox->addButton(m_searchButton, QDialogButtonBox::ActionRole); m_layout->addWidget(m_searchEdit, 0, 0); m_layout->addWidget(m_typeSelector, 1, 0); m_layout->addWidget(m_buttonBox, 0, 1, 2, 1, Qt::AlignBottom); connect(m_typeSelector, SIGNAL(valueChanged(QVariant)), this, SLOT(onSearchTypeChanged())); connect(m_searchEdit, SIGNAL(textChanged(QString)), this, SLOT(onSearchTextChanged(QString))); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(m_historyButton, SIGNAL(clicked()), this, SLOT(showHistoryDialog())); connect(m_searchButton, SIGNAL(clicked()), this, SLOT(search())); } void PluginSearchDialog::showEvent(QShowEvent *e) { Dialog::showEvent(e); m_searchEdit->setFocus(Qt::OtherFocusReason); } void PluginSearchDialog::search() { if (!MainWindow::instance()->showResource(m_searchEdit->text())) { QVariantMap type = m_typeSelector->currentValue().toMap(); Settings::instance()->addSearch(m_searchEdit->text()); MainWindow::instance()->search(m_typeModel->service(), m_searchEdit->text(), type.value("type").toString(), type.value("order").toString()); } accept(); } void PluginSearchDialog::showHistoryDialog() { SearchHistoryDialog *dialog = new SearchHistoryDialog(this); dialog->open(); connect(dialog, SIGNAL(searchChosen(QString)), m_searchEdit, SLOT(setText(QString))); } void PluginSearchDialog::onSearchTextChanged(const QString &text) { m_searchButton->setEnabled(!text.isEmpty()); } void PluginSearchDialog::onSearchTypeChanged() { Settings::instance()->setDefaultSearchType(m_typeModel->service(), m_typeSelector->valueText()); }
gpl-3.0
pokedude9/AwesomeScriptEditor
src/Scripting/ScriptBlock.cpp
3398
////////////////////////////////////////////////////////////////////////////////// // // // d88b ad8888888ba 888888888888 // d8888b d88" "88b 888 // d88'`88b Y88, 888 // d88' `88b `Y88888, 88888888 // d88Y8888Y88b `"""""88b, 888 // d88""""""""88b `88b 888 // d88' `88b Y88a a88P 888 // d88' `88b "Y8888888P" 888888888888 // // // AwesomeScriptEditor: A script editor for GBA Pokémon games. // Copyright (C) 2016 Pokedude, Diegoisawesome // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // //////////////////////////////////////////////////////////////////////////////////_ /////////////////////////////////////////////////////////// // Include files // /////////////////////////////////////////////////////////// #include <ASE/Scripting/ScriptBlock.hpp> namespace ase { /////////////////////////////////////////////////////////// // Function type: Constructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 7/3/2016 // /////////////////////////////////////////////////////////// ScriptBlock::ScriptBlock(UInt32 offset) : m_Offset(offset) { } /////////////////////////////////////////////////////////// // Function type: Destructor // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 7/3/2016 // /////////////////////////////////////////////////////////// ScriptBlock::~ScriptBlock() { } /////////////////////////////////////////////////////////// // Function type: Getter // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 7/3/2016 // /////////////////////////////////////////////////////////// UInt32 ScriptBlock::offset() const { return m_Offset; } /////////////////////////////////////////////////////////// // Function type: I/O // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 7/3/2016 // /////////////////////////////////////////////////////////// const QString ScriptBlock::readData(const qboy::Rom &rom) { Q_UNUSED(rom); return QString::null; } /////////////////////////////////////////////////////////// // Function type: I/O // Contributors: Pokedude // Last edit by: Pokedude // Date of edit: 7/3/2016 // /////////////////////////////////////////////////////////// void ScriptBlock::writeData(const qboy::Rom &rom) { Q_UNUSED(rom); } }
gpl-3.0
cgrates/cgrates
apier/v1/tproutes_it_test.go
7399
//go:build offline // +build offline /* Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments Copyright (C) ITsysCOM GmbH This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package v1 import ( "net/rpc" "net/rpc/jsonrpc" "path" "reflect" "sort" "strings" "testing" "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/engine" "github.com/cgrates/cgrates/utils" ) var ( tpRouteCfgPath string tpRouteCfg *config.CGRConfig tpRouteRPC *rpc.Client tpRoutePrf *utils.TPRouteProfile tpRouteDelay int tpRouteConfigDIR string //run tests for specific configuration ) var sTestsTPRoute = []func(t *testing.T){ testTPRouteInitCfg, testTPRouteResetStorDb, testTPRouteStartEngine, testTPRouteRPCConn, testTPRouteGetTPRouteBeforeSet, testTPRouteSetTPRoute, testTPRouteGetTPRouteAfterSet, testTPRouteGetTPRouteIDs, testTPRouteUpdateTPRoute, testTPRouteGetTPRouteAfterUpdate, testTPRouteRemTPRoute, testTPRouteGetTPRouteAfterRemove, testTPRouteKillEngine, } //Test start here func TestTPRouteIT(t *testing.T) { switch *dbType { case utils.MetaInternal: tpRouteConfigDIR = "tutinternal" case utils.MetaMySQL: tpRouteConfigDIR = "tutmysql" case utils.MetaMongo: tpRouteConfigDIR = "tutmongo" case utils.MetaPostgres: t.SkipNow() default: t.Fatal("Unknown Database type") } for _, stest := range sTestsTPRoute { t.Run(tpRouteConfigDIR, stest) } } func testTPRouteInitCfg(t *testing.T) { var err error tpRouteCfgPath = path.Join(*dataDir, "conf", "samples", tpRouteConfigDIR) tpRouteCfg, err = config.NewCGRConfigFromPath(tpRouteCfgPath) if err != nil { t.Error(err) } tpRouteDelay = 1000 } // Wipe out the cdr database func testTPRouteResetStorDb(t *testing.T) { if err := engine.InitStorDb(tpRouteCfg); err != nil { t.Fatal(err) } } // Start CGR Engine func testTPRouteStartEngine(t *testing.T) { if _, err := engine.StopStartEngine(tpRouteCfgPath, tpRouteDelay); err != nil { t.Fatal(err) } } // Connect rpc client to rater func testTPRouteRPCConn(t *testing.T) { var err error tpRouteRPC, err = jsonrpc.Dial(utils.TCP, tpRouteCfg.ListenCfg().RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal(err) } } func testTPRouteGetTPRouteBeforeSet(t *testing.T) { var reply *utils.TPRoute if err := tpRouteRPC.Call(utils.APIerSv1GetTPRouteProfile, &utils.TPTntID{TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { t.Error(err) } } func testTPRouteSetTPRoute(t *testing.T) { tpRoutePrf = &utils.TPRouteProfile{ TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf", FilterIDs: []string{"FLTR_ACNT_dan", "FLTR_DST_DE"}, ActivationInterval: &utils.TPActivationInterval{ ActivationTime: "2014-07-29T15:00:00Z", ExpiryTime: "", }, Sorting: "*lc", Routes: []*utils.TPRoute{ &utils.TPRoute{ ID: "route1", FilterIDs: []string{"FLTR_1"}, AccountIDs: []string{"Acc1", "Acc2"}, RatingPlanIDs: []string{"RPL_1"}, ResourceIDs: []string{"ResGroup1"}, StatIDs: []string{"Stat1"}, Weight: 10, Blocker: false, RouteParameters: "SortingParam1", }, }, Weight: 20, } sort.Strings(tpRoutePrf.FilterIDs) var result string if err := tpRouteRPC.Call(utils.APIerSv1SetTPRouteProfile, tpRoutePrf, &result); err != nil { t.Error(err) } else if result != utils.OK { t.Error("Unexpected reply returned", result) } } func testTPRouteGetTPRouteAfterSet(t *testing.T) { var reply *utils.TPRouteProfile if err := tpRouteRPC.Call(utils.APIerSv1GetTPRouteProfile, &utils.TPTntID{TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf"}, &reply); err != nil { t.Fatal(err) } sort.Strings(reply.FilterIDs) if !reflect.DeepEqual(tpRoutePrf, reply) { t.Errorf("Expecting : %+v, received: %+v", utils.ToJSON(tpRoutePrf), utils.ToJSON(reply)) } } func testTPRouteGetTPRouteIDs(t *testing.T) { var result []string expectedTPID := []string{"cgrates.org:RoutePrf"} if err := tpRouteRPC.Call(utils.APIerSv1GetTPRouteProfileIDs, &AttrGetTPRouteProfileIDs{TPid: "TP1"}, &result); err != nil { t.Error(err) } else if !reflect.DeepEqual(expectedTPID, result) { t.Errorf("Expecting: %+v, received: %+v", expectedTPID, result) } } func testTPRouteUpdateTPRoute(t *testing.T) { tpRoutePrf.Routes = []*utils.TPRoute{ &utils.TPRoute{ ID: "route1", FilterIDs: []string{"FLTR_1"}, AccountIDs: []string{"Acc1", "Acc2"}, RatingPlanIDs: []string{"RPL_1"}, ResourceIDs: []string{"ResGroup1"}, StatIDs: []string{"Stat1"}, Weight: 10, Blocker: true, RouteParameters: "SortingParam1", }, &utils.TPRoute{ ID: "route2", FilterIDs: []string{"FLTR_1"}, AccountIDs: []string{"Acc3"}, RatingPlanIDs: []string{"RPL_1"}, ResourceIDs: []string{"ResGroup1"}, StatIDs: []string{"Stat1"}, Weight: 20, Blocker: false, RouteParameters: "SortingParam2", }, } var result string if err := tpRouteRPC.Call(utils.APIerSv1SetTPRouteProfile, tpRoutePrf, &result); err != nil { t.Error(err) } else if result != utils.OK { t.Error("Unexpected reply returned", result) } sort.Slice(tpRoutePrf.Routes, func(i, j int) bool { return strings.Compare(tpRoutePrf.Routes[i].ID, tpRoutePrf.Routes[j].ID) == -1 }) } func testTPRouteGetTPRouteAfterUpdate(t *testing.T) { var reply *utils.TPRouteProfile if err := tpRouteRPC.Call(utils.APIerSv1GetTPRouteProfile, &utils.TPTntID{TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf"}, &reply); err != nil { t.Fatal(err) } sort.Strings(reply.FilterIDs) sort.Slice(reply.Routes, func(i, j int) bool { return strings.Compare(reply.Routes[i].ID, reply.Routes[j].ID) == -1 }) if !reflect.DeepEqual(tpRoutePrf.Routes, reply.Routes) { t.Errorf("Expecting: %+v,\n received: %+v", utils.ToJSON(tpRoutePrf), utils.ToJSON(reply)) } } func testTPRouteRemTPRoute(t *testing.T) { var resp string if err := tpRouteRPC.Call(utils.APIerSv1RemoveTPRouteProfile, &utils.TPTntID{TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf"}, &resp); err != nil { t.Error(err) } else if resp != utils.OK { t.Error("Unexpected reply returned", resp) } } func testTPRouteGetTPRouteAfterRemove(t *testing.T) { var reply *utils.TPRouteProfile if err := tpRouteRPC.Call(utils.APIerSv1GetTPRouteProfile, &utils.TPTntID{TPid: "TP1", Tenant: "cgrates.org", ID: "RoutePrf"}, &reply); err == nil || err.Error() != utils.ErrNotFound.Error() { t.Error(err) } } func testTPRouteKillEngine(t *testing.T) { if err := engine.KillEngine(tpRouteDelay); err != nil { t.Error(err) } }
gpl-3.0
qtproject/qt-creator
src/plugins/projectexplorer/devicesupport/localprocesslist.cpp
8070
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "localprocesslist.h" #include <utils/qtcprocess.h> #include <QLibrary> #include <QTimer> #ifdef Q_OS_UNIX #include <QProcess> #include <QDir> #include <signal.h> #include <errno.h> #include <string.h> #include <unistd.h> #endif #ifdef Q_OS_WIN #include <windows.h> #include <utils/winutils.h> #include <tlhelp32.h> #include <psapi.h> #endif namespace ProjectExplorer { namespace Internal { #ifdef Q_OS_WIN LocalProcessList::LocalProcessList(const IDevice::ConstPtr &device, QObject *parent) : DeviceProcessList(device, parent) { setOwnPid(GetCurrentProcessId()); } QList<DeviceProcessItem> LocalProcessList::getLocalProcesses() { QList<DeviceProcessItem> processes; PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) return processes; for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) { DeviceProcessItem p; p.pid = pe.th32ProcessID; // Image has the absolute path, but can fail. const QString image = Utils::imageName(pe.th32ProcessID); p.exe = p.cmdLine = image.isEmpty() ? QString::fromWCharArray(pe.szExeFile) : image; processes << p; } CloseHandle(snapshot); return processes; } #endif //Q_OS_WIN #ifdef Q_OS_UNIX LocalProcessList::LocalProcessList(const IDevice::ConstPtr &device, QObject *parent) : DeviceProcessList(device, parent) { setOwnPid(getpid()); } static bool isUnixProcessId(const QString &procname) { for (int i = 0; i != procname.size(); ++i) if (!procname.at(i).isDigit()) return false; return true; } // Determine UNIX processes by reading "/proc". Default to ps if // it does not exist static const char procDirC[] = "/proc/"; static QList<DeviceProcessItem> getLocalProcessesUsingProc(const QDir &procDir) { QList<DeviceProcessItem> processes; const QString procDirPath = QLatin1String(procDirC); const QStringList procIds = procDir.entryList(); foreach (const QString &procId, procIds) { if (!isUnixProcessId(procId)) continue; DeviceProcessItem proc; proc.pid = procId.toInt(); const QString root = procDirPath + procId; QFile exeFile(root + QLatin1String("/exe")); proc.exe = exeFile.symLinkTarget(); QFile cmdLineFile(root + QLatin1String("/cmdline")); if (cmdLineFile.open(QIODevice::ReadOnly)) { // process may have exited QList<QByteArray> tokens = cmdLineFile.readAll().split('\0'); if (!tokens.isEmpty()) { if (proc.exe.isEmpty()) proc.exe = QString::fromLocal8Bit(tokens.front()); foreach (const QByteArray &t, tokens) { if (!proc.cmdLine.isEmpty()) proc.cmdLine.append(QLatin1Char(' ')); proc.cmdLine.append(QString::fromLocal8Bit(t)); } } } if (proc.exe.isEmpty()) { QFile statFile(root + QLatin1String("/stat")); if (!statFile.open(QIODevice::ReadOnly)) { const QStringList data = QString::fromLocal8Bit(statFile.readAll()).split(QLatin1Char(' ')); if (data.size() < 2) continue; proc.exe = data.at(1); proc.cmdLine = data.at(1); // PPID is element 3 if (proc.exe.startsWith(QLatin1Char('(')) && proc.exe.endsWith(QLatin1Char(')'))) { proc.exe.truncate(proc.exe.size() - 1); proc.exe.remove(0, 1); } } } if (!proc.exe.isEmpty()) processes.push_back(proc); } return processes; } // Determine UNIX processes by running ps static QMap<qint64, QString> getLocalProcessDataUsingPs(const QString &column) { QMap<qint64, QString> result; Utils::QtcProcess psProcess; psProcess.setCommand({"ps", {"-e", "-o", "pid," + column}}); psProcess.start(); if (psProcess.waitForStarted()) { QByteArray output; if (psProcess.readDataFromProcess(30, &output, nullptr, false)) { // Split "457 /Users/foo.app arg1 arg2" const QStringList lines = QString::fromLocal8Bit(output).split(QLatin1Char('\n')); const int lineCount = lines.size(); const QChar blank = QLatin1Char(' '); for (int l = 1; l < lineCount; l++) { // Skip header const QString line = lines.at(l).trimmed(); const int pidSep = line.indexOf(blank); const qint64 pid = line.left(pidSep).toLongLong(); result[pid] = line.mid(pidSep + 1); } } } return result; } static QList<DeviceProcessItem> getLocalProcessesUsingPs() { QList<DeviceProcessItem> processes; // cmdLines are full command lines, usually with absolute path, // exeNames only the file part of the executable's path. const QMap<qint64, QString> exeNames = getLocalProcessDataUsingPs("comm"); const QMap<qint64, QString> cmdLines = getLocalProcessDataUsingPs("args"); for (auto it = exeNames.begin(), end = exeNames.end(); it != end; ++it) { const qint64 pid = it.key(); if (pid <= 0) continue; const QString cmdLine = cmdLines.value(pid); if (cmdLines.isEmpty()) continue; const QString exeName = it.value(); if (exeName.isEmpty()) continue; const int pos = cmdLine.indexOf(exeName); if (pos == -1) continue; processes.append({pid, cmdLine, cmdLine.left(pos + exeName.size())}); } return processes; } QList<DeviceProcessItem> LocalProcessList::getLocalProcesses() { const QDir procDir = QDir(QLatin1String(procDirC)); return procDir.exists() ? getLocalProcessesUsingProc(procDir) : getLocalProcessesUsingPs(); } #endif // QT_OS_UNIX void LocalProcessList::doKillProcess(const DeviceProcessItem &process) { DeviceProcessSignalOperation::Ptr signalOperation = device()->signalOperation(); connect(signalOperation.data(), &DeviceProcessSignalOperation::finished, this, &LocalProcessList::reportDelayedKillStatus); signalOperation->killProcess(process.pid); } void LocalProcessList::handleUpdate() { reportProcessListUpdated(getLocalProcesses()); } void LocalProcessList::doUpdate() { QTimer::singleShot(0, this, &LocalProcessList::handleUpdate); } void LocalProcessList::reportDelayedKillStatus(const QString &errorMessage) { if (errorMessage.isEmpty()) reportProcessKilled(); else reportError(errorMessage); } } // namespace Internal } // namespace ProjectExplorer
gpl-3.0
Redcolaborar/Red-Colaborar
wp-content/plugins/stream/exporters/class-exporter-json.php
1034
<?php namespace WP_Stream; class Exporter_JSON extends Exporter { /** * Exporter name * * @var string */ public $name = 'JSON'; /** * Exporter slug * * @var string */ public $slug = 'json'; /** * Outputs JSON data for download * * @param array $data Array of data to output. * @param array $columns Column names included in data set. * @return void */ public function output_file( $data, $columns ) { if ( ! defined( 'WP_STREAM_TESTS' ) || ( defined( 'WP_STREAM_TESTS' ) && ! WP_STREAM_TESTS ) ) { header( 'Content-type: text/json' ); header( 'Content-Disposition: attachment; filename="stream.json"' ); } if ( function_exists( 'wp_json_encode' ) ) { $output = wp_json_encode( $data ); } else { $output = json_encode( $data ); // @codingStandardsIgnoreLine fallback to discouraged function } echo $output; // @codingStandardsIgnoreLine text-only output if ( ! defined( 'WP_STREAM_TESTS' ) || ( defined( 'WP_STREAM_TESTS' ) && ! WP_STREAM_TESTS ) ) { exit; } } }
gpl-3.0
nhatson1987/libQGLViewer-2.5.2
examples/contribs/dvonn/drawer.cpp
19609
/**************************************************************************** Copyright (C) 2002-2013 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.5.2. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include "drawer.h" #include <QGLViewer/qglviewer.h> #include <qimage.h> #include <qstringlist.h> #include <qmessagebox.h> using namespace std; using namespace dvonn; using namespace qglviewer; namespace { static const float whiteColor[3] = {1.0f,1.0f,1.0f}; static const float blackColor[3] = {0.2f,0.2f,0.2f}; static const float redColor[3] = {1.0f,0.0f,0.0f}; static const float boardColor[3] = {1.0f,1.0f,1.0f}; static const float boardBorderColor[3] = {0.0f,0.0f,0.0f}; // Dimension (D=widht=height) of a case and of the inner border of the // case (B) const float caseD = 1.0f; const float caseB = 0.2f; // Dimension of a piece const float pieceRMax = (caseD-2.0f*caseB)/sqrtf(2.0f); const float pieceRMin = pieceRMax/3.0f; const float pieceH = 0.14f; const float pieceC = 0.25f; // curvature of normal on vring part // Dimension of the label case float hLabelW = caseD; // must be caseD float hLabelH = caseD/3.0f; float vLabelW = caseD/3.0f; float vLabelH = caseD; // must be caseD // Dimension of the board const float boardB = 0.1f; const float boardW = Board::nbSpacesMaxOnRow()*caseD+2*boardB+2*vLabelW; const float boardH = Board::nbRows()*caseD+2*boardB+2*hLabelH; const float poolB = 0.1f; void tessAndTexture(float x0,float y0,float x2,float y2, float u0=0.0f,float v0=0.0f, float u2=1.0f,float v2=1.0f) { if (x0 > x2) swap(x0,x2); if (y0 > y2) swap(y0,y2); if (x2-x0>caseD) { float x1 = (x0+x2)/2.0f; float u1 = (u0+u2)/2.0f; tessAndTexture(x0,y0,x1,y2, u0,v0,u1,v2); tessAndTexture(x1,y0,x2,y2, u1,v0,u2,v2); } else if (y2-y0>caseD) { float y1 = (y0+y2)/2.0f; float v1 = (v0+v2)/2.0f; tessAndTexture(x0,y0,x2,y1, u0,v0,u2,v1); tessAndTexture(x0,y1,x2,y2, u0,v1,u2,v2); } else { glMultiTexCoord2f(GL_TEXTURE0,x0/caseD,y0/caseD); glMultiTexCoord2f(GL_TEXTURE1,u0,v0); glVertex2f(x0,y0); glMultiTexCoord2f(GL_TEXTURE0,x2/caseD,y0/caseD); glMultiTexCoord2f(GL_TEXTURE1,u2,v0); glVertex2f(x2,y0); glMultiTexCoord2f(GL_TEXTURE0,x2/caseD,y2/caseD); glMultiTexCoord2f(GL_TEXTURE1,u2,v2); glVertex2f(x2,y2); glMultiTexCoord2f(GL_TEXTURE0,x0/caseD,y2/caseD); glMultiTexCoord2f(GL_TEXTURE1,u0,v2); glVertex2f(x0,y2); } } const Vec normal[5] = { Vec(-1.0, 0.0, 0.0), Vec( 0.0, 1.0, 0.0), Vec( 1.0, 0.0, 0.0), Vec( 0.0, -1.0, 0.0), Vec(-1.0, 0.0, 0.0) }; void drawHRing(const float rMin, const float rMax, const float height) { // TODO : tabulate the cos and sin tables const int nbSteps = 24; glNormal3f(0.0, 0.0, 1.0); glBegin(GL_QUAD_STRIP); glVertex3f(rMin, 0.0, height); glVertex3f(rMax, 0.0, height); for (int i=1; i<=nbSteps; ++i) { const float angle = i * 2.0 * M_PI / nbSteps; const float cosine = cos(angle); const float sine = sin(angle); glVertex3f(rMin*cosine, rMin*sine, height); glVertex3f(rMax*cosine, rMax*sine, height); } glEnd(); } void drawVRing(const float hMin, const float hMax, const float r, bool in) { const int nbSteps = 24; const float normalSign = (in ? -1.0 : 1.0); float thMin = hMin; float thMax = hMax; if (in) swap(thMax,thMin); glBegin(GL_QUAD_STRIP); glNormal3f(normalSign, 0.0, 0.0); for (int i=0; i<=nbSteps; ++i) { const float angle = i * 2.0 * M_PI / nbSteps; const float cosine = cos(angle); const float sine = sin(angle); glNormal3fv(Vec(normalSign*cosine, normalSign*sine, +pieceC).unit()); glVertex3f(r*cosine, r*sine, thMax); glNormal3fv(Vec(normalSign*cosine, normalSign*sine, -pieceC).unit()); glVertex3f(r*cosine, r*sine, thMin); } glEnd(); } void drawPiece(const Color& p,float a=1.0f) { static const float* colors[3] = { redColor, whiteColor, blackColor }; const float* c = colors[static_cast<int>(p)]; glColor4f(c[0]*a,c[1]*a,c[2]*a,a); drawHRing(pieceRMin, pieceRMax, pieceH); drawVRing(0.0f, pieceH, pieceRMax, false); drawVRing(0.0f, pieceH, pieceRMin, true); } void drawHLabel(unsigned int i) { glBegin(GL_QUADS); unsigned int d = Board::nbRows()/2; if (i<Board::nbSpacesMaxOnRow()-d) // Bottom { float x = boardB+vLabelW+(d+1)*(caseD/2.0f)+i*hLabelW; float y = boardB; tessAndTexture(x,y, x+hLabelH,y+hLabelH, 0.0f,0.0f, 1.0f,1.0f); tessAndTexture(x+hLabelH,y, x+hLabelW,y+hLabelH, 2.0f,2.0f, 2.0f,2.0f); } if (i>=d) { float x = boardB+vLabelW-(d+1)*(caseD/2.0f)+i*hLabelW; float y = boardB+hLabelH+Board::nbRows()*caseD; tessAndTexture(x,y, x+hLabelW-hLabelH,y+hLabelH, 2.0f,2.0f, 2.0f,2.0f); tessAndTexture(x+hLabelW-hLabelH,y, x+hLabelW,y+hLabelH, 0.0f,0.0f, 1.0f,1.0f); } glEnd(); } void drawVLabel(int i) { glBegin(GL_QUADS); int d = static_cast<int>(Board::nbRows()/2); int e = abs(d-i); float shift = e*caseD/2.0f; float x = boardB+shift; float y = boardB+hLabelH+i*vLabelH; tessAndTexture(x,y, x+vLabelW,y+vLabelH/3.0f, 2.0f,2.0f, 2.0f,2.0f); tessAndTexture(x,y+vLabelH/3.0f, x+vLabelW,y+2.0f*vLabelH/3.0f, 0.0f,0.0f, 1.0f,1.0f); tessAndTexture(x,y+2.0f*vLabelH/3.0f, x+vLabelW,y+vLabelH, 2.0f,2.0f, 2.0f,2.0f); x = boardB+shift+vLabelW+(Board::nbSpacesMaxOnRow()-e)*caseD; y = boardB+hLabelH+i*vLabelH; tessAndTexture(x,y, x+vLabelW,y+vLabelH/3.0f, 2.0f,2.0f, 2.0f,2.0f); tessAndTexture(x,y+vLabelH/3.0f, x+vLabelW,y+2.0f*vLabelH/3.0f, 0.0f,0.0f, 1.0f,1.0f); tessAndTexture(x,y+2.0f*vLabelH/3.0f, x+vLabelW,y+vLabelH, 2.0f,2.0f, 2.0f,2.0f); glEnd(); } GLuint loadTexture(const QString fileName) { QImage img("images/"+fileName); if (img.isNull()) { QMessageBox::critical(NULL, "Image not found", "Unable to load texture from "+fileName); exit(1); // TODO: be nicer! } // 1E-3 needed. Just try with width=128 and see ! if ( ( img.width() != 1<<(int)(1+log(img.width() -1+1E-3) / log(2.0)) ) || ( img.height() != 1<<(int)(1+log(img.height()-1+1E-3) / log(2.0))) ) { QMessageBox::critical(NULL, "Wrong image dimensions", "Texture dimensions are not powers of 2 in "+fileName); exit(1); // TODO: be nicer! } // cout << "Loaded "<<fileName<<endl; QImage glImg = QGLWidget::convertToGLFormat(img); // flipped 32bit RGBA // Create a texture object GLuint to; glGenTextures(1,&to); glBindTexture(GL_TEXTURE_2D,to); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, glImg.width(), glImg.height(), GL_RGBA, GL_UNSIGNED_BYTE, glImg.bits()); return to; } } //************************************************************ // Implementation of Drawer //************************************************************ Drawer::Drawer() : showTextures_(true) { } void Drawer::toggleTexture(bool b) { showTextures_ = b; } Drawer::~Drawer() { } void Drawer::init() { static const QStringList texFilenames = QStringList()<<"board.png" <<"case.png"; for (QStringList::const_iterator it = texFilenames.begin(); it != texFilenames.end();++it) { textures_[*it] = loadTexture(*it); } for (unsigned int i=0;i<Board::nbSpacesMaxOnRow();++i) { static const char* letter = "ABCDEFGHIJK"; hLabels_.push_back(loadTexture(QString("label%1.png").arg(letter[i]))); } for (unsigned int i=0;i<Board::nbRows();++i) { vLabels_.push_back(loadTexture(QString("label%1.png").arg(i+1))); } glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); } void Drawer::startTexture(const QString& t) const { glPushAttrib(GL_ENABLE_BIT); glActiveTexture(GL_TEXTURE0); map<QString,GLuint>::const_iterator fter = textures_.find(t); if (showTextures_ && fter != textures_.end()) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,fter->second); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); } else { glDisable(GL_TEXTURE_2D); } glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); } void Drawer::startTexture(const QString& t,GLuint to) const { glPushAttrib(GL_ENABLE_BIT); glActiveTexture(GL_TEXTURE0); map<QString,GLuint>::const_iterator fter = textures_.find(t); if (showTextures_ && fter != textures_.end()) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,fter->second); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); } else { glDisable(GL_TEXTURE_2D); } glActiveTexture(GL_TEXTURE1); if (showTextures_) { glBindTexture(GL_TEXTURE_2D,to); glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP); } else { glDisable(GL_TEXTURE_2D); } } void Drawer::startTexture() const { glPushAttrib(GL_ENABLE_BIT); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); } void Drawer::endTexture() const { glPopAttrib(); } void translateTo(Board::Coord c,float h = 0.0f) { static const float shifts[5] = { 1.0f,0.5f,0.0f,-0.5f,-1.0f }; glTranslatef(boardB+vLabelW+c.x()*caseD+shifts[c.y()]*caseD, boardB+hLabelH+c.y()*caseD, h); } void Drawer::drawPieces(const Board::ConstStackHandle& s) const { startTexture(); glPushMatrix(); translateTo(s.stackCoord()); glTranslatef(0.5f*caseD,0.5f*caseD,0.0f); for (Stack::const_iterator iter = s->begin(), istop= s->end(); iter != istop;++iter) { drawPiece((*iter)->color()); glTranslatef(0.0f,0.0f,pieceH); } glPopMatrix(); endTexture(); } void Drawer::drawStatus(const Board::ConstStackHandle& s,QGLViewer* v) const { startTexture(); glPushMatrix(); translateTo(s.stackCoord(),s->height()*pieceH+pieceH/2.0f); glColor3f(1.0f,1.0f,0.0f); v->renderText(0.5f*caseD,0.5f*caseD,0.0f,QString("%1").arg(s.stackStatus())); glPopMatrix(); endTexture(); } void Drawer::drawTransparentPiece(Color col, const Board::ConstStackHandle& c,float a) const { startTexture(); glPushMatrix(); translateTo(c.stackCoord(),c->height()*pieceH); glTranslatef(0.5f*caseD,0.5f*caseD,0.0f); drawPiece(col,a); glPopMatrix(); endTexture(); } void Drawer::drawTransparentPieces(Stack::const_iterator first,Stack::const_iterator last,const Board::Coord& c,float h,float a) const { startTexture(); glPushMatrix(); translateTo(c,h*pieceH); glTranslatef(0.5f*caseD,0.5f*caseD,0.0f); while (first != last) { drawPiece((*first++)->color(),a); glTranslatef(0.0f,0.0f,pieceH); } glPopMatrix(); endTexture(); } void Drawer::draw(const Board::ConstStackHandle& c) const { glPushMatrix(); translateTo(c.stackCoord()); startTexture("case.png"); glColor3fv(boardColor); glNormal3fv(boardUpVector()); glBegin(GL_QUADS); tessAndTexture(0.0f ,0.0f,caseD,caseD); glEnd(); endTexture(); glPopMatrix(); } void Drawer::drawComplement(bool showLabels) const { glPushAttrib(GL_ALL_ATTRIB_BITS); glNormal3fv(boardUpVector()); glColor3fv(boardColor); for (unsigned int i=0;i<Board::nbSpacesMaxOnRow();++i) { if (showLabels) startTexture("board.png",hLabels_[i]); else startTexture("board.png"); drawHLabel(i); endTexture(); } glColor3fv(boardColor); for (unsigned int i=0;i<Board::nbRows();++i) { if (showLabels) startTexture("board.png",vLabels_[i]); else startTexture("board.png"); drawVLabel(i); endTexture(); } startTexture("board.png"); glBegin(GL_QUADS); if (boardB > 0.0f) { glColor3fv(boardBorderColor); tessAndTexture(0.0f ,0.0f, boardW,boardB); tessAndTexture(0.0f ,boardH-boardB, boardW,boardH); tessAndTexture(0.0f,boardB, boardB,boardH-boardB); tessAndTexture(boardW-boardB,boardB, boardW,boardH-boardB); } glColor3fv(boardColor); int d = Board::nbRows()/2; tessAndTexture(boardB, boardB, boardB+vLabelW+(d+1)*caseD/2.0f, boardB+hLabelH); tessAndTexture(boardB, boardH-boardB-hLabelH, boardB+vLabelW+(d+1)*caseD/2.0f-hLabelW, boardH-boardB); tessAndTexture(boardW-(boardB+vLabelW+(d+1)*caseD/2.0f)+hLabelW, boardB, boardW-boardB, boardB+hLabelH); tessAndTexture(boardW-(boardB+vLabelW+(d+1)*caseD/2.0f), boardH-boardB-hLabelH, boardW-boardB, boardH-boardB); for (int i=0;i<d;++i) { tessAndTexture(boardB, boardB+hLabelH+i*vLabelH, boardB+(d-i)*caseD/2.0f, boardB+hLabelH+i*vLabelH+vLabelH); tessAndTexture(boardB, boardH-(boardB+hLabelH+i*vLabelH+vLabelH), boardB+(d-i)*caseD/2.0f, boardH-(boardB+hLabelH+i*vLabelH)); tessAndTexture(boardW-(boardB+(d-i)*caseD/2.0f), boardB+hLabelH+i*vLabelH, boardW-boardB, boardB+hLabelH+i*vLabelH+vLabelH); tessAndTexture(boardW-(boardB+(d-i)*caseD/2.0f), boardH-(boardB+hLabelH+i*vLabelH+vLabelH), boardW-boardB, boardH-(boardB+hLabelH+i*vLabelH)); } glEnd(); endTexture(); glPopAttrib(); } void Drawer::drawWhitePiecePools(const Board& b,bool lastTransparent) const { unsigned int d = Board::nbRows()/2; unsigned int e = Board::nbSpacesMaxOnRow()-d; startTexture(); // Draw the whites and its up to two reds unsigned int nbR = b.nbUnplacedPieces(Red); unsigned int nbW = b.nbUnplacedPieces(White); unsigned int nbRed4White = nbR/2+nbR%2; for (unsigned int istop=nbW+nbRed4White,i=0; i<istop;++i) { const float x = boardB+vLabelW+(d+1)*caseD/2.0f+(i%e)*caseD; static const float y = -poolB-caseD/2.0f; const float z = (i/e)*pieceH; glPushMatrix(); glTranslatef(x,y,z); drawPiece((i<nbW)?White:Red, (lastTransparent && i==nbW+nbRed4White-1)?0.5f:1.0f); glPopMatrix(); } endTexture(); } void Drawer::drawBlackPiecePools(const Board& b,bool lastTransparent) const { unsigned int d = Board::nbRows()/2; unsigned int e = Board::nbSpacesMaxOnRow()-d; startTexture(); // Draw the blacks and its up to one red unsigned int nbR = b.nbUnplacedPieces(Red); unsigned int nbB = b.nbUnplacedPieces(Black); unsigned int nbRed4Black = nbR/2; for (unsigned int istop=nbB+nbRed4Black,i=0; i<istop;++i) { const float x = boardW-(boardB+vLabelW+(d+1)*caseD/2.0f+(i%e)*caseD); static const float y = boardH+poolB+caseD/2.0f; const float z = (i/e)*pieceH; glPushMatrix(); glTranslatef(x,y,z); drawPiece((i<nbB)?Black:Red, (lastTransparent && i==nbB+nbRed4Black-1)?0.4f:1.0f); glPopMatrix(); } endTexture(); } void Drawer::highlight(const Board::ConstStackHandle& c) const { glPushAttrib(GL_ENABLE_BIT); glDisable(GL_LIGHTING); startTexture(); glPushMatrix(); translateTo(c.stackCoord(),0.05f*pieceH+pieceH/2.0f); glScalef(caseD,caseD,pieceH); // glutWireCube(1.0f); glPopMatrix(); endTexture(); glPopAttrib(); } void Drawer::highlightPieces(const Board::ConstStackHandle& c) const { glPushAttrib(GL_ENABLE_BIT); glDisable(GL_LIGHTING); startTexture(); glPushMatrix(); translateTo(c.stackCoord(),0.01f); glTranslatef(0.5f*caseD,0.5f*caseD,0.0f); glColor4f(0.0f,0.0f,0.3f,0.3f); drawHRing(pieceRMin, 1.2f*pieceRMax, 0.0f); glPopMatrix(); endTexture(); glPopAttrib(); } void Drawer::drawMove(const Board& b,const Game::Move m,float t) const { const float L = caseD*estimateDrawMoveLength(b,m); const float t0 = (b.heightMax()+1-b.stackAt(m.src)->height())*pieceH/L; const float t1 = 1.0f-(b.heightMax()+1-b.stackAt(m.dst)->height())*pieceH/L; Board::ConstStackHandle src = b.stackAt(m.src); glPushMatrix(); startTexture(); if (t<=t0) { t /= t0; float srcH = src->height()*pieceH; float dstH = b.heightMax()*pieceH+pieceH; translateTo(m.src); glTranslatef(0.5f*caseD,0.5f*caseD, (1-t)*srcH+t*dstH); for (Stack::const_iterator iter = src->begin(), istop= src->end(); iter != istop;++iter) { drawPiece((*iter)->color()); glTranslatef(0.0f,0.0f,pieceH); } } else if (t<=t1) { t = (t-t0)/(t1-t0); static const float shifts[5] = { 1.0f,0.5f,0.0f,-0.5f,-1.0f }; float srcX = boardB+vLabelW+m.src.x()*caseD+shifts[m.src.y()]*caseD; float srcY = boardB+hLabelH+m.src.y()*caseD; float dstX = boardB+vLabelW+m.dst.x()*caseD+shifts[m.dst.y()]*caseD; float dstY = boardB+hLabelH+m.dst.y()*caseD; glTranslatef((1.0f-t)*srcX+t*dstX+0.5f*caseD, (1.0f-t)*srcY+t*dstY+0.5f*caseD, b.heightMax()*pieceH+pieceH); for (Stack::const_iterator iter = src->begin(), istop= src->end(); iter != istop;++iter) { drawPiece((*iter)->color()); glTranslatef(0.0f,0.0f,pieceH); } } else { t = (t-t1)/(1.0f-t1); float srcH = b.heightMax()*pieceH+pieceH; float dstH = b.stackAt(m.dst)->height()*pieceH; translateTo(m.dst); glTranslatef(0.5f*caseD,0.5f*caseD, (1-t)*srcH+t*dstH); for (Stack::const_iterator iter = src->begin(), istop= src->end(); iter != istop;++iter) { drawPiece((*iter)->color()); glTranslatef(0.0f,0.0f,pieceH); } } endTexture(); glPopMatrix(); } float Drawer::estimateDrawMoveLength(const Board& b,const Game::Move m) const { static const float shifts[5] = { 1.0f,0.5f,0.0f,-0.5f,-1.0f }; float srcX = boardB+vLabelW+m.src.x()*caseD+shifts[m.src.y()]*caseD; float srcY = boardB+hLabelH+m.src.y()*caseD; float dstX = boardB+vLabelW+m.dst.x()*caseD+shifts[m.dst.y()]*caseD; float dstY = boardB+hLabelH+m.dst.y()*caseD; return (Vec(dstX-srcX,dstY-srcY,0.0f).norm()+ (b.heightMax()+1-b.stackAt(m.src)->height())*pieceH+ (b.heightMax()+1-b.stackAt(m.dst)->height())*pieceH)/caseD; } Vec Drawer::boardCenter() const { return Vec(boardW/2.0f,boardH/2.0f,0.0f); } Vec Drawer::boardUpVector() const { return Vec(0.0f,0.0f,1.0f); } float Drawer::boardRadius() const { return Vec(boardW/2.0f,boardH/2.0f,0.0).norm(); } Vec Drawer::defaultEyePosition() const { return boardCenter()+boardRadius()*Vec(0.0, -1.7f, 1.0); }
gpl-3.0
brarcher/protect-baby-monitor
app/src/main/java/protect/babymonitor/DiscoverActivity.java
10257
/** * This file is part of the Protect Baby Monitor. * * Protect Baby Monitor 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. * * Protect Baby Monitor 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 Protect Baby Monitor. If not, see <http://www.gnu.org/licenses/>. */ package protect.babymonitor; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.nsd.NsdManager; import android.net.nsd.NsdServiceInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class DiscoverActivity extends Activity { final String TAG = "BabyMonitor"; NsdManager _nsdManager; NsdManager.DiscoveryListener _discoveryListener; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "Baby monitor start"); _nsdManager = (NsdManager)this.getSystemService(Context.NSD_SERVICE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_discover); final Button discoverChildButton = (Button) findViewById(R.id.discoverChildButton); discoverChildButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadDiscoveryViaMdns(); } }); final Button enterChildAddressButton = (Button) findViewById(R.id.enterChildAddressButton); enterChildAddressButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadDiscoveryViaAddress(); } }); } private void loadDiscoveryViaMdns() { setContentView(R.layout.activity_discover_mdns); startServiceDiscovery("_babymonitor._tcp."); } private void loadDiscoveryViaAddress() { setContentView(R.layout.activity_discover_address); final Button connectButton = (Button) findViewById(R.id.connectViaAddressButton); connectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "Connecting to child device via address"); final EditText addressField = (EditText) findViewById(R.id.ipAddressField); final EditText portField = (EditText) findViewById(R.id.portField); final String addressString = addressField.getText().toString(); final String portString = portField.getText().toString(); if(addressString.length() == 0) { Toast.makeText(DiscoverActivity.this, R.string.invalidAddress, Toast.LENGTH_LONG).show(); return; } int port = 0; try { port = Integer.parseInt(portString); } catch(NumberFormatException e) { Toast.makeText(DiscoverActivity.this, R.string.invalidPort, Toast.LENGTH_LONG).show(); return; } connectToChild(addressString, port, addressString); } }); } @Override protected void onDestroy() { Log.i(TAG, "Baby monitoring stop"); if(_discoveryListener != null) { Log.i(TAG, "Unregistering monitoring service"); _nsdManager.stopServiceDiscovery(_discoveryListener); _discoveryListener = null; } super.onDestroy(); } public void startServiceDiscovery(final String serviceType) { final NsdManager nsdManager = (NsdManager)this.getSystemService(Context.NSD_SERVICE); final ListView serviceTable = (ListView) findViewById(R.id.ServiceTable); final ArrayAdapter<ServiceInfoWrapper> availableServicesAdapter = new ArrayAdapter<ServiceInfoWrapper>(this, R.layout.available_children_list); serviceTable.setAdapter(availableServicesAdapter); serviceTable.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final ServiceInfoWrapper info = (ServiceInfoWrapper) parent.getItemAtPosition(position); connectToChild(info.getAddress(), info.getPort(), info.getName()); } }); // Instantiate a new DiscoveryListener _discoveryListener = new NsdManager.DiscoveryListener() { // Called as soon as service discovery begins. @Override public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started"); } @Override public void onServiceFound(NsdServiceInfo service) { // A service was found! Do something with it. Log.d(TAG, "Service discovery success: " + service); if (!service.getServiceType().equals(serviceType)) { // Service type is the string containing the protocol and // transport layer for this service. Log.d(TAG, "Unknown Service Type: " + service.getServiceType()); } else if (service.getServiceName().contains("ProtectBabyMonitor")) { NsdManager.ResolveListener resolver = new NsdManager.ResolveListener() { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { // Called when the resolve fails. Use the error code to debug. Log.e(TAG, "Resolve failed: error " + errorCode + " for service: " + serviceInfo); } @Override public void onServiceResolved(final NsdServiceInfo serviceInfo) { Log.i(TAG, "Resolve Succeeded: " + serviceInfo); DiscoverActivity.this.runOnUiThread(new Runnable() { @Override public void run() { availableServicesAdapter.add(new ServiceInfoWrapper(serviceInfo)); } }); } }; _nsdManager.resolveService(service, resolver); } else { Log.d(TAG, "Unknown Service name: " + service.getServiceName()); } } @Override public void onServiceLost(NsdServiceInfo service) { // When the network service is no longer available. // Internal bookkeeping code goes here. Log.e(TAG, "Service lost: " + service); } @Override public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code: " + errorCode); nsdManager.stopServiceDiscovery(this); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code: " + errorCode); nsdManager.stopServiceDiscovery(this); } }; nsdManager.discoverServices( serviceType, NsdManager.PROTOCOL_DNS_SD, _discoveryListener); } /** * Launch the ListenActivity to connect to the given child device * * @param address * @param port * @param name */ private void connectToChild(final String address, final int port, final String name) { final Intent i = new Intent(getApplicationContext(), ListenActivity.class); final Bundle b = new Bundle(); b.putString("address", address); b.putInt("port", port); b.putString("name", name); i.putExtras(b); startActivity(i); } } class ServiceInfoWrapper { private NsdServiceInfo _info; public ServiceInfoWrapper(NsdServiceInfo info) { _info = info; } public String getAddress() { return _info.getHost().getHostAddress(); } public int getPort() { return _info.getPort(); } public String getName() { // If there is more than one service on the network, it will // have a number at the end, but will appear as the following: // "ProtectBabyMonitor\\032(number) // or // "ProtectBabyMonitor\032(number) // Replace \\032 and \032 with a " " String serviceName = _info.getServiceName(); serviceName = serviceName.replace("\\\\032", " "); serviceName = serviceName.replace("\\032", " "); return serviceName; } @Override public String toString() { return getName(); } }
gpl-3.0
ppwozniak/java-openid-server
jos-web/src/main/java/pl/jdevelopers/jos/web/filter/UserAgentLocalesFilter.java
4774
/** * Copyright (c) 2006-2009, Redv.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Redv.com nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * Created on 2008-6-26 01:47:18 */ package pl.jdevelopers.jos.web.filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; /** * <p> * Gets all locales from user agent and retains all that in the human language * selection list, then stores it in the request attributes. * </p> * <p/> * When I using * <p/> * <pre> * &lt;div id="hl"&gt; * &lt;ul&gt; * #foreach($l in $request.locales) * &lt;li&gt;&lt;a href= * "?hl=$l#if($!request.getParameter('self'))&amp;self=$!request * .getParameter('self')#end" * &gt;$l.getDisplayName($l)&lt;/a&gt;&lt;/li&gt; * #end &lt;li class="last-child"&gt;&lt;a href= * "hl#if($!request.getParameter('self'))?self=$!request * .getParameter('self')#end" * >»&lt;/a&gt;&lt;/li&gt; * &lt;/ul&gt; * &lt;/div&gt; * </pre> * <p/> * but got a warning: * <code> * [org.apache.velocity.app.VelocityEngine:46] - Warning! * The iterative is an Enumeration in the #foreach() loop at [0,0] in template * header.vm. Because it's not resetable, if used in more than once, this may * lead to unexpected results. * </code> * <p/> * So I create this filter. * * @author Sutra Zhou */ public class UserAgentLocalesFilter extends OncePerRequestServiceFilter { /** * The user agent locales attribute name in HTTP request. */ private static final String USER_AGENT_LOCALES_ATTRIBUTE_NAME = "userAgentLocales"; /** * Gets user agent locales from the HTTP reques. * * @param request the HTTP request * @return user agent locales */ @SuppressWarnings("unchecked") public static Collection<Locale> getUserAgentLocales( final ServletRequest request) { return (Collection<Locale>) request .getAttribute(USER_AGENT_LOCALES_ATTRIBUTE_NAME); } /** * {@inheritDoc} */ @Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { request.setAttribute(USER_AGENT_LOCALES_ATTRIBUTE_NAME, this .getLocales(request)); filterChain.doFilter(request, response); } /** * Get locales from the HTTP request, and removed all that not is * unavailable. * * @param request the HTTP request. * @return a collection */ @SuppressWarnings("unchecked") private Collection<Locale> getLocales(final HttpServletRequest request) { Enumeration<Locale> localesEnum = request.getLocales(); List<Locale> localesList = Collections.list(localesEnum); // Use LinkedHashSet to eliminate duplication as the user agent may send // duplicated locales. Collection<Locale> localesCollection = new LinkedHashSet(localesList); localesCollection.retainAll(this.getService().getAvailableLocales()); return localesCollection; } }
gpl-3.0
osanwe/Kat
vksdk/src/requests/account.cpp
659
#include "account.h" Account::Account(QObject *parent) : RequestBase(parent) {} void Account::setOnline() { QUrlQuery query; query.addQueryItem("voip", "0"); _api->makeApiGetRequest("account.setOnline", query, ApiRequest::ACCOUNT_SET_ONLINE); } void Account::banUser(int id) { QUrlQuery query; query.addQueryItem("user_id", QString::number(id)); _api->makeApiGetRequest("account.banUser", query, ApiRequest::ACCOUNT_BAN_USER); } void Account::unbanUser(int id) { QUrlQuery query; query.addQueryItem("user_id", QString::number(id)); _api->makeApiGetRequest("account.unbanUser", query, ApiRequest::ACCOUNT_UNBAN_USER); }
gpl-3.0
lcpt/xc
src/domain/load/pattern/LoadPatternIter.cpp
4106
//---------------------------------------------------------------------------- // XC program; finite element analysis code // for structural analysis and design. // // Copyright (C) Luis Claudio Pérez Tato // // This program derives from OpenSees <http://opensees.berkeley.edu> // developed by the «Pacific earthquake engineering research center». // // Except for the restrictions that may arise from the copyright // of the original program (see copyright_opensees.txt) // XC 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 software is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // // You should have received a copy of the GNU General Public License // along with this program. // If not, see <http://www.gnu.org/licenses/>. //---------------------------------------------------------------------------- /* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.1.1.1 $ // $Date: 2000/09/15 08:23:19 $ // $Source: /usr/local/cvs/OpenSees/SRC/domain/load/pattern/LoadPatternIter.cpp,v $ // File: ~/domain/load/pattern/LoadPatternIter.C // // Written: fmk // Created: Fri Sep 20 15:27:47: 1996 // Revision: A // // Description: This file contains the method definitions for class // LoadPatternIter. LoadPatternIter is a class for iterating through the // Nodal loads of a load case. #include "domain/load/pattern/LoadPatternIter.h" #include <domain/load/pattern/LoadPattern.h> #include <utility/tagged/storage/TaggedObjectIter.h> #include <utility/tagged/storage/TaggedObjectStorage.h> // LoadPatternIter(SingleDomain &theDomain): // constructor that takes the model, just the basic iter XC::LoadPatternIter::LoadPatternIter(TaggedObjectStorage *theStorage) :myIter(theStorage->getComponents()) {} void XC::LoadPatternIter::reset(void) { myIter.reset(); } XC::LoadPattern *XC::LoadPatternIter::operator()(void) { // check if we still have elements in the model // if not return 0, indicating we are done TaggedObject *theComponent = myIter(); if(theComponent == 0) return 0; else { LoadPattern *result= dynamic_cast<LoadPattern *>(theComponent); return result; } }
gpl-3.0
Slaedr/amovemesh
src/binsort/adistbinsort.hpp
1949
/** \file adistbinsort.hpp * \brief Bin sort of set of points. * \author Aditya Kashi * \date April 20, 2016 */ #ifndef __ADISTBINSORT_H #define __ADISTBINSORT_H 1 #ifndef __AMATRIX_H #include <amatrix.hpp> #endif #ifndef _GLIBCXX_CMATH #include <cmath> #endif #ifndef _GLIBCXX_VECTOR #include <vector> #endif namespace amc { /// Sorts a set of points into bins such that each bin contains points close to each other template<int _ndim> class DistBinSort { amc_int npoin; ///< total number of points const amat::Matrix<amc_real>* pointlist; ///< List of unsorted points amat::Matrix<amc_real>* sortedlist; ///< List of sorted points const int* ndbins; ///< number of bins in each direction int nbins; ///< Total number of bins std::vector<std::vector<amc_real>> rbin; ///< coordinates of bin-divisions; contains an array of numbers for each coordinate direction std::vector<amc_int> bmap; ///< Stores the bin-sorted index of each point in the input array std::vector<amc_int> invbmap; ///< For each bin-sorted point index, stores its index in the original array const amc_real epsilon; ///< A tolerance, used for increasing the size of the bounding cell slightly /// Returns the bin number given the 'position' of a bin in the coordinate directions int binfunc(const int* r) const; public: /// Set data and compute bin sort /** \param[in] point_list is the initial list of unsorted points * \param[in] num_bins is an array containing the number of bins to use in each coordinate direction * \param[out] sorted_list is a pre-allocated list which will be filled with the sorted points */ DistBinSort(const amat::Matrix<amc_real>* const point_list, const int* num_bins, amat::Matrix<amc_real>* const sorted_list); inline amc_int gbmap(const amc_int index) const { return bmap[index]; } inline amc_int ginvbmap(const amc_int index) const { return invbmap[index]; } }; } #endif
gpl-3.0
Floydtm/cherry-shortcodes
assets/js/shotcodes/page-anchor.js
4700
(function($){ "use strict"; $.extend( $.expr[ ':' ], { 'position_fixed': function( element, index, match ) { return $( element ).css( 'position' ) === 'fixed'; } }); CHERRY_API.utilites.namespace( 'shortcode.row.page_anchor' ); CHERRY_API.shortcode.row.page_anchor = { $window:CHERRY_API.variable.$window, html_body: $('html, body'), wp_menu: '.menu', wp_menu_item: '.menu-item-type-custom', speed: anchor_scroll_speed, anchors: {}, items: $( '[data-anchor][data-id]' ), window_height: 0, do_animation: true, timer:null, //Window load handler init: function () { if( CHERRY_API.status.is_ready ){ this.events.do_script(); }else{ CHERRY_API.variable.$document.ready( this.do_script.bind( this ) ); } }, do_script:function(){ this.set_page_anchor(); $( this.wp_menu_item, this.wp_menu ).on('click', 'a[href^="#"]', this.on_anchor_change); this.$window .on( 'resize.page_anchor', $.proxy( this.set_window_height, this ) ) .on( 'mousedown.page_anchor', $.proxy( this.on_mousedown, this ) ) .on( 'mouseup.page_anchor', $.proxy( this.on_mouseup, this ) ) .on( 'hashchange.page_anchor', $.proxy( this.on_anchor_change, this ) ) .on( 'hashchange.page_anchor', $.proxy( this.set_activ_button, this ) ) .on( 'scroll.page_anchor', $.proxy( this.on_scroll, this ) ) .trigger( 'resize.page_anchor' ); if ( 'onwheel' in document ) { window.addEventListener( 'wheel', $.proxy( this.on_wheel, this ) ); }else if ( 'onmousewheel' in document ) { window.addEventListener( 'mousewheel', $.proxy( this.on_wheel, this ) ); }else if ( 'ontouchmove' in document ) { window.addEventListener("touchmove", $.proxy( this.on_wheel, this ), false); } this.on_anchor_change(); this.set_activ_button(); }, on_mousedown:function(){ this.do_animation = false; }, on_mouseup:function(){ this.do_animation = true; }, on_anchor_change:function(){ var hash = '', scroll_to = null, current_position = 0, coef, self = CHERRY_API.shortcode.row.page_anchor; if( this === self){ hash = window.location.hash.slice(1); }else{ hash = $( this ).attr( 'href' ).slice( 1 ); } if(self.do_animation){ self.do_animation = false; scroll_to = self.get_target_offset( $( '[data-anchor][data-id="' + hash + '"]' ) ); if( scroll_to ){ current_position = self.$window.scrollTop(); coef = self.speed * ( Math.abs( scroll_to - current_position ) / self.window_height ); self.animation_stop().html_body.animate( { 'scrollTop': scroll_to }, coef , 'linear', function(){ self.do_animation = true; }); } } }, on_wheel:function(event){ var self = this; self.do_animation = false; self.animation_stop(); clearTimeout( self.timer ) this.timer = setTimeout(function(){ self.do_animation = true; }, 100) }, set_activ_button:function(){ $( '.current-menu-item, .current_page_item', this.wp_menu ).removeClass('current-menu-item current_page_item'); $( this.wp_menu_item + ' a[href="' + window.location.hash + '"]', this.wp_menu ).parent().addClass('current-menu-item current_page_item'); }, set_window_height:function(){ this.window_height = window.innerHeight; this.set_page_anchor(); }, on_scroll:function(){ var salf = this, anchor; for (anchor in this.anchors) { if ( this.anchors.hasOwnProperty(anchor) ){ if( salf.in_viewport( anchor ) ){ window.location.hash = anchor; }; }; }; }, set_page_anchor:function(){ var self = this; self.items.each( function(){ var $this = $(this); self.anchors[$this.data('id')] = [ self.get_target_offset( $this ), $this.outerHeight() ]; } ); }, animation_stop:function(){ this.html_body.stop().clearQueue(); return this; }, get_target_offset:function( target ){ var position = 0; if( sticky_data.args.active ){ var fixed_header = $('header#header'); position = target[0] ? target.offset().top - fixed_header.outerHeight() - fixed_header.position().top : false ; }else{ position= target[0] ? target.offset().top : false ; } return Math.round( position ); }, in_viewport:function( target ){ var start_position = this.anchors[target][0], end_position = this.anchors[target][2], top_point = this.$window.scrollTop(), bottom_point = top_point + this.window_height / 2; if( start_position > top_point && start_position < bottom_point || end_position > top_point && end_position < bottom_point){ return true; }else{ return false; } } } CHERRY_API.shortcode.row.page_anchor.init(); }(jQuery));
gpl-3.0
madeITBelgium/vesta
web/download/backup/index.php
896
<?php // Init error_reporting(NULL); session_start(); include($_SERVER['DOCUMENT_ROOT']."/inc/main.php"); // Check token if ((!isset($_GET['token'])) || ($_SESSION['token'] != $_GET['token'])) { header('Location: /login/'); exit(); } $backup = basename($_GET['backup']); // Check if the backup exists if (!file_exists('/backup/'.$backup)) { exit(0); } // Data if ($_SESSION['user'] == 'admin') { header('Content-type: application/gzip'); header("Content-Disposition: attachment; filename=\"".$backup."\";" ); header("X-Accel-Redirect: /backup/" . $backup); } if ((!empty($_SESSION['user'])) && ($_SESSION['user'] != 'admin')) { if (strpos($backup, $user.'.') === 0) { header('Content-type: application/gzip'); header("Content-Disposition: attachment; filename=\"".$backup."\";" ); header("X-Accel-Redirect: /backup/" . $backup); } }
gpl-3.0
thm-projects/arsnova-flashcards
imports/ui/filter/index/item/bottom/item/editTranscript.js
1114
import "./editTranscript.html"; import {Template} from "meteor/templating"; import {Route} from "../../../../../../util/route"; import {TranscriptBonus} from "../../../../../../api/subscriptions/transcriptBonus"; import {TranscriptBonusList} from "../../../../../../util/transcriptBonus"; import { FlowRouter } from 'meteor/ostrio:flow-router-extra'; /* * ############################################################################ * filterIndexItemBottomEditTranscript * ############################################################################ */ Template.filterIndexItemBottomEditTranscript.helpers({ isBonusTranscriptsRouteAndDeadlineExpired: function () { if (Route.isMyBonusTranscripts() || Route.isTranscriptBonus()) { let bonusTranscript = TranscriptBonus.findOne({card_id: this._id}); if (bonusTranscript !== undefined) { return TranscriptBonusList.isDeadlineExpired(bonusTranscript, true); } } } }); Template.filterIndexItemBottomEditTranscript.events({ 'click .editCard': function (event) { FlowRouter.go('editTranscript', {card_id: $(event.target).data('id')}); } });
gpl-3.0
msoni11/elismoodle
lib/pear/PHPUnit/Framework.php
2187
<?php /** * PHPUnit * * Copyright (c) 2002-2010, Sebastian Bergmann <sebastian@phpunit.de>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package PHPUnit * @author Sebastian Bergmann <sebastian@phpunit.de> * @copyright 2002-2010 Sebastian Bergmann <sebastian@phpunit.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://www.phpunit.de/ * @since File available since Release 3.0.0 */ require_once 'PHP/CodeCoverage/Filter.php'; PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'PHPUNIT'); //trigger_error('Please no longer include "PHPUnit/Framework.php".', E_USER_NOTICE);
gpl-3.0
kipr/harrogate
shared/client/doc/search/searchdata.js
760
var indexSectionsWithContent = { 0: "_abcdefghijklmnoprstuvwxyz~", 1: "_abcdeghimnoprstvx", 2: "bcs", 3: "abcdegimrstuvw", 4: "_abcdefghijlmnoprstuvwxyz~", 5: "_abcdghilmnrstuvwxyz", 6: "ceoprstv", 7: "beikmr", 8: "abcfhklmnoprswxyz", 9: "_bceginopsv", 10: "abcdgimst", 11: "d" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "namespaces", 3: "files", 4: "functions", 5: "variables", 6: "typedefs", 7: "enums", 8: "enumvalues", 9: "defines", 10: "groups", 11: "pages" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Namespaces", 3: "Files", 4: "Functions", 5: "Variables", 6: "Typedefs", 7: "Enumerations", 8: "Enumerator", 9: "Macros", 10: "Modules", 11: "Pages" };
gpl-3.0
jazzsequence/games-collector
vendor/wp-coding-standards/wpcs/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
7865
<?php /** * WordPress Coding Standard. * * @package WPCS\WordPressCodingStandards * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards * @license https://opensource.org/licenses/MIT MIT */ namespace WordPress\Sniffs\NamingConventions; use WordPress\AbstractFunctionParameterSniff; /** * Use lowercase letters in action and filter names. Separate words via underscores. * * This sniff is only testing the hook invoke functions as when using 'add_action'/'add_filter' * you can't influence the hook name. * * Hook names invoked with `do_action_deprecated()` and `apply_filters_deprecated()` are ignored. * * @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#naming-conventions * * @package WPCS\WordPressCodingStandards * * @since 0.10.0 * @since 0.11.0 Extends the WordPress_AbstractFunctionParameterSniff class. * @since 0.13.0 Class name changed: this class is now namespaced. */ class ValidHookNameSniff extends AbstractFunctionParameterSniff { /** * Additional word separators. * * This public variable allows providing additional word separators which * will be allowed in hook names via a property in the phpcs.xml config file. * * Example usage: * <rule ref="WordPress.NamingConventions.ValidHookName"> * <properties> * <property name="additionalWordDelimiters" value="-"/> * </properties> * </rule> * * Provide several extra delimiters as one string: * <rule ref="WordPress.NamingConventions.ValidHookName"> * <properties> * <property name="additionalWordDelimiters" value="-/."/> * </properties> * </rule> * * @var string */ public $additionalWordDelimiters = ''; /** * Regular expression to test for correct punctuation of a hook name. * * The placeholder will be replaced by potentially provided additional * word delimiters in the `prepare_regex()` method. * * @var string */ protected $punctuation_regex = '`[^\w%s]`'; /** * Groups of function to restrict. * * @since 0.11.0 * * @return array */ public function getGroups() { $this->target_functions = $this->hookInvokeFunctions; return parent::getGroups(); } /** * Process the parameters of a matched function. * * @since 0.11.0 * * @param int $stackPtr The position of the current token in the stack. * @param array $group_name The name of the group which was matched. * @param string $matched_content The token content (function name) which was matched. * @param array $parameters Array with information about the parameters. * * @return void */ public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { // Ignore deprecated hook names. if ( strpos( $matched_content, '_deprecated' ) > 0 ) { return; } if ( ! isset( $parameters[1] ) ) { return; } $regex = $this->prepare_regex(); $case_errors = 0; $underscores = 0; $content = array(); $expected = array(); for ( $i = $parameters[1]['start']; $i <= $parameters[1]['end']; $i++ ) { $content[ $i ] = $this->tokens[ $i ]['content']; $expected[ $i ] = $this->tokens[ $i ]['content']; if ( \in_array( $this->tokens[ $i ]['code'], array( \T_CONSTANT_ENCAPSED_STRING, \T_DOUBLE_QUOTED_STRING ), true ) ) { $string = $this->strip_quotes( $this->tokens[ $i ]['content'] ); /* * Here be dragons - a double quoted string can contain extrapolated variables * which don't have to comply with these rules. */ if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $i ]['code'] ) { $transform = $this->transform_complex_string( $string, $regex ); $case_transform = $this->transform_complex_string( $string, $regex, 'case' ); $punct_transform = $this->transform_complex_string( $string, $regex, 'punctuation' ); } else { $transform = $this->transform( $string, $regex ); $case_transform = $this->transform( $string, $regex, 'case' ); $punct_transform = $this->transform( $string, $regex, 'punctuation' ); } if ( $string === $transform ) { continue; } if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $i ]['code'] ) { $expected[ $i ] = '"' . $transform . '"'; } else { $expected[ $i ] = '\'' . $transform . '\''; } if ( $string !== $case_transform ) { $case_errors++; } if ( $string !== $punct_transform ) { $underscores++; } } } $data = array( implode( '', $expected ), implode( '', $content ), ); if ( $case_errors > 0 ) { $error = 'Hook names should be lowercase. Expected: %s, but found: %s.'; $this->phpcsFile->addError( $error, $stackPtr, 'NotLowercase', $data ); } if ( $underscores > 0 ) { $error = 'Words in hook names should be separated using underscores. Expected: %s, but found: %s.'; $this->phpcsFile->addWarning( $error, $stackPtr, 'UseUnderscores', $data ); } } /** * Prepare the punctuation regular expression. * * Merges the existing regular expression with potentially provided extra word delimiters to allow. * This is done 'late' and for each found token as otherwise inline `@codingStandardsChangeSetting` * directives would be ignored. * * @return string */ protected function prepare_regex() { $extra = ''; if ( '' !== $this->additionalWordDelimiters && \is_string( $this->additionalWordDelimiters ) ) { $extra = preg_quote( $this->additionalWordDelimiters, '`' ); } return sprintf( $this->punctuation_regex, $extra ); } /** * Transform an arbitrary string to lowercase and replace punctuation and spaces with underscores. * * @param string $string The target string. * @param string $regex The punctuation regular expression to use. * @param string $transform_type Whether to a partial or complete transform. * Valid values are: 'full', 'case', 'punctuation'. * @return string */ protected function transform( $string, $regex, $transform_type = 'full' ) { switch ( $transform_type ) { case 'case': return strtolower( $string ); case 'punctuation': return preg_replace( $regex, '_', $string ); case 'full': default: return preg_replace( $regex, '_', strtolower( $string ) ); } } /** * Transform a complex string which may contain variable extrapolation. * * @param string $string The target string. * @param string $regex The punctuation regular expression to use. * @param string $transform_type Whether to a partial or complete transform. * Valid values are: 'full', 'case', 'punctuation'. * @return string */ protected function transform_complex_string( $string, $regex, $transform_type = 'full' ) { $output = preg_split( '`([\{\}\$\[\] ])`', $string, -1, \PREG_SPLIT_DELIM_CAPTURE ); $is_variable = false; $has_braces = false; $braces = 0; foreach ( $output as $i => $part ) { if ( \in_array( $part, array( '$', '{' ), true ) ) { $is_variable = true; if ( '{' === $part ) { $has_braces = true; $braces++; } continue; } if ( true === $is_variable ) { if ( '[' === $part ) { $has_braces = true; $braces++; } if ( \in_array( $part, array( '}', ']' ), true ) ) { $braces--; } if ( false === $has_braces && ' ' === $part ) { $is_variable = false; $output[ $i ] = $this->transform( $part, $regex, $transform_type ); } if ( ( true === $has_braces && 0 === $braces ) && false === \in_array( $output[ ( $i + 1 ) ], array( '{', '[' ), true ) ) { $has_braces = false; $is_variable = false; } continue; } $output[ $i ] = $this->transform( $part, $regex, $transform_type ); } return implode( '', $output ); } }
gpl-3.0