code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
----------------------------------- -- Area: The Eldieme Necropolis (S) (175) -- MOB: Ulbrecht ----------------------------------- -- ----------------------------------- function onMobDeath(mob, player, isKiller) end;
m3rlin87/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/mobs/Ulbrecht.lua
Lua
gpl-3.0
221
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_10) on Sat May 04 18:49:09 EDT 2013 --> <title>Uses of Class com.github.computerdude5000.terracrafttools.modules.utility.FireWorksCreator</title> <meta name="date" content="2013-05-04"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.github.computerdude5000.terracrafttools.modules.utility.FireWorksCreator"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li> <a href="../../../../../../../com/github/computerdude5000/terracrafttools/modules/utility/FireWorksCreator.html" title="class in com.github.computerdude5000.terracrafttools.modules.utility">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li> <a href="../../../../../../../index.html?com/github/computerdude5000/terracrafttools/modules/utility/class-use/FireWorksCreator.html" target="_top">Frames</a></li> <li><a href="FireWorksCreator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.github.computerdude5000.terracrafttools.modules.utility.FireWorksCreator" class="title">Uses of Class<br>com.github.computerdude5000.terracrafttools.modules.utility.FireWorksCreator</h2> </div> <div class="classUseContainer">No usage of com.github.computerdude5000.terracrafttools.modules.utility.FireWorksCreator </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li> <a href="../../../../../../../com/github/computerdude5000/terracrafttools/modules/utility/FireWorksCreator.html" title="class in com.github.computerdude5000.terracrafttools.modules.utility">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li> <a href="../../../../../../../index.html?com/github/computerdude5000/terracrafttools/modules/utility/class-use/FireWorksCreator.html" target="_top">Frames</a></li> <li><a href="FireWorksCreator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
computerdude5000/InfiniumCraftTools
javadocs/com/github/computerdude5000/terracrafttools/modules/utility/class-use/FireWorksCreator.html
HTML
gpl-3.0
5,188
<!DOCTYPE html> <html class="um landscape min-width-240px min-width-320px min-width-480px min-width-768px min-width-1024px"> <head> <meta charset="utf-8"> <title></title> <meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="css/fonts/font-awesome.min.css"> <link rel="stylesheet" href="css/ui-box.css"> <link rel="stylesheet" href="css/ui-base.css"> <link rel="stylesheet" href="css/ui-color.css"> <link rel="stylesheet" href="css/appcan.icon.css"> <link rel="stylesheet" href="css/appcan.control.css"> <link rel="stylesheet" href="css/main.css"> <style> /*input聚焦时不要出现边框*/ input{ outline:medium; } input::-webkit-input-placeholder { /* WebKit browsers */ color: #808080; } </style> </head> <body class="um-vp c_wh" ontouchstart> <div id="page_0" class="up ub ub-ver bc_e9" tabindex="0"> <!--header开始--> <div id="header" class="uh bc-text-head ub bc-head"> <div class="ub ub-f1 ub-ac ub-img" id="nav-left" > <div class="nav-btn" style="min-width: 3em"><div class="back"></div></div> </div> <h1 class="ut ub-f1 ulev-3 ut-s tx-c" tabindex="0">登录</h1> <div class="ub ub-f1 ub-ac ub-pe" id="nav-right"> <div class="setting ub-img" style="min-width: 3em;"></div> </div> </div> <!--header结束--><!--content开始--> <div id="content" class="ub ub-ver ub-f1 bc_e9 ulev30"> <div class="ub ub-f2 ub-ac ub-pc" style=""> <div class="headPortrait"></div> </div> <div class="ub ub-ver umar_i01"> <div class="ub ub-f1 c-wh umh25 ub-ac uc-a1 " style="padding:.75em"> <div class="logType umar_r04"></div> <div class="ub-f1 ub ub-ac" > <div id="idText" class="ub-f1 umar_l01" style="border: none"> <!-- <div class="select"> <div class="text"> 请选择</div> <div class="icon"></div> <select selectedindex="0"> <option>身份证</option> <option>军官证</option> <option>士兵证</option> <option>户口本</option> <option>警官</option> <option>昵称</option> </select> </div> --> </div> </div> </div> <div class="ub ub-ver umar_t1"> <div class="ub ub-f1 c-wh umh25 ub-ac uc-t1" style="padding:.35em .75em 0;"> <div class="ub ub-f1 ubb" style="border-color:#e3e3e3;padding-bottom: .35em" > <div class="logNumber"></div> <div id="logn_wrap" class="ub-f1 ub ub-ac umar_l04" style="min-height: 1.5em;"> <div class="ub-f1 umar_l04 umar_r04" style="border: none;"> <input class="uinput1" type="text" oninput='setInvaid()' placeholder="" style="border:none;font-size: 1em;background-color: #FFFFFF;" value="" id='lognumber' maxlength="18"> </div> <div id="red_icon"></div> </div> </div> </div> <div class="ub ub-f1 c-wh umh25 ub-ac uc-b1" style="padding:.35em .75em;"> <div class="pwd"></div> <div id="psd_wrap" class="ub-f1 ub ub-ac umar_l04" style="min-height: 1.5em;"> <div class="ub-f1 umar_l04 umar_r04" style="border: none;"> <input class="uinput1" placeholder="请输入您的密码" style="border:none;font-size: 1em;background-color: #FFFFFF;" value="" id='password' type="password"> </div> </div> </div> </div> <div class="ub ub-ac t_666 umar_t05 umar_l04 umar_r04"> <div class="ub ub-f1 ub-ac"> <div class="checkbox umar-r"> <input id="accCheckbox" type="checkbox" class="uabs ub-con" checked="checked"> </div> <div class="">记住账号</div> </div> <div id="fgtPwd" style="" class="ub-f1 tx-r t-red"><span ontouchstart="appcan.touch()">忘记密码</span></div> </div> </div> <div class="ub ub-f3 ub-ver"> <div class="ub t-wh umar_i02"> <div id="register" class="ub ub-f1 c-red ub-ac ub-pc uc-a1" style="padding:.65em 0;min-width:3em;margin-right: 2em;background-color: #ff6061"><div class="ub ub-ac ub-pc" style="min-width: 4em">免费开户</div></div> <div id="login" class="ub ub-f1 c-blu ub-ac ub-pc uc-a1" style="padding:.65em 0;;background-color: #73a8ec"><div class="ub ub-ac ub-pc" style="min-width: 4em">登&nbsp;&nbsp;录</div></div> </div> <div class="ub ub-pc ub-ver t_666 umar_t05 umar_i03" > <div> 温馨提示:</div> <div class="ft_4i1 umar_t04"> 1、南方基金网上直销客户,请使用交易密码登录。 </div> <div class="ft_4i1 umar_t04"> 2、通过银行、券商等机构购买基金的客户,请使用查询密码登录。 </div> </div> </div> <div id="postmessage" class="t_868 ulev-1 umar_t02" style="word-wrap:break-word;word-break:break-all;"> </div> </div> </div> </body> <script src="js/appcan.min.js"></script> <script src="js/appcan.control.js"></script> <script src="js/aes.js"></script> <script src="js/config.js"></script> <script src="js/identify.js"></script> <script src="js/main.js"></script> <script> zy_init(); var placeTxt = ""; function initSelCerType(){ var scerType= '身份证'; if(getLocVal('reAccount')=='true'){ scerType=getCerType(getLocVal('certificatetype')); if(scerType=='昵称'){ placeTxt = getLocVal('lognumber'); }else{ placeTxt = hidelogNumber(getLocVal('lognumber')); } }else{ placeTxt = "请输入证件号码"; } if(isAndroid){ var str ='<div class="select"><div class="text" id="selcerType">'+scerType +'</div><div class="icon"></div><select id="cerType" selectedindex="0">' +'<option value="0">身份证</option>' +'<option value="2">军官证</option>' +'<option value="3">士兵证</option>' +'<option value="5">户口本</option>' +'<option value="9">警官</option>' +'<option value="7">昵称</option>' +'</select> ' +'</div>'; $('#idText').html(str); var selcerType=$("#cerType").find("option[value='"+getLocVal('certificatetype')+"']") selcerType.attr("selected",true); appcan.select(".select", "", function(ele,value) {//select }); }else{ $('#idText').html('<div class="select"><div class="text" id="selcerType">'+scerType +'</div><div class="icon"></div></div>'); //$('#idText').html('<div id="selcerType" class="ub" style="padding-left: 2em;">'+scerType+'</div>'); appcan.button("#idText", "", function() {//按钮效果 createActionSheet(); uexWindow.cbActionSheet = cbActionSheet; }); } } initSelCerType();//初始化登陆类型选择下拉框 var certificatetype=getLocVal('reAccount')=='true'?getLocVal('certificatetype'):'0';//证件类型 var logtype=2;//登陆类型,1:基金账号;2:证件号码;3:客户编号(暂只支持ET模式);N:基金昵称;R:注册用户 var cerList = ['身份证','军官证','士兵证','户口本','警官','昵称'];//登录类型 var get_flag = false; var accoValid = false; if(getLocVal('reAccount')=='true') { accoValid = true; } appcan.ready(function() { if(getLocVal('exitPage')=='securityExit'){//安全退出页面时才关闭 clearLocVal('exitPage'); uescript('account','winClose()'); } uescript('gesture_verification','winClose(-1)'); initPage(); getKey(); }); function initPage(){//记住账号初始化 $("#lognumber").attr('placeholder',placeTxt); if(getLocVal('reAccount')=='true'){//有记住账号是显示红叉 document.getElementById('red_icon').className = 'red_icon ub-img'; appcan.button("#red_icon", "ani-act", function() {//select clearAcc(); }); //$('#lognumber').val(getLocVal('lognumber')); //从缓存中获取,处理成***(加密) var logtype=getLocVal('logtype');//1:基金账号,2:证件号码,N:基金昵称,R:注册用户 certificateType = getLocVal('certificateType'); } if(isPhone) { if(isIPhone) { $("#password").attr("disabled",'disabled'); $("#lognumber").attr("disabled",'disabled'); inintinput(); //密码键盘初始化 inintinput2(); //账号键盘初始化 } } } function login(){ if(isAndroid){ certificatetype=$('#cerType').val(); } if(isPhone) { var lognumber = accoValid?getLocVal("lognumber"):$('#lognumber').val();//记住账号且无修改删除则使用缓存账号 }else { var lognumber = $('#lognumber').val()||getLocVal("lognumber"); password = $("#password").val(); } if(isAndroid||isIPad){ password = rem_bla($("#password").val()); } if(lognumber == "") { appcan.window.openToast('请输入账号','3000','5','0'); return; }else { if(certificatetype=='0'){ if(!IdCardValidate(lognumber)){ $toast('对不起!您输入的证件号格式有误',1000); return; } } } if(certificatetype=='7'){ logtype='N'; } if(!isDefine(password)) { $toast('请输入密码',1000); return; } var j={"function": "P003","logtype":logtype,"certificatetype":certificatetype,"crypt":"1","lognumber":lognumber,"password": Encrypt(password),"devicetype":getLocVal("devicetype"),"udid": getLocVal("devicetoken"),"devicetoken": getLocVal("devicetoken"),"clientVersion":getLocVal("clientVersion"),"version":getLocVal("version")}; toast('正在登陆…'); appcan.request.post(serverIp ,j ,function(data){ console.log(json2str(data)) closeToast(); if(data.code == "ETS-5BP0000") { //登录成功后再进行记住账号操作 if(document.getElementById('accCheckbox').checked){//选中并且不包括** setLocVal('reAccount','true');//记住账号 }else if(!document.getElementById('accCheckbox').checked){ setLocVal('reAccount',''); } setLocVal("sessionkey",data.sessionkey); setLocVal("lognumber",lognumber); setLocVal("certificatetype",certificatetype); setLocVal("logtype",logtype); setLocVal("eqcustno",data.eqcustno); setLocVal("email",data.email); setLocVal("handset",data.handset); setLocVal("riskUpdateTime",data.riskUpdateTime);//风险评估测评 setLocVal("riskability",data.riskability); setLocVal("customerappellation",data.customerappellation); setLocVal("idtype",data.idtype); setLocVal("idno",data.idno); setLocVal("riskexpired",data.riskexpired); setLocVal('isLogin','true');//是否登陆 setLocVal('originalString',data.originalString);//是否代销客户:值为DCVALID ueppscript('index','content','initData()'); uescript('index','init()');//修改登录注册按钮 ueppscript('zhangzb','content','update(true)');// if(!isOldUser(lognumber)){ clearLocVal('confirmStr'); clearLocVal('openAccount'); setLocVal('confrimPage','login_setGesture'); var s=window.getComputedStyle(document.body,null); uexWindow.openPopover("confirmTip","0","confirmTip.html","",0,0,parseInt(s.width),parseInt(s.height),parseInt(s.fontSize),"0"); }else{ uescript("index","setTimeout('loginCallback()',500)") winClose(-1); } }else{ $toast(data.message,2000); } },'json',function(){ closeToast(); getAjaxError(arguments[1]); },timeout);//默认设置20秒 } //清除账号信息方法 function clearAcc(){ accoValid = false; $('#lognumber').attr('placeholder',''); if(isAndroid){ $('#lognumber').val(""); }else { clearData("name"); } } function clearData() {//调键盘插件的input清空值 var jsonData = {"type":"name"}; //uexRandomKeyboard.clearData(JSON.stringify(jsonData)); uexRandomKeyboard.clearData(JSON.stringify(jsonData)); } function inintinput(){ var screenW = window.screen.width;//屏幕宽 var pageW = $("#header").offset().width;//页面宽 var s = window.getComputedStyle(document.getElementById("psd_wrap"),null); var aa = getPosition(document.getElementById("psd_wrap")).split(','); var inputHeight = parseInt(document.getElementById("psd_wrap").offsetHeight); var f = screenW/pageW; var y = parseInt(aa[1]); var x = parseInt(aa[0]); var w = parseInt(s.width); var h = parseInt(inputHeight); var ft = parseInt(s.fontSize); if(f!=0) { y=y*f; x=x*f; w=w*f; h=h*f; ft=ft*f; } var jsonData = {"fontSize":parseInt(ft),"fontColor":"#000","placeholderText":"请输入您的密码","secureTextEntry":"1","backgroundColor":"#FFFFFF","randomLetterKeyboard":"1","randomDigitalKeyboard":"0","defaultKeyboard":"0","isSystemKeyboard":"1","isTextRight":"0"}; uexRandomKeyboard.onGetContent = onGetContent; uexRandomKeyboard.open(parseInt(x),parseInt(y),parseInt(w),parseInt(h),JSON.stringify(jsonData)); } function inintinput2(){ var screenW = window.screen.width;//屏幕宽 var pageW = $("#header").offset().width;//页面宽 var s = window.getComputedStyle(document.getElementById('logn_wrap'),null); var aa = getPosition(document.getElementById('logn_wrap')).split(','); //var bb = getPosition(document.getElementById("ww1")).split(','); var inputHeight = parseInt(document.getElementById("logn_wrap").offsetHeight); var f = screenW/pageW; var y = parseInt(aa[1]); var x = parseInt(aa[0]); var w = parseInt(s.width); var h = parseInt(inputHeight); var ft = parseInt(s.fontSize); if(f!=0) { y=y*f; x=x*f; w=w*f; h=h*f; ft=ft*f; } var jsonData = {"fontSize":parseInt(ft),"fontColor":"#000","placeholderText":placeTxt,"secureTextEntry":"0","backgroundColor":"#FFFFFF","randomLetterKeyboard":"1","randomDigitalKeyboard":"0","defaultKeyboard":"0","isSystemKeyboard":"0","isTextRight":"0"}; uexRandomKeyboard.onGetContent = onGetContent; uexRandomKeyboard.open(parseInt(x),parseInt(y),parseInt(w),parseInt(h),JSON.stringify(jsonData)); } function onGetContent(a,b,c){ var j = eval("("+ c +")"); //返回json数据 if(j.type == "passWord") { password = rem_bla(j.text); }else if(j.type == "name") { if(j.text != "") { accoValid = false; } $("#lognumber").val(rem_bla(j.text)); } if(j.complete=="0") { login(); } } function hidelogNumber(logNumber){ if(logNumber.length >8){ var start=logNumber.substr(0,4); var end=logNumber.substr(-4,4); var str = start; for(var i =0;i<logNumber.length -8;i++){ str += "*"; } return str+end; }else{ var start=logNumber.substr(0,2); var end=logNumber.substr(-2,2); var str = start; for(var i =0;i<logNumber.length -8;i++){ str += "*"; } return str+end; } } function setInvaid() { accoValid = false; } var cardFlag = false; function isOldUser(lognumber){ var oldUser=getLocVal("oldUser")?(JSON.parse(getLocVal("oldUser"))):[]; for(var i=0;i<oldUser.length;i++){ if(oldUser[i]==lognumber){ return true; } } oldUser.push(lognumber); setLocVal("oldUser",JSON.stringify(oldUser)); return false; } function createActionSheet(){ uexWindow.actionSheet("请选择证件类型","取消","身份证,军官证,士兵证,户口本,警官,昵称"); } function cbActionSheet(opId, dataType, data){ if(data==0){ certificatetype=0; logtype='2'; }else if(data==1){ certificatetype=2; logtype='2'; }else if(data==2){ certificatetype=3; logtype='2'; }else if(data==3){ certificatetype=5; logtype='2'; }else if(data==4){ certificatetype=9; logtype='2'; }else if(data==5){ certificatetype=7; logtype='N'; }else{ return ; } $("#selcerType").text(cerList[data]); } function getCerType(certype){ var scerType =''; if(certype=='0'){ scerType='身份证'; }else if(certype=='2'){ scerType='军官证'; }else if(certype=='3'){ scerType='士兵证'; }else if(certype=='5'){ scerType='户口本'; }else if(certype=='9'){ scerType='警官'; }else if(certype=='7'){ scerType='昵称'; } return scerType; } appcan.button("#login", "ani-act", function() {//按钮效果 login(); }); appcan.button("#fgtPwd", "ani-act", function() {//按钮效果 if(isAndroid){ setTimeout('winClose()',500); } openNewWin('find_pwd','account/find_pwd.html') }); appcan.button("#register", "ani-act", function() {//按钮效果 if(isAndroid){ openNewWin('openAccount','account/openAccount.html'); setTimeout('winClose()',500); }else if(isIPhone){ var s=window.getComputedStyle(document.body,null); uexWindow.openPopover("openAccount_content","0","account/openAccount_content.html","",0,$('#header').offset().height,parseInt(s.width),$('#content').offset().height,parseInt(s.fontSize),"0"); //uescript("index","openAcco()"); //winClose(); }else if(isIPad){ uescript("index","openAcco()"); setTimeout("winClose()",500); } }); appcan.button(".nav-btn", "btn-act", function() { appcan.window.close(-1); }); appcan.button("#nav-right", "btn-act", function() { openNewWin('more','account/more.html',10); }); </script> </html>
LiguofuIOS/pluginCase
测试widget/widget_uexSina/widget/login.html
HTML
gpl-3.0
20,855
// Copyright 2009-2014 Josh Close and Contributors // This file is a part of CsvHelper and is licensed under the MS-PL // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html // http://csvhelper.com using System; using System.IO; using CsvHelper.Configuration; #if WINRT_4_5 using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace CsvHelper.Tests { [TestClass] public class CsvParserConstructorTests { [TestMethod] public void EnsureInternalsAreSetupWhenPassingReaderAndConfigTest() { using( var stream = new MemoryStream() ) using( var reader = new StreamReader( stream ) ) { var config = new CsvConfiguration(); using( var parser = new CsvParser( reader, config ) ) { Assert.AreSame( config, parser.Configuration ); } } } } }
worldexplorer/SquareOne
CsvHelper261-master/src/CsvHelper.Tests/CsvParserConstructorTests.cs
C#
gpl-3.0
920
#ifndef HEALTHBAR_H #define HEALTHBAR_H #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <GLFW/glfw3.h> #include "Player.h" class Player; class HealthBar : public GameObject { public: HealthBar(Player * o); virtual void update(); virtual void render(GLuint shaderID, glm::mat4 MVP, Camera camera, Lights lights, glm::mat4 shadowMVP); private: Player* origin = 0; }; #endif /* HEALTHBAR_H */
Mimoja/HookWars
HealthBar.h
C
gpl-3.0
460
/* * example_fdtd_2dte_lence.cpp * * Created on: Nov 2, 2016 * Author: Dr. Yevgeniy Kolokoltsev */ #include <iostream> #include <cmath> #include <algorithm> #include <memory> #include "../../lib_fdtd/advanced/example_fdtd_2nd_mur.hpp" #include "../../lib_fdtd/diplay/em_field_intensity_display.hpp" using namespace std; class ExDifInt : public ExFDTD2ndTEMur { public: using tBase = ExFDTD2ndTEMur; using tCell = tBase::tCell; using tSourceBase = typename tBase::tSourceBase; using tInit = tBase::tInit; ExDifInt(tInit ti) : tBase(ti){ double lda = 20*dl; // = Vg*T = 2pi/w double Vg = 1; double w = 2*M_PI*Vg/(lda); sources.clear(); sources.resize(Ny); int Cy1 = Ny/2.0 + Ny/8.0; int Cy2 = Ny/2.0 - Ny/8.0; for(int j = 0; j < Ny; j++){ for(int i = 0; i < Nx; i++){ if(i >= Nx/5 && i <= (Nx/5+1)){ if(!((j >= Cy1-2 && j <= Cy1+2) || (j >= Cy2-2 && j <= Cy2+2)) && (j >= 3 && j <=Ny-3)) field[i][j].c.eps = 100; } } double mag = GaussianMag(lda,0, 2*dl, j*dl, 2*dl, dl*Ny/2, lda); sources[j] = shared_ptr<tSourceBase>((tSourceBase*)new SinSource<Plain2DIndex>(w,mag)); sources[j]->i = 2; sources[j]->j = j; } }; private: tContainer &field = tBase::container; vector<shared_ptr<tSourceBase>> &sources = tBase::sources; }; int main(int argc, char **argv){ shared_ptr<ExDifInt> field(new ExDifInt(ExDifInt::tInit{400,200})); Window w(unique_ptr<LogEnergyDensityDisplay<ExDifInt>>(new LogEnergyDensityDisplay<ExDifInt>(field))); w.create_window(600,300); while(1){ if(!w.is_running()) break; field->evaluate(); } std::cout << "exit" << std::endl; return 0; }
YKolokoltsev/CompPhysFWK
src/examples/fdtd/diafragm.cpp
C++
gpl-3.0
1,657
<?php include("inc/database.php"); ?> <!DOCTYPE html> <html> <head> <title>PRO Rank Tracker</title> <link rel="stylesheet" type="text/css" href="css/track.css"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/graphs.js"></script> <script type="text/javascript" src="js/graphcat.js"></script> <script type="text/javascript"> $(function() { var rank = [ <?php function array_s($arr, $keyword) { foreach($arr as $index => $string) { if (strpos($string, $keyword) !== FALSE) return $index; } } function do_getdata($database, $nickname, $cat) { $stmt = $database->prepare("SELECT `rdata` FROM `track_new` WHERE `rtype` = '$cat' AND `nickname` = '$nickname'"); $stmt->execute(); if($stmt->rowCount() < 1){ return -1; } else{ $rank = $stmt->fetch(PDO::FETCH_OBJ); return $rank->rdata; } } if(!isset($_GET['u']) && !isset($_GET['c'])){ die(""); } else{ $rank_raw = do_getdata($bd, $_GET['u'], $_GET['c']); if($rank_raw == -1){ die(""); } else{ $rank_pt1 = explode("!", $rank_raw); date_default_timezone_set('UTC'); $rank_dte = date("j/n/y"); $rank_dte = date("j/n/y"); $rank_pos = array_s($rank_pt1, $rank_dte); $rank_pt2 = explode("|", $rank_pt1[$rank_pos]); $rank_pt3 = explode("#", $rank_pt2[1]); foreach($rank_pt3 as $rank_hdt){ $rank_pt4 = explode("-", $rank_hdt); echo '["'.$rank_pt4[0].'", '.$rank_pt4[1].'],'; } } } ?> ]; $.plot("#rankholder", [ rank ], { xaxis: { mode: "categories" }, grid: { hoverable: true }, yaxis: { tickDecimals: 0, min: 1, max: 25, ticks: 10, transform: function (v) { return -v; }, inverseTransform: function (v) { return -v; } } } ); }); </script> </head> <body> <?php if($_GET['c'] > 2){ date_default_timezone_set('UTC'); echo ' <span class="font12">'.$_GET['u'].' Rank data</span><br> <span class="font22">'.date("F, d").' - PRO Servertime</span><br><br> <div id="rankholder"></div> '; } else{ date_default_timezone_set('UTC'); echo ' <span class="font1">'.$_GET['u'].' Rank data</span><br> <span class="font2">'.date("F, d").' - PRO Servertime</span><br><br> <div id="rankholder"></div> '; } ?> </body> </html>
XTWebdesign/PRORanking
track.php
PHP
gpl-3.0
2,706
package de.upb.reconos.grasp.gui.menus; import java.awt.event.ActionEvent; import de.upb.reconos.grasp.objects.StateMachineNode; import de.upb.reconos.grasp.objects.World; public class StateMachineMenu extends BasicMenu { private static final long serialVersionUID = 1L; private StateMachineNode node; public StateMachineMenu(World w){ super(w); addItem("New State"); addItem("New Signal"); addItem("New Port"); addSeparator(); addItem("Remove This State Machine"); addSeparator(); addItem("Options"); } public void setStateMachineNode(StateMachineNode n){ node = n; } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand().toLowerCase(); double wx = worldPosition.getX(); double wy = worldPosition.getY(); if(cmd.equals("new state")){ world.createStateNode(node, wx,wy); } if(cmd.equals("new signal")){ world.createSignalNode(node, wx,wy); } if(cmd.equals("new port")){ world.createPortNode(node, wx,wy); } if(cmd.equals("remove this state machine")){ world.dissolve(node); node = null; } } }
luebbers/reconos
attic/tools/java/grasp/de/upb/reconos/grasp/gui/menus/StateMachineMenu.java
Java
gpl-3.0
1,096
from Collisions.Collidable import Collidable from Collisions.TypeBasedCollision import TypeBasedCollision from Drawing.Drawable import Drawable from Drawing.DrawPlatform import DrawPlatform from Movement.Movable import Movable, Movable2D from Movement.State import State2D from Utility.Entity import Entity ################################################################################ ################################################################################ class Platform(Entity, Movable, Drawable, Collidable): ############################################################################## def __init__(self, Window, xPosition, yPosition, TileType, Length = 1): Entity.__init__(self) InitialState = \ State2D(xPosition, yPosition, Width = Length * 64, Height = 64) Movable.__init__(self, Movable2D(InitialState)) DrawFunctor = \ DrawPlatform(Window, "Images/platformPack/PNG/Tiles/" + TileType, Length) Drawable.__init__(self, DrawFunctor, InitialState) Collidable.__init__(self, TypeBasedCollision(), InitialState) ################################################################################ ################################################################################
dloman/FiestaMonsterz
Entities/Platform.py
Python
gpl-3.0
1,236
/*********************************************************** * Programming Assignment 3 * * Distance program * * Programmer: Mark Eatough * * Course: CS1410 * * Created February 28, 2012 * * Modified March 6, 2012 * * Modified by Mark Eatough * ***********************************************************/ import java.util.Scanner; public class Trapezoid extends Quadrilateral { Scanner input = new Scanner(System.in); public double side1; public double side2; public double side3; public double side4; public double height; double area; public Trapezoid() //default constructor { } public Trapezoid(double s1, double s2, double s3, double s4, double h) //parameterized constructor { side1 = s1; side2 = s2; side3 = s3; side4 = s4; height = h; } public void buildTrapezoid() //Need Trig HERE!!! { System.out.printf("Enter length of larger base "); side1 = input.nextDouble(); System.out.printf("enter length of smaller base "); side3 = input.nextDouble(); System.out.printf("enter length of right side "); side2 = input.nextDouble(); System.out.printf("enter length of left side "); side4 = input.nextDouble(); System.out.printf("enter height less than or equal to shorter of the 2 sides "); height = input.nextDouble(); } public void trapezoidPoints() { point2X = side1; point3X = side1 - Math.sqrt(side2*side2 - height*height); point3Y = height; point4X = Math.sqrt(side4*side4 - height*height); point4Y = height; System.out.printf("\n\nThe four points of Trapezoid are: (%.1f, %.1f) (%.1f, %.1f) (%.1f, %.1f) (%.1f, %.1f)\n\n\n", point1X, point1Y, point2X, point2Y,point3X, point3Y, point4X, point4Y); } public void trapezoidArea() { area = (0.5)*(side1 + side3)*height; System.out.printf("Area = %.2f", area); } }
meatough/Marks-Programs
cs 1410/Assignment 3/Trapezoid.java
Java
gpl-3.0
1,914
#include <ros/ros.h> #include <std_msgs/String.h> #include <stdio.h> #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Vector3Stamped.h" #include <mavros_msgs/SetMode.h> #include <mavros_msgs/State.h> #include <apriltags/AprilTagDetections.h> #include <mavros_msgs/CommandBool.h> geometry_msgs::PoseStamped CurrentPoseStamped; void AprilMessageReceived(const apriltags::AprilTagDetections& detectionsMsg); void AprilMessageReceived(const apriltags::AprilTagDetections& detectionsMsg) { CurrentPoseStamped.header = detectionsMsg.header; CurrentPoseStamped.pose.position.x = -detectionsMsg.detections[0].pose.position.x; CurrentPoseStamped.pose.position.y = detectionsMsg.detections[0].pose.position.y; CurrentPoseStamped.pose.position.z = detectionsMsg.detections[0].pose.position.z; CurrentPoseStamped.pose.orientation.x = detectionsMsg.detections[0].pose.orientation.w; CurrentPoseStamped.pose.orientation.y = -detectionsMsg.detections[0].pose.orientation.z; CurrentPoseStamped.pose.orientation.z = detectionsMsg.detections[0].pose.orientation.y; CurrentPoseStamped.pose.orientation.w = detectionsMsg.detections[0].pose.orientation.x; } int main(int argc, char **argv) { ros::init(argc, argv, "hover"); ros::NodeHandle n; ros::NodeHandle n_apriltags; ros::Publisher chatter_pub = n.advertise<geometry_msgs::PoseStamped>("/mavros/setpoint_position/local",100); ros::Publisher current_pub = n.advertise<geometry_msgs::PoseStamped>("/mavros/mocap/pose",100); ros::Subscriber sub_apriltags = n_apriltags.subscribe("/apriltags/detections", 1000, &AprilMessageReceived); ros::ServiceClient set_mode_client = n.serviceClient<mavros_msgs::SetMode>("mavros/set_mode"); ros::Rate loop_rate(100); ros::spinOnce(); geometry_msgs::PoseStamped msg; int count = 1; while(ros::ok()){ msg.header.stamp = ros::Time::now(); msg.header.seq=count; msg.header.frame_id = 1; msg.pose.position.x = 0.0; msg.pose.position.y = 0.0; msg.pose.position.z = 1.0; msg.pose.orientation.x = 0; msg.pose.orientation.y = 0; msg.pose.orientation.z = 0; msg.pose.orientation.w = 1; if(count == 100) { mavros_msgs::SetMode offb_set_mode; offb_set_mode.request.custom_mode = "OFFBOARD"; ROS_INFO("OFFBOARD mode set"); mavros_msgs::CommandBool arm_cmd; arm_cmd.request.value = true; } chatter_pub.publish(msg); current_pub.publish(CurrentPoseStamped); ros::spinOnce(); count++; loop_rate.sleep(); } return 0; }
chickonice/AutonomousFlight
px4_new_ws/src/px4_nav/src/hover.cpp
C++
gpl-3.0
2,676
Function Rename-DbaLogin { <# .SYNOPSIS Rename-DbaLogin will rename login and database mapping for a specified login. .DESCRIPTION There are times where you might want to rename a login that was copied down, or if the name is not descriptive for what it does. It can be a pain to update all of the mappings for a spefic user, this does it for you. .PARAMETER SqlInstance Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater. .PARAMETER Destination Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater. .PARAMETER SqlCredential Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use: $scred = Get-Credential, then pass $scred object to the -SourceSqlCredential parameter. Windows Authentication will be used if DestinationSqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials. To connect as a different Windows user, run PowerShell as that user. .PARAMETER Login The current Login on the server .PARAMETER NewLogin The new Login that you wish to use. If it is a windows user login, then the SID must match. .PARAMETER Confirm Prompts to confirm actions .PARAMETER WhatIf Shows what would happen if the command were to run. No actions are actually performed. .NOTES Original Author: Mitchell Hamann (@SirCaptainMitch) dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com) Copyright (C) 2016 Chrissy LeMaire 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/>. .LINK https://dbatools.io/Rename-DbaLogin .EXAMPLE Rename-DbaLogin -SqlInstance localhost -Login DbaToolsUser -NewLogin captain SQL Login Example .EXAMPLE Rename-DbaLogin -SqlInstance localhost -Login domain\oldname -NewLogin domain\newname Change the windowsuser login name. .EXAMPLE Rename-DbaLogin -SqlInstance localhost -Login dbatoolsuser -NewLogin captain -WhatIf WhatIf Example #> [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true)] param ( [parameter(Mandatory = $true)] [object]$SqlInstance, [System.Management.Automation.PSCredential]$SqlCredential, [parameter(Mandatory = $true)] [String]$NewLogin ) DynamicParam { if ($SqlInstance) { return Get-ParamSqlLogin -SqlServer $SqlInstance -SqlCredential $SqlCredential } } BEGIN { $Login = $psboundparameters.Login if (!$Login) { throw "You must specify a login" } $server = Connect-SqlServer -SqlServer $SqlInstance -SqlCredential $SqlCredential $Databases = $server.Databases $currentLogin = $server.Logins[$Login] } PROCESS { if ($Pscmdlet.ShouldProcess($SqlInstance, "Changing Login name from [$Login] to [$NewLogin]")) { try { $dbenums = $currentLogin.EnumDatabaseMappings() $currentLogin.rename($NewLogin) [pscustomobject]@{ SqlInstance = $server.name Database = "N/A" OldLogin = $Login NewLogin = $NewLogin Notes = "Successfully renamed login" } } catch { $dbenums = $null [pscustomobject]@{ SqlInstance = $server.name Database = $null OldLogin = $Login NewLogin = $NewLogin Notes = "Failure to rename login" } Write-Exception $_ continue } } foreach ($db in $dbenums) { $db = $databases[$db.DBName] $user = $db.Users[$Login] Write-Verbose "Starting update for $db" if ($Pscmdlet.ShouldProcess($SqlInstance, "Changing database $db user $user from [$Login] to [$NewLogin]")) { try { $oldname = $user.name $user.Rename($NewLogin) [pscustomobject]@{ SqlInstance = $server.name Database = $db.name OldUser = $oldname NewUser = $NewLogin Notes = "Successfully renamed database user" } } catch { Write-Warning "Rolling back update to login: $Login" $currentLogin.rename($Login) [pscustomobject]@{ SqlInstance = $server.name Database = $db.name OldUser = $NewLogin NewUser = $oldname Notes = "Failure to rename. Rolled back change." } Write-Exception $_ break } } } } }
abbgrade/dbatools
functions/Rename-DbaLogin.ps1
PowerShell
gpl-3.0
4,793
#pragma once #include "stdafx.h" #include "MUAC.h" #include "Constants.h" #include "Colours.h" #include "MenuBar.h" #include "FontManager.h" #include <EuroScopePlugIn.h> #include <string> #include <vector> #include <map> #include <algorithm> using namespace std; using namespace EuroScopePlugIn; class CMTCDWindow { private: private: POINT TopLeftPosition; CSize WindowSize; bool Display = true; bool Released = true; string lengthString = "AAA0000 AAA0000 00 00 00.0 00.0 ^"; int PaddingSides = 3; int PaddingTops = 5; public: CMTCDWindow(POINT TopLeft) { TopLeftPosition = TopLeft; }; void Move(CRect Area, bool isReleased) { Released = isReleased; TopLeftPosition = { Area.left, Area.top }; }; POINT GetTopLeftPosition() { return TopLeftPosition; }; CRect Render(CDC* dc, CRadarScreen* instance, POINT mousePt, CMTCD* mtcd, multimap<string, string> veraTools, bool display) { Display = display; if (!Display) return {0, 0, 0, 0}; int saveDc = dc->SaveDC(); FontManager::SelectStandardFont(dc); // We need to count how many we show in the vera list int veraLn = 0; map<pair<string, string>, VERA::VERADataStruct> veraPrecalcData; for (auto &kv : veraTools) { if (mtcd->IsPairInMtcd(kv.first, kv.second)) continue; CRadarTarget FirstTarget = instance->GetPlugIn()->RadarTargetSelect(kv.first.c_str()); CRadarTarget SecondTarget = instance->GetPlugIn()->RadarTargetSelect(kv.second.c_str()); VERA::VERADataStruct vera = VERA::Calculate(FirstTarget, SecondTarget); if (vera.minDistanceSeconds == -1) continue; veraPrecalcData.insert(std::pair<pair<string, string>, VERA::VERADataStruct>(kv, vera)); veraLn++; } // Always at least one line for topbar int lineNumbers = veraLn + mtcd->Alerts.size() + 1; // We need to calculate the size of the menu CSize TextSize = dc->GetTextExtent(lengthString.c_str()); WindowSize.cx = TextSize.cx + PaddingSides * 2; WindowSize.cy = TextSize.cy * lineNumbers + PaddingTops * 2; int LineHeight = (int)TextSize.cy + PaddingTops; // Whole window CRect Window(TopLeftPosition.x, TopLeftPosition.y, TopLeftPosition.x + WindowSize.cx, TopLeftPosition.y + WindowSize.cy); if (Released) dc->FillSolidRect(Window, Colours::MenuButtonBottom.ToCOLORREF()); // Black outline CRect WinOutline = Window; WinOutline.InflateRect(1, 1); WinOutline.NormalizeRect(); CPen BlackPen(PS_SOLID, 1, RGB(0, 0, 0)); CPen GreyPen(PS_SOLID, 1, Colours::AircraftLightGrey.ToCOLORREF()); if (IsInRect(mousePt, Window) || !Released) dc->SelectObject(&GreyPen); else dc->SelectObject(&BlackPen); dc->SelectStockObject(NULL_BRUSH); dc->Rectangle(WinOutline); instance->AddScreenObject(MTCD_WINDOW, "", Window, true, ""); if (!Released) return Window; // Topbar CRect TopBar(TopLeftPosition.x, TopLeftPosition.y, TopLeftPosition.x + WindowSize.cx, TopLeftPosition.y + LineHeight); dc->FillSolidRect(TopBar, Colours::DarkBlueMenu.ToCOLORREF()); dc->SetTextColor(Colours::GreyTextMenu.ToCOLORREF()); // // Topbar text // dc->SetTextAlign(TA_LEFT | TA_BASELINE); dc->TextOutA(TopLeftPosition.x + 3, TopBar.bottom - PaddingSides, " MTCD VERA"); // Close button, first one for size, second one for render dc->SetTextAlign(TA_LEFT | TA_TOP); int LeftButtonOffset = TopBar.right - dc->GetTextExtent("X").cx * 2 - 3; CRect ButtonRect = MenuBar::DrawMenuBarButton(dc, { LeftButtonOffset, TopLeftPosition.y }, "X", mousePt, false); instance->AddScreenObject(MTCD_WINDOW_BUTTONS, "CLOSE", ButtonRect, false, "Close MTCD Window"); dc->SetTextColor(Colours::AircraftBlue.ToCOLORREF()); // MTCD List first int TopOffset = TopBar.bottom + 2; for (auto &mtcdAlert : mtcd->Alerts) { string veraString = " DIV"; if (mtcdAlert.vera.minDistanceSeconds != -1) { string veraTime = padWithZeros(2, (int)(mtcdAlert.vera.minDistanceSeconds / 60)) + "." + to_string(mtcdAlert.vera.minDistanceSeconds % 60).substr(0, 1); string veraDistance = to_string(mtcdAlert.vera.minDistanceNm); size_t decimal_pos = veraDistance.find("."); veraDistance = veraDistance.substr(0, decimal_pos + 2); if (mtcdAlert.vera.minDistanceNm < 10) veraDistance = "0" + veraDistance; veraString = veraTime + " " + veraDistance; } string line = mtcdAlert.sourceCallsign + " " + mtcdAlert.conflictCallsign + " " + padWithZeros(2, mtcdAlert.minDistanceMin) + " " + padWithZeros(2, mtcdAlert.minDistanceNm) + " " + veraString; CSize extent = dc->GetTextExtent(line.c_str()); dc->TextOutA(TopBar.left + 3, TopOffset, line.c_str()); TopOffset += extent.cy; } CPen WhitePen(PS_SOLID, 1, Colours::AircraftLightGrey.ToCOLORREF()); dc->SelectObject(&WhitePen); dc->MoveTo(TopBar.left + 2, TopOffset); dc->LineTo(TopBar.right - 2, TopOffset); // VERA List for (auto &kv : veraTools) { if (mtcd->IsPairInMtcd(kv.first, kv.second)) continue; VERA::VERADataStruct vera = veraPrecalcData[kv]; if (vera.minDistanceSeconds == -1) continue; string veraTime = padWithZeros(2, (int)(vera.minDistanceSeconds / 60)) + "." + to_string(vera.minDistanceSeconds % 60).substr(0, 1); string veraDistance = to_string(vera.minDistanceNm); size_t decimal_pos = veraDistance.find("."); veraDistance = veraDistance.substr(0, decimal_pos + 2); if (vera.minDistanceNm < 10) veraDistance = "0" + veraDistance; string line = kv.first + " " + kv.second + " 00 00 " + veraTime + " " + veraDistance; CSize extent = dc->GetTextExtent(string(line + " ").c_str()); dc->TextOutA(TopBar.left + 3, TopOffset, line.c_str()); // Push to mtcd button CSize singleExtent = dc->GetTextExtent("^"); dc->TextOutA(TopBar.left + 3 + extent.cx, TopOffset, "^"); CRect pushRect = { TopBar.left + 3 + extent.cx, TopOffset, TopBar.left + 3 + extent.cx + singleExtent.cx, TopOffset + singleExtent.cy }; CPen YellowPen(PS_SOLID, 1, Colours::YellowHighlight.ToCOLORREF()); if (IsInRect(mousePt, pushRect)) { dc->SelectStockObject(NULL_BRUSH); dc->SelectObject(&YellowPen); dc->Rectangle(pushRect); } TopOffset += extent.cy; } dc->RestoreDC(saveDc); return Window; }; };
pierr3/UACPlugin
MUAC/MTCDWindow.h
C
gpl-3.0
6,283
/* * Copyright (C) 2017 Oasis Feng. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.condom; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.content.Context; import android.content.ContextWrapper; import android.os.Handler; import android.os.Looper; import android.os.Process; import android.support.test.InstrumentationRegistry; import android.telephony.TelephonyManager; import com.oasisfeng.condom.kit.NullDeviceIdKit; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.READ_PHONE_STATE; import static android.Manifest.permission.WRITE_SECURE_SETTINGS; import static android.Manifest.permission.WRITE_SETTINGS; import static android.content.pm.PackageManager.PERMISSION_DENIED; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.M; import static android.os.Build.VERSION_CODES.O; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Test cases for {@link CondomKit} * * Created by Oasis on 2017/7/22. */ public class CondomKitTest { @Test public void testBasicKit() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { final ActivityManager am = createActivityManager(context); final CondomOptions option = new CondomOptions().addKit(new CondomKit() { @Override public void onRegister(final CondomKitRegistry registry) { registry.registerSystemService(Context.ACTIVITY_SERVICE, new SystemServiceSupplier() { @Override public Object getSystemService(final Context context, final String name) { return am; }}); registry.addPermissionSpoof(WRITE_SETTINGS); registry.addPermissionSpoof(ACCESS_COARSE_LOCATION); }}); final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "KitTest", option); assertEquals(am, condom.getSystemService(Context.ACTIVITY_SERVICE)); assertEquals(am, condom.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)); Assert.assertNotNull(condom.getSystemService(Context.NOTIFICATION_SERVICE)); // Service not registered in kit assertPermission(condom, WRITE_SETTINGS, true); assertPermission(condom.getApplicationContext(), WRITE_SETTINGS, true); assertPermission(condom, ACCESS_COARSE_LOCATION, true); assertPermission(condom.getApplicationContext(), ACCESS_COARSE_LOCATION, true); assertPermission(condom, WRITE_SECURE_SETTINGS, false); // Permission not registered to spoof in kit assertPermission(condom.getApplicationContext(), WRITE_SECURE_SETTINGS, false); } @Test @SuppressLint("HardwareIds") public void testNullDeviceIdKit() { final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "NullDeviceId", new CondomOptions().addKit(new NullDeviceIdKit())); final TelephonyManager tm = (TelephonyManager) condom.getSystemService(Context.TELEPHONY_SERVICE); assertTrue(condom.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE).getClass().getName().startsWith(NullDeviceIdKit.class.getName())); assertPermission(condom, READ_PHONE_STATE, true); assertNull(tm.getDeviceId()); if (SDK_INT >= M) assertNull(tm.getDeviceId(0)); assertNull(tm.getImei()); assertNull(tm.getImei(0)); if (SDK_INT >= O) assertNull(tm.getMeid()); if (SDK_INT >= O) assertNull(tm.getMeid(0)); assertNull(tm.getSimSerialNumber()); assertNull(tm.getLine1Number()); assertNull(tm.getSubscriberId()); } private static void assertPermission(final Context context, final String permission, final boolean granted) { final int state = granted ? PERMISSION_GRANTED : PERMISSION_DENIED; assertEquals(state, context.checkPermission(permission, Process.myPid(), Process.myUid())); if (SDK_INT >= M) assertEquals(state, context.checkSelfPermission(permission)); } private static ActivityManager createActivityManager(final Context context) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { final Constructor<ActivityManager> am_constructor = ActivityManager.class.getDeclaredConstructor(Context.class, Handler.class); am_constructor.setAccessible(true); return am_constructor.newInstance(context, new Handler(Looper.getMainLooper())); } private final Context context = InstrumentationRegistry.getTargetContext(); }
Trumeet/MiPushFramework
condom/src/androidTest/java/com/oasisfeng/condom/CondomKitTest.java
Java
gpl-3.0
5,252
<?php /** --------------------------------------------------------------------- * app/lib/Plugins/Media/Audio.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2006-2020 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage Media * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ /** * Plugin for processing audio media using ffmpeg */ include_once(__CA_LIB_DIR__."/Plugins/Media/BaseMediaPlugin.php"); include_once(__CA_LIB_DIR__."/Plugins/IWLPlugMedia.php"); include_once(__CA_LIB_DIR__."/Configuration.php"); include_once(__CA_APP_DIR__."/helpers/mediaPluginHelpers.php"); include_once(__CA_APP_DIR__."/helpers/avHelpers.php"); include_once(__CA_APP_DIR__."/helpers/utilityHelpers.php"); include_once(__CA_LIB_DIR__."/Parsers/OggParser.php"); class WLPlugMediaAudio Extends BaseMediaPlugin Implements IWLPlugMedia { var $errors = array(); var $filepath; var $handle; var $ohandle; var $properties; var $oproperties; var $metadata = array(); var $input_bitrate; var $input_channels; var $input_sample_frequency; var $opo_config; var $ops_path_to_ffmpeg; var $ops_mediainfo_path; var $info = array( "IMPORT" => array( "audio/mpeg" => "mp3", "audio/x-aiff" => "aiff", "audio/wav" => "wav", "audio/x-wav" => "wav", "audio/x-wave" => "wav", "audio/mp4" => "aac", "audio/ogg" => "ogg", "audio/x-flac" => "flac" ), "EXPORT" => array( "audio/mpeg" => "mp3", "audio/x-aiff" => "aiff", "audio/wav" => "wav", "audio/x-wav" => "wav", "audio/x-wave" => "wav", "audio/mp4" => "aac", "video/x-flv" => "flv", "image/png" => "png", "image/jpeg" => "jpg", "audio/ogg" => "ogg", "audio/x-flac" => "flac" ), "TRANSFORMATIONS" => array( "SET" => array("property", "value"), "SCALE" => array("width", "height", "mode", "antialiasing"), "ANNOTATE" => array("text", "font", "size", "color", "position", "inset"), // dummy "WATERMARK" => array("image", "width", "height", "position", "opacity"), // dummy "INTRO" => array("filepath"), "OUTRO" => array("filepath") ), "PROPERTIES" => array( "width" => 'W', "height" => 'W', "version_width" => 'R', // width version icon should be output at (set by transform()) "version_height" => 'R', // height version icon should be output at (set by transform()) "intro_filepath" => 'R', "outro_filepath" => 'R', "mimetype" => 'R', "typename" => 'R', "bandwidth" => 'R', "title" => 'R', "author" => 'R', "copyright" => 'R', "description" => 'R', "duration" => 'R', "filesize" => 'R', "getID3_tags" => 'W', 'colorspace' => 'W', "quality" => "W", // required for JPEG compatibility "bitrate" => 'W', // in kbps (ex. 64) "channels" => 'W', // 1 or 2, typically "sample_frequency" => 'W', // in khz (ex. 44100) "version" => 'W' // required of all plug-ins ), "NAME" => "Audio", "NO_CONVERSION" => 0 ); var $typenames = array( "audio/mpeg" => "MPEG-3", "audio/x-aiff" => "AIFF", "audio/x-wav" => "WAV", "audio/x-wave" => "WAV", "audio/wav" => "WAV", "audio/mp4" => "AAC", "image/png" => "PNG", "image/jpeg" => "JPEG", "audio/ogg" => "Ogg Vorbis", "audio/x-flac" => "FLAC" ); # # Alternative extensions for supported types # var $alternative_extensions = [ 'aif' => 'audio/x-aiff', 'wave' => "audio/x-wave" ]; # ------------------------------------------------ public function __construct() { $this->description = _t('Provides audio processing and conversion using ffmpeg'); } # ------------------------------------------------ # Tell WebLib what kinds of media this plug-in supports # for import and export public function register() { $this->opo_config = Configuration::load(); $this->ops_path_to_ffmpeg = caMediaPluginFFmpegInstalled(); $this->ops_mediainfo_path = caMediaInfoInstalled(); $this->info["INSTANCE"] = $this; return $this->info; } # ------------------------------------------------ public function checkStatus() { $va_status = parent::checkStatus(); $this->register(); $va_status['available'] = true; if (!$this->ops_path_to_ffmpeg) { $va_status['errors'][] = _t("Incoming audio files will not be transcoded because ffmpeg is not installed."); } if ($this->ops_mediainfo_path) { $va_status['notices'][] = _t("MediaInfo will be used to extract metadata from audio files."); } return $va_status; } # ------------------------------------------------ public function divineFileFormat($filepath) { $ID3 = new getID3(); $info = $ID3->analyze($filepath); if (($info['fileformat'] == 'riff') && (!isset($info['video']))) { if (isset($info['audio']['dataformat']) && ($info['audio']['dataformat'] == 'wav')) { $info['mime_type'] = 'audio/x-wav'; } } if ( ($info['fileformat'] == 'quicktime') && ($info['audio']['codec'] == 'Fraunhofer MPEG Layer-III alias') && ($info['video']['resolution_x'] == 0) && ($info['video']['resolution_y'] == 0) ) { // Quicktime-wrapped MP3 $info['mime_type'] = 'audio/mpeg'; } if (in_array(strtolower(trim($info["mime_type"])), ['audio/wave', 'audio/wav', 'audio/x-wave'], true)) { $info["mime_type"] = 'audio/x-wav'; } if (($info["mime_type"]) && isset($this->info["IMPORT"][$info["mime_type"]]) && $this->info["IMPORT"][$info["mime_type"]]) { $this->handle = $this->ohandle = $info; $this->metadata = $info; // populate with getID3 data because it's handy return $info["mime_type"]; } else { // is it Ogg? $info = new OggParser($filepath); if (!$info->LastError && is_array($info->Streams) && (sizeof($info->Streams) > 0)) { if (!isset($info->Streams['theora'])) { $this->handle = $this->ohandle = $info->Streams; return $this->handle['mime_type'] = 'audio/ogg'; } } # file format is not supported by this plug-in return ""; } } # ---------------------------------------------------------- public function get($property) { if ($this->handle) { if ($this->info["PROPERTIES"][$property]) { return $this->properties[$property]; } else { print "Invalid property '$property'"; return ""; } } else { return ""; } } # ---------------------------------------------------------- public function set($property, $value) { if ($this->handle) { if ($this->info["PROPERTIES"][$property]) { switch($property) { default: if ($this->info["PROPERTIES"][$property] == 'W') { $this->properties[$property] = $value; } else { # read only return ""; } break; } } else { # invalid property $this->postError(1650, _t("Can't set property %1", $property), "WLPlugAudio->set()"); return ""; } } else { return ""; } } # ------------------------------------------------ /** * Returns array of extracted metadata, key'ed by metadata type or empty array if plugin doesn't support metadata extraction * * @return Array Extracted metadata */ public function getExtractedMetadata() { return $this->metadata; } # ------------------------------------------------ public function read ($filepath, $mimetype="", $options=null) { if (!file_exists($filepath)) { $this->postError(1650, _t("File %1 does not exist", $filepath), "WLPlugAudio->read()"); $this->handle = ""; $this->filepath = ""; return false; } if (!(($this->handle) && ($this->handle["filepath"] == $filepath))) { $ID3 = new getid3(); $info = $ID3->analyze($filepath); if ($info["mime_type"] === 'audio/x-wave') { $info["mime_type"] = 'audio/x-wav'; } if ( ($info['fileformat'] == 'quicktime') && ($info['audio']['codec'] == 'Fraunhofer MPEG Layer-III alias') && ($info['video']['resolution_x'] == 0) && ($info['video']['resolution_y'] == 0) ) { // Quicktime-wrapped MP3 $info['mime_type'] = 'audio/mpeg'; } $this->handle = $this->ohandle = $info; if($this->ops_mediainfo_path){ $this->metadata = caExtractMetadataWithMediaInfo($filepath); } else { $this->metadata = $this->handle; } if (!$this->handle['mime_type']) { // is it Ogg? $info = new OggParser($filepath); if (!$info->LastError) { if (!isset($info->Streams['theora'])) { $this->handle = $this->ohandle = $info->Streams; $this->handle['mime_type'] = 'audio/ogg'; $this->handle['playtime_seconds'] = $this->handle['duration']; } } } } if (!((isset($this->handle["error"])) && (is_array($this->handle["error"])) && (sizeof($this->handle["error"]) > 0))) { $this->filepath = $filepath; //$this->properties = $this->handle; $this->properties = []; $this->properties["mimetype"] = $this->handle["mime_type"]; $this->properties["typename"] = $this->typenames[$this->properties["mimetype"]] ? $this->typenames[$this->properties["mimetype"]] : "Unknown"; $this->properties["duration"] = $this->handle["playtime_seconds"]; $this->properties["filesize"] = filesize($filepath); switch($this->properties["mimetype"]) { case 'audio/mpeg': if (is_array($this->handle["tags"]["id3v1"]["title"])) { $this->properties["title"] = join("; ",$this->handle["tags"]["id3v1"]["title"]); } if (is_array($this->handle["tags"]["id3v1"]["artist"])) { $this->properties["author"] = join("; ",$this->handle["tags"]["id3v1"]["artist"]); } if (is_array($this->handle["tags"]["id3v1"]["comment"])) { $this->properties["copyright"] = join("; ",$this->handle["tags"]["id3v1"]["comment"]); } if ( (is_array($this->handle["tags"]["id3v1"]["album"])) && (is_array($this->handle["tags"]["id3v1"]["year"])) && (is_array($this->handle["tags"]["id3v1"]["genre"]))) { $this->properties["description"] = join("; ",$this->handle["tags"]["id3v1"]["album"])." ".join("; ",$this->handle["tags"]["id3v1"]["year"])." ".join("; ",$this->handle["tags"]["id3v1"]["genre"]); } $this->properties["type_specific"] = array("audio" => $this->handle["audio"], "tags" => $this->handle["tags"]); $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = $this->handle["tags"]; $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-aiff': $this->properties["type_specific"] = array("audio" => $this->handle["audio"], "riff" => $this->handle["riff"]); $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-flac': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/x-wav': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/mp4': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle["audio"]; $this->properties["bandwidth"] = array("min" => $this->handle["bitrate"], "max" => $this->handle["bitrate"]); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle["bitrate"]; $this->properties["channels"] = $input_channels = $this->handle["audio"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["audio"]["sample_rate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; case 'audio/ogg': $this->properties["type_specific"] = array(); $this->properties["audio"] = $this->handle['vorbis']; $this->properties["bandwidth"] = array("min" => $this->handle['vorbis']['bitrate'], "max" => $this->handle['vorbis']['bitrate']); $this->properties["getID3_tags"] = array(); $this->properties["bitrate"] = $input_bitrate = $this->handle['vorbis']['bitrate']; $this->properties["channels"] = $input_channels = $this->handle["vorbis"]["channels"]; $this->properties["sample_frequency"] = $input_sample_frequency = $this->handle["vorbis"]["samplerate"]; $this->properties["duration"] = $this->handle["playtime_seconds"]; break; } $this->oproperties = $this->properties; return 1; } else { $this->postError(1650, join("; ", $this->handle["error"]), "WLPlugAudio->read()"); $this->handle = ""; $this->filepath = ""; return false; } } # ---------------------------------------------------------- public function transform($operation, $parameters) { if (!$this->handle) { return false; } if (!($this->info["TRANSFORMATIONS"][$operation])) { # invalid transformation $this->postError(1655, _t("Invalid transformation %1", $operation), "WLPlugAudio->transform()"); return false; } # get parameters for this operation $sparams = $this->info["TRANSFORMATIONS"][$operation]; $this->properties["version_width"] = $w = $parameters["width"]; $this->properties["version_height"] = $h = $parameters["height"]; if (!$parameters["width"]) { $this->properties["version_width"] = $w = $parameters["height"]; } if (!$parameters["height"]) { $this->properties["version_height"] = $h = $parameters["width"]; } $cw = $this->get("width"); $ch = $this->get("height"); if (!$cw) { $cw = $w; } if (!$ch) { $ch = $h; } switch($operation) { # ----------------------- case "SET": while(list($k, $v) = each($parameters)) { $this->set($k, $v); } break; # ----------------------- case 'SCALE': switch($parameters["mode"]) { # ---------------- case "width": $scale_factor = $w/$cw; $h = $ch * $scale_factor; break; # ---------------- case "height": $scale_factor = $h/$ch; $w = $cw * $scale_factor; break; # ---------------- case "bounding_box": $scale_factor_w = $w/$cw; $scale_factor_h = $h/$ch; $w = $cw * (($scale_factor_w < $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $h = $ch * (($scale_factor_w < $scale_factor_h) ? $scale_factor_w : $scale_factor_h); break; # ---------------- case "fill_box": $scale_factor_w = $w/$cw; $scale_factor_h = $h/$ch; $w = $cw * (($scale_factor_w > $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $h = $ch * (($scale_factor_w > $scale_factor_h) ? $scale_factor_w : $scale_factor_h); $do_crop = 1; break; # ---------------- } $w = round($w); $h = round($h); if (!($w > 0 && $h > 0)) { $this->postError(1610, _t("Width or height was zero"), "WLPlugAudio->transform()"); return false; } if ($do_crop) { $this->properties["width"] = $parameters["width"]; $this->properties["height"] = $parameters["height"]; } else { $this->properties["width"] = $w; $this->properties["height"] = $h; } break; # ----------------------- case 'INTRO': $this->properties["intro_filepath"] = $parameters["filepath"]; break; # ----------------------- case 'OUTRO': $this->properties["outro_filepath"] = $parameters["filepath"]; break; # ----------------------- } return 1; } # ---------------------------------------------------------- public function write($filepath, $mimetype, $pa_options=null) { if (!$this->handle) { return false; } if (!($ext = $this->info["EXPORT"][$mimetype])) { # this plugin can't write this mimetype $this->postError(1610, _t("Can't convert '%1' to '%2': unsupported format", $this->handle["mime_type"], $mimetype), "WLPlugAudio->write()"); return false; } $o_config = Configuration::load(); $va_tags = $this->get("getID3_tags"); $vs_intro_filepath = $this->get("intro_filepath"); $vs_outro_filepath = $this->get("outro_filepath"); if (($vn_output_bitrate = $this->get("bitrate"))< 32) { $vn_output_bitrate = 64; } if (($vn_sample_frequency = $this->get("sample_frequency")) < 4096) { $vn_sample_frequency = 44100; } if (($vn_channels = $this->get("channels")) < 1) { $vn_channels = 1; } if ( ($this->properties["mimetype"] == $mimetype) && (!(($this->properties["mimetype"] == "audio/mpeg") && ($vs_intro_filepath || $vs_outro_filepath))) && (($vn_output_bitrate == $this->input_bitrate) && ($vn_sample_frequency == $this->input_sample_frequency) && ($vn_channels == $this->input_channels)) ) { # write the file if ( !copy($this->filepath, $filepath.".".$ext) ) { $this->postError(1610, _t("Couldn't write file to '%1'", $filepath), "WLPlugAudio->write()"); return false; } } else { if (($mimetype != "image/png") && ($mimetype != "image/jpeg") && ($this->ops_path_to_ffmpeg)) { # # Do conversion # if ($mimetype == 'audio/ogg') { caExec($this->ops_path_to_ffmpeg." -f ".$this->info["IMPORT"][$this->properties["mimetype"]]." -i ".caEscapeShellArg($this->filepath)." -acodec libvorbis -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($filepath.".".$ext).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); } else { caExec($this->ops_path_to_ffmpeg." -f ".$this->info["IMPORT"][$this->properties["mimetype"]]." -i ".caEscapeShellArg($this->filepath)." -f ".$this->info["EXPORT"][$mimetype]." -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($filepath.".".$ext).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); } if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting file to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } if ($mimetype == "audio/mpeg") { if ($vs_intro_filepath || $vs_outro_filepath) { // add intro $vs_tmp_filename = tempnam(caGetTempDirPath(), "audio"); if ($vs_intro_filepath) { caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($vs_intro_filepath)." -f mp3 -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($vs_tmp_filename).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting intro to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } } $r_fp = fopen($vs_tmp_filename, "a"); $r_mp3fp = fopen($filepath.".".$ext, "r"); while (!feof($r_mp3fp)) { fwrite($r_fp, fread($r_mp3fp, 8192)); } fclose($r_mp3fp); if ($vs_outro_filepath) { $vs_tmp_outro_filename = tempnam(caGetTempDirPath(), "audio"); caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($vs_outro_filepath)." -f mp3 -ab ".$vn_output_bitrate." -ar ".$vn_sample_frequency." -ac ".$vn_channels." -y ".caEscapeShellArg($vs_tmp_outro_filename).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($filepath.".".$ext); $this->postError(1610, _t("Error converting outro to %1 [%2]: %3", $this->typenames[$mimetype], $mimetype, join("; ", $va_output)), "WLPlugAudio->write()"); return false; } $r_mp3fp = fopen($vs_tmp_outro_filename, "r"); while (!feof($r_mp3fp)) { fwrite($r_fp, fread($r_mp3fp, 8192)); } unlink($vs_tmp_outro_filename); } fclose($r_fp); copy($vs_tmp_filename, $filepath.".".$ext); unlink($vs_tmp_filename); } $o_getid3 = new getid3(); $va_mp3_output_info = $o_getid3->analyze($filepath.".".$ext); $this->properties = array(); if (is_array($va_mp3_output_info["tags"]["id3v1"]["title"])) { $this->properties["title"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["title"]); } if (is_array($va_mp3_output_info["tags"]["id3v1"]["artist"])) { $this->properties["author"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["artist"]); } if (is_array($va_mp3_output_info["tags"]["id3v1"]["comment"])) { $this->properties["copyright"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["comment"]); } if ( (is_array($va_mp3_output_info["tags"]["id3v1"]["album"])) && (is_array($va_mp3_output_info["tags"]["id3v1"]["year"])) && (is_array($va_mp3_output_info["tags"]["id3v1"]["genre"]))) { $this->properties["description"] = join("; ",$va_mp3_output_info["tags"]["id3v1"]["album"])." ".join("; ",$va_mp3_output_info["tags"]["id3v1"]["year"])." ".join("; ",$va_mp3_output_info["tags"]["id3v1"]["genre"]); } $this->properties["type_specific"] = array("audio" => $va_mp3_output_info["audio"], "tags" => $va_mp3_output_info["tags"]); $this->properties["bandwidth"] = array("min" => $va_mp3_output_info["bitrate"], "max" => $va_mp3_output_info["bitrate"]); $this->properties["bitrate"] = $va_mp3_output_info["bitrate"]; $this->properties["channels"] = $va_mp3_output_info["audio"]["channels"]; $this->properties["sample_frequency"] = $va_mp3_output_info["audio"]["sample_rate"]; $this->properties["duration"] = $va_mp3_output_info["playtime_seconds"]; } } else { # use default media icons if ffmpeg is not present or the current version is an image if(!$this->get("width") && !$this->get("height")){ $this->set("width",580); $this->set("height",200); } return __CA_MEDIA_AUDIO_DEFAULT_ICON__; } } if ($mimetype == "audio/mpeg") { // try to write getID3 tags (if set) if (is_array($pa_options) && is_array($pa_options) && sizeof($pa_options) > 0) { $o_tagwriter = new getid3_writetags(); $o_tagwriter->filename = $filepath.".".$ext; $o_tagwriter->tagformats = array('id3v2.3'); $o_tagwriter->tag_data = $pa_options; // write them tags if (!@$o_tagwriter->WriteTags()) { // failed to write tags } } } $this->properties["mimetype"] = $mimetype; $this->properties["typename"] = $this->typenames[$mimetype]; return $filepath.".".$ext; } # ------------------------------------------------ /** * */ # This method must be implemented for plug-ins that can output preview frames for videos or pages for documents public function &writePreviews($ps_filepath, $pa_options) { return null; } # ------------------------------------------------ /** * */ public function writeClip($ps_filepath, $ps_start, $ps_end, $pa_options=null) { $o_tc = new TimecodeParser(); $vn_start = $vn_end = 0; if ($o_tc->parse($ps_start)) { $vn_start = (float)$o_tc->getSeconds(); } if ($o_tc->parse($ps_end)) { $vn_end = (float)$o_tc->getSeconds(); } if ($vn_end == 0) { return null; } if ($vn_start >= $vn_end) { return null; } $vn_duration = $vn_end - $vn_start; caExec($this->ops_path_to_ffmpeg." -i ".caEscapeShellArg($this->filepath)." -f mp3 -t {$vn_duration} -y -ss {$vn_start} ".caEscapeShellArg($ps_filepath).(caIsPOSIX() ? " 2>&1" : ""), $va_output, $vn_return); if ($vn_return != 0) { @unlink($ps_filepath); $this->postError(1610, _t("Error extracting clip from %1 to %2: %3", $ps_start, $ps_end, join("; ", $va_output)), "WLPlugAudio->writeClip()"); return false; } return true; } # ------------------------------------------------ public function getOutputFormats() { return $this->info["EXPORT"]; } # ------------------------------------------------ public function getTransformations() { return $this->info["TRANSFORMATIONS"]; } # ------------------------------------------------ public function getProperties() { return $this->info["PROPERTIES"]; } # ------------------------------------------------ public function mimetype2extension($mimetype) { return $this->info["EXPORT"][$mimetype]; } # ------------------------------------------------ public function extension2mimetype($extension) { reset($this->info["EXPORT"]); while(list($k, $v) = each($this->info["EXPORT"])) { if ($v === $extension) { return $k; } } return ""; } # ------------------------------------------------ public function mimetype2typename($mimetype) { return $this->typenames[$mimetype]; } # ------------------------------------------------ public function reset() { $this->errors = array(); $this->properties = $this->oproperties; return $this->handle = $this->ohandle; } # ------------------------------------------------ public function init() { $this->errors = array(); $this->filepath = ""; $this->handle = ""; $this->properties = ""; $this->metadata = array(); } # ------------------------------------------------ public function htmlTag($ps_url, $pa_properties, $pa_options=null, $pa_volume_info=null) { if (!is_array($pa_options)) { $pa_options = array(); } foreach(array( 'name', 'show_controls', 'url', 'text_only', 'viewer_width', 'viewer_height', 'id', 'data_url', 'poster_frame_url', 'viewer_parameters', 'viewer_base_url', 'width', 'height', 'vspace', 'hspace', 'alt', 'title', 'usemap', 'align', 'border', 'class', 'style', 'duration', 'pages' ) as $vs_k) { if (!isset($pa_options[$vs_k])) { $pa_options[$vs_k] = null; } } switch($pa_properties["mimetype"]) { # ------------------------------------------------ case 'audio/ogg': $vs_id = $pa_options["id"] ? $pa_options["id"] : "mp4_player"; $vs_poster_frame_url = $pa_options["poster_frame_url"]; $vn_width = $pa_options["viewer_width"] ? $pa_options["viewer_width"] : $pa_properties["width"]; $vn_height = $pa_options["viewer_height"] ? $pa_options["viewer_height"] : $pa_properties["height"]; if (!$vn_width) { $vn_width = 300; } if (!$vn_height) { $vn_height = 32; } return "<div style='width: {$vn_width}px; height: {$vn_height}px;'><audio id='{$vs_id}' src='{$ps_url}' width='{$vn_width}' height='{$vn_height}' controls='1'></audio></div>"; break; # ------------------------------------------------ case 'audio/mpeg': $viewer_base_url = $pa_options["viewer_base_url"]; $vs_id = $pa_options["id"] ? $pa_options["id"] : "mp3player"; AssetLoadManager::register("mediaelement"); $vn_width = ($pa_options["viewer_width"] > 0) ? $pa_options["viewer_width"] : 400; $vn_height = ($pa_options["viewer_height"] > 0) ? $pa_options["viewer_height"] : 95; ob_start(); ?> <div class="<?php print (isset($pa_options["class"]) ? $pa_options["class"] : "caAudioPlayer"); ?>"> <audio id="<?php print $vs_id; ?>" src="<?php print $ps_url; ?>" <?php print ($vs_poster_url = caGetOption('posterURL', $pa_options, null) ? "poster='{$vs_poster_url}'" : ''); ?> type="audio/mp3" controls="controls"></audio> </div> <script type="text/javascript"> jQuery(document).ready(function() { var m = jQuery('#<?php print $vs_id; ?>').mediaelementplayer({ showTimecodeFrameCount: true, framesPerSecond: 100, audioWidth: '<?php print $vn_width; ?>', audioHeight: '<?php print $vn_height; ?>', success: function (mediaElement, domObject) { var m = mediaElement; m.addEventListener("play", function(e){ // Force poster image to remain visible during playback var $thisMediaElement = (mediaElement.id) ? jQuery("#"+mediaElement.id) : jQuery(mediaElement); $thisMediaElement.parents(".mejs-inner").find(".mejs-poster").show(); }); m.addEventListener("canplay", function(e){ var $thisMediaElement = (mediaElement.id) ? jQuery("#"+mediaElement.id) : jQuery(mediaElement); $thisMediaElement.parents(".mejs-inner").find(".mejs-poster").on('click', function() { caUI.mediaPlayerManager.isPlaying("<?php print $vs_id; ?>") ? caUI.mediaPlayerManager.stop("<?php print $vs_id; ?>") : caUI.mediaPlayerManager.play("<?php print $vs_id; ?>"); }); }); } }); if (caUI.mediaPlayerManager) { caUI.mediaPlayerManager.register("<?php print $vs_id; ?>", m, 'MediaElement'); } }); </script> <?php return ob_get_clean(); break; # ------------------------------------------------ case 'audio/mp4': case 'audio/x-aiff': case 'audio/x-flac': case 'audio/x-wav': $name = $pa_options["name"] ? $pa_options["name"] : "mp3player"; ob_start(); $vn_width = ($pa_options["viewer_width"] > 0) ? $pa_options["viewer_width"] : 400; $vn_height = ($pa_options["viewer_height"] > 0) ? $pa_options["viewer_height"] : 95; ?> <div style="width: {$vn_width}px; height: {$vn_height}px;"> <table> <tr> <td> <embed width="<?php print $pa_properties["width"]; ?>" height="<?php print $pa_properties["height"] + 16; ?>" src="<?php print $ps_url; ?>" type="audio/x-wav"> </td> </tr> </table> </div> <?php return ob_get_clean(); break; # ------------------------------------------------ case 'image/jpeg': case 'image/png': if (!is_array($pa_options)) { $pa_options = array(); } if (!is_array($pa_properties)) { $pa_properties = array(); } return caHTMLImage($ps_url, array_merge($pa_options, $pa_properties)); break; # ------------------------------------------------ } } # ------------------------------------------------ public function cleanup() { return; } # ------------------------------------------------ }
kehh/providence
app/lib/Plugins/Media/Audio.php
PHP
gpl-3.0
32,591
<?php /** * LiskPhp - A PHP wrapper for the LISK API * Copyright (c) 2017 Marcus Puchalla <cb0@0xcb0.com> * * LiskPhp 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. * * LiskPhp 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 LiskPhp. If not, see <http://www.gnu.org/licenses/>. */ namespace Lisk\Api\Apps; use Lisk\AbstractRequest; use Lisk\Cli\Parameters; class InstallAppRequest extends AbstractRequest { private $id; public function __construct($id) { parent::__construct(); $this->id = $id; } public function setEndpoint() { $this->endpoint = "/api/dapps/install"; } public function setType() { $this->type = self::POST; } public function getPayload() { return [ Parameters::ID => $this->id ]; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } }
cb0/LiskPHP
src/lib/Api/Apps/InstallAppRequest.php
PHP
gpl-3.0
1,505
<?php /* Plugin Name: Postie Plugin URI: http://PostiePlugin.com/ Description: Create posts via email. Signifigantly upgrades the Post by Email features of Word Press. Version: 1.7.32 Author: Wayne Allen Author URI: http://PostiePlugin.com/ License: GPL2 Text Domain: postie */ /* Copyright (c) 2015 Wayne Allen (email : wayne@allens-home.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* $Id: postie.php 1396811 2016-04-15 19:40:39Z WayneAllen $ */ require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "lib_autolink.php"); require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "postie-functions.php"); define('POSTIE_VERSION', '1.7.32'); define("POSTIE_ROOT", dirname(__FILE__)); define("POSTIE_URL", WP_PLUGIN_URL . '/' . basename(dirname(__FILE__))); //register the hooks early in the page in case some method needs the result of one of them (i.e. cron_schedules) add_action('init', 'postie_disable_kses_content', 20); add_action('check_postie_hook', 'check_postie'); add_action('parse_request', 'postie_parse_request'); add_action('admin_init', 'postie_admin_init'); add_action('admin_menu', 'postie_admin_menu'); add_action('admin_head', 'postie_admin_head'); add_filter('whitelist_options', 'postie_whitelist'); add_filter('cron_schedules', 'postie_more_reccurences'); add_filter('query_vars', 'postie_query_vars'); add_filter("plugin_action_links_" . plugin_basename(__FILE__), 'postie_plugin_action_links'); add_filter('plugin_row_meta', 'postie_plugin_row_meta', 10, 2); register_activation_hook(__FILE__, 'activate_postie'); register_activation_hook(__FILE__, 'postie_cron'); register_deactivation_hook(__FILE__, 'postie_decron'); if (isset($_GET["postie_read_me"])) { include_once(ABSPATH . "wp-admin/admin.php"); include(ABSPATH . 'wp-admin/admin-header.php'); postie_ShowReadMe(); include(ABSPATH . 'wp-admin/admin-footer.php'); } //Add Menu Configuration if (is_admin()) { if (function_exists('load_plugin_textdomain')) { function postie_load_domain() { $plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__)); load_plugin_textdomain('postie', false, dirname(plugin_basename(__FILE__)) . '/languages/'); } add_action('init', 'postie_load_domain'); } postie_warnings(); } //****************** functions ************************* function postie_admin_head() { ?> <style type="text/css"> #adminmenu #toplevel_page_postie-settings div.wp-menu-image:before { content: "\f466"; } </style> <?php } function postie_plugin_row_meta($links, $file) { if (strpos($file, plugin_basename(__FILE__)) !== false) { $new_links = array( '<a href="http://postieplugin.com/" target="_blank">Support</a>', '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HPK99BJ88V4C2" target="_blank">Donate</a>' ); $links = array_merge($links, $new_links); } return $links; } function postie_plugin_action_links($links) { $links[] = '<a href="admin.php?page=postie-settings">Settings</a>'; return $links; } function postie_query_vars($vars) { $vars[] = 'postie'; return $vars; } function postie_parse_request($wp) { if (array_key_exists('postie', $wp->query_vars)) { switch ($wp->query_vars['postie']) { case 'get-mail': postie_get_mail(); die(); case 'test-config': postie_test_config(); die(); default : dir('Unknown option: ' . $wp->query_vars['postie']); } } } function postie_admin_init() { wp_register_style('postie-style', plugins_url('css/style.css', __FILE__)); register_setting('postie-settings', 'postie-settings', 'config_ValidateSettings'); } function postie_admin_menu() { $page = add_menu_page('Postie', 'Postie', 'manage_options', 'postie-settings', 'postie_loadjs_options_page'); add_action('admin_print_styles-' . $page, 'postie_admin_styles'); } function postie_loadjs_options_page() { require_once POSTIE_ROOT . '/config_form.php'; } function postie_admin_page() { if (!current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.', 'postie')); } include 'config_form.php'; } function postie_admin_styles() { wp_enqueue_style('postie-style'); } /* * called by WP when activating the plugin * Note that you can't do any output during this funtion or activation * will fail on some systems. This means no DebugEcho, EchoInfo or DebugDump. */ function activate_postie() { static $init = false; $options = config_Read(); if ($init) { return; } if (!$options) { $options = array(); } $default_options = config_GetDefaults(); $old_config = array(); $result = config_GetOld(); if (is_array($result)) { foreach ($result as $key => $val) { $old_config[strtolower($key)] = $val; } } // overlay the options on top of each other: // the current value of $options takes priority over the $old_config, which takes priority over the $default_options $options = array_merge($default_options, $old_config, $options); $options = config_ValidateSettings($options); update_option('postie-settings', $options); $init = true; } /** * set up actions to show relevant warnings, * if mail server is not set, or if IMAP extension is not available */ function postie_warnings() { $config = config_Read(); if ((empty($config['mail_server']) || empty($config['mail_server_port']) || empty($config['mail_userid']) || empty($config['mail_password']) ) && !isset($_POST['submit'])) { function postie_enter_info() { echo "<div id='postie-info-warning' class='updated fade'><p><strong>" . __('Postie is almost ready.', 'postie') . "</strong> " . sprintf(__('You must <a href="%1$s">enter your email settings</a> for it to work.', 'postie'), "admin.php?page=postie-settings") . "</p></div> "; } add_action('admin_notices', 'postie_enter_info'); } $p = strtolower($config['input_protocol']); if (!function_exists('imap_mime_header_decode') && ($p == 'imap' || $p == 'imap-ssl' || $p == 'pop-ssl')) { function postie_imap_warning() { echo "<div id='postie-imap-warning' class='error'><p><strong>"; echo __('Warning: the IMAP php extension is not installed. Postie can not use IMAP, IMAP-SSL or POP-SSL without this extension.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_imap_warning'); } if ($p == 'pop3' && $config['email_tls']) { function postie_tls_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; echo __('Warning: The POP3 connector does not support TLS.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_tls_warning'); } if (isMarkdownInstalled() && $config['prefer_text_type'] == 'html') { function postie_markdown_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; _e("You currently have the Markdown plugin installed. It will cause problems if you send in HTML email. Please turn it off if you intend to send email using HTML.", 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_markdown_warning'); } if (!HasIconvInstalled()) { function postie_iconv_warning() { echo "<div id='postie-lst-warning' class='error'><p><strong>"; _e("Warning! Postie requires that iconv be enabled.", 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_iconv_warning'); } $userdata = WP_User::get_data_by('login', $config['admin_username']); if (!$userdata) { function postie_adminuser_warning() { echo "<div id='postie-mbstring-warning' class='error'><p><strong>"; echo __('Warning: the Admin username is not a valid WordPress login. Postie may reject emails if this is not corrected.', 'postie'); echo "</strong></p></div>"; } add_action('admin_notices', 'postie_adminuser_warning'); } } function postie_disable_kses_content() { remove_filter('content_save_pre', 'wp_filter_post_kses'); } function postie_whitelist($options) { $added = array('postie-settings' => array('postie-settings')); $options = add_option_whitelist($added, $options); return $options; } //don't use DebugEcho or EchoInfo here as it is not defined when called as an action function check_postie() { //error_log("check_postie"); postie_get_mail(); } function postie_cron($interval = false) { //Do not echo output in filters, it seems to break some installs //error_log("postie_cron: setting up cron task: $interval"); //$schedules = wp_get_schedules(); //error_log("postie_cron\n" . print_r($schedules, true)); if (!$interval) { $config = config_Read(); $interval = $config['interval']; //error_log("postie_cron: setting up cron task from config: $interval"); } if (!$interval || $interval == '') { $interval = 'hourly'; //error_log("Postie: setting up cron task: defaulting to hourly"); } if ($interval == 'manual') { postie_decron(); //error_log("postie_cron: clearing cron (manual)"); } else { if ($interval != wp_get_schedule('check_postie_hook')) { postie_decron(); //remove existing //try to create the new schedule with the first run in 5 minutes if (false === wp_schedule_event(time() + 5 * 60, $interval, 'check_postie_hook')) { //error_log("postie_cron: Failed to set up cron task: $interval"); } else { //error_log("postie_cron: Set up cron task: $interval"); } } else { //error_log("postie_cron: OK: $interval"); //don't need to do anything, cron already scheduled } } } function postie_decron() { //error_log("postie_decron: clearing cron"); wp_clear_scheduled_hook('check_postie_hook'); } /* here we add some more cron options for how often to check for email */ function postie_more_reccurences($schedules) { //Do not echo output in filters, it seems to break some installs //error_log("postie_more_reccurences: setting cron schedules"); $schedules['weekly'] = array('interval' => (60 * 60 * 24 * 7), 'display' => __('Once Weekly', 'postie')); $schedules['twiceperhour'] = array('interval' => 60 * 30, 'display' => __('Twice per hour', 'postie')); $schedules['tenminutes'] = array('interval' => 60 * 10, 'display' => __('Every 10 minutes', 'postie')); $schedules['fiveminutes'] = array('interval' => 60 * 5, 'display' => __('Every 5 minutes', 'postie')); $schedules['oneminute'] = array('interval' => 60 * 1, 'display' => __('Every 1 minute', 'postie')); $schedules['thirtyseconds'] = array('interval' => 30, 'display' => __('Every 30 seconds', 'postie')); $schedules['fifteenseconds'] = array('interval' => 15, 'display' => __('Every 15 seconds', 'postie')); return $schedules; }
palibaacsi/ask
wp-content/plugins/postie/postie.php
PHP
gpl-3.0
12,137
# Cicada The Cicada is a basic language interpreter which you can turn your basic files to fully working .exe file! Learning source code file added. # Featurs #### Some of features of cicada: * Interactive * Expression parsing * Smart Debug * SQL Language Support ### Expressions hierarchical graph function parser ![capture](https://cloud.githubusercontent.com/assets/19537065/22619885/524a4c94-eb13-11e6-88bb-d842e7bb0990.PNG)
MasterCna/Cicada
README.md
Markdown
gpl-3.0
431
// $Id: CbcHeuristicDINS.cpp 2094 2014-11-18 11:15:36Z forrest $ // Copyright (C) 2006, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). // edwin 12/5/09 carved out of CbcHeuristicRINS #if defined(_MSC_VER) // Turn off compiler warning about long names # pragma warning(disable:4786) #endif #include <cassert> #include <cstdlib> #include <cmath> #include <cfloat> #include "OsiSolverInterface.hpp" #include "CbcModel.hpp" #include "CbcMessage.hpp" #include "CbcHeuristicDINS.hpp" #include "CbcBranchActual.hpp" #include "CbcStrategy.hpp" #include "CglPreProcess.hpp" // Default Constructor CbcHeuristicDINS::CbcHeuristicDINS() : CbcHeuristic() { numberSolutions_ = 0; numberSuccesses_ = 0; numberTries_ = 0; howOften_ = 100; decayFactor_ = 0.5; maximumKeepSolutions_ = 5; numberKeptSolutions_ = 0; numberIntegers_ = -1; localSpace_ = 10; values_ = NULL; } // Constructor with model - assumed before cuts CbcHeuristicDINS::CbcHeuristicDINS(CbcModel & model) : CbcHeuristic(model) { numberSolutions_ = 0; numberSuccesses_ = 0; numberTries_ = 0; howOften_ = 100; decayFactor_ = 0.5; assert(model.solver()); maximumKeepSolutions_ = 5; numberKeptSolutions_ = 0; numberIntegers_ = -1; localSpace_ = 10; values_ = NULL; } // Destructor CbcHeuristicDINS::~CbcHeuristicDINS () { for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; } // Clone CbcHeuristic * CbcHeuristicDINS::clone() const { return new CbcHeuristicDINS(*this); } // Assignment operator CbcHeuristicDINS & CbcHeuristicDINS::operator=( const CbcHeuristicDINS & rhs) { if (this != &rhs) { CbcHeuristic::operator=(rhs); numberSolutions_ = rhs.numberSolutions_; howOften_ = rhs.howOften_; numberSuccesses_ = rhs.numberSuccesses_; numberTries_ = rhs.numberTries_; for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; maximumKeepSolutions_ = rhs.maximumKeepSolutions_; numberKeptSolutions_ = rhs.numberKeptSolutions_; numberIntegers_ = rhs.numberIntegers_; localSpace_ = rhs.localSpace_; if (model_ && rhs.values_) { assert (numberIntegers_ >= 0); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = CoinCopyOfArray(rhs.values_[i], numberIntegers_); } else { values_ = NULL; } } return *this; } // Create C++ lines to get to current state void CbcHeuristicDINS::generateCpp( FILE * fp) { CbcHeuristicDINS other; fprintf(fp, "0#include \"CbcHeuristicDINS.hpp\"\n"); fprintf(fp, "3 CbcHeuristicDINS heuristicDINS(*cbcModel);\n"); CbcHeuristic::generateCpp(fp, "heuristicDINS"); if (howOften_ != other.howOften_) fprintf(fp, "3 heuristicDINS.setHowOften(%d);\n", howOften_); else fprintf(fp, "4 heuristicDINS.setHowOften(%d);\n", howOften_); if (maximumKeepSolutions_ != other.maximumKeepSolutions_) fprintf(fp, "3 heuristicDINS.setMaximumKeep(%d);\n", maximumKeepSolutions_); else fprintf(fp, "4 heuristicDINS.setMaximumKeep(%d);\n", maximumKeepSolutions_); fprintf(fp, "3 cbcModel->addHeuristic(&heuristicDINS);\n"); } // Copy constructor CbcHeuristicDINS::CbcHeuristicDINS(const CbcHeuristicDINS & rhs) : CbcHeuristic(rhs), numberSolutions_(rhs.numberSolutions_), howOften_(rhs.howOften_), numberSuccesses_(rhs.numberSuccesses_), numberTries_(rhs.numberTries_), maximumKeepSolutions_(rhs.maximumKeepSolutions_), numberKeptSolutions_(rhs.numberKeptSolutions_), numberIntegers_(rhs.numberIntegers_), localSpace_(rhs.localSpace_) { if (model_ && rhs.values_) { assert (numberIntegers_ >= 0); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = CoinCopyOfArray(rhs.values_[i], numberIntegers_); } else { values_ = NULL; } } // Resets stuff if model changes void CbcHeuristicDINS::resetModel(CbcModel * ) { //CbcHeuristic::resetModel(model); for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; numberKeptSolutions_ = 0; numberIntegers_ = -1; numberSolutions_ = 0; values_ = NULL; } /* First tries setting a variable to better value. If feasible then tries setting others. If not feasible then tries swaps Returns 1 if solution, 0 if not */ int CbcHeuristicDINS::solution(double & solutionValue, double * betterSolution) { numCouldRun_++; int returnCode = 0; const double * bestSolution = model_->bestSolution(); if (!bestSolution) return 0; // No solution found yet #ifdef HEURISTIC_INFORM printf("Entering heuristic %s - nRuns %d numCould %d when %d\n", heuristicName(),numRuns_,numCouldRun_,when_); #endif if (numberSolutions_ < model_->getSolutionCount()) { // new solution - add info numberSolutions_ = model_->getSolutionCount(); int numberIntegers = model_->numberIntegers(); const int * integerVariable = model_->integerVariable(); if (numberIntegers_ < 0) { numberIntegers_ = numberIntegers; assert (!values_); values_ = new int * [maximumKeepSolutions_]; for (int i = 0; i < maximumKeepSolutions_; i++) values_[i] = NULL; } else { assert (numberIntegers >= numberIntegers_); } // move solutions (0 will be most recent) { int * temp = values_[maximumKeepSolutions_-1]; for (int i = maximumKeepSolutions_ - 1; i > 0; i--) values_[i] = values_[i-1]; if (!temp) temp = new int [numberIntegers_]; values_[0] = temp; } int i; for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; double value = bestSolution[iColumn]; double nearest = floor(value + 0.5); values_[0][i] = static_cast<int> (nearest); } numberKeptSolutions_ = CoinMin(numberKeptSolutions_ + 1, maximumKeepSolutions_); } int finalReturnCode = 0; if (((model_->getNodeCount() % howOften_) == howOften_ / 2 || !model_->getNodeCount()) && (model_->getCurrentPassNumber() <= 1 || model_->getCurrentPassNumber() == 999999)) { OsiSolverInterface * solver = model_->solver(); //int numberIntegers = model_->numberIntegers(); const int * integerVariable = model_->integerVariable(); const double * currentSolution = solver->getColSolution(); int localSpace = localSpace_; // 0 means finished but no solution, 1 solution, 2 node limit int status = -1; double cutoff = model_->getCutoff(); while (status) { status = 0; OsiSolverInterface * newSolver = cloneBut(3); // was model_->continuousSolver()->clone(); const double * colLower = solver->getColLower(); const double * colUpper = solver->getColUpper(); double primalTolerance; solver->getDblParam(OsiPrimalTolerance, primalTolerance); const double * continuousSolution = newSolver->getColSolution(); // Space for added constraint double * element = new double [numberIntegers_]; int * column = new int [numberIntegers_]; int i; int nFix = 0; int nCouldFix = 0; int nCouldFix2 = 0; int nBound = 0; int nEl = 0; double bias = localSpace; int okSame = numberKeptSolutions_ - 1; for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; const OsiObject * object = model_->object(i); // get original bounds double originalLower; double originalUpper; getIntegerInformation( object, originalLower, originalUpper); double valueInt = bestSolution[iColumn]; if (valueInt < originalLower) { valueInt = originalLower; } else if (valueInt > originalUpper) { valueInt = originalUpper; } int intValue = static_cast<int> (floor(valueInt + 0.5)); double currentValue = currentSolution[iColumn]; double currentLower = colLower[iColumn]; double currentUpper = colUpper[iColumn]; if (fabs(valueInt - currentValue) >= 0.5) { // Re-bound nBound++; if (intValue >= currentValue) { currentLower = CoinMax(currentLower, ceil(2 * currentValue - intValue)); currentUpper = intValue; } else { currentLower = intValue; currentUpper = CoinMin(currentUpper, floor(2 * currentValue - intValue)); } newSolver->setColLower(iColumn, currentLower); newSolver->setColUpper(iColumn, currentUpper); } else { // See if can fix bool canFix = false; double continuousValue = continuousSolution[iColumn]; if (fabs(currentValue - valueInt) < 10.0*primalTolerance) { if (currentUpper - currentLower > 1.0) { // General integer variable canFix = true; } else if (fabs(continuousValue - valueInt) < 10.0*primalTolerance) { int nSame = 1; //assert (intValue==values_[0][i]); for (int k = 1; k < numberKeptSolutions_; k++) { if (intValue == values_[k][i]) nSame++; } if (nSame >= okSame) { // can fix canFix = true; } else { nCouldFix++; } } else { nCouldFix2++; } } if (canFix) { newSolver->setColLower(iColumn, intValue); newSolver->setColUpper(iColumn, intValue); nFix++; } else { if (currentUpper - currentLower > 1.0) { // General integer variable currentLower = floor(currentValue); if (intValue >= currentLower && intValue <= currentLower + 1) { newSolver->setColLower(iColumn, currentLower); newSolver->setColUpper(iColumn, currentLower + 1.0); } else { // fix double value; if (intValue < currentLower) value = currentLower; else value = currentLower + 1; newSolver->setColLower(iColumn, value); newSolver->setColUpper(iColumn, value); nFix++; } } else { // 0-1 (ish) column[nEl] = iColumn; if (intValue == currentLower) { bias += currentLower; element[nEl++] = 1.0; } else if (intValue == currentUpper) { bias += currentUpper; element[nEl++] = -1.0; } else { printf("bad DINS logic\n"); abort(); } } } } } char generalPrint[200]; sprintf(generalPrint, "%d fixed, %d same as cont/int, %d same as int - %d bounded %d in cut\n", nFix, nCouldFix, nCouldFix2, nBound, nEl); model_->messageHandler()->message(CBC_FPUMP2, model_->messages()) << generalPrint << CoinMessageEol; if (nFix > numberIntegers_ / 10) { #ifdef JJF_ZERO newSolver->initialSolve(); printf("obj %g\n", newSolver->getObjValue()); for (i = 0; i < numberIntegers_; i++) { int iColumn = integerVariable[i]; printf("%d new bounds %g %g - solutions %g %g\n", iColumn, newSolver->getColLower()[iColumn], newSolver->getColUpper()[iColumn], bestSolution[iColumn], currentSolution[iColumn]); } #endif if (nEl > 0) newSolver->addRow(nEl, column, element, -COIN_DBL_MAX, bias); //printf("%d integers have same value\n",nFix); returnCode = smallBranchAndBound(newSolver, numberNodes_, betterSolution, solutionValue, cutoff, "CbcHeuristicDINS"); if (returnCode < 0) { returnCode = 0; // returned on size status = 0; } else { numRuns_++; if ((returnCode&2) != 0) { // could add cut as complete search returnCode &= ~2; if ((returnCode&1) != 0) { numberSuccesses_++; status = 1; } else { // no solution status = 0; } } else { if ((returnCode&1) != 0) { numberSuccesses_++; status = 1; } else { // no solution but node limit status = 2; if (nEl) localSpace -= 5; else localSpace = -1; if (localSpace < 0) status = 0; } } if ((returnCode&1) != 0) { cutoff = CoinMin(cutoff, solutionValue - model_->getCutoffIncrement()); finalReturnCode = 1; } } } delete [] element; delete [] column; delete newSolver; } numberTries_++; if ((numberTries_ % 10) == 0 && numberSuccesses_*3 < numberTries_) howOften_ += static_cast<int> (howOften_ * decayFactor_); } return finalReturnCode; } // update model void CbcHeuristicDINS::setModel(CbcModel * model) { model_ = model; // Get a copy of original matrix assert(model_->solver()); for (int i = 0; i < numberKeptSolutions_; i++) delete [] values_[i]; delete [] values_; numberKeptSolutions_ = 0; numberIntegers_ = -1; numberSolutions_ = 0; values_ = NULL; }
phines/acsimsep
ThirdParty/Coin-Bonmin/Cbc/src/CbcHeuristicDINS.cpp
C++
gpl-3.0
16,193
#!/usr/bin/perl -w ################################################### ## ## DnsExit.Com Dynamic IP update setup script ## v1.6 ## ################################################## use Http_get; use strict; my $cfile = '/etc/dnsexit.conf'; my $geturlfrom = 'http://www.dnsexit.com/ipupdate/dyndata.txt'; my $proxyservs = 'ip.dnsexit.com;ip2.dnsexit.com;ip3.dnsexit.com'; my $logfile = '/var/log/dnsexit.log'; my $cachefile = '/tmp/dnsexit-ip.txt'; my $pidfile = '/var/run/ipUpdate.pid'; my $URL_VALIDATE='http://www.dnsexit.com/ipupdate/account_validate.jsp'; my $URL_DOMAINS='http://www.dnsexit.com/ipupdate/domains.jsp'; my $URL_HOSTS='http://www.dnsexit.com/ipupdate/hosts.jsp'; my $MSG_WELCOME= "Wecome in DnsExit.Com Dynamic IP update setup script.\n". "Please follow instructions to setup our script.\n\n"; my $MSG_USERNAME="Please type username you have created on www.dnsexit.com (blank to leave setup):\n"; my $MSG_PASSWORD="Please type password for your username:\n"; my $MSG_CHECKING_USERPASS="Checking your username and password...\n"; my $MSG_CHECKING_DOMAINS="Checking your registered domains. This may take a while...\n\n"; my $MSG_USERPASSOK="Username and password correct...\n\n"; my $MSG_HOSTS="Please type password for your username:\n"; my $MSG_SELECT_DOMAINS="Please select your domains (if you want to select more than\n". "one domain, please separete them by space):\n"; my $MSG_SELECT_DOMAINS_AFTER="Your selection: "; my $MSG_FETCHING_HOSTS="Feching hosts in your domains. This may take a while...\n"; my $MSG_SELECT_HOSTS="Please select host you want to be updated (if you want to \n". "select more than one domain, please separete them by space):\n"; my $MSG_SELECT_HOSTS_AFTER="Your selection: "; my $MSG_YOU_HAVE_SELECTED="You have selected following hosts to be updated:\n"; my $MSG_SELECT_PROXY="If you want to use the IP address of your proxy server instead of the\n". "IP of the local host, set the value to \"yes\"\n"; my $MSG_PROXY_SEL="Your choice [no]: "; my $MSG_SELECT_DAEMON="Do you want to run it as a daemon?\n"; my $MSG_DAEMON_SEL="Your choice [yes]: "; my $MSG_SELECT_INTERVAL="How often (in minutes) should the program check IP change?\n". "It will only be posted to dnsExit.com when IP address is\n". "changed from the last update. It need to be at least 3 minutes.\n"; my $MSG_INTERVAL_SEL="Your choice [10]: "; my $MSG_INTERVAL_TOLOW="Interval too low. It need to be at least 3 minutes.\n"; my $MSG_SELECT_PIDFILE="Select path to pidfile.\n"; my $MSG_PIDFILE_SEL="Your choice [/var/run/ipUpdate.pid]: "; my $MSG_PIDFILE_BAD="You have selected invalid file name.\n"; my $MSG_GENERATING_CFG="Generating config file..."; my $MSG_DONE="Done creating config file. You can run the script now.\n". "To do it you can run ipUpdate.pl or use init script.\n\n". "File '$cachefile' will cache the ip address of\n". "the last successful IP update to our system. For next\n". "update, if the IP stays the same, the update request\n". "won't be sent to our server. You can simply change the\n". "IP at dnsexit-ip.txt file to force the update to DNSEXIT.\n\n"; my $MSG_PATHS="Here are paths to some intresting files:\n"; my $MSG_END="Don't forget to read README.txt file in doc directory!\n"; my $ERR_DOMAINS="Can't get list of your domains from the server"; my $ERR_NO_DOMAINS="You don't have any domain registered. You should login to your control panel ". "at www.dnsexit.com and register some domain.\n"; my $ERR_NO_DOMAINS_SELECTED="You have not selected any domains. Exiting...\n"; my $ERR_NO_HOSTS_SELECTED="You have not selected any hosts. Exiting...\n"; my $ERR_NO_URL="Can't fetach url info from dnsexit.com. Please try again later...\n"; my $get = new Http_get; print $MSG_WELCOME; # # Delete ald cache file # unlink $cachefile; # # Get url from dnsexit.com # my $url; $get->request($geturlfrom); if($get->is_success) { my $result = $get->content; if ( $result =~ /url=(.+)/ ) { $url=$1; if((my $chr=chop($url)) ne "\n"){ $url.=$chr; } } } if(!$url) { print $ERR_NO_URL; exit; } # # Get username/password and validate it. # my $userpassok=0; my $message=undef; my $username; my $password; do { if($message) { print "\nError: $message\n\n"; } # Get username print $MSG_USERNAME; $username=<STDIN>; chop $username; if($username eq "") { exit; }; # Get password print $MSG_PASSWORD; $password=<STDIN>; chop $password; print $MSG_CHECKING_USERPASS; # Check username/password $get->request($URL_VALIDATE."?login=$username&password=$password"); if($get->is_success) { my $result = $get->content; if ( $result =~ /(\d+)=(.+)/ ) { $userpassok=$1; $message=$2; if((my $chr=chop($message)) ne "\n"){ $message.=$chr; } } } } until($userpassok==0); print $MSG_USERPASSOK; # # Get list of domains and ask user which of them should be explored # my @domains; print $MSG_CHECKING_DOMAINS; $get->request($URL_DOMAINS."?login=$username&password=$password"); if($get->is_success) { my $result = $get->content; if ( $result =~ /(\d+)=(.+)/ ) { $message=$2; if((my $code=$1)==0) { @domains=split(/ +/, $message); } elsif($code==1) { print "\n$ERR_NO_DOMAINS\n\n"; exit; } else { print"\nError: $message\n\n"; exit; } } else { print "\n$ERR_DOMAINS\n\n"; exit; } } else { print "\n$ERR_DOMAINS\n\n"; exit; } print $MSG_SELECT_DOMAINS; my @hosts; my $i=0; my @domainno; foreach my $domain (@domains) { $domain =~ s/\s+//g; next if $domain eq ""; print $i." $domain\n"; $domainno[$i++]=$domain; } print $MSG_SELECT_DOMAINS_AFTER; # # Get list of hosts from selected domains and ask user which should be added # to the config file. # my $line=<STDIN>; my $check=$line; $check =~ s/\s+//g; if($check eq "") { print $ERR_NO_DOMAINS_SELECTED; exit; } my @tofilter=split(/ +/, $line); my @selected; foreach my $fil (@tofilter) { $fil =~ s/\s+//g; next if $fil eq ""; if($domainno[$fil]) { push @selected, $fil; } } if(!@selected) { print $ERR_NO_DOMAINS_SELECTED; exit; } print $MSG_FETCHING_HOSTS; foreach my $select (@selected) { my $domain=$domainno[$select]; $get->request($URL_HOSTS."?login=$username&password=$password&domain=$domain"); if($get->is_success) { my $result=$get->content; if ( $result =~ /(\d+)=(.+)/ ) { $message=$2; if((my $code=$1)==0) { my @myhosts=split(/\ /, $message); foreach my $host (@myhosts) { $host =~ s/\s+//g; push (@hosts,$host); } } } } } print $MSG_SELECT_HOSTS; $i=0; foreach my $host (@hosts) { print $i." $host\n"; $domainno[$i++]=$host; } print $MSG_SELECT_DOMAINS_AFTER; $line=<STDIN>; $check=$line; $check =~ s/\s+//g; if($check eq "") { print $ERR_NO_HOSTS_SELECTED; exit; } @tofilter=split(/ +/, $line); my @select; foreach my $fil (@tofilter) { $fil =~ s/\s+//g; next if $fil eq ""; if($domainno[$fil]) { push @select, $fil; } } if(!@select) { print $ERR_NO_HOSTS_SELECTED; exit; } my $hosts; print "\n".$MSG_YOU_HAVE_SELECTED; foreach my $sel (@select) { $sel =~ s/\s+//g; print "$domainno[$sel]\n"; $hosts.=$domainno[$sel]; $hosts.=';'; } print "\n"; chop $hosts; # # Ask user whants daemon mode. # print "\n"; print $MSG_SELECT_DAEMON; my $daemon=''; do { print $MSG_DAEMON_SEL; $daemon=<STDIN>; if($daemon eq "\n") { $daemon='yes'; } else { $daemon=lc($daemon); if((my $chr=chop($daemon)) ne "\n"){ $daemon.=$chr; } } } until $daemon eq 'yes' || $daemon eq 'no'; # # If deamon=YES then ask for an interval # my $interval; if($daemon eq 'yes') { print "\n"; print $MSG_SELECT_INTERVAL; do { print $MSG_INTERVAL_SEL; $interval=<STDIN>; if($interval eq "\n") { $interval='10'; } elsif (! ($interval =~ /^[0-9]+$/)) { $interval=undef; } elsif( $interval<3) { $interval=undef; print $MSG_INTERVAL_TOLOW; } else { if((my $chr=chop($interval)) ne "\n"){ $interval.=$chr; } } $interval*=60; } until $interval ; } else { $interval=''; } # # Generate config file # print "\n".$MSG_GENERATING_CFG; open (CFG, "> $cfile") || die "Fail open config file $cfile. Please check if have proper permissions."; print CFG "login=$username\n"; print CFG "password=$password\n"; print CFG "host=$hosts\n"; print CFG "daemon=$daemon\n"; print CFG "interval=$interval\n"; print CFG "proxyservs=$proxyservs\n"; print CFG "pidfile=$pidfile\n"; print CFG "logfile=$logfile\n"; print CFG "cachefile=$cachefile\n"; print CFG "url=$url\n"; close(CFG); print "\n".$MSG_DONE; print $MSG_PATHS; print "Pid file: $pidfile\n"; print "Log file: $logfile\n"; print "Cache file: $cachefile\n"; print "\n".$MSG_END;
meosch/dnsexit-virtualmin-dns-updater
usr/sbin/dnsexit-setup.pl
Perl
gpl-3.0
9,167
/* ============================== Written by id software, nightmare and hk of mdd This file is part of mdd client proxymod. mdd client proxymod 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. mdd client proxymod 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 mdd client proxymod. If not, see <http://www.gnu.org/licenses/>. ============================== Note: mdd client proxymod contains large quantities from the quake III arena source code */ #ifndef __CG_LOCAL_H__ #define __CG_LOCAL_H__ #ifdef WIN32 # include <Windows.h> # pragma warning( disable : 4996 ) # define QDECL __cdecl # ifdef linux # undef linux # endif # define __DLLEXPORT__ __declspec(dllexport) #else # include <string.h> # define QDECL # define __DLLEXPORT__ #endif # include <stdint.h> /* Mod stuff */ #define DEFAULT_MODDIR "baseq3" #define DEFAULT_VMPATH "vm/cgame.qvm" #define GAME "Q3A" //<mayor>.<compat>.<minor>.<build> #define VERSION "0.0.1.0" typedef int32_t (QDECL *syscall_t)(uint32_t, ...); typedef uint32_t (*pfn_t)(int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t, int32_t); typedef void (*Function)( void ); extern syscall_t g_syscall; // Quake3 Defines... typedef uint8_t byte; typedef enum {qfalse, qtrue} qboolean; //typedef int32_t fileHandle_t; // mode parm for FS_FOpenFile typedef enum { FS_READ, FS_WRITE, FS_APPEND, FS_APPEND_SYNC } fsMode_t; typedef enum { FS_SEEK_CUR, FS_SEEK_END, FS_SEEK_SET } fsOrigin_t; typedef enum { CG_PRINT, CG_ERROR, CG_MILLISECONDS, CG_CVAR_REGISTER, CG_CVAR_UPDATE, CG_CVAR_SET, CG_CVAR_VARIABLESTRINGBUFFER, CG_ARGC, CG_ARGV, CG_ARGS, CG_FS_FOPENFILE, CG_FS_READ, CG_FS_WRITE, CG_FS_FCLOSEFILE, CG_SENDCONSOLECOMMAND, CG_ADDCOMMAND, CG_SENDCLIENTCOMMAND, CG_UPDATESCREEN, CG_CM_LOADMAP, CG_CM_NUMINLINEMODELS, CG_CM_INLINEMODEL, CG_CM_LOADMODEL, CG_CM_TEMPBOXMODEL, CG_CM_POINTCONTENTS, CG_CM_TRANSFORMEDPOINTCONTENTS, CG_CM_BOXTRACE, CG_CM_TRANSFORMEDBOXTRACE, CG_CM_MARKFRAGMENTS, CG_S_STARTSOUND, CG_S_STARTLOCALSOUND, CG_S_CLEARLOOPINGSOUNDS, CG_S_ADDLOOPINGSOUND, CG_S_UPDATEENTITYPOSITION, CG_S_RESPATIALIZE, CG_S_REGISTERSOUND, CG_S_STARTBACKGROUNDTRACK, CG_R_LOADWORLDMAP, CG_R_REGISTERMODEL, CG_R_REGISTERSKIN, CG_R_REGISTERSHADER, CG_R_CLEARSCENE, CG_R_ADDREFENTITYTOSCENE, CG_R_ADDPOLYTOSCENE, CG_R_ADDLIGHTTOSCENE, CG_R_RENDERSCENE, CG_R_SETCOLOR, CG_R_DRAWSTRETCHPIC, CG_R_MODELBOUNDS, CG_R_LERPTAG, CG_GETGLCONFIG, CG_GETGAMESTATE, CG_GETCURRENTSNAPSHOTNUMBER, CG_GETSNAPSHOT, CG_GETSERVERCOMMAND, CG_GETCURRENTCMDNUMBER, CG_GETUSERCMD, CG_SETUSERCMDVALUE, CG_R_REGISTERSHADERNOMIP, CG_MEMORY_REMAINING, CG_R_REGISTERFONT, CG_KEY_ISDOWN, CG_KEY_GETCATCHER, CG_KEY_SETCATCHER, CG_KEY_GETKEY, CG_PC_ADD_GLOBAL_DEFINE, CG_PC_LOAD_SOURCE, CG_PC_FREE_SOURCE, CG_PC_READ_TOKEN, CG_PC_SOURCE_FILE_AND_LINE, CG_S_STOPBACKGROUNDTRACK, CG_REAL_TIME, CG_SNAPVECTOR, CG_REMOVECOMMAND, CG_R_LIGHTFORPOINT, CG_CIN_PLAYCINEMATIC, CG_CIN_STOPCINEMATIC, CG_CIN_RUNCINEMATIC, CG_CIN_DRAWCINEMATIC, CG_CIN_SETEXTENTS, CG_R_REMAP_SHADER, CG_S_ADDREALLOOPINGSOUND, CG_S_STOPLOOPINGSOUND, CG_CM_TEMPCAPSULEMODEL, CG_CM_CAPSULETRACE, CG_CM_TRANSFORMEDCAPSULETRACE, CG_R_ADDADDITIVELIGHTTOSCENE, CG_GET_ENTITY_TOKEN, CG_R_ADDPOLYSTOSCENE, CG_R_INPVS, // 1.32 CG_FS_SEEK, /* CG_LOADCAMERA, CG_STARTCAMERA, CG_GETCAMERAINFO, */ CG_MEMSET = 100, CG_MEMCPY, CG_STRNCPY, CG_SIN, CG_COS, CG_ATAN2, CG_SQRT, CG_FLOOR, CG_CEIL, CG_TESTPRINTINT, CG_TESTPRINTFLOAT, CG_ACOS } cgameImport_t; /* cg_utils.c */ char* vaf( char* format, ... ); /* cg_vm.c */ int32_t callVM( int32_t cmd, int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5, int32_t arg6, int32_t arg7, int32_t arg8, int32_t arg9, int32_t arg10, int32_t arg11 ); int32_t callVM_Destroy( void ); int32_t setVMPtr( int32_t arg0 ); int32_t initVM( void ); /* cg_modules */ int32_t loadModules( void ); typedef uint32_t qhandle_t; #define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString #define MAX_CONFIGSTRINGS 1024 #define MAX_GAMESTATE_CHARS 16000 #define BIG_INFO_STRING 8192 // used for system info key only typedef struct { int32_t stringOffsets[MAX_CONFIGSTRINGS]; char stringData[MAX_GAMESTATE_CHARS]; int32_t dataCount; } gameState_t; /* ** glconfig_t ** ** Contains variables specific to the OpenGL configuration ** being run right now. These are constant once the OpenGL ** subsystem is initialized. */ typedef enum { TC_NONE, TC_S3TC } textureCompression_t; typedef enum { GLDRV_ICD, // driver is integrated with window system // WARNING: there are tests that check for // > GLDRV_ICD for minidriverness, so this // should always be the lowest value in this // enum set GLDRV_STANDALONE, // driver is a non-3Dfx standalone driver GLDRV_VOODOO // driver is a 3Dfx standalone driver } glDriverType_t; typedef enum { GLHW_GENERIC, // where everthing works the way it should GLHW_3DFX_2D3D, // Voodoo Banshee or Voodoo3, relevant since if this is // the hardware type then there can NOT exist a secondary // display adapter GLHW_RIVA128, // where you can't interpolate alpha GLHW_RAGEPRO, // where you can't modulate alpha on alpha textures GLHW_PERMEDIA2 // where you don't have src*dst } glHardwareType_t; typedef struct { char renderer_string[MAX_STRING_CHARS]; char vendor_string[MAX_STRING_CHARS]; char version_string[MAX_STRING_CHARS]; char extensions_string[BIG_INFO_STRING]; int32_t maxTextureSize; // queried from GL int32_t maxActiveTextures; // multitexture ability int32_t colorBits, depthBits, stencilBits; glDriverType_t driverType; glHardwareType_t hardwareType; qboolean deviceSupportsGamma; textureCompression_t textureCompression; qboolean textureEnvAddAvailable; int32_t vidWidth, vidHeight; // aspect is the screen's physical width / height, which may be different // than scrWidth / scrHeight if the pixels are non-square // normal screens should be 4/3, but wide aspect monitors may be 16/9 float windowAspect; int32_t displayFrequency; // synonymous with "does rendering consume the entire screen?", therefore // a Voodoo or Voodoo2 will have this set to TRUE, as will a Win32 ICD that // used CDS. qboolean isFullscreen; qboolean stereoEnabled; qboolean smpActive; // dual processor } glconfig_t; typedef struct { /* GFX Handles */ qhandle_t gfxDeferSymbol; qhandle_t gfxWhiteShader; qhandle_t gfxCharsetShader; qhandle_t gfxCharsetProp; qhandle_t gfxCharsetPropGlow; qhandle_t gfxCharsetPropB; qhandle_t gfxLogo; /* Ammo hud */ qhandle_t gfxAmmo[16]; } cgMedia_t; typedef struct { /* from cgs_t */ gameState_t gameState; // gamestate from server glconfig_t glconfig; // rendering configuration int32_t clientNum; float screenXScale; // derived from glconfig float screenYScale; int32_t levelStartTime; float screenXBias; /* from cg */ int32_t time; cgMedia_t media; } cgs_t; extern cgs_t cgs; const char *CG_ConfigString( int32_t index ); #define PROP_GAP_WIDTH 3 #define PROP_SPACE_WIDTH 8 #define PROP_HEIGHT 27 #define PROP_SMALL_SIZE_SCALE 0.75 #define BLINK_DIVISOR 200 #define PULSE_DIVISOR 75 #define UI_LEFT 0x00000000 // default #define UI_CENTER 0x00000001 #define UI_RIGHT 0x00000002 #define UI_FORMATMASK 0x00000007 #define UI_SMALLFONT 0x00000010 #define UI_BIGFONT 0x00000020 // default #define UI_GIANTFONT 0x00000040 #define UI_DROPSHADOW 0x00000800 #define UI_BLINK 0x00001000 #define UI_INVERSE 0x00002000 #define UI_PULSE 0x00004000 typedef float vec_t; typedef vec_t vec2_t[2]; typedef vec_t vec3_t[3]; typedef vec_t vec4_t[4]; typedef vec_t vec5_t[5]; typedef int32_t fixed4_t; typedef int32_t fixed8_t; typedef int32_t fixed16_t; typedef int32_t sfxHandle_t; typedef int32_t fileHandle_t; typedef int32_t clipHandle_t; #ifndef M_PI #define M_PI 3.14159265358979323846f // matches value in gcc v2 math.h #endif // markfragments are returned by CM_MarkFragments() typedef struct { int32_t firstPoint; int32_t numPoints; } markFragment_t; #define MAX_QPATH 64 // max length of a quake game pathname #define GLYPH_START 0 #define GLYPH_END 255 #define GLYPH_CHARSTART 32 #define GLYPH_CHAREND 127 #define GLYPHS_PER_FONT GLYPH_END - GLYPH_START + 1 typedef struct { int32_t height; // number of scan lines int32_t top; // top of glyph in buffer int32_t bottom; // bottom of glyph in buffer int32_t pitch; // width for copying int32_t xSkip; // x adjustment int32_t imageWidth; // width of actual image int32_t imageHeight; // height of actual image float s; // x offset in image where glyph starts float t; // y offset in image where glyph starts float s2; float t2; qhandle_t glyph; // handle to the shader with the glyph char shaderName[32]; } glyphInfo_t; typedef struct { glyphInfo_t glyphs [GLYPHS_PER_FONT]; float glyphScale; char name[MAX_QPATH]; } fontInfo_t; typedef enum { RT_MODEL, RT_POLY, RT_SPRITE, RT_BEAM, RT_RAIL_CORE, RT_RAIL_RINGS, RT_LIGHTNING, RT_PORTALSURFACE, // doesn't draw anything, just info for portals RT_MAX_REF_ENTITY_TYPE } refEntityType_t; typedef struct { refEntityType_t reType; int32_t renderfx; qhandle_t hModel; // opaque type outside refresh // most recent data vec3_t lightingOrigin; // so multi-part models can be lit identically (RF_LIGHTING_ORIGIN) float shadowPlane; // projection shadows go here, stencils go slightly lower vec3_t axis[3]; // rotation vectors qboolean nonNormalizedAxes; // axis are not normalized, i.e. they have scale float origin[3]; // also used as MODEL_BEAM's "from" int32_t frame; // also used as MODEL_BEAM's diameter // previous data for frame interpolation float oldorigin[3]; // also used as MODEL_BEAM's "to" int32_t oldframe; float backlerp; // 0.0 = current, 1.0 = old // texturing int32_t skinNum; // inline skin index qhandle_t customSkin; // NULL for default skin qhandle_t customShader; // use one image for the entire thing // misc byte shaderRGBA[4]; // colors used by rgbgen entity shaders float shaderTexCoord[2]; // texture coordinates used by tcMod entity modifiers float shaderTime; // subtracted from refdef time to control effect start times // extra sprite information float radius; float rotation; } refEntity_t; #define MAX_TOKENLENGTH 1024 typedef struct pc_token_s { int32_t type; int32_t subtype; int32_t intvalue; float floatvalue; char string[MAX_TOKENLENGTH]; } pc_token_t; #define MAX_RENDER_STRINGS 8 #define MAX_RENDER_STRING_LENGTH 32 #define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility typedef struct { int32_t x, y, width, height; float fov_x, fov_y; vec3_t vieworg; vec3_t viewaxis[3]; // transformation matrix // time in milliseconds for shader effects and other time dependent rendering issues int32_t time; int32_t rdflags; // RDF_NOWORLDMODEL, etc // 1 bits will prevent the associated area from rendering at all byte areamask[MAX_MAP_AREA_BYTES]; // text messages for deform text shaders char text[MAX_RENDER_STRINGS][MAX_RENDER_STRING_LENGTH]; } refdef_t; typedef struct qtime_s { int32_t tm_sec; /* seconds after the minute - [0,59] */ int32_t tm_min; /* minutes after the hour - [0,59] */ int32_t tm_hour; /* hours since midnight - [0,23] */ int32_t tm_mday; /* day of the month - [1,31] */ int32_t tm_mon; /* months since January - [0,11] */ int32_t tm_year; /* years since 1900 */ int32_t tm_wday; /* days since Sunday - [0,6] */ int32_t tm_yday; /* days since January 1 - [0,365] */ int32_t tm_isdst; /* daylight savings time flag */ } qtime_t; typedef struct { vec3_t xyz; float st[2]; byte modulate[4]; } polyVert_t; // usercmd_t is sent to the server each client frame typedef struct usercmd_s { int32_t serverTime; int32_t angles[3]; int32_t buttons; byte weapon; // weapon signed char forwardmove, rightmove, upmove; } usercmd_t; // player_state->stats[] indexes // NOTE: may not have more than 16 typedef enum { STAT_HEALTH, STAT_HOLDABLE_ITEM, STAT_WEAPONS, // 16 bit fields STAT_ARMOR, STAT_DEAD_YAW, // look this direction when dead (FIXME: get rid of?) STAT_CLIENTS_READY, // bit mask of clients wishing to exit the intermission (FIXME: configstring?) STAT_MAX_HEALTH // health / armor limit, changable by handicap } statIndex_t; typedef enum { WP_NONE, WP_GAUNTLET, WP_MACHINEGUN, WP_SHOTGUN, WP_GRENADE_LAUNCHER, WP_ROCKET_LAUNCHER, WP_LIGHTNING, WP_RAILGUN, WP_PLASMAGUN, WP_BFG, WP_GRAPPLING_HOOK, WP_NUM_WEAPONS } weapon_t; #define MAX_GENTITIES (1<<10) #define ENTITYNUM_NONE (MAX_GENTITIES-1) #define MAX_ENTITIES_IN_SNAPSHOT 256 // bit field limits #define MAX_STATS 16 #define MAX_PERSISTANT 16 #define MAX_POWERUPS 16 #define MAX_WEAPONS 16 #define MAX_PS_EVENTS 2 typedef struct playerState_s { int32_t commandTime; // cmd->serverTime of last executed command int32_t pm_type; int32_t bobCycle; // for view bobbing and footstep generation int32_t pm_flags; // ducked, jump_held, etc int32_t pm_time; vec3_t origin; vec3_t velocity; int32_t weaponTime; int32_t gravity; int32_t speed; int32_t delta_angles[3]; // add to command angles to get view direction // changed by spawns, rotating objects, and teleporters int32_t groundEntityNum;// ENTITYNUM_NONE = in air int32_t legsTimer; // don't change low priority animations until this runs out int32_t legsAnim; // mask off ANIM_TOGGLEBIT int32_t torsoTimer; // don't change low priority animations until this runs out int32_t torsoAnim; // mask off ANIM_TOGGLEBIT int32_t movementDir; // a number 0 to 7 that represents the reletive angle // of movement to the view angle (axial and diagonals) // when at rest, the value will remain unchanged // used to twist the legs during strafing vec3_t grapplePoint; // location of grapple to pull towards if PMF_GRAPPLE_PULL int32_t eFlags; // copied to entityState_t->eFlags int32_t eventSequence; // pmove generated events int32_t events[MAX_PS_EVENTS]; int32_t eventParms[MAX_PS_EVENTS]; int32_t externalEvent; // events set on player from another source int32_t externalEventParm; int32_t externalEventTime; int32_t clientNum; // ranges from 0 to MAX_CLIENTS-1 int32_t weapon; // copied to entityState_t->weapon int32_t weaponstate; vec3_t viewangles; // for fixed views int32_t viewheight; // damage feedback int32_t damageEvent; // when it changes, latch the other parms int32_t damageYaw; int32_t damagePitch; int32_t damageCount; int32_t stats[MAX_STATS]; int32_t persistant[MAX_PERSISTANT]; // stats that aren't cleared on death int32_t powerups[MAX_POWERUPS]; // level.time that the powerup runs out int32_t ammo[MAX_WEAPONS]; int32_t generic1; int32_t loopSound; int32_t jumppad_ent; // jumppad entity hit this frame // not communicated over the net at all int32_t ping; // server to game info for scoreboard int32_t pmove_framecount; // FIXME: don't transmit over the network int32_t jumppad_frame; int32_t entityEventSequence; } playerState_t; // if entityState->solid == SOLID_BMODEL, modelindex is an inline model number #define SOLID_BMODEL 0xffffff typedef enum { TR_STATIONARY, TR_INTERPOLATE, // non-parametric, but interpolate between snapshots TR_LINEAR, TR_LINEAR_STOP, TR_SINE, // value = base + sin( time / duration ) * delta TR_GRAVITY } trType_t; typedef struct { trType_t trType; int32_t trTime; int32_t trDuration; // if non 0, trTime + trDuration = stop time vec3_t trBase; vec3_t trDelta; // velocity, etc } trajectory_t; // entityState_t is the information conveyed from the server // in an update message about entities that the client will // need to render in some way // Different eTypes may use the information in different ways // The messages are delta compressed, so it doesn't really matter if // the structure size is fairly large typedef struct entityState_s { int32_t number; // entity index int32_t eType; // entityType_t int32_t eFlags; trajectory_t pos; // for calculating position trajectory_t apos; // for calculating angles int32_t time; int32_t time2; vec3_t origin; vec3_t origin2; vec3_t angles; vec3_t angles2; int32_t otherEntityNum; // shotgun sources, etc int32_t otherEntityNum2; int32_t groundEntityNum; // -1 = in air int32_t constantLight; // r + (g<<8) + (b<<16) + (intensity<<24) int32_t loopSound; // constantly loop this sound int32_t modelindex; int32_t modelindex2; int32_t clientNum; // 0 to (MAX_CLIENTS - 1), for players and corpses int32_t frame; int32_t solid; // for client side prediction, trap_linkentity sets this properly int32_t event; // impulse events -- muzzle flashes, footsteps, etc int32_t eventParm; // for players int32_t powerups; // bit flags int32_t weapon; // determines weapon and flash model, etc int32_t legsAnim; // mask off ANIM_TOGGLEBIT int32_t torsoAnim; // mask off ANIM_TOGGLEBIT int32_t generic1; } entityState_t; // snapshots are a view of the server at a given time // Snapshots are generated at regular time intervals by the server, // but they may not be sent if a client's rate level is exceeded, or // they may be dropped by the network. typedef struct { int32_t snapFlags; // SNAPFLAG_RATE_DELAYED, etc int32_t ping; int32_t serverTime; // server time the message is valid for (in msec) byte areamask[MAX_MAP_AREA_BYTES]; // portalarea visibility bits playerState_t ps; // complete information about the current player at this time int32_t numEntities; // all of the entities that need to be presented entityState_t entities[MAX_ENTITIES_IN_SNAPSHOT]; // at the time of this snapshot int32_t numServerCommands; // text based server commands to execute when this int32_t serverCommandSequence; // snapshot becomes current } snapshot_t; extern vec4_t g_color_table[10]; #define Q_COLOR_ESCAPE '^' #define Q_IsColorString(p) ( p && *(p) == Q_COLOR_ESCAPE && *((p)+1) && *((p)+1) != Q_COLOR_ESCAPE ) #define COLOR_BLACK '0' #define COLOR_RED '1' #define COLOR_GREEN '2' #define COLOR_YELLOW '3' #define COLOR_BLUE '4' #define COLOR_CYAN '5' #define COLOR_MAGENTA '6' #define COLOR_WHITE '7' #define COLOR_ORANGE '8' #define COLOR_MDGREY '9' #define ColorIndex(c) ( ( ( (c) - '0' ) &15 ) %10 ) #define S_COLOR_BLACK "^0" #define S_COLOR_RED "^1" #define S_COLOR_GREEN "^2" #define S_COLOR_YELLOW "^3" #define S_COLOR_BLUE "^4" #define S_COLOR_CYAN "^5" #define S_COLOR_MAGENTA "^6" #define S_COLOR_WHITE "^7" #define S_COLOR_ORANGE "^8" #define S_COLOR_MDGREY "^9" #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 #define TINYCHAR_WIDTH (SMALLCHAR_WIDTH) #define TINYCHAR_HEIGHT (SMALLCHAR_HEIGHT/2) #define SMALLCHAR_WIDTH 8 #define SMALLCHAR_HEIGHT 16 #define BIGCHAR_WIDTH 16 #define BIGCHAR_HEIGHT 16 #define GIANTCHAR_WIDTH 32 #define GIANTCHAR_HEIGHT 48 #endif // __CG_LOCAL_H__
czimnick/cgame_proxymod
cg_local.h
C
gpl-3.0
20,752
/* * Copyright (C) 2020 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo 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. * * ESPResSo 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 "ContextManager.hpp" #include "GlobalContext.hpp" #include "LocalContext.hpp" #include <utils/serialization/pack.hpp> #include <cassert> #include <memory> #include <string> #include <utility> namespace ScriptInterface { std::shared_ptr<ObjectHandle> ContextManager::make_shared(CreationPolicy policy, std::string const &name, const VariantMap &parameters) { return context(policy)->make_shared(name, parameters); } std::shared_ptr<ObjectHandle> ContextManager::deserialize(std::string const &state_) { auto const state = Utils::unpack<std::pair<CreationPolicy, std::string>>(state_); auto ctx = context(state.first); assert(ctx); return ObjectHandle::deserialize(state.second, *ctx); } std::string ContextManager::serialize(const ObjectHandle *o) const { /* We treat objects without a context as local. */ auto ctx = o->context() ? o->context() : m_local_context.get(); return Utils::pack(std::make_pair(policy(ctx), o->serialize())); } ContextManager::ContextManager(Communication::MpiCallbacks &callbacks, const Utils::Factory<ObjectHandle> &factory) { auto local_context = std::make_shared<LocalContext>(factory); /* If there is only one node, we can treat all objects as local, and thus * never invoke any callback. */ m_global_context = (callbacks.comm().size() > 1) ? std::make_shared<GlobalContext>(callbacks, local_context) : std::static_pointer_cast<Context>(local_context); m_local_context = std::move(local_context); } } // namespace ScriptInterface
fweik/espresso
src/script_interface/ContextManager.cpp
C++
gpl-3.0
2,328
<?php if (is_ajax()) { if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists $action = $_POST["action"]; switch($action) { //Switch case for value of action case "updateKataster": updateKataster(); break; case "saveKataster": saveKataster(); break; case "loadMesstrupps": loadMesstrupps(); break; case "saveMesstrupps": saveMesstrupps(); break; } } } //Function to check if the request is an AJAX request function is_ajax() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } function updateKataster(){ include("config.php"); require("session.php"); $UID = !empty($_POST['UID']) ? $_POST['UID']:$_SESSION['userid']; if ($UID == 'su') { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messpunkte = $stmt->fetch(); } else { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = :UID AND opt_kataster > ''"); $stmt->bindParam(':UID', $UID, PDO::PARAM_STR); $stmt->execute(); $messpunkte = $stmt->fetch(); if (!$messpunkte) // Überprüft, ob persönliche Messpunkte gespeichert sind und lädt anderenfalls die globalen Vorgaben { $stmt = $pdo->prepare("SELECT opt_kataster FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messpunkte = $stmt->fetch(); } if (!$messpunkte) // Wenn globale Vorgaben nicht definiert sind, wird ein Standardwert angenommen { $messpunkte = array('opt_kataster' => '[{"ID":"1","Nummer":"01-00","Bezeichnung":"Mustername","Adresse":"Musterstraße 1, 12345 Musterstadt","ODL":"0","IPS":"0","Koordinaten":"52.514036, 13.404107"}]', "0" => '[{"ID":"1","Nummer":"01-00","Bezeichnung":"Mustername","Adresse":"Musterstraße 1, 12345 Musterstadt","ODL":"0","IPS":"0","Koordinaten":"52.514036, 13.404107"}]'); } } echo json_encode($messpunkte); } function saveKataster(){ include("config.php"); require("session.php"); $kataster = !empty($_POST['data']) ? $_POST['data']:''; $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { if ($_SESSION['accessLevel'] == "admin") { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_kataster) VALUES ('0', :points) ON DUPLICATE KEY UPDATE opt_kataster = :points"); $stmt->bindParam(':points', $kataster, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successGlobal'); } else { echo json_encode('noAdmin'); } } else { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_kataster) VALUES (:UID, :points) ON DUPLICATE KEY UPDATE opt_kataster = :points"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_INT); $stmt->bindParam(':points', $kataster, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successLocal'); } } function loadMesstrupps(){ // Lädt die Messtrupps, die der angemeldete Benutzer erstellt hat. require('session.php'); include("config.php"); $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = '0'"); $stmt->execute(); $messtrupps = $stmt->fetch(); } else { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = :UID AND opt_cars > ''"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_STR); $stmt->execute(); $messtrupps = $stmt->fetch(); if (!$messtrupps) // Überprüft, ob persönliche Messtrupps gespeichert sind und lädt anderenfalls die globalen Vorgaben { $stmt = $pdo->prepare("SELECT opt_cars FROM options WHERE opt_UID = '0' AND opt_cars > ''"); $stmt->execute(); $messtrupps = $stmt->fetch(); } if (!$messtrupps) // Wenn globale Vorgaben nicht definiert sind, wird ein Standardwert angenommen { $messtrupps = array('opt_cars' => '[{"ID":"0","key":"","name":"Keine Zuordnung","color":"#000000"}]', "0" => '[{"ID":"0","key":"","name":"Keine Zuordnung","color":"#000000"}]'); } } echo json_encode($messtrupps); } function saveMesstrupps(){ include("config.php"); require("session.php"); $trupps = !empty($_POST['data']) ? $_POST['data']:''; $UID = !empty($_POST['UID']) ? $_POST['UID']:''; if ($UID == 'su') { if ($_SESSION['accessLevel'] == "admin") { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_cars) VALUES ('0', :cars) ON DUPLICATE KEY UPDATE opt_cars = :cars"); $stmt->bindParam(':cars', $trupps, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successGlobal'); } else { echo json_encode('noAdmin'); } } else { $stmt = $pdo->prepare("INSERT INTO options (opt_UID, opt_cars) VALUES (:UID, :cars) ON DUPLICATE KEY UPDATE opt_cars = :cars"); $stmt->bindParam(':UID', $_SESSION['userid'], PDO::PARAM_INT); $stmt->bindParam(':cars', $trupps, PDO::PARAM_STR); $stmt->execute(); echo json_encode('successLocal'); } } ?>
cuzcomd/DALUS
php/options.php
PHP
gpl-3.0
4,972
package quests; import l2s.gameserver.ThreadPoolManager; import l2s.gameserver.model.instances.NpcInstance; import l2s.gameserver.model.quest.Quest; import l2s.gameserver.model.quest.QuestState; import l2s.gameserver.network.l2.components.NpcString; import l2s.gameserver.scripts.Functions; import l2s.gameserver.scripts.ScriptFile; //By Evil_dnk public class _10772_ReportsfromCrumaTowerPart1 extends Quest implements ScriptFile { // NPC's private static final int YANSEN = 30484; private static final int MAGICOWL = 33991; //ITEMS private static final int DOORCOIN = 37045; private static final int ENCHANTARMOR = 23420; private NpcInstance owl = null; public _10772_ReportsfromCrumaTowerPart1() { super(PARTY_NONE); addStartNpc(YANSEN); addTalkId(YANSEN); addTalkId(MAGICOWL); addQuestCompletedCheck(_10771_Volatile_Power.class); addLevelCheck(45); addRaceCheck(false, false, false, false, false, false, true); } @Override public String onEvent(String event, QuestState st, NpcInstance npc) { String htmltext = event; if(event.equalsIgnoreCase("30484-5.htm")) { owl = null; st.setState(STARTED); st.setCond(1); } else if(event.equalsIgnoreCase("30484-9.htm")) { st.getPlayer().addExpAndSp(127575, 30); st.giveItems(DOORCOIN, 4); st.giveItems(ENCHANTARMOR, 2); st.exitCurrentQuest(false); } else if(event.equalsIgnoreCase("summonbird")) { if (owl == null) owl = st.addSpawn(MAGICOWL, 17640, 114968, -11753, 0, 0, 120000); return null; } else if(event.equalsIgnoreCase("send")) { st.setCond(2); Functions.npcSay(owl, NpcString.TO_QUEEN_NAVARI_OF_FAERON); ThreadPoolManager.getInstance().schedule(() -> { npc.doDie(null); npc.endDecayTask(); }, 6000L); return null; } return htmltext; } @Override public String onTalk(NpcInstance npc, QuestState st) { int npcId = npc.getNpcId(); int cond = st.getCond(); String htmltext = "noquest"; switch (npcId) { case YANSEN: if(cond == 0) { if(checkStartCondition(st.getPlayer())) htmltext = "30484-1.htm"; else htmltext = "30484-0.htm"; } else if (cond == 1) htmltext = "30484-7.htm"; else if (cond == 2) htmltext = "30484-8.htm"; break; case MAGICOWL: if (cond == 1) htmltext = "33991-1.htm"; break; } return htmltext; } @Override public void onLoad() { } @Override public void onReload() { // } @Override public void onShutdown() { // } }
pantelis60/L2Scripts_Underground
dist/gameserver/data/scripts/quests/_10772_ReportsfromCrumaTowerPart1.java
Java
gpl-3.0
2,517
/* * Copyright 2010-2011, Leo Franchi <lfranchi@kde.org> * Copyright 2010-2012, Jeff Mitchell <jeff@tomahawk-player.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SOURCE_ITEM_H #define SOURCE_ITEM_H #include "sourcetreeitem.h" class TemporaryPageItem; class GenericPageItem; class CategoryItem; namespace Tomahawk { class ViewPage; } class SourceItem : public SourceTreeItem { Q_OBJECT public: SourceItem( SourcesModel* model, SourceTreeItem* parent, const Tomahawk::source_ptr& source ); virtual QString text() const; virtual QIcon icon() const; virtual int peerSortValue() const; virtual int IDValue() const; virtual bool localLatchedOn() const; virtual Tomahawk::PlaylistInterface::LatchMode localLatchMode() const; Tomahawk::source_ptr source() const; CategoryItem* stationsCategory() const { return m_stations; } CategoryItem* playlistsCategory() const { return m_playlists; } void setStationsCategory( CategoryItem* item ) { m_stations = item; } void setPlaylistsCategory( CategoryItem* item ) { m_playlists = item; } public slots: virtual void activate(); private slots: void onPlaylistsAdded( const QList<Tomahawk::playlist_ptr>& playlists ); void onPlaylistDeleted( const Tomahawk::playlist_ptr& playlists ); void onAutoPlaylistsAdded( const QList<Tomahawk::dynplaylist_ptr>& playlists ); void onAutoPlaylistDeleted( const Tomahawk::dynplaylist_ptr& playlists ); void onStationsAdded( const QList<Tomahawk::dynplaylist_ptr>& stations ); void onStationDeleted( const Tomahawk::dynplaylist_ptr& stations ); void latchedOn( const Tomahawk::source_ptr&, const Tomahawk::source_ptr& ); void latchedOff( const Tomahawk::source_ptr&, const Tomahawk::source_ptr& ); void latchModeChanged( Tomahawk::PlaylistInterface::LatchMode mode ); void requestExpanding(); Tomahawk::ViewPage* sourceInfoClicked(); Tomahawk::ViewPage* getSourceInfoPage() const; Tomahawk::ViewPage* collectionClicked(); Tomahawk::ViewPage* getCollectionPage() const; Tomahawk::ViewPage* coolPlaylistsClicked(); Tomahawk::ViewPage* getCoolPlaylistsPage() const; Tomahawk::ViewPage* lovedTracksClicked(); Tomahawk::ViewPage* getLovedTracksPage() const; Tomahawk::ViewPage* latestAdditionsClicked(); Tomahawk::ViewPage* getLatestAdditionsPage() const; Tomahawk::ViewPage* recentPlaysClicked(); Tomahawk::ViewPage* getRecentPlaysPage() const; private: void playlistsAddedInternal( SourceTreeItem* parent, const QList< Tomahawk::dynplaylist_ptr >& playlists ); template< typename T > void playlistDeletedInternal( SourceTreeItem* parent, const T& playlists ); Tomahawk::source_ptr m_source; QPixmap m_superCol, m_defaultAvatar; CategoryItem* m_playlists; CategoryItem* m_stations; bool m_latchedOn; Tomahawk::source_ptr m_latchedOnTo; GenericPageItem* m_collectionItem; GenericPageItem* m_sourceInfoItem; GenericPageItem* m_coolPlaylistsItem; GenericPageItem* m_lovedTracksItem; GenericPageItem* m_latestAdditionsItem; GenericPageItem* m_recentPlaysItem; Tomahawk::ViewPage* m_collectionPage; Tomahawk::ViewPage* m_sourceInfoPage; Tomahawk::ViewPage* m_coolPlaylistsPage; Tomahawk::ViewPage* m_lovedTracksPage; Tomahawk::ViewPage* m_latestAdditionsPage; Tomahawk::ViewPage* m_recentPlaysPage; Tomahawk::ViewPage* m_whatsHotPage; }; #endif
neycho/tomahawk
src/sourcetree/items/sourceitem.h
C
gpl-3.0
4,198
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.compatibility.common.util; /** * Represents a filter for including and excluding tests. */ public class TestFilter { private final String mAbi; private final String mName; private final String mTest; /** * Builds a new {@link TestFilter} from the given string. Filters can be in one of four forms, * the instance will be initialized as; * -"name" -> abi = null, name = "name", test = null * -"name" "test..." -> abi = null, name = "name", test = "test..." * -"abi" "name" -> abi = "abi", name = "name", test = null * -"abi" "name" "test..." -> abi = "abi", name = "name", test = "test..." * * Test identifier can contain multiple parts, eg parameterized tests. * * @param filter the filter to parse * @return the {@link TestFilter} */ public static TestFilter createFrom(String filter) { if (filter.isEmpty()) { throw new IllegalArgumentException("Filter was empty"); } String[] parts = filter.split(" "); String abi = null, name = null, test = null; // Either: // <name> // <name> <test> // <abi> <name> // <abi> <name> <test> if (parts.length == 1) { name = parts[0]; } else { int index = 0; if (AbiUtils.isAbiSupportedByCompatibility(parts[0])) { abi = parts[0]; index++; } name = parts[index]; index++; parts = filter.split(" ", index + 1); if (parts.length > index) { test = parts[index]; } } return new TestFilter(abi, name, test); } /** * Creates a new {@link TestFilter} from the given parts. * * @param abi The ABI must be supported {@link AbiUtils#isAbiSupportedByCompatibility(String)} * @param name The module's name * @param test The test's identifier eg <package>.<class>#<method> */ public TestFilter(String abi, String name, String test) { mAbi = abi; mName = name; mTest = test; } /** * Returns a String representation of this filter. This function is the inverse of * {@link TestFilter#createFrom(String)}. * * For a valid filter f; * <pre> * {@code * new TestFilter(f).toString().equals(f) * } * </pre> */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (mAbi != null) { sb.append(mAbi.trim()); sb.append(" "); } if (mName != null) { sb.append(mName.trim()); } if (mTest != null) { sb.append(" "); sb.append(mTest.trim()); } return sb.toString(); } /** * @return the abi of this filter, or null if not specified. */ public String getAbi() { return mAbi; } /** * @return the module name of this filter, or null if not specified. */ public String getName() { return mName; } /** * @return the test identifier of this filter, or null if not specified. */ public String getTest() { return mTest; } }
wiki2014/Learning-Summary
alps/cts/common/util/src/com/android/compatibility/common/util/TestFilter.java
Java
gpl-3.0
3,932
package org.um.feri.ears.problems.real_world.cec2011; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.lang3.ArrayUtils; import org.um.feri.ears.problems.Problem; import org.um.feri.ears.util.Util; /** * Problem function! * * @author Matej Črepinšek * @version 1 * **/ public class CEC2011_Problem_11_7_ELD_140 extends Problem { private double g_constrains[]; //internal /* */ private static double[][] Data1= {{71,119,1220.645,61.24200,0.03288800,0,0}, {120,189,1315.118,41.09500,0.008280000,0,0}, {125,190,874.2880,46.31000,0.003849000,0,0}, {125,190,874.2880,46.31000,0.003849000,0,0}, {90,190,1976.469,54.24200,0.04246800,700,0.08}, {90,190,1338.087,61.21500,0.01499200,0,0}, {280,490,1818.299,11.79100,0.007039000,0,0}, {280,490,1133.978,15.05500,0.003079000,0,0}, {260,496,1320.636,13.22600,0.005063000,0,0}, {260,496,1320.636,13.22600,0.005063000,600,0.055}, {260,496,1320.636,13.22600,0.005063000,0,0}, {260,496,1106.539,14.49800,0.003552000,0,0}, {260,506,1176.504,14.65100,0.003901000,0,0}, {260,509,1176.504,14.65100,0.003901000,0,0}, {260,506,1176.504,14.65100,0.003901000,800,0.06}, {260,505,1176.504,14.65100,0.003901000,0,0}, {260,506,1017.406,15.66900,0.002393000,0,0}, {260,506,1017.406,15.66900,0.002393000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {260,505,1229.131,14.65600,0.003684000,600,0.05}, {260,505,1267.894,14.37800,0.004004000,0,0}, {260,505,1229.131,14.65600,0.003684000,0,0}, {280,537,975.9260,16.26100,0.001619000,0,0}, {280,537,1532.093,13.36200,0.005093000,0,0}, {280,549,641.9890,17.20300,0.0009930000,0,0}, {280,549,641.9890,17.20300,0.0009930000,0,0}, {260,501,911.5330,15.27400,0.002473000,0,0}, {260,501,910.5330,15.21200,0.002547000,0,0}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,506,1074.810,15.03300,0.003542000,600,0.043}, {260,506,1074.810,15.03300,0.003542000,0,0}, {260,500,1278.460,13.99200,0.003132000,0,0}, {260,500,861.7420,15.67900,0.001323000,0,0}, {120,241,408.8340,16.54200,0.002950000,0,0}, {120,241,408.8340,16.54200,0.002950000,0,0}, {423,774,1288.815,16.51800,0.0009910000,0,0}, {423,769,1436.251,15.81500,0.001581000,600,0.043}, {3,19,699.9880,75.46400,0.9023600,0,0}, {3,28,134.5440,129.5440,0.1102950,0,0}, {160,250,3427.912,56.61300,0.02449300,0,0}, {160,250,3751.772,54.45100,0.02915600,0,0}, {160,250,3918.780,54.73600,0.02466700,0,0}, {160,250,3379.580,58.03400,0.01651700,0,0}, {160,250,3345.296,55.98100,0.02658400,0,0}, {160,250,3138.754,61.52000,0.007540000,0,0}, {160,250,3453.050,58.63500,0.01643000,0,0}, {160,250,5119.300,44.64700,0.04593400,0,0}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {165,504,1898.415,71.58400,4.4e-05,1100,0.043}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {165,504,1898.415,71.58400,4.4e-05,0,0}, {180,471,2473.390,85.12000,0.002528000,0,0}, {180,561,2781.705,87.68200,0.0001310000,0,0}, {103,341,5515.508,69.53200,0.01037200,0,0}, {198,617,3478.300,78.33900,0.007627000,0,0}, {100,312,6240.909,58.17200,0.01246400,0,0}, {153,471,9960.110,46.63600,0.03944100,0,0}, {163,500,3671.997,76.94700,0.007278000,0,0}, {95,302,1837.383,80.76100,4.4e-05,0,0}, {160,511,3108.395,70.13600,4.4e-05,0,0}, {160,511,3108.395,70.13600,4.4e-05,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {196,490,3392.732,65.40400,0.01085200,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {196,490,7095.484,49.84000,0.01882700,0,0}, {130,432,4288.320,66.46500,0.03456000,0,0}, {130,432,13813.0010,22.94100,0.08154000,1200,0.03}, {137,455,4435.493,64.31400,0.02353400,0,0}, {137,455,9750.750,45.01700,0.03547500,1000,0.05}, {195,541,1042.366,70.64400,0.0009150000,0,0}, {175,536,1159.895,70.95900,4.4e-05,0,0}, {175,540,1159.895,70.95900,4.4e-05,0,0}, {175,538,1303.990,70.30200,0.001307000,0,0}, {175,540,1156.193,70.66200,0.0003920000,0,0}, {330,574,2118.968,71.10100,8.7e-05,0,0}, {160,531,779.5190,37.85400,0.0005210000,0,0}, {160,531,829.8880,37.76800,0.0004980000,0,0}, {200,542,2333.690,67.98300,0.001046000,0,0}, {56,132,2028.954,77.83800,0.1320500,0,0}, {115,245,4412.017,63.67100,0.09696800,0,0}, {115,245,2982.219,79.45800,0.05486800,1000,0.05}, {115,245,2982.219,79.45800,0.05486800,0,0}, {207,307,3174.939,93.96600,0.01438200,0,0}, {207,307,3218.359,94.72300,0.01316100,0,0}, {175,345,3723.822,66.91900,0.01603300,0,0}, {175,345,3551.405,68.18500,0.01365300,0,0}, {175,345,4332.615,60.82100,0.02814800,0,0}, {175,345,3493.739,68.55100,0.01347000,0,0}, {360,580,226.7990,2.842000,6.4e-05,0,0}, {415,645,382.9320,2.946000,0.0002520000,0,0}, {795,984,156.9870,3.096000,2.2e-05,0,0}, {795,978,154.4840,3.040000,2.2e-05,0,0}, {578,682,332.8340,1.709000,0.0002030000,0,0}, {615,720,326.5990,1.668000,0.0001980000,0,0}, {612,718,345.3060,1.789000,0.0002150000,0,0}, {612,720,350.3720,1.815000,0.0002180000,0,0}, {758,964,370.3770,2.726000,0.0001930000,0,0}, {755,958,367.0670,2.732000,0.0001970000,0,0}, {750,1007,124.8750,2.651000,0.0003240000,0,0}, {750,1006,130.7850,2.798000,0.0003440000,0,0}, {713,1013,878.7460,1.595000,0.00069,0,0}, {718,1020,827.9590,1.503000,0.00065,0,0}, {791,954,432.0070,2.425000,0.0002330000,0,0}, {786,952,445.6060,2.499000,0.0002390000,0,0}, {795,1006,467.2230,2.674000,0.0002610000,0,0}, {795,1013,475.9400,2.692000,0.0002590000,0,0}, {795,1021,899.4620,1.633000,0.0007070000,0,0}, {795,1015,1000.367,1.816000,0.0007860000,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {94,203,1269.132,89.83000,0.01435500,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {244,379,4965.124,64.12500,0.03026600,0,0}, {95,190,2243.185,76.12900,0.02402700,0,0}, {95,189,2290.381,81.80500,0.001580000,600,0.07}, {116,194,1681.533,81.14000,0.02209500,0,0}, {175,321,6743.302,46.66500,0.07681000,1200,0.043}, {2,19,394.3980,78.41200,0.9534430,0,0}, {4,59,1243.165,112.0880,4.4e-05,0,0}, {15,83,1454.740,90.87100,0.07246800,0,0}, {9,53,1011.051,97.11600,0.0004480000,0,0}, {12,37,909.2690,83.24400,0.5991120,0,0}, {10,34,689.3780,95.66500,0.2447060,0,0}, {112,373,1443.792,91.20200,4.2e-05,0,0}, {4,20,535.5530,104.5010,0.08514500,0,0}, {5,38,617.7340,83.01500,0.5247180,0,0}, {5,19,90.96600,127.7950,0.1765150,0,0}, {50,98,974.4470,77.92900,0.06341400,0,0}, {5,10,263.8100,92.77900,2.740485,0,0}, {42,74,1335.594,80.95000,0.1124380,0,0}, {42,74,1033.871,89.07300,0.04152900,0,0}, {41,105,1391.325,161.2880,0.0009110000,0,0}, {17,51,4477.110,161.8290,0.005245000,0,0}, {7,19,57.79400,84.97200,0.2347870,0,0}, {7,19,57.79400,84.97200,0.2347870,0,0}, {26,40,1258.437,16.08700,1.111878,0,0}}; // % % % ============= 6 unit system data ========== // % Data1= [Pmin Pmax a b c]; /*private static double[][] Data1= {{71, 119, 1220.645, 61.242, 0.032888}, {120, 189, 1315.118, 41.095, 0.00828}, {125, 190, 874.288, 46.31, 0.003849}, {125, 190, 874.288, 46.31, 0.003849}, {90, 190, 1976.469, 54.242, 0.042468}, {90, 190, 1338.087, 61.215, 0.014992}, {280, 490, 1818.299, 11.791, 0.007039}, {280, 490, 1133.978, 15.055, 0.003079}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1320.636, 13.226, 0.005063}, {260, 496, 1106.539, 14.498, 0.003552}, {260, 506, 1176.504, 14.651, 0.003901}, {260, 509, 1176.504, 14.651, 0.003901}, {260, 506, 1176.504, 14.651, 0.003901}, {260, 505, 1176.504, 14.651, 0.003901}, {260, 506, 1017.406, 15.669, 0.002393}, {260, 506, 1017.406, 15.669, 0.002393}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1229.131, 14.656, 0.003684}, {260, 505, 1267.894, 14.378, 0.004004}, {260, 505, 1229.131, 14.656, 0.003684}, {280, 537, 975.926, 16.261, 0.001619}, {280, 537, 1532.093, 13.362, 0.005093}, {280, 549, 641.989, 17.203, 0.000993}, {280, 549, 641.989, 17.203, 0.000993}, {260, 501, 911.533, 15.274, 0.002473}, {260, 501, 910.533, 15.212, 0.002547}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 506, 1074.81, 15.033, 0.003542}, {260, 500, 1278.46, 13.992, 0.003132}, {260, 500, 861.742, 15.679, 0.001323}, {120, 241, 408.834, 16.542, 0.00295}, {120, 241, 408.834, 16.542, 0.00295}, {423, 774, 1288.815, 16.518, 0.000991}, {423, 769, 1436.251, 15.815, 0.001581}, {3, 19, 699.988, 75.464, 0.90236}, {3, 28, 134.544, 129.544, 0.110295}, {160, 250, 3427.912, 56.613, 0.024493}, {160, 250, 3751.772, 54.451, 0.029156}, {160, 250, 3918.78, 54.736, 0.024667}, {160, 250, 3379.58, 58.034, 0.016517}, {160, 250, 3345.296, 55.981, 0.026584}, {160, 250, 3138.754, 61.52, 0.00754}, {160, 250, 3453.05, 58.635, 0.01643}, {160, 250, 5119.3, 44.647, 0.045934}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {165, 504, 1898.415, 71.584, 0.000044}, {180, 471, 2473.39, 85.12, 0.002528}, {180, 561, 2781.705, 87.682, 0.000131}, {103, 341, 5515.508, 69.532, 0.010372}, {198, 617, 3478.3, 78.339, 0.007627}, {100, 312, 6240.909, 58.172, 0.012464}, {153, 471, 9960.11, 46.636, 0.039441}, {163, 500, 3671.997, 76.947, 0.007278}, {95, 302, 1837.383, 80.761, 0.000044}, {160, 511, 3108.395, 70.136, 0.000044}, {160, 511, 3108.395, 70.136, 0.000044}, {196, 490, 7095.484, 49.84, 0.018827}, {196, 490, 3392.732, 65.404, 0.010852}, {196, 490, 7095.484, 49.84, 0.018827}, {196, 490, 7095.484, 49.84, 0.018827}, {130, 432, 4288.32, 66.465, 0.03456}, {130, 432, 13813.001, 22.941, 0.08154}, {137, 455, 4435.493, 64.314, 0.023534}, {137, 455, 9750.75, 45.017, 0.035475}, {195, 541, 1042.366, 70.644, 0.000915}, {175, 536, 1159.895, 70.959, 0.000044}, {175, 540, 1159.895, 70.959, 0.000044}, {175, 538, 1303.99, 70.302, 0.001307}, {175, 540, 1156.193, 70.662, 0.000392}, {330, 574, 2118.968, 71.101, 0.000087}, {160, 531, 779.519, 37.854, 0.000521}, {160, 531, 829.888, 37.768, 0.000498}, {200, 542, 2333.69, 67.983, 0.001046}, {56, 132, 2028.954, 77.838, 0.13205}, {115, 245, 4412.017, 63.671, 0.096968}, {115, 245, 2982.219, 79.458, 0.054868}, {115, 245, 2982.219, 79.458, 0.054868}, {207, 307, 3174.939, 93.966, 0.014382}, {207, 307, 3218.359, 94.723, 0.013161}, {175, 345, 3723.822, 66.919, 0.016033}, {175, 345, 3551.405, 68.185, 0.013653}, {175, 345, 4332.615, 60.821, 0.028148}, {175, 345, 3493.739, 68.551, 0.01347}, {360, 580, 226.799, 2.842, 0.000064}, {415, 645, 382.932, 2.946, 0.000252}, {795, 984, 156.987, 3.096, 0.000022}, {795, 978, 154.484, 3.04, 0.000022}, {578, 682, 332.834, 1.709, 0.000203}, {615, 720, 326.599, 1.668, 0.000198}, {612, 718, 345.306, 1.789, 0.000215}, {612, 720, 350.372, 1.815, 0.000218}, {758, 964, 370.377, 2.726, 0.000193}, {755, 958, 367.067, 2.732, 0.000197}, {750, 1007, 124.875, 2.651, 0.000324}, {750, 1006, 130.785, 2.798, 0.000344}, {713, 1013, 878.746, 1.595, 0.00069}, {718, 1020, 827.959, 1.503, 0.00065}, {791, 954, 432.007, 2.425, 0.000233}, {786, 952, 445.606, 2.499, 0.000239}, {795, 1006, 467.223, 2.674, 0.000261}, {795, 1013, 475.94, 2.692, 0.000259}, {795, 1021, 899.462, 1.633, 0.000707}, {795, 1015, 1000.367, 1.816, 0.000786}, {94, 203, 1269.132, 89.83, 0.014355}, {94, 203, 1269.132, 89.83, 0.014355}, {94, 203, 1269.132, 89.83, 0.014355}, {244, 379, 4965.124, 64.125, 0.030266}, {244, 379, 4965.124, 64.125, 0.030266}, {244, 379, 4965.124, 64.125, 0.030266}, {95, 190, 2243.185, 76.129, 0.024027}, {95, 189, 2290.381, 81.805, 0.00158}, {116, 194, 1681.533, 81.14, 0.022095}, {175, 321, 6743.302, 46.665, 0.07681}, {2, 19, 394.398, 78.412, 0.953443}, {4, 59, 1243.165, 112.088, 0.000044}, {15, 83, 1454.74, 90.871, 0.072468}, {9, 53, 1011.051, 97.116, 0.000448}, {12, 37, 909.269, 83.244, 0.599112}, {10, 34, 689.378, 95.665, 0.244706}, {112, 373, 1443.792, 91.202, 0.000042}, {4, 20, 535.553, 104.501, 0.085145}, {5, 38, 617.734, 83.015, 0.524718}, {5, 19, 90.966, 127.795, 0.176515}, {50, 98, 974.447, 77.929, 0.063414}, {5, 10, 263.81, 92.779, 2.740485}, {42, 74, 1335.594, 80.95, 0.112438}, {42, 74, 1033.871, 89.073, 0.041529}, {41, 105, 1391.325, 161.288, 0.000911}, {17, 51, 4477.11, 161.829, 0.005245}, {7, 19, 57.794, 84.972, 0.234787}, {7, 19, 57.794, 84.972, 0.234787}, {26, 40, 1258.437, 16.087, 1.111878}}; */ private static double[][] Data2= {{ 98.4, 30, 120, 0,0,0,0,0,0}, {134, 30, 120, 0,0,0,0,0,0}, {141.5, 60, 60, 0,0,0,0,0,0}, {183.3, 60, 60, 0,0,0,0,0,0}, {125, 150, 150, 0,0,0,0,0,0}, {91.3, 150, 150, 0,0,0,0,0,0}, {401.1, 180, 300, 0,0,0,0,0,0}, {329.5, 180, 300,250,280,305,335,420,450}, {386.1, 300, 510, 0,0,0,0,0,0}, {427.3, 300, 510, 0,0,0,0,0,0}, {412.2, 300, 510, 0,0,0,0,0,0}, {370.1, 300, 510, 0,0,0,0,0,0}, {301.8, 600, 600, 0,0,0,0,0,0}, {368, 600, 600, 0,0,0,0,0,0}, {301.9, 600, 600, 0,0,0,0,0,0}, {476.4, 600, 600, 0,0,0,0,0,0}, {283.1, 600, 600, 0,0,0,0,0,0}, {414.1, 600, 600, 0,0,0,0,0,0}, {328, 600, 600, 0,0,0,0,0,0}, {389.4, 600, 600, 0,0,0,0,0,0}, {354.7, 600, 600, 0,0,0,0,0,0}, {262, 600, 600, 0,0,0,0,0,0}, {461.5, 600, 600, 0,0,0,0,0,0}, {371.6, 600, 600, 0,0,0,0,0,0}, {462.6, 300, 300, 0,0,0,0,0,0}, {379.2, 300, 300, 0,0,0,0,0,0}, {530.8, 360, 360, 0,0,0,0,0,0}, {391.9, 360, 360, 0,0,0,0,0,0}, {480.1, 180, 180, 0,0,0,0,0,0}, {319, 180, 180, 0,0,0,0,0,0}, {329.5, 600, 600, 0,0,0,0,0,0}, {333.8, 600, 600,220,250,320,350,390,420}, {390, 600, 600, 0,0,0,0,0,0}, {432, 600, 600, 0,0,0,0,0,0}, {402, 660, 660, 0,0,0,0,0,0}, {428, 900, 900, 0,0,0,0,0,0}, {178.4, 180, 180, 0,0,0,0,0,0}, {194.1, 180, 180, 0,0,0,0,0,0}, {474, 600, 600, 0,0,0,0,0,0}, {609.8, 600, 600, 0,0,0,0,0,0}, {17.8, 210, 210, 0,0,0,0,0,0}, {6.9, 366, 366, 0,0,0,0,0,0}, {224.3, 702, 702, 0,0,0,0,0,0}, {210, 702, 702, 0,0,0,0,0,0}, {212, 702, 702, 0,0,0,0,0,0}, {200.8, 702, 702, 0,0,0,0,0,0}, {220, 702, 702, 0,0,0,0,0,0}, {232.9, 702, 702, 0,0,0,0,0,0}, {168, 702, 702, 0,0,0,0,0,0}, {208.4, 702, 702, 0,0,0,0,0,0}, {443.9, 1350, 1350, 0,0,0,0,0,0}, {426.0, 1350, 1350, 0,0,0,0,0,0}, {434.1, 1350, 1350, 0,0,0,0,0,0}, {402.5, 1350, 1350, 0,0,0,0,0,0}, {357.4, 1350, 1350, 0,0,0,0,0,0}, {423, 720, 720, 0,0,0,0,0,0}, {220, 720, 720, 0,0,0,0,0,0}, {369.4, 2700, 2700, 0,0,0,0,0,0}, {273.5, 1500, 1500, 0,0,0,0,0,0}, {336, 1656, 1656, 0,0,0,0,0,0}, {432, 2160, 2160, 0,0,0,0,0,0}, {220, 900, 900, 0,0,0,0,0,0}, {410.6, 1200, 1200, 0,0,0,0,0,0}, {422.7, 1200, 1200, 0,0,0,0,0,0}, {351, 1014, 1014, 0,0,0,0,0,0}, {296, 1014, 1014, 0,0,0,0,0,0}, {411.1, 1014, 1014, 0,0,0,0,0,0}, {263.2, 1014, 1014, 0,0,0,0,0,0}, {370.3, 1350, 1350, 0,0,0,0,0,0}, {418.7, 1350, 1350, 0,0,0,0,0,0}, {409.6, 1350, 1350, 0,0,0,0,0,0}, {412, 1350, 1350, 0,0,0,0,0,0}, {423.2, 780, 780, 0,0,0,0,0,0}, {428, 1650, 1650,230,255,365,395,430,455}, {436, 1650, 1650, 0,0,0,0,0,0}, {428, 1650, 1650, 0,0,0,0,0,0}, {425, 1650, 1650, 0,0,0,0,0,0}, {497.2, 1620, 1620, 0,0,0,0,0,0}, {510, 1482, 1482, 0,0,0,0,0,0}, {470, 1482, 1482, 0,0,0,0,0,0}, {464.1, 1668, 1668, 0,0,0,0,0,0}, {118.1, 120, 120, 0,0,0,0,0,0}, {141.3, 180, 180, 0,0,0,0,0,0}, {132, 120, 180, 0,0,0,0,0,0}, {135, 120, 180, 0,0,0,0,0,0}, {252, 120, 180, 0,0,0,0,0,0}, {221, 120, 180, 0,0,0,0,0,0}, {245.9, 318, 318, 0,0,0,0,0,0}, {247.9, 318, 318, 0,0,0,0,0,0}, {183.6, 318, 318, 0,0,0,0,0,0}, {288, 318, 318, 0,0,0,0,0,0}, {557.4, 18, 18, 0,0,0,0,0,0}, {529.5, 18, 18, 0,0,0,0,0,0}, {800.8, 36, 36, 0,0,0,0,0,0}, {801.5, 36, 36, 0,0,0,0,0,0}, {582.7, 138, 204, 0,0,0,0,0,0}, {680.7, 144, 216, 0,0,0,0,0,0}, {670.7, 144, 216, 0,0,0,0,0,0}, {651.7, 144, 216, 0,0,0,0,0,0}, {921, 48, 48, 0,0,0,0,0,0}, {916.8, 48, 48, 0,0,0,0,0,0}, {911.9, 36, 54, 0,0,0,0,0,0}, {898, 36, 54, 0,0,0,0,0,0}, {905, 30, 30, 0,0,0,0,0,0}, {846.5, 30, 30, 0,0,0,0,0,0}, {850.9, 30, 30, 0,0,0,0,0,0}, {843.7, 30, 30, 0,0,0,0,0,0}, {841.4, 36, 36, 0,0,0,0,0,0}, {835.7, 36, 36, 0,0,0,0,0,0}, {828.8, 36, 36, 0,0,0,0,0,0}, {846, 36, 36, 0,0,0,0,0,0}, {179, 120, 120, 0,0,0,0,0,0}, {120.8, 120, 120, 0,0,0,0,0,0}, {121, 120, 120, 0,0,0,0,0,0}, {317.4, 480, 480, 0,0,0,0,0,0}, {318.4, 480, 480, 0,0,0,0,0,0}, {335.8, 480, 480, 0,0,0,0,0,0}, {151, 240, 240, 0,0,0,0,0,0}, {129.5, 240, 240, 0,0,0,0,0,0}, {130, 120, 120, 0,0,0,0,0,0}, {218.9, 180, 180, 0,0,0,0,0,0}, {5.4, 90, 90, 0,0,0,0,0,0}, {45, 90, 90, 0,0,0,0,0,0}, {20, 300, 300, 0,0,0,0,0,0}, {16.3, 162, 162, 0,0,0,0,0,0}, {20, 114, 114, 0,0,0,0,0,0}, {22.1, 120, 120, 0,0,0,0,0,0}, {125, 1080, 1080, 0,0,0,0,0,0}, {10, 60, 60, 0,0,0,0,0,0}, {13, 66, 66, 0,0,0,0,0,0}, {7.5, 12, 6, 0,0,0,0,0,0}, {53.2, 300, 300, 0,0,0,0,0,0}, {6.4, 6, 6, 0,0,0,0,0,0}, {69.1, 60, 60, 0,0,0,0,0,0}, {49.9, 60, 60, 0,0,0,0,0,0}, {91, 528, 528,50,75,85,95,0,0}, {41, 300, 300, 0,0,0,0,0,0}, {13.7, 18, 30, 0,0,0,0,0,0}, {7.4, 18, 30, 0,0,0,0,0,0}, {28.6, 72, 120, 0,0,0,0,0,0}}; private static double[][] Data3 ={{5, 700, 0.080}, {10, 600, 0.055}, {15, 800, 0.060}, {22, 600, 0.050}, {33, 600, 0.043}, {40, 600, 0.043}, {52, 1100, 0.043}, {70, 1200, 0.030}, {72, 1000, 0.050}, {84, 1000, 0.050}, {119,600, 0.070}, {121,1200, 0.043}}; private static double[][] Data4 = {{ 8, 250, 280, 305, 335, 420, 450}, {32, 220, 250, 320, 350, 390, 420}, {74, 230, 255, 365, 395, 430, 455}, {136,50, 75, 85, 95, 0, 0}}; //% Loss Co-efficients private static double[][] B1={ }; private static double[] B2={}; private static double B3=0; private static double Power_Demand = 49342;; // in MW private static int Pmin_data1_col=0;// = Data1(:,1)'; private static int Pmax_data1_col=1;// = Data1(:,2)'; private static int a_data1_col=4; private static int b_data1_col=3; private static int c_data1_col=2; private static int e_data1_col=5; private static int f_data1_col=6; private static int Initial_Generations_data2_col=0; private static int Up_Ramp_data2_col=1; private static int Down_Ramp_data2_col=2; public CEC2011_Problem_11_7_ELD_140() { super(140,4); lowerLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, 0.0)); upperLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, 0.0)); for (int z=0; z<numberOfDimensions; z++) { lowerLimit.set(z, Data1[z][0]); upperLimit.set(z, Data1[z][1]); } name = "RWP_11_7_ELD_140"; description = "RWP_11_7_ELD_140 Static Economic Load Dispatch (ELD) Problem "; } private double produkt(double x[], double y[]) { double t=0; for (int i=0;i<x.length; i++) { t+=x[i]*y[i]; } return t; } private double[] produkt2(double x[],double y[][]) { double t[]=new double[numberOfDimensions]; //dim?? for (int i=0;i<x.length; i++) { double tt=0; for (int ii=0;ii<x.length; ii++) { tt+=x[i]*y[ii][i]; } t[i]=tt; } return t; } protected double sum(double x[]) { double tt=0; for (int ii=0;ii<x.length; ii++) { tt+=x[ii]; } return tt; } public static double Up_Ramp_Limit(int i) { //System.out.println("Pmax "+Data1[i][Pmax_data1_col]+" Initial_Generations:"+Data2[i][Initial_Generations_data2_col]+" Up_Ramp:"+Data2[i][Up_Ramp_data2_col]+" "+Data2[i][Initial_Generations_data2_col]+Data2[i][Up_Ramp_data2_col]); return Math.min(Data1[i][Pmax_data1_col],Data2[i][Initial_Generations_data2_col]+Data2[i][Up_Ramp_data2_col]); } //Down_Ramp_Limit = max(Pmin,Initial_Generations-Down_Ramp); public static double Down_Ramp_Limit(int i) { return Math.max(Data1[i][Pmin_data1_col],Data2[i][Initial_Generations_data2_col]-Data2[i][Down_Ramp_data2_col]); } public static int No_of_POZ_Limits() { //System.out.println(Data2[0].length-4+1); return Data2[0].length-4+1; } public static double Prohibited_Operating_Zones_POZ(int i, int j) { //y,x //System.out.println("D2="+D2+" len:"+Data2.length); return Data2[j][3+i]; } public static double POZ_Lower_Limits(int i, int j) { return Prohibited_Operating_Zones_POZ(i*2,j); } public static double POZ_Upper_Limits(int i, int j) { return Prohibited_Operating_Zones_POZ(i*2+1,j); } public double[] calc_constrains(double x[]) { g_constrains = new double[numberOfConstraints]; double Power_Loss = 0; double Power_Balance_Penalty = Math.abs(Power_Demand + Power_Loss - sum(x)); double Capacity_Limits_Penalty=0; for (int i=0; i<numberOfDimensions; i++) { //Capacity_Limits_Penalty = sum(abs(x-Pmin)-(x-Pmin)) + sum(abs(Pmax-x)-(Pmax-x)); Capacity_Limits_Penalty+=Math.abs(x[i]-Data1[i][Pmin_data1_col])-(x[i]-Data1[i][Pmin_data1_col]); //sum(abs(x-Pmin)-(x-Pmin)) Capacity_Limits_Penalty+=Math.abs(Data1[i][Pmax_data1_col]-x[i])-(Data1[i][Pmax_data1_col]-x[i]); //sum(abs(Pmax-x)-(Pmax-x)) } double Ramp_Limits_Penalty=0; for (int i=0; i<numberOfDimensions; i++) { // Ramp_Limits_Penalty = sum(abs(x-Down_Ramp_Limit)-(x-Down_Ramp_Limit)) + sum(abs(Up_Ramp_Limit-x)-(Up_Ramp_Limit-x)); Ramp_Limits_Penalty+=Math.abs(x[i]-Down_Ramp_Limit(i))-(x[i]-Down_Ramp_Limit(i)); //sum(abs(x-Down_Ramp_Limit)-(x-Down_Ramp_Limit)) Ramp_Limits_Penalty+=Math.abs(Up_Ramp_Limit(i)-x[i])-(Up_Ramp_Limit(i)-x[i]); //sum(abs(Up_Ramp_Limit-x)-(Up_Ramp_Limit-x)); } // System.out.println("Ramp_Limits_Penalty="+Ramp_Limits_Penalty); double POZ_Penalty=0; //temp_x = repmat(x,No_of_POZ_Limits/2,1); //POZ_Penalty = sum(sum((POZ_Lower_Limits<temp_x & temp_x<POZ_Upper_Limits).*min(temp_x-POZ_Lower_Limits,POZ_Upper_Limits-temp_x))); for (int j=0; j<No_of_POZ_Limits()/2; j++) { for (int i=0; i<numberOfDimensions; i++) { if ((POZ_Lower_Limits(j,i)<x[i]) && (x[i]<POZ_Upper_Limits(j,i))) { POZ_Penalty+=Math.min(x[i]-POZ_Lower_Limits(j, i), POZ_Upper_Limits(j, i)-x[i]); } } } g_constrains[0] = 1e7*Power_Balance_Penalty; g_constrains[1] = 1e5*Capacity_Limits_Penalty; g_constrains[2] = 1e7*Ramp_Limits_Penalty ; g_constrains[3] = 1e5*POZ_Penalty ; return g_constrains; //do I need deep copy? } public double eval(double x[]) { double f = 0,ff; for (int i=0; i<numberOfDimensions; i++) { ff=Data1[i][a_data1_col]*x[i]*x[i]+Data1[i][b_data1_col]*x[i]+Data1[i][c_data1_col]+Math.abs(Data1[i][e_data1_col]*Math.sin(Data1[i][e_data1_col]*(Data1[i][Pmin_data1_col]-x[i]))); //System.out.print(ff+" "); f+=ff; } //System.out.println(); // System.out.println("f:"+f+" Total_Penalty:"+Total_Penalty); return f; } public double eval11(double x[]) { double f = 0,ff; System.out.print("a "); for (int i=0; i<20; i++) { System.out.print(Data1[i][a_data1_col]+" "); } System.out.println(); for (int i=0; i<20; i++) { ff=Data1[i][a_data1_col]*x[i]*x[i]+Data1[i][b_data1_col]*x[i]+Data1[i][c_data1_col]+Math.abs(Data1[i][e_data1_col]*Math.sin(Data1[i][e_data1_col]*(Data1[i][Pmin_data1_col]-x[i]))); System.out.print(ff+" "); f+=ff; } System.out.println(); // System.out.println("f:"+f+" Total_Penalty:"+Total_Penalty); return f; } @Override public double eval(Double[] ds) { return eval(ArrayUtils.toPrimitive(ds)); } public double getOptimumEval() { return 0; //OK } }
scrmtrey91/EARS
src/org/um/feri/ears/problems/real_world/cec2011/CEC2011_Problem_11_7_ELD_140.java
Java
gpl-3.0
25,259
<?php require_once ('./application/class/mercadopago.php'); require_once '../aplication/class/dbConn.php'; class confirmacionPago { public function __construct() { $data = self::getTokenYIdMercado(); $mp = new MP($data['idMercado'], $data['tokenMercado']); $mp->sandbox_mode(TRUE); $payment_info = $mp->get_payment_info($_GET["id"]); if ($payment_info["status"] == 200) { print_r($payment_info["response"]); $sql = "INSERT INTO `pagos`(`data`) VALUES ('" . $payment_info["status"] . "');"; $db = new dbConn; $db->query($sql); } } public function getTokenYIdMercado() { try { $db = new dbConn; $err = ''; } catch (PDOException $e) { $err = "Error: " . $e->getMessage(); } $stmt = $db->conn->query("SELECT * FROM `Configuracion` LIMIT 1;"); $result = $stmt->fetch_assoc(); return $result; } }
Nahuel-BM/Celtis-Tala
application/controllers/confirmacionPago.php
PHP
gpl-3.0
1,004
<?php /** * @In the name of God! * @author: Iman Moodi (Iman92) * @email: info@apadanacms.ir * @link: http://www.apadanacms.ir * @license: http://www.gnu.org/licenses/ * @copyright: Copyright © 2012-2015 ApadanaCms.ir. All rights reserved. * @Apadana CMS is a Free Software */ defined('security') or exit('Direct Access to this location is not allowed.'); member::check_admin_page_access('cache') or warning('عدم دسترسی!', 'شما دسترسی لازم برای مشاهده این بخش را ندارید!'); function _index() { global $tpl, $options, $page; set_title('مدیریت کش'); $itpl = new template('engine/admin/template/cache.tpl'); $handle = opendir(engine_dir.'cache'); while ($file = readdir($handle)) { if (get_extension($file) == 'cache') { $cachedFile = engine_dir.'cache/'.$file; $itpl->add_for('cache', array( '{odd-even}' => odd_even(), '{name}' => apadana_substr($file, 0, -6), '{time}' => get_past_time(filemtime($cachedFile)) )); $is_cache = true; } } closedir($handle); unset($handle, $file); if (isset($is_cache)) { $itpl->assign(array( '[cache]' => null, '[/cache]' => null, )); $itpl->block('#\\[not-cache\\](.*?)\\[/not-cache\\]#s', ''); } else { $itpl->assign(array( '[not-cache]' => null, '[/not-cache]' => null, )); $itpl->block('#\\[cache\\](.*?)\\[/cache\\]#s', ''); } if (is_ajax()) { $itpl->display(); define('no_template', true); } else { set_content(false, $itpl->get_var()); } unset($itpl); } function _delete() { $name = get_param($_GET, 'name'); $name = alphabet($name); if (!empty($name)) { remove_cache($name); echo message('کش <b>'.$name.'</b> حذف شد!', 'success'); } else { $handle = opendir(engine_dir.'cache'); while ($file = readdir($handle)) { if (get_extension($file) == 'cache') { $cachedFile = engine_dir.'cache/'.$file; @unlink($cachedFile); } } closedir($handle); unset($handle, $file); echo message('فایل های کش حذف شدند!', 'success'); } _index(); } $_GET['do'] = get_param($_GET, 'do'); switch($_GET['do']) { case 'delete': _delete(); break; default: _index(); break; } ?>
Apadana/apadana-cms
engine/admin/modules/cache.php
PHP
gpl-3.0
2,326
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>phpCAS: docs/examples/example_lang.php Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <div class="header"> <div class="headertitle"> <h1>docs/examples/example_lang.php</h1> </div> </div> <div class="contents"> <a href="example__lang_8php.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 &lt;?php <a name="l00002"></a>00002 <a name="l00003"></a>00003 <span class="comment">//</span> <a name="l00004"></a>00004 <span class="comment">// phpCAS simple client configured with another language</span> <a name="l00005"></a>00005 <span class="comment">//</span> <a name="l00006"></a>00006 <a name="l00007"></a>00007 <span class="comment">// import phpCAS lib</span> <a name="l00008"></a>00008 include_once(<span class="stringliteral">&#39;CAS.php&#39;</span>); <a name="l00009"></a>00009 <a name="l00010"></a>00010 <span class="comment">// initialize phpCAS</span> <a name="l00011"></a>00011 <a class="code" href="group__publicInit.html#gaac131c0cead58496e2239ed2ccbcecef">phpCAS::client</a>(<a class="code" href="group__public.html#ga33db27557b9b055f0cff75481f46a4bc">CAS_VERSION_2_0</a>,<span class="stringliteral">&#39;sso-cas.univ-rennes1.fr&#39;</span>,443,<span class="stringliteral">&#39;&#39;</span>); <a name="l00012"></a>00012 <a name="l00013"></a>00013 <span class="comment">// no SSL validation for the CAS server</span> <a name="l00014"></a>00014 <a class="code" href="group__publicAuth.html#gacff185b5b08e4ff603d0f6f1cb76e4ce">phpCAS::setNoCasServerValidation</a>(); <a name="l00015"></a>00015 <a name="l00016"></a>00016 <span class="comment">// set the language to french</span> <a name="l00017"></a>00017 <a class="code" href="group__publicLang.html#ga7eea67859bdfac8e89460a95f5bc961e">phpCAS::setLang</a>(<a class="code" href="group__publicLang.html#ga2625c23a266bd8018ac7ed2dd8bc592c">PHPCAS_LANG_FRENCH</a>); <a name="l00018"></a>00018 <a name="l00019"></a>00019 <span class="comment">// force CAS authentication</span> <a name="l00020"></a>00020 <a class="code" href="group__publicAuth.html#ga78e2d918ae65a0ff649e755a34ed9bf3">phpCAS::forceAuthentication</a>(); <a name="l00021"></a>00021 <a name="l00022"></a>00022 <span class="comment">// at this step, the user has been authenticated by the CAS server</span> <a name="l00023"></a>00023 <span class="comment">// and the user&#39;s login name can be read with phpCAS::getUser().</span> <a name="l00024"></a>00024 <a name="l00025"></a>00025 <span class="comment">// moreover, a PGT was retrieved from the CAS server that will</span> <a name="l00026"></a>00026 <span class="comment">// permit to gain accesses to new services.</span> <a name="l00027"></a>00027 <a name="l00028"></a>00028 <span class="comment">// for this test, simply print that the authentication was successfull</span> <a name="l00029"></a>00029 ?&gt; <a name="l00030"></a>00030 &lt;html&gt; <a name="l00031"></a>00031 &lt;head&gt; <a name="l00032"></a>00032 &lt;title&gt;Exemple d<span class="stringliteral">&#39;internationalisation de phpCAS&lt;/title&gt;</span> <a name="l00033"></a>00033 <span class="stringliteral"> &lt;/head&gt;</span> <a name="l00034"></a>00034 <span class="stringliteral"> &lt;body&gt;</span> <a name="l00035"></a>00035 <span class="stringliteral"> &lt;h1&gt;Authentification r&amp;eacute;ussie&amp;nbsp;!&lt;/h1&gt;</span> <a name="l00036"></a>00036 <span class="stringliteral"> &lt;p&gt;L&#39;</span>utilisateur connect&amp;eacute; est &lt;b&gt;&lt;?php echo <a class="code" href="group__publicAuth.html#ga4c9f984b474b550cf316396e87670b18">phpCAS::getUser</a>(); ?&gt;&lt;/b&gt;.&lt;/p&gt; <a name="l00037"></a>00037 &lt;p&gt;La version de <a class="code" href="classphpCAS.html">phpCAS</a> est &lt;b&gt;&lt;?php echo <a class="code" href="group__public.html#ga5c971143e0c319b1268233907ca193b9">phpCAS::getVersion</a>(); ?&gt;&lt;/b&gt;.&lt;/p&gt; <a name="l00038"></a>00038 &lt;/body&gt; <a name="l00039"></a>00039 &lt;/html&gt; </pre></div></div> </div> <hr class="footer"/><address class="footer"><small>Generated on Sat Mar 26 2011 12:11:03 for phpCAS by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
REI-Systems/GovDashboard-Community
webapp/sites/all/libraries/CAS/docs/api/example__lang_8php_source.html
HTML
gpl-3.0
5,372
// Copyright © 2011-2015 Yanick Castonguay // // This file is part of Sessions, a music player for musicians. // // Sessions 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. // // Sessions 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 Sessions. If not, see <http://www.gnu.org/licenses/>. using System; using System.IO; using System.Linq; using System.Timers; using ObjCRuntime; using org.sessionsapp.player; using UIKit; namespace playersampleiosxamarin { public partial class PlayerViewController : UIViewController { private Timer _timerRefreshPosition; private static SSPPosition _length; private LogDelegate _logDelegate; private StateChangedDelegate _stateChangedDelegate; private PlaylistIndexChangedDelegate _playlistIndexChangedDelegate; private AudioInterruptedDelegate _audioInterruptedDelegate; // TOOD: Find a way to use the IntPtr user parameter instead static PlayerViewController CurrentViewController { get; set; } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public PlayerViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); CurrentViewController = this; InitializePlayer(); _timerRefreshPosition = new Timer(100); _timerRefreshPosition.Elapsed += HandleTimerRefreshPositionElapsed; } private void InitializePlayer() { int version = SSP.SSP_GetVersion(); lblVersion.Text = string.Format("Version {0}", version); Console.WriteLine("libssp_player version: {0}", version); int error = SSP.SSP_Init(null); if (error != SSP.SSP_OK) { Console.WriteLine("libssp_player init failed with error code: {0}", error); return; } _logDelegate = new LogDelegate(HandleLog); _stateChangedDelegate = new StateChangedDelegate(HandleStateChanged); _playlistIndexChangedDelegate = new PlaylistIndexChangedDelegate(HandlePlaylistIndexChanged); _audioInterruptedDelegate = new AudioInterruptedDelegate(HandleAudioInterrupted); SSP.SSP_SetLogCallback(_logDelegate, IntPtr.Zero); SSP.SSP_SetStateChangedCallback(_stateChangedDelegate, IntPtr.Zero); SSP.SSP_SetPlaylistIndexChangedCallback(_playlistIndexChangedDelegate, IntPtr.Zero); SSP.SSP_SetAudioInterruptedCallback(_audioInterruptedDelegate, IntPtr.Zero); error = SSP.SSP_InitDevice(-1, 44100, 1000, 100, true); if (error != SSP.SSP_OK) { Console.WriteLine("libssp_player init device failed with error code: {0}", error); return; } error = SSP.SSP_IOS_ConfigureAirPlay(true); if (error != SSP.SSP_OK) { Console.WriteLine("libssp_player failed to configure AirPlay with error code: {0}", error); return; } error = SSP.SSP_IOS_ConfigureAudioInterruptionNotification(true); if (error != SSP.SSP_OK) { Console.WriteLine("libssp_player failed to configure audio interruption notification with error code: {0}", error); return; } var device = new SSP_DEVICE(); SSP.SSP_GetDevice(ref device); Console.WriteLine("libssp_player init successful!"); } private void HandleTimerRefreshPositionElapsed(object sender, ElapsedEventArgs e) { var position = new SSPPosition(); SSP.SSP_GetPosition(ref position.Struct); InvokeOnMainThread(() => { lblPosition.Text = string.Format("Position: {0} / {1}", position.Str, _length.Str); }); } [MonoPInvokeCallback(typeof(LogDelegate))] private static void HandleLog(IntPtr user, string str) { Console.WriteLine("libssp_player :: {0}", str); } [MonoPInvokeCallback(typeof(StateChangedDelegate))] private static void HandleStateChanged(IntPtr user, SSPPlayerState state) { CurrentViewController.InvokeOnMainThread(() => { CurrentViewController.lblState.Text = string.Format("State: {0}", state); }); } [MonoPInvokeCallback(typeof(PlaylistIndexChangedDelegate))] private static void HandlePlaylistIndexChanged(IntPtr user) { var item = new SSPPlaylistItem(); int index = SSP.SSP_Playlist_GetCurrentIndex(); int count = SSP.SSP_Playlist_GetCount(); SSP.SSP_Playlist_GetItemAt(index, ref item.Struct); var length = new SSPPosition(); SSP.SSP_GetPositionFromBytes(item.Length, ref length.Struct); _length = length; CurrentViewController.InvokeOnMainThread(() => { CurrentViewController.lblPlaylist.Text = string.Format("Playlist [{0}/{1}]", index+1, count); CurrentViewController.lblFilePath.Text = string.Format("File path: {0}", item.FilePath); }); } [MonoPInvokeCallback(typeof(AudioInterruptedDelegate))] private static void HandleAudioInterrupted(IntPtr user, bool ended) { Console.WriteLine("libssp_player -- Audio has been interrupted; ended: {0}", ended); } partial void buttonPlay_TouchUpInside(UIButton sender) { SSP.SSP_Playlist_Clear(); var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string[] extensions = { ".mp3", ".flac", ".ape", ".wav", ".ogg", ".mpc", ".wv" }; foreach (string file in Directory.EnumerateFiles(documents, "*.*", SearchOption.AllDirectories) .Where(s => extensions.Any(ext => ext == Path.GetExtension(s)))) { SSP.SSP_Playlist_AddItem(file, string.Empty); } SSP.SSP_Play(); _timerRefreshPosition.Start(); } partial void buttonPause_TouchUpInside(UIButton sender) { SSP.SSP_Pause(); } partial void buttonStop_TouchUpInside(UIButton sender) { SSP.SSP_Stop(); } partial void buttonPrevious_TouchUpInside(UIButton sender) { SSP.SSP_Previous(); } partial void buttonNext_TouchUpInside(UIButton sender) { SSP.SSP_Next(); } private void CheckForError(int error) { if (error != SSP.SSP_OK) { Console.WriteLine("SSP Error: {0}", error); } } } }
ycastonguay/libssp_player
player-sample-ios-xamarin/PlayerViewController.cs
C#
gpl-3.0
7,452
<?php /** * This file is part of GESSEH project * * @author: Pierre-François ANGRAND <gesseh@medlibre.fr> * @copyright: Copyright 2017 Pierre-François Angrand * @license: GPLv3 * See LICENSE file or http://www.gnu.org/licenses/gpl.html */ namespace Gesseh\RegisterBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request, Symfony\Component\HttpFoundation\ResponseHeaderBag; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use JMS\DiExtraBundle\Annotation as DI, JMS\SecurityExtraBundle\Annotation as Security; use Gesseh\RegisterBundle\Entity\Partner, Gesseh\RegisterBundle\Form\PartnerType, Gesseh\RegisterBundle\Form\PartnerHandler; /** * RegisterBundle PartnerController * * @Route("/") */ class PartnerController extends Controller { /** @DI\Inject */ private $session; /** @DI\Inject("doctrine.orm.entity_manager") */ private $em; /** @DI\Inject("fos_user.user_manager") */ private $um; /** @DI\Inject("kdb_parameters.manager") */ private $pm; /** * @Route("/partners", name="GRegister_PaIndex") * @Security\Secure(roles="ROLE_ADMIN") * @Template() */ public function indexAction() { $partners = $this->em->getRepository('GessehRegisterBundle:Partner')->findAll(); return array( 'partners' => $partners, ); } /** * @Route("/partner/{id}", name="GRegister_PaEdit", requirements={"id" = "\d+"}) * @Security\Secure(roles="ROLE_ADMIN") * @Template() */ public function editAction(Request $request, Partner $partner = null) { $questions = $this->em->getRepository('GessehRegisterBundle:MemberQuestion')->findAll(); $form = $this->createForm(new PartnerType(), $partner, array('questions' => $questions)); $form_handler = new PartnerHandler($form, $request, $this->em, $this->um); if ($form_handler->process()) { $this->session->getFlashBag()->add('notice', 'Partenaire ' . $partner . ' enregistré.'); return $this->redirect($this->generateUrl('GRegister_PaIndex')); } return array( 'form' => $form->createView(), 'partner' => $partner, ); } /** * @Route("/partner/{id}/delete", name="GRegister_PaDelete", requirements={"id" = "\d+"}) * @Security\Secure(roles="ROLE_ADMIN") */ public function deleteAction(Partner $partner) { $this->em->remove($partner); $this->em->flush(); $this->session->getFlashBag()->add('notice', 'Partenaire ' . $partner . ' supprimé.'); return $this->redirect($this->generateUrl('GRegister_PaIndex')); } }
CaraGk/gesseh
src/Gesseh/RegisterBundle/Controller/PartnerController.php
PHP
gpl-3.0
2,826
#pragma once #include <fstream> #include <map> #include <string> using namespace std; class IniSimpleParser { private: ifstream input_file_; ofstream output_file_; map<string, string> settings_pairs_; bool is_content_available(string& content); string parse_key(string& content, int& seperator_pos); string parse_value(string& content, int start_pos); public: IniSimpleParser(); ~IniSimpleParser(); bool parse(const char* file_path); bool get_value(const string& key, string& value); void set_value(const string& key, const string& value); bool write(const char* file_path); static void lower_convert(string& str); };
BUPTSSE-Zero/Dream-Gobang
src/tools/IniSimpleParser.h
C
gpl-3.0
637
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'qtype_calculatedmulti', language 'de', branch 'MOODLE_22_STABLE' * * @package qtype_calculatedmulti * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['pluginname'] = 'Berechnete Multiple-Choice-Frage'; $string['pluginname_help'] = 'Berechnete Multiple-Choice-Fragen entsprechen normalen MultipleChoice-Fragen, können aber zusätzlich Variablen in geschweiften Klammern (Wildcards) enthalten. In diese Variablen werden bei der Testdurchführung gegen zufällige Zahlen aus der Wertemenge eingesetzt. Beispiel: Auf die Frage "Welche Fläche hat ein Rechteck mit der Länge {l} und der Breite {b}?" wäre die Antwort "{={l}*{b}}". Der Stern (*) steht für die Multiplikation.'; $string['pluginnameadding'] = 'Berechnete Multiple-Choice-Frage hinzufügen'; $string['pluginnameediting'] = 'Berechnete Multiple-Choice-Frage bearbeiten'; $string['pluginnamesummary'] = 'Berechnete Multiple-Choice-Fragen können Variablen enthalten, in die bei der Testdurchführung zufällige Zahlen aus der Wertemenge eingesetzt werden.';
danielbonetto/twig_MVC
lang/de/qtype_calculatedmulti.php
PHP
gpl-3.0
1,886
.PHONY:clean TARGETS = foobar.db all: $(TARGETS) foobar.db: create_database.sql fill_database.sql sqlite3 $@ < create_database.sql sqlite3 $@ < fill_database.sql clean: find . -name "octave-workspace" -exec rm {} \; rm -f $(TARGETS)
Andy1978/octave-sqlite
test/Makefile
Makefile
gpl-3.0
241
<!DOCTYPE html SYSTEM "about:legacy-compat"> <html lang="en-us"> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"><meta name="copyright" content="(C) Copyright 2015"> <meta name="DC.rights.owner" content="(C) Copyright 2015"> <meta name="DC.Type" content="reference"> <meta name="description" content="In addition to error messages generated by the DITA Open Toolkit, you might also encounter error messages generated by Java or other tools."><meta name="DC.Relation" scheme="URI" content="../user-guide/troubleshooting-overview.html"> <meta name="DC.Format" content="XHTML"> <meta name="DC.Identifier" content="troubleshooting"> <meta name="DC.Language" content="en-us"> <link rel="stylesheet" type="text/css" href="../css/commonltr.css"> <link rel="stylesheet" type="text/css" href="../css/dita-ot-doc.css"> <title>Other error messages</title> </head> <body id="troubleshooting"> <main role="main"><article role="article" aria-labelledby="ariaid-title1"> <h1 class="title topictitle1" id="ariaid-title1">Other error messages</h1> <div class="body refbody"><p class="shortdesc">In addition to error messages generated by the DITA Open Toolkit, you might also encounter error messages generated by Java or other tools.</p> <section class="section" id="troubleshooting__section_stj_4gj_wd"><h2 class="title sectiontitle">Out of Memory error</h2> <p class="p">In some cases, you might receive a message stating the build has failed due to an <samp class="ph msgph">Out of Memory</samp> error. Try the following approaches to resolve the problem:</p> <ol class="ol" id="troubleshooting__ol_rfb_c2p_qg"> <li class="li">Increase the memory available to Java; see <a class="xref" href="increasing-the-jvm.html" title="If you are working with large documents with extensive metadata or key references, you will need to increase the memory allocation for the Java process. You can do this from the command-line prompt for a specific session, or you can increase the value of the ANT_OPTS environment variable.">Increasing Java memory allocation</a>.</li> <li class="li">Reduce memory consumption by setting the <span class="keyword option">generate-debug-attributes</span> option to <samp class="ph codeph">false</samp>. This option is set in the <span class="ph filepath">lib/configuration.properties</span> file. This will disable debug attribute generation (used to trace DITA-OT error messages back to source files) and will reduce memory consumption.</li> <li class="li">Set <samp class="ph codeph">dita.preprocess.reloadstylesheet</samp> Ant property to <samp class="ph codeph">true</samp>. This will allow the XSLT processor to release memory when converting multiple files.</li> <li class="li">Run the transformation again.</li> </ol> </section> <section class="section"><h2 class="title sectiontitle">java.io.IOException: Can't store Document</h2> <p class="p">After running a JavaHelp transformation, you may receive a <samp class="ph msgph">java.io.IOException: Can't store Document</samp> message. </p> <p class="p">This problem occurs when HTML files unrelated to the current transformation are found in the output directory. Delete the content of the output directory and run the transformation again.</p> </section> <section class="section"><h2 class="title sectiontitle">Stack Overflow error</h2> <p class="p">If you receive an error about a stack memory overflow, increase the JVM and run the transformation again. See <a class="xref" href="increasing-the-jvm.html" title="If you are working with large documents with extensive metadata or key references, you will need to increase the memory allocation for the Java process. You can do this from the command-line prompt for a specific session, or you can increase the value of the ANT_OPTS environment variable.">Increasing Java memory allocation</a>.</p> </section> </div> <nav role="navigation" class="related-links"> <div class="familylinks"> <div class="parentlink"><strong>Parent topic:</strong> <a class="link" href="../user-guide/troubleshooting-overview.html" title="This section contains information about problems that you might encounter and how to resolve them.">Error messages and troubleshooting</a></div> </div> </nav></article></main></body> </html>
parson-AG/COMTecnica_2016
dita-rng/framework/DITA-OT/doc/user-guide/other-errors.html
HTML
gpl-3.0
4,494
package main import ( "future" "log" "time" ) // usage example // creating and using an asynchronous service func main() { server = startServer() startClients() var never chan struct{} <-never } const ( latencyFactor = 1 // latency of each service request numClients = 10 // number of concurrent clients loadFactor = 10 * numClients // load factor ) var server chan<- *asyncRequest // --- the clients ----------------------------------- func startClients() { for i := uint(0); i < numClients; i++ { go func(cid uint) { log.Printf("client %d started\n", cid) var n = 0 var tocnt = 0 var t0 time.Time = time.Now() for { // make the request and get the future.FutureResult // note: calling time.Now in loop significantly impacts // performance. sampled results values do not reflect // actual future usage perf. cost. fresult := callService(cid, time.Now()) // TryGet the future result // note: tryget & then get on timeout is non-optimal // used here only to show api usage result, timeout := fresult.TryGet(time.Microsecond * 10) if timeout { result = fresult.Get() // wait for it } // client 0 will dump its results as a sample if cid == 0 { switch { case timeout: tocnt++ case result.IsError(): /* nop - just api demo */ } n++ if n == 1000 { delta := time.Now().Sub(t0) log.Printf("(sample of %d) : %04d requests in %d nsec with %d timeouts\n", numClients, n, delta, tocnt) n = 0 tocnt = 0 t0 = time.Now() } } } }(i) } } // --- the service ----------------------------------- type asyncRequest struct { cid uint t0 time.Time fobj interface{} } func callService(cid uint, t0 time.Time) future.Future { // create the Future object fobj := future.NewUntypedFuture() // create an asyncRequest // server will use future object to post its response request := &asyncRequest{cid, time.Now(), fobj} // queue the request server <- request // Return the FutureResult of the Future object to the caller return fobj } func startServer() chan<- *asyncRequest { c := make(chan *asyncRequest) go func() { for { // process request queue or sleep if none pending // select { case request := <-c: // sleep for fake service latency time.Sleep(time.Duration(latencyFactor) * time.Nanosecond) // get the future object from the request fobj := request.fobj // result is just the delta of t0 of request and time now t0 := request.t0 delta := time.Now().Sub(t0) fobj.(future.Provider).SetValue(delta) default: time.Sleep(1 * time.Nanosecond) } } }() return c }
alphazero/future
example/async_service.go
GO
gpl-3.0
2,754
package dna.metrics.paths; import dna.graph.IElement; import dna.graph.nodes.Node; import dna.metrics.algorithms.IRecomputation; import dna.series.data.distributions.DistributionLong; public class UnweightedAllPairsShortestPathsR extends UnweightedAllPairsShortestPaths implements IRecomputation { public UnweightedAllPairsShortestPathsR() { super("UnweightedAllPairsShortestPathsR"); } @Override public boolean recompute() { this.apsp = new DistributionLong("APSP"); for (IElement n_ : this.g.getNodes()) { this.compute((Node) n_); } return true; } }
timgrube/DNA
src/dna/metrics/paths/UnweightedAllPairsShortestPathsR.java
Java
gpl-3.0
577
package SMM::Controller::API::Upload; use Moose; use JSON; BEGIN { extends 'Catalyst::Controller::REST' } __PACKAGE__->config( default => 'application/json' ); sub base : Chained('/api/base') : PathPart('upload') : CaptureArgs(0) { my ( $self, $c ) = @_; } 1;
eokoe/De-Olho-Nas-Metas
api/lib/SMM/Controller/API/Upload.pm
Perl
gpl-3.0
270
## awg_iq class # two channels of awgs and a local oscillator used to feed a single iq mixer # maximum settings of the current mixer that should not be exceeded import numpy as np import logging from .save_pkl import * from .config import get_config from matplotlib import pyplot as plt class awg_iq: """Interface for IQ modulation of RF signals wth two AWG channels. IQ modulation requires two low (intermediate) frequency arbitrary waveform generators for the I and Q connectors of the mixer and one for the LO input connector. Modulated signal is output at RF (radio frequency). Attributes: awg_I (:obj:`awg`): Instance of an AWG class (for example, Tektronix AWG5014C or AWG500) that is connected to the I input of the mixer. Should implement the methods get_nop, get_clock, set_clock, set_waveform, set_status, set_trigger_mode, run and stop. awg_Q (:obj:`awg`): Instance of an AWG class that is connected to the Q input of the mixer. awg_I and awg_Q are normaly the same device (I and Q are connected to different channels of the same device). awg_ch_I (int): Channel id of the device awg_I that is connected to the I connector of the mixer. awg_ch_Q (int): Channel id of the device awg_I that is connected to the Q connector of the mixer. lo (:obj:`psg`): Instance of a sinusodial signal generator. Should implement the methods get_frequency and set_frequency. """ def __init__(self, awg_I, awg_Q, awg_ch_I, awg_ch_Q, lo):#, mixer): """ """ self.awg_I = awg_I self.awg_Q = awg_Q self.awg_ch_I = awg_ch_I self.awg_ch_Q = awg_ch_Q self.lo = lo self._if = 0 self.frequency = lo.get_frequency() self.calibrations = {} self.sideband_id = 0 self.ignore_calibration_drift = False self.frozen = False #self.mixer = mixer #@property def get_nop(self): """int: Number of samples in segment.""" I_nop = self.awg_I.get_nop() Q_nop = self.awg_Q.get_nop() if I_nop != Q_nop: raise ValueError('Number of points in I channel awg and Q channel should coincide') return I_nop def get_clock(self): """int: Sample rate of I and Q channels (complex amplitude envelope).""" I_clock = self.awg_I.get_clock() Q_clock = self.awg_Q.get_clock() if I_clock != Q_clock: raise ValueError('Clock rate in I channel awg and Q channel should coincide') return I_clock def set_nop(self, nop): """int: Sets number of samples in segment.""" self.awg_I.set_nop(nop) self.awg_Q.set_nop(nop) def set_clock(self, clock): """Sets sampling rate.""" self.awg_I.set_clock(clock) self.awg_Q.set_clock(clock) def set_status(self, status): """Turns on and off the lo and awg channels.""" self.lo.set_status(status) self.awg_I.set_status(status, channel=self.awg_ch_I) self.awg_Q.set_status(status, channel=self.awg_ch_Q) def set_waveform_IQ_cmplx_raw(self, waveform_cmplx): self.__set_waveform_IQ_cmplx(waveform_cmplx) def __set_waveform_IQ_cmplx(self, waveform_cmplx): """Sets the real part of the waveform on the I channel and the imaginary part of the waveform on the Q channel. No intermediate frequency multiplication and mixer calibration corrections are performed. This is a low-level function that is normally only called for debugging purposes. Pulse sequence generators do not normally call this function, but rather sate_waveform.""" waveform_I = np.real(waveform_cmplx) waveform_Q = np.imag(waveform_cmplx) self.awg_I.stop() if self.awg_I != self.awg_Q: self.awg_Q.stop() self.awg_I.set_waveform(waveform_I, channel=self.awg_ch_I) self.awg_Q.set_waveform(waveform_Q, channel=self.awg_ch_Q) self.awg_I.run() if self.awg_I != self.awg_Q: self.awg_Q.run() #import matplotlib.pyplot as plt #plt.plot(waveform_I) #plt.plot(waveform_Q) #if np.any(np.abs(waveform_I)>1.0) or np.any(np.abs(waveform_Q)>1.0): #logging.warning('Waveform clipped!') def calib(self, cname): if self.ignore_calibration_drift: if cname not in self.calibrations: c = [calib for calib in self.calibrations.values()] return c[0] if cname not in self.calibrations: print ('Calibration not loaded. Use ignore_calibration_drift to use any calibration.') return self.calibrations[cname] def set_waveform(self, waveform_cmplx): """Sets the real part of the waveform on the I channel and the imaginary part of the waveform on the Q channel. This function multiplies the waveform with the intermediate frequency oscillation and sideband calibration amplitudes. he function accepts a complex waveform envelope and effectively forms a RF output waveform of the given envelope at the frequency given by the frequency attribute.""" t = np.linspace(0, self.get_nop()/self.get_clock(), self.get_nop(), endpoint=False) waveform_if = waveform_cmplx*np.exp(1j*2*np.pi*t*self.get_if()) waveform_I = np.real(self.calib(self.cname())['I']*waveform_if)+np.real(self.calib(self.cname())['dc']) waveform_Q = np.imag(self.calib(self.cname())['Q']*waveform_if)+np.imag(self.calib(self.cname())['dc']) self.__set_waveform_IQ_cmplx(waveform_I+1j*waveform_Q) self.waveform = waveform_cmplx return np.max([np.max(np.abs(waveform_I)), np.max(np.abs(waveform_Q))]) def get_waveform(self): return self.waveform def set_trigger_mode(self, mode): self.awg_I.set_trigger_mode(mode) self.awg_Q.set_trigger_mode(mode) # clip DC to prevent mixer damage def clip_dc(self, x): """Clips the dc complonent of the output at both channels of the AWG to prevent mixer damage.""" x = [np.real(x), np.imag(x)] for c in (0,1): if x[c] < -0.5: x[c] = -0.5 if x[c] > 0.5: x[c] = 0.5 x = x[0] + 1j * x[1] return x def _set_dc(self, x): """Clips the dc complonent of the output at both channels of the AWG to prevent mixer damage.""" x = self.clip_dc(x) self.__set_waveform_IQ_cmplx([x]*self.get_nop()) def _set_if_cw(self, dc, I, Q): """Sets a CW with arbitrary calibration. This functions is invoked by _calibrate_sa to find the optimal values of the I and Q complex amplitudes and dc offsets that correspond to the minimum SFDR.""" t = np.linspace(0, self.get_nop()/self.get_clock(), self.get_nop(), endpoint=False) dc = self.clip_dc(dc) waveform_I = np.real(I*np.exp(2*np.pi*1j*t*self.get_if()))+np.real(dc) waveform_Q = np.imag(Q*np.exp(2*np.pi*1j*t*self.get_if()))+np.imag(dc) self.__set_waveform_IQ_cmplx(waveform_I+1j*waveform_Q) return np.max([np.max(np.abs(waveform_I)), np.max(np.abs(waveform_Q))]) def cname(self): return ('if', self.get_if()), ('frequency', self.get_frequency()), ('sideband_id', self.sideband_id) def get_calibration(self, sa=None): """User-level function to sort out mxer calibration matters. Checks if there is a saved calibration for the given LO and IF frequencies and loads it. When invoked with a spectrum analyzer instance as an argument it perform and save the calibration with the current frequencies. """ calibration_path = get_config()['datadir']+'/calibrations/' filename = 'IQ-if{0:5.3g}-rf{1:5.3g}-sb-{2}'.format(self.get_if(), self.get_frequency(), self.sideband_id) try: self.calibrations[self.cname()] = load_pkl(filename, location=calibration_path) except Exception as e: if not sa: logging.error('No ready calibration found and no spectrum analyzer to calibrate') else: self._calibrate_cw_sa(sa) self.save_calibration() return self.calibrations[self.cname()] def save_calibration(self): calibration_path = get_config()['datadir']+'/calibrations/' print (calibration_path) filename = 'IQ-if{0:5.3g}-rf{1:5.3g}-sb-{2}'.format(self.get_if(), self.get_frequency(), self.sideband_id) save_pkl(None, self.calibrations[self.cname()], location=calibration_path, filename=filename, plot=False) def _calibrate_cw_sa(self, sa, num_sidebands = 7): """Performs IQ mixer calibration with the spectrum analyzer sa with the intermediate frequency.""" from scipy.optimize import fmin import time dc = self._calibrate_zero_sa(sa) res_bw = 1e5 video_bw = 1e4 if hasattr(sa, 'set_nop'): sa.set_centerfreq(self.lo.get_frequency()) sa.set_span((num_sidebands-1)*self.get_if()) sa.set_nop(num_sidebands) sa.set_detector('POS') sa.set_res_bw(res_bw) sa.set_video_bw(video_bw) self.set_trigger_mode('CONT') else: sa.set_detector('rms') sa.set_res_bw(res_bw) sa.set_video_bw(video_bw) sa.set_span(res_bw) sa.set_sweep_time_auto(1) self.lo.set_status(True) sideband_ids = np.asarray(np.linspace(-(num_sidebands-1)/2, (num_sidebands-1)/2, num_sidebands), dtype=int) self.awg_I.run() self.awg_Q.run() solution = [np.real(dc), np.imag(dc), 0.5, 0.5, 0.5, 0.5] for iter_id in range(1): def tfunc(x): dc = x[0] + x[1]*1j I = x[2] + x[3]*1j Q = x[4] + x[5]*1j max_amplitude = self._set_if_cw(dc, I, Q) if max_amplitude < 1: clipping = 0 else: clipping = (max_amplitude-1) # if we can measure all sidebands in a single sweep, do it if hasattr(sa, 'set_nop'): result = sa.measure()['Power'].ravel() else: # otherwise, sweep through each sideband result = [] for sideband_id in range(num_sidebands): sa.set_centerfreq(self.lo.get_frequency()+(sideband_id-(num_sidebands-1)/2.)*self.get_if()) print (sa.get_centerfreq()) #time.sleep(0.1) #result.append(np.log10(np.sum(10**(sa.measure()['Power']/10)))*10) result.append(np.log10(np.sum(sa.measure()['Power']))*10) #time.sleep(0.1) result = np.asarray(result) bad_power = np.sum(10**((result[sideband_ids != self.sideband_id])/20)) good_power = np.sum(10**((result[sideband_ids==self.sideband_id])/20)) bad_power_dbm = np.log10(bad_power)*20 good_power_dbm = np.log10(good_power)*20 print ('dc: {0: 4.2e}\tI: {1: 4.2e}\tQ:{2: 4.2e}\tB: {3:4.2f} G: {4:4.2f}, C:{5:4.2f}\r'.format(dc, I, Q, bad_power_dbm, good_power_dbm, clipping)) print (result) return -good_power/bad_power+np.abs(good_power/bad_power)*10*clipping solution = fmin(tfunc, solution, maxiter=75, xtol=2**(-14)) score = tfunc(solution) self.calibrations[self.cname()] = {'dc': self.clip_dc(solution[0]+solution[1]*1j), 'I': solution[2]+solution[3]*1j, 'Q': solution[4]+solution[5]*1j, 'score': score, 'num_sidebands': num_sidebands} return self.calibrations[self.cname()] def _calibrate_zero_sa(self, sa): """Performs IQ mixer calibration for DC signals at the I and Q inputs.""" import time from scipy.optimize import fmin print(self.lo.get_frequency()) res_bw = 1e5 video_bw = 1e4 sa.set_res_bw(res_bw) sa.set_video_bw(video_bw) sa.set_detector('rms') sa.set_centerfreq(self.lo.get_frequency()) sa.set_sweep_time(1e-3) #time.sleep(0.1) if hasattr(sa, 'set_nop'): sa.set_span(0) sa.set_nop(1) self.set_trigger_mode('CONT') else: sa.set_span(res_bw) self.lo.set_status(True) def tfunc(x): self.awg_I.stop() self.awg_Q.stop() self._set_dc(x[0]+x[1]*1j) self.awg_I.run() self.awg_Q.run() if hasattr(sa, 'set_nop'): result = sa.measure()['Power'].ravel()[0] else: #result = np.log10(np.sum(10**(sa.measure()['Power']/10)))*10 result = np.log10(np.sum(sa.measure()['Power']))*10 print (x, result) return result solution = fmin(tfunc, [0.3,0.3], maxiter=30, xtol=2**(-14)) x = self.clip_dc(solution[0]+1j*solution[1]) self.zero = x return x def set_if(self, _if): self._if = _if def get_if(self): return self._if def set_sideband_id(self, sideband_id): self.sideband_id = sideband_id def get_sideband_id(self): return self.sideband_id def set_frequency(self, frequency): self.lo.set_frequency(frequency-self.get_sideband_id()*self.get_if()) self.frequency = self.lo.get_frequency()+self.get_sideband_id()*self.get_if() def set_uncal_frequency(self, frequency): self.lo.set_frequency(frequency-self.get_sideband_id()*self.get_if()) def get_frequency(self): return self.frequency def freeze(self): self.frozen = True def unfreeze(self): if self.frozen: self.frozen = False #self.assemble_waveform()
ooovector/qtlab_replacement
awg_iq.py
Python
gpl-3.0
12,232
#!/usr/bin/env python # Bootstrap installation of Distribute from importlib import import_module import os, sys from distutils.core import setup from distutils.command.install import install from setuptools.command.develop import develop import subprocess # from subprocess import call # command = partial(subprocess.call, shell=True, stdout=sys.stdout, stdin=sys.stdin) def package_env(file_name, strict=False): file_path = os.path.join(os.path.dirname(__file__),file_name) if os.path.exists(file_path) or strict: return open(file_path).read() else: return u'' PACKAGE = u'public-forms' PROJECT = u'public_forms' PROJECT_SLUG = u'public_forms' VERSION = package_env('VERSION') URL = package_env('URL') AUTHOR_AND_EMAIL = [v.strip('>').strip() for v \ in package_env('AUTHOR').split('<mailto:')] if len(AUTHOR_AND_EMAIL)==2: AUTHOR, AUTHOR_EMAIL = AUTHOR_AND_EMAIL else: AUTHOR = AUTHOR_AND_EMAIL AUTHOR_EMAIL = u'' DESC = "feincms extension templated from django.contrib.skeleton.application" PACKAGE_NAMESPACE = [s for s in 'feincms.page.extensions'.strip()\ .strip('"')\ .strip("'")\ .strip()\ .split('.') if s] NSLIST = lambda sep:(sep.join(PACKAGE_NAMESPACE[:i+1]) for i,n in enumerate(PACKAGE_NAMESPACE)) PACKAGE_NAMESPACE_WITH_PACKAGE = PACKAGE_NAMESPACE + [PROJECT_SLUG,] NSLIST_WITH_PACKAGE = lambda sep:(sep.join(PACKAGE_NAMESPACE_WITH_PACKAGE[:i+1]) \ for i,n in enumerate(PACKAGE_NAMESPACE_WITH_PACKAGE)) PACKAGE_DIRS = dict(zip(NSLIST_WITH_PACKAGE('.'), NSLIST_WITH_PACKAGE('/'))) class install_requirements(object): def install_requirements(self): if os.environ.get('INSTALL_SKELETON_REQUIREMENTS', False): for r in self.requirements: if os.path.exists(r): subprocess.call('pip install -r %s'%r, shell=True, stdout=sys.stdout, stderr=sys.stderr) class post_install(install, install_requirements): requirements = ['requirements.txt'] def run(self): install.run(self) self.install_requirements() class post_develop(develop, install_requirements): requirements = ['requirements.txt', 'requirements.dev.txt'] def run(self): develop.run(self) self.install_requirements() if __name__ == '__main__': setup( cmdclass={"install": post_install, "develop": post_develop,}, name=PROJECT, version=VERSION, description=DESC, long_description=package_env('README.rst'), author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, license=package_env('LICENSE'), namespace_packages=list(NSLIST('.')), packages=list(NSLIST_WITH_PACKAGE('.')), package_dir=PACKAGE_DIRS, include_package_data=True, zip_safe=False, test_suite = 'tests', # install_requires=['argparse.extra',], classifiers=[ 'License :: OSI Approved', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Framework :: Django', ], )
lamerzan/public-forms
setup.py
Python
gpl-3.0
3,570
/**************************************************************************** * Copyright (C) 2015 * by Dimok * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. ***************************************************************************/ #ifndef __CURL_FUNCTIONS_H_ #define __CURL_FUNCTIONS_H_ #ifdef __cplusplus extern "C" { #endif #include <gctypes.h> #include "socket_functions.h" typedef int socklen_t; #include <curl/curl.h> #include <curl/easy.h> void InitCurlFunctionPointers(void); extern CURLcode (* n_curl_global_init)(long flags); extern CURL * (* n_curl_easy_init)(void); extern CURLcode (* n_curl_easy_setopt)(CURL *curl, CURLoption option, ...); extern CURLcode (* n_curl_easy_perform)(CURL *curl); extern void (* n_curl_easy_cleanup)(CURL *curl); extern CURLcode (* n_curl_easy_getinfo)(CURL *curl, CURLINFO info, ...); #ifdef __cplusplus } #endif #endif // __CURL_FUNCTIONS_H_
z0mb3/loadiine_gx2-fork
src/dynamic_libs/curl_functions.h
C
gpl-3.0
1,712
all: mpicc -g -Wall -o soma soma.c -lm run: mpirun -n 8 ./soma < arq0.in
iomartin/mc900
proj04/Makefile
Makefile
gpl-3.0
76
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Arionide: src/ch/innovazion/arionide/ui/core/gl/links Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Arionide &#160;<span id="projectnumber">1.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_12316fcaf64173b9a92c525552ec07f0.html">ch</a></li><li class="navelem"><a class="el" href="dir_a2d99e8c4ab7d8b0354396ff2925acbe.html">innovazion</a></li><li class="navelem"><a class="el" href="dir_0fe6bc50e6e1f3a650e7392611a29500.html">arionide</a></li><li class="navelem"><a class="el" href="dir_b9762b9dbcfebaa07b421a04617673aa.html">ui</a></li><li class="navelem"><a class="el" href="dir_7d02df48cd08ad5a0fa33f24ac810182.html">core</a></li><li class="navelem"><a class="el" href="dir_d627d2624395b6467ff3b34c4506de8b.html">gl</a></li><li class="navelem"><a class="el" href="dir_9ed948c06c0459550679640622b73947.html">links</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">links Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:_link_8java"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_link_8java.html">Link.java</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_link_context_8java"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_link_context_8java.html">LinkContext.java</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_link_indices_generator_8java"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_link_indices_generator_8java.html">LinkIndicesGenerator.java</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_link_settings_8java"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_link_settings_8java.html">LinkSettings.java</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:_link_tessellator_8java"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_link_tessellator_8java.html">LinkTessellator.java</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.16 </small></address> </body> </html>
thedreamer979/Arionide
doc/html/dir_9ed948c06c0459550679640622b73947.html
HTML
gpl-3.0
5,430
#ifndef FUNCTION_HAS_IF_STMT_H #define FUNCTION_HAS_IF_STMT_H #include "ibp/foundation/integer.h" ibp::Integer get_larger( ibp::Integer x, ibp::Integer y ); #endif
isaac-benson-powell/ibp_software
projects/language/test/test_io/for_ag_tests/input/parse_tree_nodes/Node_Function/expect_parser_pass/function_has_if_stmt/expected_cpp_translation/function_has_if_stmt.h
C
gpl-3.0
195
/**************************************************************************** ** ** 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 "connectionmodel.h" #include "connectionview.h" #include <bindingproperty.h> #include <variantproperty.h> #include <signalhandlerproperty.h> #include <rewritertransaction.h> #include <nodeabstractproperty.h> #include <exception.h> #include <QMessageBox> #include <QTableView> #include <QTimer> #include <QItemEditorFactory> #include <QStyleFactory> namespace { QStringList prependOnForSignalHandler(const QStringList &signalNames) { QStringList signalHandlerNames; foreach (const QString &signalName, signalNames) { QString signalHandlerName = signalName; if (!signalHandlerName.isEmpty()) { QChar firstChar = signalHandlerName.at(0).toUpper(); signalHandlerName[0] = firstChar; signalHandlerName.prepend(QLatin1String("on")); signalHandlerNames.append(signalHandlerName); } } return signalHandlerNames; } QStringList propertyNameListToStringList(const QmlDesigner::PropertyNameList &propertyNameList) { QStringList stringList; foreach (QmlDesigner::PropertyName propertyName, propertyNameList) { stringList << QString::fromUtf8(propertyName); } return stringList; } bool isConnection(const QmlDesigner::ModelNode &modelNode) { return (modelNode.type() == "Connections" || modelNode.type() == "QtQuick.Connections" || modelNode.type() == "Qt.Connections"); } enum ColumnRoles { TargetModelNodeRow = 0, TargetPropertyNameRow = 1, SourceRow = 2 }; } //namespace namespace QmlDesigner { namespace Internal { ConnectionModel::ConnectionModel(ConnectionView *parent) : QStandardItemModel(parent), m_connectionView(parent), m_lock(false) { connect(this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(handleDataChanged(QModelIndex,QModelIndex))); } void ConnectionModel::resetModel() { beginResetModel(); clear(); QStringList labels; labels << tr("Target"); labels << tr("Signal Handler"); labels <<tr("Action"); setHorizontalHeaderLabels(labels); if (connectionView()->isAttached()) { foreach (const ModelNode modelNode, connectionView()->allModelNodes()) { addModelNode(modelNode); } } const int columnWidthTarget = connectionView()->connectionTableView()->columnWidth(0); connectionView()->connectionTableView()->setColumnWidth(0, columnWidthTarget - 80); endResetModel(); } SignalHandlerProperty ConnectionModel::signalHandlerPropertyForRow(int rowNumber) const { const int internalId = data(index(rowNumber, TargetModelNodeRow), Qt::UserRole + 1).toInt(); const QString targetPropertyName = data(index(rowNumber, TargetModelNodeRow), Qt::UserRole + 2).toString(); ModelNode modelNode = connectionView()->modelNodeForInternalId(internalId); if (modelNode.isValid()) return modelNode.signalHandlerProperty(targetPropertyName.toUtf8()); return SignalHandlerProperty(); } void ConnectionModel::addModelNode(const ModelNode &modelNode) { if (isConnection(modelNode)) addConnection(modelNode); } void ConnectionModel::addConnection(const ModelNode &modelNode) { foreach (const AbstractProperty &property, modelNode.properties()) { if (property.isSignalHandlerProperty() && property.name() != "target") { addSignalHandler(property.toSignalHandlerProperty()); } } } void ConnectionModel::addSignalHandler(const SignalHandlerProperty &signalHandlerProperty) { QStandardItem *targetItem; QStandardItem *signalItem; QStandardItem *actionItem; QString idLabel; ModelNode connectionsModelNode = signalHandlerProperty.parentModelNode(); if (connectionsModelNode.bindingProperty("target").isValid()) { idLabel =connectionsModelNode.bindingProperty("target").expression(); } targetItem = new QStandardItem(idLabel); updateCustomData(targetItem, signalHandlerProperty); const QString propertyName = QString::fromUtf8(signalHandlerProperty.name()); const QString source = signalHandlerProperty.source(); signalItem = new QStandardItem(propertyName); QList<QStandardItem*> items; items.append(targetItem); items.append(signalItem); actionItem = new QStandardItem(source); items.append(actionItem); appendRow(items); } void ConnectionModel::removeModelNode(const ModelNode &modelNode) { if (isConnection(modelNode)) removeConnection(modelNode); } void ConnectionModel::removeConnection(const ModelNode & /*modelNode*/) { } void ConnectionModel::updateSource(int row) { SignalHandlerProperty signalHandlerProperty = signalHandlerPropertyForRow(row); const QString sourceString = data(index(row, SourceRow)).toString(); RewriterTransaction transaction = connectionView()->beginRewriterTransaction(QByteArrayLiteral("ConnectionModel::updateSource")); try { signalHandlerProperty.setSource(sourceString); transaction.commit(); } catch (Exception &e) { m_exceptionError = e.description(); QTimer::singleShot(200, this, SLOT(handleException())); } } void ConnectionModel::updateSignalName(int rowNumber) { SignalHandlerProperty signalHandlerProperty = signalHandlerPropertyForRow(rowNumber); const PropertyName newName = data(index(rowNumber, TargetPropertyNameRow)).toString().toUtf8(); const QString source = signalHandlerProperty.source(); ModelNode connectionNode = signalHandlerProperty.parentModelNode(); if (!newName.isEmpty()) { RewriterTransaction transaction = connectionView()->beginRewriterTransaction(QByteArrayLiteral("ConnectionModel::updateSignalName")); try { connectionNode.signalHandlerProperty(newName).setSource(source); connectionNode.removeProperty(signalHandlerProperty.name()); transaction.commit(); //committing in the try block } catch (Exception &e) { //better save then sorry QMessageBox::warning(0, tr("Error"), e.description()); } QStandardItem* idItem = item(rowNumber, 0); SignalHandlerProperty newSignalHandlerProperty = connectionNode.signalHandlerProperty(newName); updateCustomData(idItem, newSignalHandlerProperty); } else { qWarning() << "BindingModel::updatePropertyName invalid property name"; } } void ConnectionModel::updateTargetNode(int rowNumber) { SignalHandlerProperty signalHandlerProperty = signalHandlerPropertyForRow(rowNumber); const QString newTarget = data(index(rowNumber, TargetModelNodeRow)).toString(); ModelNode connectionNode = signalHandlerProperty.parentModelNode(); if (!newTarget.isEmpty()) { RewriterTransaction transaction = connectionView()->beginRewriterTransaction(QByteArrayLiteral("ConnectionModel::updateTargetNode")); try { connectionNode.bindingProperty("target").setExpression(newTarget); transaction.commit(); //committing in the try block } catch (Exception &e) { //better save then sorry QMessageBox::warning(0, tr("Error"), e.description()); } QStandardItem* idItem = item(rowNumber, 0); updateCustomData(idItem, signalHandlerProperty); } else { qWarning() << "BindingModel::updatePropertyName invalid target id"; } } void ConnectionModel::updateCustomData(QStandardItem *item, const SignalHandlerProperty &signalHandlerProperty) { item->setData(signalHandlerProperty.parentModelNode().internalId(), Qt::UserRole + 1); item->setData(signalHandlerProperty.name(), Qt::UserRole + 2); } ModelNode ConnectionModel::getTargetNodeForConnection(const ModelNode &connection) const { BindingProperty bindingProperty = connection.bindingProperty("target"); if (bindingProperty.isValid()) { if (bindingProperty.expression() == QLatin1String("parent")) return connection.parentProperty().parentModelNode(); return connectionView()->modelNodeForId(bindingProperty.expression()); } return ModelNode(); } void ConnectionModel::addConnection() { ModelNode rootModelNode = connectionView()->rootModelNode(); if (rootModelNode.isValid() && rootModelNode.metaInfo().isValid()) { NodeMetaInfo nodeMetaInfo = connectionView()->model()->metaInfo("QtQuick.Connections"); if (nodeMetaInfo.isValid()) { RewriterTransaction transaction = connectionView()->beginRewriterTransaction(QByteArrayLiteral("ConnectionModel::addConnection")); try { ModelNode newNode = connectionView()->createModelNode("QtQuick.Connections", nodeMetaInfo.majorVersion(), nodeMetaInfo.minorVersion()); rootModelNode.nodeAbstractProperty(rootModelNode.metaInfo().defaultPropertyName()).reparentHere(newNode); newNode.signalHandlerProperty("onClicked").setSource(QLatin1String("print(\"clicked\")")); if (connectionView()->selectedModelNodes().count() == 1 && !connectionView()->selectedModelNodes().first().id().isEmpty()) { ModelNode selectedNode = connectionView()->selectedModelNodes().first(); newNode.bindingProperty("target").setExpression(selectedNode.id()); } else { newNode.bindingProperty("target").setExpression(QLatin1String("parent")); } transaction.commit(); } catch (Exception &e) { //better save then sorry QMessageBox::warning(0, tr("Error"), e.description()); } } } } void ConnectionModel::bindingPropertyChanged(const BindingProperty &bindingProperty) { if (isConnection(bindingProperty.parentModelNode())) resetModel(); } void ConnectionModel::variantPropertyChanged(const VariantProperty &variantProperty) { if (isConnection(variantProperty.parentModelNode())) resetModel(); } void ConnectionModel::deleteConnectionByRow(int currentRow) { signalHandlerPropertyForRow(currentRow).parentModelNode().destroy(); } void ConnectionModel::handleException() { QMessageBox::warning(0, tr("Error"), m_exceptionError); resetModel(); } void ConnectionModel::handleDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { if (topLeft != bottomRight) { qWarning() << "ConnectionModel::handleDataChanged multi edit?"; return; } m_lock = true; int currentColumn = topLeft.column(); int currentRow = topLeft.row(); switch (currentColumn) { case TargetModelNodeRow: { updateTargetNode(currentRow); } break; case TargetPropertyNameRow: { updateSignalName(currentRow); } break; case SourceRow: { updateSource(currentRow); } break; default: qWarning() << "ConnectionModel::handleDataChanged column" << currentColumn; } m_lock = false; } ConnectionView *ConnectionModel::connectionView() const { return m_connectionView; } QStringList ConnectionModel::getSignalsForRow(int row) const { QStringList stringList; SignalHandlerProperty signalHandlerProperty = signalHandlerPropertyForRow(row); if (signalHandlerProperty.isValid()) { stringList.append(getPossibleSignalsForConnection(signalHandlerProperty.parentModelNode())); } return stringList; } QStringList ConnectionModel::getPossibleSignalsForConnection(const ModelNode &connection) const { QStringList stringList; if (connection.isValid()) { ModelNode targetNode = getTargetNodeForConnection(connection); if (targetNode.isValid() && targetNode.metaInfo().isValid()) { stringList.append(propertyNameListToStringList(targetNode.metaInfo().signalNames())); } } return stringList; } ConnectionDelegate::ConnectionDelegate(QWidget *parent) : QStyledItemDelegate(parent) { static QItemEditorFactory *factory = 0; if (factory == 0) { factory = new QItemEditorFactory; QItemEditorCreatorBase *creator = new QItemEditorCreator<ConnectionComboBox>("text"); factory->registerEditor(QVariant::String, creator); } setItemEditorFactory(factory); } QWidget *ConnectionDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QWidget *widget = QStyledItemDelegate::createEditor(parent, option, index); const ConnectionModel *connectionModel = qobject_cast<const ConnectionModel*>(index.model()); //model->connectionView()->allModelNodes(); ConnectionComboBox *bindingComboBox = qobject_cast<ConnectionComboBox*>(widget); if (!connectionModel) { qWarning() << "ConnectionDelegate::createEditor no model"; return widget; } if (!connectionModel->connectionView()) { qWarning() << "ConnectionDelegate::createEditor no connection view"; return widget; } if (!bindingComboBox) { qWarning() << "ConnectionDelegate::createEditor no bindingComboBox"; return widget; } switch (index.column()) { case TargetModelNodeRow: { foreach (const ModelNode &modelNode, connectionModel->connectionView()->allModelNodes()) { if (!modelNode.id().isEmpty()) { bindingComboBox->addItem(modelNode.id()); } } } break; case TargetPropertyNameRow: { bindingComboBox->addItems(prependOnForSignalHandler(connectionModel->getSignalsForRow(index.row()))); } break; case SourceRow: { ModelNode rootModelNode = connectionModel->connectionView()->rootModelNode(); if (QmlItemNode::isValidQmlItemNode(rootModelNode) && !rootModelNode.id().isEmpty()) { QString itemText = tr("Change to default state"); QString source = QString::fromLatin1("{ %1.state = \"\" }").arg(rootModelNode.id()); bindingComboBox->addItem(itemText, source); foreach (const QmlModelState &state, QmlItemNode(rootModelNode).states().allStates()) { QString itemText = tr("Change state to %1").arg(state.name()); QString source = QString::fromLatin1("{ %1.state = \"%2\" }").arg(rootModelNode.id()).arg(state.name()); bindingComboBox->addItem(itemText, source); } } } break; default: qWarning() << "ConnectionDelegate::createEditor column" << index.column(); } connect(bindingComboBox, SIGNAL(activated(QString)), this, SLOT(emitCommitData(QString))); return widget; } void ConnectionDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem opt = option; opt.state &= ~QStyle::State_HasFocus; QStyledItemDelegate::paint(painter, opt, index); } void ConnectionDelegate::emitCommitData(const QString & /*text*/) { ConnectionComboBox *bindingComboBox = qobject_cast<ConnectionComboBox*>(sender()); emit commitData(bindingComboBox); } ConnectionComboBox::ConnectionComboBox(QWidget *parent) : QComboBox(parent) { static QScopedPointer<QStyle> style(QStyleFactory::create(QLatin1String("windows"))); setEditable(true); if (style) setStyle(style.data()); } QString ConnectionComboBox::text() const { int index = findText(currentText()); if (index > -1) { QVariant variantData = itemData(index); if (variantData.isValid()) return variantData.toString(); } return currentText(); } void ConnectionComboBox::setText(const QString &text) { setEditText(text); } } // namespace Internal } // namespace QmlDesigner
pivonroll/Qt_Creator
src/plugins/qmldesigner/qmldesignerextension/connectioneditor/connectionmodel.cpp
C++
gpl-3.0
17,074
#include <unistd.h> #include <stdlib.h> #include <math.h> #include <zlib.h> #include <errno.h> #include "bcf.h" #include "prob1.h" #include "kstring.h" #include "time.h" #include "kseq.h" KSTREAM_INIT(gzFile, gzread, 16384) #define VC_NO_GENO 2 #define VC_BCFOUT 4 #define VC_CALL 8 #define VC_VARONLY 16 #define VC_VCFIN 32 #define VC_UNCOMP 64 #define VC_KEEPALT 256 #define VC_ACGT_ONLY 512 #define VC_QCALL 1024 #define VC_CALL_GT 2048 #define VC_ADJLD 4096 #define VC_NO_INDEL 8192 #define VC_ANNO_MAX 16384 #define VC_FIX_PL 32768 #define VC_EM 0x10000 #define VC_PAIRCALL 0x20000 #define VC_QCNT 0x40000 typedef struct { int flag, prior_type, n1, n_sub, *sublist, n_perm; uint32_t *trio_aux; char *prior_file, **subsam, *fn_dict; uint8_t *ploidy; double theta, pref, indel_frac, min_perm_p, min_smpl_frac, min_lrt; void *bed; } viewconf_t; void *bed_read(const char *fn); void bed_destroy(void *_h); int bed_overlap(const void *_h, const char *chr, int beg, int end); typedef struct { double p[4]; int mq, depth, is_tested, d[4]; } anno16_t; static double ttest(int n1, int n2, int a[4]) { extern double kf_betai(double a, double b, double x); double t, v, u1, u2; if (n1 == 0 || n2 == 0 || n1 + n2 < 3) return 1.0; u1 = (double)a[0] / n1; u2 = (double)a[2] / n2; if (u1 <= u2) return 1.; t = (u1 - u2) / sqrt(((a[1] - n1 * u1 * u1) + (a[3] - n2 * u2 * u2)) / (n1 + n2 - 2) * (1./n1 + 1./n2)); v = n1 + n2 - 2; // printf("%d,%d,%d,%d,%lf,%lf,%lf\n", a[0], a[1], a[2], a[3], t, u1, u2); return t < 0.? 1. : .5 * kf_betai(.5*v, .5, v/(v+t*t)); } static int test16_core(int anno[16], anno16_t *a) { extern double kt_fisher_exact(int n11, int n12, int n21, int n22, double *_left, double *_right, double *two); double left, right; int i; a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.; memcpy(a->d, anno, 4 * sizeof(int)); a->depth = anno[0] + anno[1] + anno[2] + anno[3]; a->is_tested = (anno[0] + anno[1] > 0 && anno[2] + anno[3] > 0); if (a->depth == 0) return -1; a->mq = (int)(sqrt((anno[9] + anno[11]) / a->depth) + .499); kt_fisher_exact(anno[0], anno[1], anno[2], anno[3], &left, &right, &a->p[0]); for (i = 1; i < 4; ++i) a->p[i] = ttest(anno[0] + anno[1], anno[2] + anno[3], anno+4*i); return 0; } static int test16(bcf1_t *b, anno16_t *a) { char *p; int i, anno[16]; a->p[0] = a->p[1] = a->p[2] = a->p[3] = 1.; a->d[0] = a->d[1] = a->d[2] = a->d[3] = 0.; a->mq = a->depth = a->is_tested = 0; if ((p = strstr(b->info, "I16=")) == 0) return -1; p += 4; for (i = 0; i < 16; ++i) { errno = 0; anno[i] = strtol(p, &p, 10); if (anno[i] == 0 && (errno == EINVAL || errno == ERANGE)) return -2; ++p; } return test16_core(anno, a); } static void rm_info(bcf1_t *b, const char *key) { char *p, *q; if ((p = strstr(b->info, key)) == 0) return; for (q = p; *q && *q != ';'; ++q); if (p > b->info && *(p-1) == ';') --p; memmove(p, q, b->l_str - (q - b->str)); b->l_str -= q - p; bcf_sync(b); } static int update_bcf1(bcf1_t *b, const bcf_p1aux_t *pa, const bcf_p1rst_t *pr, double pref, int flag, double em[10], int cons_llr, int64_t cons_gt) { kstring_t s; int has_I16, is_var; double fq, r; anno16_t a; has_I16 = test16(b, &a) >= 0? 1 : 0; rm_info(b, "I16="); // FIXME: probably this function has a bug. If I move it below, I16 will not be removed! memset(&s, 0, sizeof(kstring_t)); kputc('\0', &s); kputs(b->ref, &s); kputc('\0', &s); kputs(b->alt, &s); kputc('\0', &s); kputc('\0', &s); kputs(b->info, &s); if (b->info[0]) kputc(';', &s); { // print EM if (em[0] >= 0) ksprintf(&s, "AF1=%.4g", 1 - em[0]); if (em[4] >= 0 && em[4] <= 0.05) ksprintf(&s, ";G3=%.4g,%.4g,%.4g;HWE=%.3g", em[3], em[2], em[1], em[4]); if (em[5] >= 0 && em[6] >= 0) ksprintf(&s, ";AF2=%.4g,%.4g", 1 - em[5], 1 - em[6]); if (em[7] >= 0) ksprintf(&s, ";LRT=%.3g", em[7]); if (em[8] >= 0) ksprintf(&s, ";LRT2=%.3g", em[8]); //if (em[9] >= 0) ksprintf(&s, ";LRT1=%.3g", em[9]); } if (cons_llr > 0) { ksprintf(&s, ";CLR=%d", cons_llr); if (cons_gt > 0) ksprintf(&s, ";UGT=%c%c%c;CGT=%c%c%c", cons_gt&0xff, cons_gt>>8&0xff, cons_gt>>16&0xff, cons_gt>>32&0xff, cons_gt>>40&0xff, cons_gt>>48&0xff); } if (pr == 0) { // if pr is unset, return kputc('\0', &s); kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); return 1; } is_var = (pr->p_ref < pref); r = is_var? pr->p_ref : pr->p_var; // ksprintf(&s, ";CI95=%.4g,%.4g", pr->cil, pr->cih); // FIXME: when EM is not used, ";" should be omitted! ksprintf(&s, ";AC1=%d", pr->ac); if (has_I16) ksprintf(&s, ";DP4=%d,%d,%d,%d;MQ=%d", a.d[0], a.d[1], a.d[2], a.d[3], a.mq); fq = pr->p_ref_folded < 0.5? -4.343 * log(pr->p_ref_folded) : 4.343 * log(pr->p_var_folded); if (fq < -999) fq = -999; if (fq > 999) fq = 999; ksprintf(&s, ";FQ=%.3g", fq); if (pr->cmp[0] >= 0.) { // two sample groups int i, q[3]; for (i = 1; i < 3; ++i) { double x = pr->cmp[i] + pr->cmp[0]/2.; q[i] = x == 0? 255 : (int)(-4.343 * log(x) + .499); if (q[i] > 255) q[i] = 255; } if (pr->perm_rank >= 0) ksprintf(&s, ";PR=%d", pr->perm_rank); // ksprintf(&s, ";LRT3=%.3g", pr->lrt); ksprintf(&s, ";PCHI2=%.3g;PC2=%d,%d", q[1], q[2], pr->p_chi2); } if (has_I16 && a.is_tested) ksprintf(&s, ";PV4=%.2g,%.2g,%.2g,%.2g", a.p[0], a.p[1], a.p[2], a.p[3]); kputc('\0', &s); kputs(b->fmt, &s); kputc('\0', &s); free(b->str); b->m_str = s.m; b->l_str = s.l; b->str = s.s; b->qual = r < 1e-100? 999 : -4.343 * log(r); if (b->qual > 999) b->qual = 999; bcf_sync(b); if (!is_var) bcf_shrink_alt(b, 1); else if (!(flag&VC_KEEPALT)) bcf_shrink_alt(b, pr->rank0 < 2? 2 : pr->rank0+1); if (is_var && (flag&VC_CALL_GT)) { // call individual genotype int i, x, old_n_gi = b->n_gi; s.m = b->m_str; s.l = b->l_str - 1; s.s = b->str; kputs(":GT:GQ", &s); kputc('\0', &s); b->m_str = s.m; b->l_str = s.l; b->str = s.s; bcf_sync(b); for (i = 0; i < b->n_smpl; ++i) { x = bcf_p1_call_gt(pa, pr->f_exp, i); ((uint8_t*)b->gi[old_n_gi].data)[i] = (x&3) == 0? 1<<3|1 : (x&3) == 1? 1 : 0; ((uint8_t*)b->gi[old_n_gi+1].data)[i] = x>>2; } } return is_var; } static char **read_samples(const char *fn, int *_n) { gzFile fp; kstream_t *ks; kstring_t s; int dret, n = 0, max = 0; char **sam = 0; *_n = 0; s.l = s.m = 0; s.s = 0; fp = gzopen(fn, "r"); if (fp == 0) return 0; // fail to open file ks = ks_init(fp); while (ks_getuntil(ks, 0, &s, &dret) >= 0) { int l; if (max == n) { max = max? max<<1 : 4; sam = realloc(sam, sizeof(void*)*max); } l = s.l; sam[n] = malloc(s.l + 2); strcpy(sam[n], s.s); sam[n][l+1] = 2; // by default, diploid if (dret != '\n') { if (ks_getuntil(ks, 0, &s, &dret) >= 0) { // read ploidy, 1 or 2 int x = (int)s.s[0] - '0'; if (x == 1 || x == 2) sam[n][l+1] = x; else fprintf(stderr, "(%s) ploidy can only be 1 or 2; assume diploid\n", __func__); } if (dret != '\n') ks_getuntil(ks, '\n', &s, &dret); } ++n; } ks_destroy(ks); gzclose(fp); free(s.s); *_n = n; return sam; } static void write_header(bcf_hdr_t *h) { kstring_t str; str.l = h->l_txt? h->l_txt - 1 : 0; str.m = str.l + 1; str.s = h->txt; if (!strstr(str.s, "##INFO=<ID=DP,")) kputs("##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Raw read depth\">\n", &str); if (!strstr(str.s, "##INFO=<ID=DP4,")) kputs("##INFO=<ID=DP4,Number=4,Type=Integer,Description=\"# high-quality ref-forward bases, ref-reverse, alt-forward and alt-reverse bases\">\n", &str); if (!strstr(str.s, "##INFO=<ID=MQ,")) kputs("##INFO=<ID=MQ,Number=1,Type=Integer,Description=\"Root-mean-square mapping quality of covering reads\">\n", &str); if (!strstr(str.s, "##INFO=<ID=FQ,")) kputs("##INFO=<ID=FQ,Number=1,Type=Float,Description=\"Phred probability of all samples being the same\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AF1,")) kputs("##INFO=<ID=AF1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele frequency (assuming HWE)\">\n", &str); if (!strstr(str.s, "##INFO=<ID=AC1,")) kputs("##INFO=<ID=AC1,Number=1,Type=Float,Description=\"Max-likelihood estimate of the first ALT allele count (no HWE assumption)\">\n", &str); if (!strstr(str.s, "##INFO=<ID=G3,")) kputs("##INFO=<ID=G3,Number=3,Type=Float,Description=\"ML estimate of genotype frequencies\">\n", &str); if (!strstr(str.s, "##INFO=<ID=HWE,")) kputs("##INFO=<ID=HWE,Number=1,Type=Float,Description=\"Chi^2 based HWE test P-value based on G3\">\n", &str); if (!strstr(str.s, "##INFO=<ID=CLR,")) kputs("##INFO=<ID=CLR,Number=1,Type=Integer,Description=\"Log ratio of genotype likelihoods with and without the constraint\">\n", &str); if (!strstr(str.s, "##INFO=<ID=UGT,")) kputs("##INFO=<ID=UGT,Number=1,Type=String,Description=\"The most probable unconstrained genotype configuration in the trio\">\n", &str); if (!strstr(str.s, "##INFO=<ID=CGT,")) kputs("##INFO=<ID=CGT,Number=1,Type=String,Description=\"The most probable constrained genotype configuration in the trio\">\n", &str); // if (!strstr(str.s, "##INFO=<ID=CI95,")) // kputs("##INFO=<ID=CI95,Number=2,Type=Float,Description=\"Equal-tail Bayesian credible interval of the site allele frequency at the 95% level\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PV4,")) kputs("##INFO=<ID=PV4,Number=4,Type=Float,Description=\"P-values for strand bias, baseQ bias, mapQ bias and tail distance bias\">\n", &str); if (!strstr(str.s, "##INFO=<ID=INDEL,")) kputs("##INFO=<ID=INDEL,Number=0,Type=Flag,Description=\"Indicates that the variant is an INDEL.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PC2,")) kputs("##INFO=<ID=PC2,Number=2,Type=Integer,Description=\"Phred probability of the nonRef allele frequency in group1 samples being larger (,smaller) than in group2.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=PCHI2,")) kputs("##INFO=<ID=PCHI2,Number=1,Type=Float,Description=\"Posterior weighted chi^2 P-value for testing the association between group1 and group2 samples.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=QCHI2,")) kputs("##INFO=<ID=QCHI2,Number=1,Type=Integer,Description=\"Phred scaled PCHI2.\">\n", &str); if (!strstr(str.s, "##INFO=<ID=RP,")) kputs("##INFO=<ID=PR,Number=1,Type=Integer,Description=\"# permutations yielding a smaller PCHI2.\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GT,")) kputs("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GQ,")) kputs("##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=GL,")) kputs("##FORMAT=<ID=GL,Number=3,Type=Float,Description=\"Likelihoods for RR,RA,AA genotypes (R=ref,A=alt)\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=DP,")) kputs("##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"# high-quality bases\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=SP,")) kputs("##FORMAT=<ID=SP,Number=1,Type=Integer,Description=\"Phred-scaled strand bias P-value\">\n", &str); if (!strstr(str.s, "##FORMAT=<ID=PL,")) kputs("##FORMAT=<ID=PL,Number=-1,Type=Integer,Description=\"List of Phred-scaled genotype likelihoods, number of values is (#ALT+1)*(#ALT+2)/2\">\n", &str); h->l_txt = str.l + 1; h->txt = str.s; } double bcf_pair_freq(const bcf1_t *b0, const bcf1_t *b1, double f[4]); int bcfview(int argc, char *argv[]) { extern int bcf_2qcall(bcf_hdr_t *h, bcf1_t *b); extern void bcf_p1_indel_prior(bcf_p1aux_t *ma, double x); extern int bcf_fix_gt(bcf1_t *b); extern int bcf_anno_max(bcf1_t *b); extern int bcf_shuffle(bcf1_t *b, int seed); extern uint32_t *bcf_trio_prep(int is_x, int is_son); extern int bcf_trio_call(uint32_t *prep, const bcf1_t *b, int *llr, int64_t *gt); extern int bcf_pair_call(const bcf1_t *b); extern int bcf_min_diff(const bcf1_t *b); bcf_t *bp, *bout = 0; bcf1_t *b, *blast; int c, *seeds = 0; uint64_t n_processed = 0, qcnt[256]; viewconf_t vc; bcf_p1aux_t *p1 = 0; bcf_hdr_t *hin, *hout; int tid, begin, end; char moder[4], modew[4]; tid = begin = end = -1; memset(&vc, 0, sizeof(viewconf_t)); vc.prior_type = vc.n1 = -1; vc.theta = 1e-3; vc.pref = 0.5; vc.indel_frac = -1.; vc.n_perm = 0; vc.min_perm_p = 0.01; vc.min_smpl_frac = 0; vc.min_lrt = 1; memset(qcnt, 0, 8 * 256); while ((c = getopt(argc, argv, "FN1:l:cC:eHAGvbSuP:t:p:QgLi:IMs:D:U:X:d:T:Y")) >= 0) { switch (c) { case '1': vc.n1 = atoi(optarg); break; case 'l': vc.bed = bed_read(optarg); break; case 'D': vc.fn_dict = strdup(optarg); break; case 'F': vc.flag |= VC_FIX_PL; break; case 'N': vc.flag |= VC_ACGT_ONLY; break; case 'G': vc.flag |= VC_NO_GENO; break; case 'A': vc.flag |= VC_KEEPALT; break; case 'b': vc.flag |= VC_BCFOUT; break; case 'S': vc.flag |= VC_VCFIN; break; case 'c': vc.flag |= VC_CALL; break; case 'e': vc.flag |= VC_EM; break; case 'v': vc.flag |= VC_VARONLY | VC_CALL; break; case 'u': vc.flag |= VC_UNCOMP | VC_BCFOUT; break; case 'g': vc.flag |= VC_CALL_GT | VC_CALL; break; case 'I': vc.flag |= VC_NO_INDEL; break; case 'M': vc.flag |= VC_ANNO_MAX; break; case 'Y': vc.flag |= VC_QCNT; break; case 't': vc.theta = atof(optarg); break; case 'p': vc.pref = atof(optarg); break; case 'i': vc.indel_frac = atof(optarg); break; case 'Q': vc.flag |= VC_QCALL; break; case 'L': vc.flag |= VC_ADJLD; break; case 'U': vc.n_perm = atoi(optarg); break; case 'C': vc.min_lrt = atof(optarg); break; case 'X': vc.min_perm_p = atof(optarg); break; case 'd': vc.min_smpl_frac = atof(optarg); break; case 's': vc.subsam = read_samples(optarg, &vc.n_sub); vc.ploidy = calloc(vc.n_sub + 1, 1); for (tid = 0; tid < vc.n_sub; ++tid) vc.ploidy[tid] = vc.subsam[tid][strlen(vc.subsam[tid]) + 1]; tid = -1; break; case 'T': if (strcmp(optarg, "trioauto") == 0) vc.trio_aux = bcf_trio_prep(0, 0); else if (strcmp(optarg, "trioxd") == 0) vc.trio_aux = bcf_trio_prep(1, 0); else if (strcmp(optarg, "trioxs") == 0) vc.trio_aux = bcf_trio_prep(1, 1); else if (strcmp(optarg, "pair") == 0) vc.flag |= VC_PAIRCALL; else { fprintf(stderr, "[%s] Option '-T' can only take value trioauto, trioxd or trioxs.\n", __func__); return 1; } break; case 'P': if (strcmp(optarg, "full") == 0) vc.prior_type = MC_PTYPE_FULL; else if (strcmp(optarg, "cond2") == 0) vc.prior_type = MC_PTYPE_COND2; else if (strcmp(optarg, "flat") == 0) vc.prior_type = MC_PTYPE_FLAT; else vc.prior_file = strdup(optarg); break; } } if (argc == optind) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: bcftools view [options] <in.bcf> [reg]\n\n"); fprintf(stderr, "Input/output options:\n\n"); fprintf(stderr, " -A keep all possible alternate alleles at variant sites\n"); fprintf(stderr, " -b output BCF instead of VCF\n"); fprintf(stderr, " -D FILE sequence dictionary for VCF->BCF conversion [null]\n"); fprintf(stderr, " -F PL generated by r921 or before (which generate old ordering)\n"); fprintf(stderr, " -G suppress all individual genotype information\n"); fprintf(stderr, " -l FILE list of sites (chr pos) or regions (BED) to output [all sites]\n"); fprintf(stderr, " -L calculate LD for adjacent sites\n"); fprintf(stderr, " -N skip sites where REF is not A/C/G/T\n"); fprintf(stderr, " -Q output the QCALL likelihood format\n"); fprintf(stderr, " -s FILE list of samples to use [all samples]\n"); fprintf(stderr, " -S input is VCF\n"); fprintf(stderr, " -u uncompressed BCF output (force -b)\n"); fprintf(stderr, "\nConsensus/variant calling options:\n\n"); fprintf(stderr, " -c SNP calling (force -e)\n"); fprintf(stderr, " -d FLOAT skip loci where less than FLOAT fraction of samples covered [0]\n"); fprintf(stderr, " -e likelihood based analyses\n"); fprintf(stderr, " -g call genotypes at variant sites (force -c)\n"); fprintf(stderr, " -i FLOAT indel-to-substitution ratio [%.4g]\n", vc.indel_frac); fprintf(stderr, " -I skip indels\n"); fprintf(stderr, " -p FLOAT variant if P(ref|D)<FLOAT [%.3g]\n", vc.pref); fprintf(stderr, " -P STR type of prior: full, cond2, flat [full]\n"); fprintf(stderr, " -t FLOAT scaled substitution mutation rate [%.4g]\n", vc.theta); fprintf(stderr, " -T STR constrained calling; STR can be: pair, trioauto, trioxd and trioxs (see manual) [null]\n"); fprintf(stderr, " -v output potential variant sites only (force -c)\n"); fprintf(stderr, "\nContrast calling and association test options:\n\n"); fprintf(stderr, " -1 INT number of group-1 samples [0]\n"); fprintf(stderr, " -C FLOAT posterior constrast for LRT<FLOAT and P(ref|D)<0.5 [%g]\n", vc.min_lrt); fprintf(stderr, " -U INT number of permutations for association testing (effective with -1) [0]\n"); fprintf(stderr, " -X FLOAT only perform permutations for P(chi^2)<FLOAT [%g]\n", vc.min_perm_p); fprintf(stderr, "\n"); return 1; } if (vc.flag & VC_CALL) vc.flag |= VC_EM; if ((vc.flag & VC_VCFIN) && (vc.flag & VC_BCFOUT) && vc.fn_dict == 0) { fprintf(stderr, "[%s] For VCF->BCF conversion please specify the sequence dictionary with -D\n", __func__); return 1; } if (vc.n1 <= 0) vc.n_perm = 0; // TODO: give a warning here! if (vc.n_perm > 0) { seeds = malloc(vc.n_perm * sizeof(int)); srand48(time(0)); for (c = 0; c < vc.n_perm; ++c) seeds[c] = lrand48(); } b = calloc(1, sizeof(bcf1_t)); blast = calloc(1, sizeof(bcf1_t)); strcpy(moder, "r"); if (!(vc.flag & VC_VCFIN)) strcat(moder, "b"); strcpy(modew, "w"); if (vc.flag & VC_BCFOUT) strcat(modew, "b"); if (vc.flag & VC_UNCOMP) strcat(modew, "u"); bp = vcf_open(argv[optind], moder); hin = hout = vcf_hdr_read(bp); if (vc.fn_dict && (vc.flag & VC_VCFIN)) vcf_dictread(bp, hin, vc.fn_dict); bout = vcf_open("-", modew); if (!(vc.flag & VC_QCALL)) { if (vc.n_sub) { vc.sublist = calloc(vc.n_sub, sizeof(int)); hout = bcf_hdr_subsam(hin, vc.n_sub, vc.subsam, vc.sublist); } if (vc.flag & VC_CALL) write_header(hout); vcf_hdr_write(bout, hout); } if (vc.flag & VC_CALL) { p1 = bcf_p1_init(hout->n_smpl, vc.ploidy); if (vc.prior_file) { if (bcf_p1_read_prior(p1, vc.prior_file) < 0) { fprintf(stderr, "[%s] fail to read the prior AFS.\n", __func__); return 1; } } else bcf_p1_init_prior(p1, vc.prior_type, vc.theta); if (vc.n1 > 0 && vc.min_lrt > 0.) { // set n1 bcf_p1_set_n1(p1, vc.n1); bcf_p1_init_subprior(p1, vc.prior_type, vc.theta); } if (vc.indel_frac > 0.) bcf_p1_indel_prior(p1, vc.indel_frac); // otherwise use the default indel_frac } if (optind + 1 < argc && !(vc.flag&VC_VCFIN)) { void *str2id = bcf_build_refhash(hout); if (bcf_parse_region(str2id, argv[optind+1], &tid, &begin, &end) >= 0) { bcf_idx_t *idx; idx = bcf_idx_load(argv[optind]); if (idx) { uint64_t off; off = bcf_idx_query(idx, tid, begin); if (off == 0) { fprintf(stderr, "[%s] no records in the query region.\n", __func__); return 1; // FIXME: a lot of memory leaks... } bgzf_seek(bp->fp, off, SEEK_SET); bcf_idx_destroy(idx); } } } while (vcf_read(bp, hin, b) > 0) { int is_indel, cons_llr = -1; int64_t cons_gt = -1; double em[10]; if ((vc.flag & VC_VARONLY) && strcmp(b->alt, "X") == 0) continue; if ((vc.flag & VC_VARONLY) && vc.min_smpl_frac > 0.) { extern int bcf_smpl_covered(const bcf1_t *b); int n = bcf_smpl_covered(b); if ((double)n / b->n_smpl < vc.min_smpl_frac) continue; } if (vc.n_sub) bcf_subsam(vc.n_sub, vc.sublist, b); if (vc.flag & VC_FIX_PL) bcf_fix_pl(b); is_indel = bcf_is_indel(b); if ((vc.flag & VC_NO_INDEL) && is_indel) continue; if ((vc.flag & VC_ACGT_ONLY) && !is_indel) { int x; if (b->ref[0] == 0 || b->ref[1] != 0) continue; x = toupper(b->ref[0]); if (x != 'A' && x != 'C' && x != 'G' && x != 'T') continue; } if (vc.bed && !bed_overlap(vc.bed, hin->ns[b->tid], b->pos, b->pos + strlen(b->ref))) continue; if (tid >= 0) { int l = strlen(b->ref); l = b->pos + (l > 0? l : 1); if (b->tid != tid || b->pos >= end) break; if (!(l > begin && end > b->pos)) continue; } ++n_processed; if (vc.flag & VC_QCNT) { // summarize the difference int x = bcf_min_diff(b); if (x > 255) x = 255; if (x >= 0) ++qcnt[x]; } if (vc.flag & VC_QCALL) { // output QCALL format; STOP here bcf_2qcall(hout, b); continue; } if (vc.trio_aux) // do trio calling bcf_trio_call(vc.trio_aux, b, &cons_llr, &cons_gt); else if (vc.flag & VC_PAIRCALL) cons_llr = bcf_pair_call(b); if (vc.flag & (VC_CALL|VC_ADJLD|VC_EM)) bcf_gl2pl(b); if (vc.flag & VC_EM) bcf_em1(b, vc.n1, 0x1ff, em); else { int i; for (i = 0; i < 9; ++i) em[i] = -1.; } if (vc.flag & VC_CALL) { // call variants bcf_p1rst_t pr; int calret = bcf_p1_cal(b, (em[7] >= 0 && em[7] < vc.min_lrt), p1, &pr); if (n_processed % 100000 == 0) { fprintf(stderr, "[%s] %ld sites processed.\n", __func__, (long)n_processed); bcf_p1_dump_afs(p1); } if (pr.p_ref >= vc.pref && (vc.flag & VC_VARONLY)) continue; if (vc.n_perm && vc.n1 > 0 && pr.p_chi2 < vc.min_perm_p) { // permutation test bcf_p1rst_t r; int i, n = 0; for (i = 0; i < vc.n_perm; ++i) { #ifdef BCF_PERM_LRT // LRT based permutation is much faster but less robust to artifacts double x[10]; bcf_shuffle(b, seeds[i]); bcf_em1(b, vc.n1, 1<<7, x); if (x[7] < em[7]) ++n; #else bcf_shuffle(b, seeds[i]); bcf_p1_cal(b, 1, p1, &r); if (pr.p_chi2 >= r.p_chi2) ++n; #endif } pr.perm_rank = n; } if (calret >= 0) update_bcf1(b, p1, &pr, vc.pref, vc.flag, em, cons_llr, cons_gt); } else if (vc.flag & VC_EM) update_bcf1(b, 0, 0, 0, vc.flag, em, cons_llr, cons_gt); if (vc.flag & VC_ADJLD) { // compute LD double f[4], r2; if ((r2 = bcf_pair_freq(blast, b, f)) >= 0) { kstring_t s; s.m = s.l = 0; s.s = 0; if (*b->info) kputc(';', &s); ksprintf(&s, "NEIR=%.3f;NEIF4=%.3f,%.3f,%.3f,%.3f", r2, f[0], f[1], f[2], f[3]); bcf_append_info(b, s.s, s.l); free(s.s); } bcf_cpy(blast, b); } if (vc.flag & VC_ANNO_MAX) bcf_anno_max(b); if (vc.flag & VC_NO_GENO) { // do not output GENO fields b->n_gi = 0; b->fmt[0] = '\0'; b->l_str = b->fmt - b->str + 1; } else bcf_fix_gt(b); vcf_write(bout, hout, b); } if (vc.prior_file) free(vc.prior_file); if (vc.flag & VC_CALL) bcf_p1_dump_afs(p1); if (hin != hout) bcf_hdr_destroy(hout); bcf_hdr_destroy(hin); bcf_destroy(b); bcf_destroy(blast); vcf_close(bp); vcf_close(bout); if (vc.fn_dict) free(vc.fn_dict); if (vc.ploidy) free(vc.ploidy); if (vc.trio_aux) free(vc.trio_aux); if (vc.n_sub) { int i; for (i = 0; i < vc.n_sub; ++i) free(vc.subsam[i]); free(vc.subsam); free(vc.sublist); } if (vc.bed) bed_destroy(vc.bed); if (vc.flag & VC_QCNT) for (c = 0; c < 256; ++c) fprintf(stderr, "QT\t%d\t%lld\n", c, (long long)qcnt[c]); if (seeds) free(seeds); if (p1) bcf_p1_destroy(p1); return 0; }
jelena-tica/TIGER
external/samtools-0.1.17/bcftools/call1.c
C
gpl-3.0
23,298
/* This file is part of Darling. Copyright (C) 2019 Lubos Dolezel Darling 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. Darling 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 Darling. If not, see <http://www.gnu.org/licenses/>. */ #include <Foundation/Foundation.h> @protocol MKMapServiceCategoriesTicket @end
darlinghq/darling
src/frameworks/MapKit/include/MapKit/MKMapServiceCategoriesTicket.h
C
gpl-3.0
762
<?xml version="1.0" encoding="utf-8"?> <html> <head> <title>GLib.VariantType.key -- Vala Binding Reference</title> <link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript"> </script> </head> <body> <div class="site_header">GLib.VariantType.key Reference Manual</div> <div class="site_body"> <div class="site_navigation"> <ul class="navi_main"> <li class="package_index"><a href="../index.html">Packages</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="package"><a href="index.htm">glib-2.0</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="namespace"><a href="GLib.html">GLib</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="class"><a href="GLib.VariantType.html">VariantType</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="static_method"><a href="GLib.VariantType.string_is_valid.html">string_is_valid</a></li> <li class="static_method"><a href="GLib.VariantType.string_scan.html">string_scan</a></li> <li class="creation_method"><a href="GLib.VariantType.VariantType.html">VariantType</a></li> <li class="creation_method"><a href="GLib.VariantType.VariantType.array.html">VariantType.array</a></li> <li class="creation_method"><a href="GLib.VariantType.VariantType.dict_entry.html">VariantType.dict_entry</a></li> <li class="creation_method"><a href="GLib.VariantType.VariantType.maybe.html">VariantType.maybe</a></li> <li class="creation_method"><a href="GLib.VariantType.VariantType.tuple.html">VariantType.tuple</a></li> <li class="method"><a href="GLib.VariantType.dup_string.html">dup_string</a></li> <li class="method"><a href="GLib.VariantType.element.html">element</a></li> <li class="method"><a href="GLib.VariantType.equal.html">equal</a></li> <li class="method"><a href="GLib.VariantType.first.html">first</a></li> <li class="method"><a href="GLib.VariantType.get_string_length.html">get_string_length</a></li> <li class="method"><a href="GLib.VariantType.hash.html">hash</a></li> <li class="method"><a href="GLib.VariantType.is_array.html">is_array</a></li> <li class="method"><a href="GLib.VariantType.is_basic.html">is_basic</a></li> <li class="method"><a href="GLib.VariantType.is_container.html">is_container</a></li> <li class="method"><a href="GLib.VariantType.is_definite.html">is_definite</a></li> <li class="method"><a href="GLib.VariantType.is_dict_entry.html">is_dict_entry</a></li> <li class="method"><a href="GLib.VariantType.is_maybe.html">is_maybe</a></li> <li class="method"><a href="GLib.VariantType.is_subtype_of.html">is_subtype_of</a></li> <li class="method"><a href="GLib.VariantType.is_tuple.html">is_tuple</a></li> <li class="method"><a href="GLib.VariantType.is_variant.html">is_variant</a></li> <li class="method">key</li> <li class="method"><a href="GLib.VariantType.n_items.html">n_items</a></li> <li class="method"><a href="GLib.VariantType.next.html">next</a></li> <li class="method"><a href="GLib.VariantType.peek_string.html">peek_string</a></li> <li class="method"><a href="GLib.VariantType.value.html">value</a></li> <li class="field"><a href="GLib.VariantType.ANY.html">ANY</a></li> <li class="field"><a href="GLib.VariantType.ARRAY.html">ARRAY</a></li> <li class="field"><a href="GLib.VariantType.BASIC.html">BASIC</a></li> <li class="field"><a href="GLib.VariantType.BOOLEAN.html">BOOLEAN</a></li> <li class="field"><a href="GLib.VariantType.BYTE.html">BYTE</a></li> <li class="field"><a href="GLib.VariantType.BYTESTRING.html">BYTESTRING</a></li> <li class="field"><a href="GLib.VariantType.BYTESTRING_ARRAY.html">BYTESTRING_ARRAY</a></li> <li class="field"><a href="GLib.VariantType.DICTIONARY.html">DICTIONARY</a></li> <li class="field"><a href="GLib.VariantType.DICT_ENTRY.html">DICT_ENTRY</a></li> <li class="field"><a href="GLib.VariantType.DOUBLE.html">DOUBLE</a></li> <li class="field"><a href="GLib.VariantType.HANDLE.html">HANDLE</a></li> <li class="field"><a href="GLib.VariantType.INT16.html">INT16</a></li> <li class="field"><a href="GLib.VariantType.INT32.html">INT32</a></li> <li class="field"><a href="GLib.VariantType.INT64.html">INT64</a></li> <li class="field"><a href="GLib.VariantType.MAYBE.html">MAYBE</a></li> <li class="field"><a href="GLib.VariantType.OBJECT_PATH.html">OBJECT_PATH</a></li> <li class="field"><a href="GLib.VariantType.OBJECT_PATH_ARRAY.html">OBJECT_PATH_ARRAY</a></li> <li class="field"><a href="GLib.VariantType.SIGNATURE.html">SIGNATURE</a></li> <li class="field"><a href="GLib.VariantType.STRING.html">STRING</a></li> <li class="field"><a href="GLib.VariantType.STRING_ARRAY.html">STRING_ARRAY</a></li> <li class="field"><a href="GLib.VariantType.TUPLE.html">TUPLE</a></li> <li class="field"><a href="GLib.VariantType.UINT16.html">UINT16</a></li> <li class="field"><a href="GLib.VariantType.UINT32.html">UINT32</a></li> <li class="field"><a href="GLib.VariantType.UINT64.html">UINT64</a></li> <li class="field"><a href="GLib.VariantType.UNIT.html">UNIT</a></li> <li class="field"><a href="GLib.VariantType.VARDICT.html">VARDICT</a></li> <li class="field"><a href="GLib.VariantType.VARIANT.html">VARIANT</a></li> </ul> </div> <div class="site_content"> <h1 class="main_title">key</h1> <hr class="main_hr"/> <h2 class="main_title">Description:</h2> <div class="main_code_definition"><span class="main_keyword">public</span> <span class="main_keyword">unowned</span> <span class="main_type"><a href="GLib.VariantType.html" class="class">VariantType</a></span> <b><span css="method">key</span></b> () </div> </div> </div><br/> <div class="site_footer">Generated by <a href="http://www.valadoc.org/">Valadoc</a> </div> </body> </html>
themightyug/ledborg-server
doc/glib-2.0/GLib.VariantType.key.html
HTML
gpl-3.0
6,462
# Makefile for NETCONF Agent project # # netconfd directory ############### SOURCE PROFILE ############################## SUBDIR_NM=netconfd SUBDIR_CPP= ############### TARGET PROFILE ############################## TARGET=$(TBASE)/$(SUBDIR_NM) BIN_INST=$(TBASE)/bin REAL_INST=$(DESTDIR)$(PREFIX)/sbin ifdef FREEBSD LIB_INST=$(DESTDIR)$(PREFIX)/lib/yuma else ifdef LIB64 LIB_INST=$(DESTDIR)$(PREFIX)/lib64/yuma else LIB_INST=$(DESTDIR)$(PREFIX)/lib/yuma endif endif PROG=netconfd ##################### LIBRARIES ######################## # The order of these LIBS matters! # # If the linker can't find external symbols you know should # be there and you get an Unresolved External error # file foo : unresolved external to bar # Then put the library that contains 'foo' BEFORE the one # that contains 'bar'. # The ncx library should be last 'internal' library LIBS = -lagt -lncx -lxml2 -lrt -lz -lm ifndef FREEBSD LIBS += -ldl endif LIBTARGS= $(LBASE)/libagt.$(LIBNCXSUFFIX) $(LBASE)/libncx.$(LIBNCXSUFFIX) ############################# MAKE RULES ################## ifdef DEVELOPER all: else all: netconfd endif # DEVELOPER #################### PLATFORM DEFINITIONS ############ include ../platform/platform.profile ################ DEPENDENCIES ######################### # depend rule must be included after the 'all' make rule include ../platform/platform.profile.depend ifneq ($(YUMA_CXX_BUILD),) CFLAGS+= -x c++ LFLAGS+= -x none endif clean: rm -f $(OBJS) $(BIN_INST)/$(PROG) superclean: rm -f *~ *.D dependencies $(OBJS) $(BIN_INST)/$(PROG) test: install: ifndef DEVELOPER mkdir -p $(REAL_INST) mkdir -p $(LIB_INST) install -m 755 $(BIN_INST)/$(PROG) $(REAL_INST) endif # DEVELOPER uninstall: rm -f $(REAL_INST)/$(PROG) rm -rf $(LIB_INST) distclean: superclean # this real rule keeps make from deleting the $(OBJS) as # intermediate files netconfd: $(OBJS) $(LIBTARGS) $(LINK) $(CFLAGS) $(LFLAGS) -rdynamic $(OBJS) \ -o $(BIN_INST)/$(PROG) -L$(PREFIX)/lib $(LPATH) $(FPATH) $(LIBS) .PHONY: netconfd # prevent the make program from choking on all the symbols # that get generated from autogenerated make rules .NOEXPORT: include ./dependencies
Melacon/WirelessTransportEmulator
OpenYuma/netconf/src/netconfd/Makefile
Makefile
gpl-3.0
2,197
/* @file SymbolArea.java * * @author marco corvi * @date dec 2012 * * @brief TopoDroid drawing: area symbol * -------------------------------------------------------- * Copyright This software is distributed under GPL-3.0 or later * See the file COPYING. * -------------------------------------------------------- */ package com.topodroid.DistoX; import com.topodroid.utils.TDMath; import com.topodroid.utils.TDLog; import com.topodroid.utils.TDFile; import com.topodroid.utils.TDColor; import com.topodroid.prefs.TDSetting; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Shader.TileMode; class SymbolArea extends Symbol { String mName; int mColor; boolean mCloseHorizontal; boolean mOrientable; // PRIVATE // FIXME AREA_ORIENT double mOrientation; private Paint mPaint; private Path mPath; Bitmap mBitmap; Bitmap mShaderBitmap = null; BitmapShader mShader; // paint bitmap shader TileMode mXMode; TileMode mYMode; @Override public String getName() { return mName; } @Override public Paint getPaint() { return mPaint; } @Override public Path getPath() { return mPath; } @Override public boolean isOrientable() { return mOrientable; } // @Override public boolean isEnabled() { return mEnabled; } // @Override public void setEnabled( boolean enabled ) { mEnabled = enabled; } // @Override public void toggleEnabled() { mEnabled = ! mEnabled; } // FIXME AREA_ORIENT @Override public boolean setAngle( float angle ) { if ( mBitmap == null ) return false; mOrientation = angle; // TDLog.Error( "ERROR area symbol set orientation " + angle + " not supported" ); android.graphics.Matrix m = new android.graphics.Matrix(); m.preRotate( (float)mOrientation ); mShader.setLocalMatrix( m ); return true; } // FIXME AREA_ORIENT @Override public int getAngle() { return (int)mOrientation; } /** * color 0xaarrggbb * level canvas level */ SymbolArea( String name, String th_name, String group, String fname, int color, Bitmap bitmap, TileMode xmode, TileMode ymode, boolean close_horizontal, int level, int rt ) { super( Symbol.TYPE_AREA, th_name, group, fname, rt ); mName = name; mColor = color; mLevel = level; mBitmap = bitmap; mXMode = xmode; mYMode = ymode; mCloseHorizontal = close_horizontal; mOrientable = false; // FIXME AREA_ORIET mOrientation = 0; mPaint = new Paint(); mPaint.setDither(true); mPaint.setColor( mColor ); mPaint.setAlpha( 0x66 ); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth( TDSetting.mLineThickness ); makeShader( mBitmap, mXMode, mYMode, true ); makeAreaPath(); } // FIXME AREA_ORIENT void rotateGradArea( double a ) { if ( mOrientable ) { // TDLog.Error( "ERROR area symbol rotate by " + a + " not implementd" ); // mOrientation += a; // while ( mOrientation >= 360 ) mOrientation -= 360; // while ( mOrientation < 0 ) mOrientation += 360; mOrientation = TDMath.in360( mOrientation + a ); if ( mShader != null ) { android.graphics.Matrix m = new android.graphics.Matrix(); m.preRotate( (float)mOrientation ); mShader.setLocalMatrix( m ); } } } private void makeAreaPath() { mPath = new Path(); if ( mCloseHorizontal ) { mPath.moveTo( -10, -5 ); mPath.cubicTo( -10, 0, -5, 5, 0, 5 ); mPath.cubicTo( 5, 5, 10, 0, 10, -5 ); mPath.close(); } else { mPath.addCircle( 0, 0, 10, Path.Direction.CCW ); } } SymbolArea( String filepath, String fname, String locale, String iso ) { super( Symbol.TYPE_AREA, null, null, fname, Symbol.W2D_DETAIL_SHP ); mOrientable = false; // FIXME AREA_ORIENT mOrientation = 0; readFile( filepath, locale, iso ); makeAreaPath(); } private Bitmap makeBitmap( int[] pxl, int w1, int h1 ) { if ( w1 > 0 && h1 > 0 ) { int w2 = w1 * 2; int h2 = h1 * 2; int[] pxl2 = new int[ w2 * h2 ]; for ( int j=0; j<h1; ++j ) { for ( int i=0; i < w1; ++i ) { pxl2[j*w2+i] = pxl2[j*w2+i+w1] = pxl2[(j+h1)*w2+i] = pxl2[(j+h1)*w2+i+w1] = pxl[j*w1+i]; } } Bitmap bitmap = Bitmap.createBitmap( w2, h2, Bitmap.Config.ARGB_8888 ); bitmap.setPixels( pxl2, 0, w2, 0, 0, w2, h2 ); // bitmap.setPixels( pxl, 0, width, width, 0, width, height ); // bitmap.setPixels( pxl, 0, width, 0, height, width, height ); // bitmap.setPixels( pxl, 0, width, width, height, width, height ); return bitmap; } return null; } private void makeShader( Bitmap bitmap, TileMode xmode, TileMode ymode, boolean subimage ) { if ( bitmap == null ) return; int width = bitmap.getWidth(); int height = bitmap.getHeight(); if ( width > 0 && height > 0 ) { if ( subimage ) { int w1 = width / 2; int h1 = height / 2; mShaderBitmap = Bitmap.createBitmap( bitmap, w1/2, h1/2, w1, h1 ); } mShader = new BitmapShader( mShaderBitmap, xmode, ymode ); mPaint.setShader( mShader ); } } /** create a symbol reading it from a file * The file syntax is * symbol area * name NAME * th_name THERION_NAME * color 0xHHHHHH_COLOR 0xAA_ALPHA * endsymbol */ private void readFile( String filename, String locale, String iso ) { // TDLog.v( "Area read " + filename + " " + locale + " " + iso ); String name = null; String th_name = null; String group = null; int color = 0; int alpha = 0x66; int alpha_bg = 0x33; mBitmap = null; int width = 0; int height = 0; mXMode = TileMode.REPEAT; mYMode = TileMode.REPEAT; int[] pxl = null; String options = null; try { // FileReader fr = TDFile.getFileReader( filename ); // TDLog.Log( TDLog.LOG_IO, "read symbol area file <" + filename + ">" ); FileInputStream fr = TDFile.getFileInputStream( filename ); BufferedReader br = new BufferedReader( new InputStreamReader( fr, iso ) ); boolean insymbol = false; String line; line = br.readLine(); while ( line != null ) { line = line.trim(); String[] vals = line.split(" "); int s = vals.length; for (int k=0; k<s; ++k ) { if ( vals[k].startsWith( "#" ) ) break; if ( vals[k].length() == 0 ) continue; if ( ! insymbol ) { if ( vals[k].equals("symbol") ) { name = null; th_name = null; mColor = TDColor.TRANSPARENT; insymbol = true; } } else { if ( vals[k].equals("name") || vals[k].equals(locale) ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { // TDLog.v( "found name " + vals[k] ); name = (new String( vals[k].getBytes(iso) )).replace("_", " "); // should .trim(); for tab etc. } // TDLog.v( "area name <" + name + "> locale " + locale ); } else if ( vals[k].equals("th_name") ) { // therion name must not have spaces ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { // should .trim(); for tab etc. ? no: require syntax without tabs etc. th_name = deprefix_u( vals[k] ); } } else if ( vals[k].equals("group") ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { group = vals[k]; // should .trim(); for tab etc. ? no: require syntax without tabs etc. } } else if ( vals[k].equals("options") ) { StringBuilder sb = new StringBuilder(); boolean space = false; for ( ++k; k < s; ++k ) { if ( vals[k].length() > 0 ) { if ( space ) { sb.append(" "); } else { space = true; } sb.append( vals[k] ); } } options = sb.toString(); } else if ( vals[k].equals("csurvey") ) { // csurvey <layer> <category> <pen_type> <brush_type> } else if ( vals[k].equals("level") ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { mLevel = ( Integer.parseInt( vals[k] ) ); } catch( NumberFormatException e ) { TDLog.Error("Non-integer level"); } } } else if ( vals[k].equals("roundtrip") ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { mRoundTrip = ( Integer.parseInt( vals[k] ) ); } catch( NumberFormatException e ) { TDLog.Error("Non-integer roundtrip"); } } } else if ( vals[k].equals("color") ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { color = Integer.decode( vals[k] ); } catch( NumberFormatException e ) { TDLog.Error("Non-integer color"); } } ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { alpha = Integer.decode( vals[k] ); } catch( NumberFormatException e ) { TDLog.Error("Non-integer alpha"); } } ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { alpha_bg = Integer.decode( vals[k] ); } catch( NumberFormatException e ) { TDLog.Error("Non-integer alpha-bg"); } } } else if ( vals[k].equals("bitmap") ) { ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { try { width = Integer.parseInt( vals[k] ); ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { height = Integer.parseInt( vals[k] ); mXMode = TileMode.REPEAT; mYMode = TileMode.REPEAT; ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { if ( vals[k].equals("M") ) { mXMode = TileMode.MIRROR; } ++k; while ( k < s && vals[k].length() == 0 ) ++k; if ( k < s ) { if ( vals[k].equals("M") ) { mYMode = TileMode.MIRROR; } } } if ( width > 0 && height > 0 ) { pxl = new int[ width * height]; int col = (color & 0x00ffffff) | ( alpha_bg << 24 ) ; for ( int j=0; j<height; ++j ) { for ( int i=0; i<width; ++i ) pxl[j*width+i] = col; } col = (color & 0x00ffffff) | ( alpha << 24 ); // TDLog.v( "bitmap " + width + " " + height ); for ( int j=0; j<height; ++j ) { line = br.readLine().trim(); // TDLog.v( "bitmap line <" + line + ">" ); if ( line.startsWith("endbitmap") ) { mBitmap = makeBitmap( pxl, width, height ); pxl = null; break; } for ( int i=0; i<width && i <line.length(); ++i ) if ( line.charAt(i) == '1' ) pxl[j*width+i] = col; } } } } catch ( NumberFormatException e ) { TDLog.Error( filename + " parse bitmap error: " + line ); } } } else if ( vals[k].equals("endbitmap") ) { mBitmap = makeBitmap( pxl, width, height ); pxl = null; } else if ( vals[k].equals("orientable") ) { mOrientable = true; } else if ( vals[k].equals("close-horizontal") ) { mCloseHorizontal = true; } else if ( vals[k].equals("endsymbol") ) { if ( name != null && th_name != null ) { // at this point if both are not null, they have both positive length mName = name; setThName( th_name ); mGroup = group; mDefaultOptions = options; mPaint = new Paint(); mPaint.setDither(true); mColor = (alpha << 24) | color; mPaint.setColor( color ); mPaint.setAlpha( alpha ); // mPaint.setStyle(Paint.Style.STROKE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth( TDSetting.mLineThickness ); } insymbol = false; } } } line = br.readLine(); } } catch ( FileNotFoundException e ) { TDLog.Error( "File not found: " + e.getMessage() ); } catch( IOException e ) { TDLog.Error( "I/O error: " + e.getMessage() ); } makeShader( mBitmap, mXMode, mYMode, true ); } }
marcocorvi/topodroid
src/com/topodroid/DistoX/SymbolArea.java
Java
gpl-3.0
13,878
/***************************************************************************** * Copyright 2014 Christoph Wick * * This file is part of Mencus. * * Mencus 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. * * Mencus 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 * Mencus. If not, see http://www.gnu.org/licenses/. *****************************************************************************/ #include "Sprite.hpp" #include "SpriteTransformPipeline.hpp" #include "XMLHelper.hpp" #include "Map.hpp" using namespace XMLHelper; const Ogre::Vector2 CSpriteTexture::DEFAULT_TEXTURE_TOP_LEFT(0, 1); const Ogre::Vector2 CSpriteTexture::DEFAULT_TEXTURE_BOTTOM_RIGHT(1, 0); CSprite::CSprite(CMap &map, const std::string &sID, CEntity *pParent, const CSpriteTransformPipeline *pTransformPipeline, Ogre2dManager *pSpriteManager, const Ogre::Vector2 &vPosition, const Ogre::Vector2 &vSize, const Ogre::Vector2 &vScale, const Ogre::Radian radRotation) : CPhysicsEntity(map, sID, pParent), m_pTransformPipeline(pTransformPipeline), m_pSpriteManager(pSpriteManager), m_radRotation(radRotation), m_pTextureToDraw(&m_Texture), m_Colour(Ogre::ColourValue::White) { setPosition(vPosition); setSize(vSize); setScale(vScale); setRelativeBoundingBox(CBoundingBox2d(Ogre::Vector2::ZERO, vSize * vScale)); } CSprite::CSprite(CMap &map, CEntity *pParent, const CSpriteTransformPipeline *pTransformPipeline, Ogre2dManager *pSpriteManager, const tinyxml2::XMLElement *pElem, const Ogre::Vector2 &vSize) : CPhysicsEntity(map, pParent, pElem, Ogre::Vector2::ZERO, vSize), m_pTransformPipeline(pTransformPipeline), m_pSpriteManager(pSpriteManager), m_radRotation(RealAttribute(pElem, "sp_radRotation", 0)), m_pTextureToDraw(&m_Texture), m_Colour(Ogre::StringConverter::parseColourValue(Attribute(pElem, "sp_colour", "1 1 1 1"), Ogre::ColourValue::White)) { } CSprite::CSprite(const CSprite &src) : CPhysicsEntity(src), m_pSpriteManager(src.m_pSpriteManager), m_radRotation(src.m_radRotation), m_Texture(src.m_Texture), m_pTextureToDraw(src.m_pTextureToDraw), m_Colour(src.m_Colour) { setPosition(src.m_vPosition); setSize(src.m_vSize); setScale(src.m_vScale); setRelativeBoundingBox(src.m_bbRelativeBoundingBox); } CSprite::~CSprite() { } void CSprite::update(Ogre::Real tpf) { CPhysicsEntity::update(tpf); } void CSprite::render(Ogre::Real tpf) { if (!m_bVisible) {return;} //Ogre::LogManager::getSingleton().logMessage("Test1" + Ogre::StringConverter::toString(m_vPosition) + " //// " + Ogre::StringConverter::toString(m_vSize)); Ogre::Vector2 vStart = m_pTransformPipeline->transformPosition(m_vPosition + m_pTextureToDraw->getSpriteOffset()); Ogre::Vector2 vEnd = m_pTransformPipeline->transformPosition(m_vPosition + m_pTextureToDraw->getSpriteOffset() + m_vSize * m_pTextureToDraw->getSpriteScale()); if (!m_pTransformPipeline->isVisible(vStart, vEnd)) { // not visible return; } m_pSpriteManager->spriteBltFull( m_pTextureToDraw->getTexture()->getName(), vStart.x, vStart.y, vEnd.x, vEnd.y, m_pTextureToDraw->getTexturePosTopLeft().x, m_pTextureToDraw->getTexturePosTopLeft().y, m_pTextureToDraw->getTexturePosBottomRight().x, m_pTextureToDraw->getTexturePosBottomRight().y, m_Colour); CPhysicsEntity::render(tpf); } void CSprite::setTexture(const string &sName) { m_Texture.setTexture(Ogre::TextureManager::getSingleton().getByName(sName)); if (m_Texture.getTexture().isNull()) { m_Texture.setTexture(Ogre::TextureManager::getSingleton().load(sName,Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)); //throw Ogre::Exception(Ogre::Exception::ERR_FILE_NOT_FOUND, sName + " is not found as a texture!", __FILE__); } } void CSprite::writeToXMLElement(tinyxml2::XMLElement *pElem, EOutputStyle eStyle) const { CPhysicsEntity::writeToXMLElement(pElem, eStyle); using namespace XMLHelper; if (eStyle == OS_FULL) { SetAttribute(pElem, "sp_radRotation", m_radRotation.valueRadians()); SetAttribute<Ogre::ColourValue>(pElem, "sp_colour", m_Colour); } }
ChWick/Mencus
Game/Sprite.cpp
C++
gpl-3.0
4,646
require 'chewy/query/filters' class GamesSearch include ActiveModel::Model attr_accessor :query attr_accessor :platform attr_accessor :type attr_accessor :not_id def index GamesIndex end def search query_string end def expansions_count index.filter(type: { value: 'expansion' }).search_type(:count) end def editions_count index.filter(type: { value: 'edition' }).search_type(:count) end def all if platform.present? index.query(match: { platform_id: platform }) else index.filter { match_all } end end def all_except(edition_ids, expansion_ids) all .filter(not: {terms: {edition_id: edition_ids}}) .filter(not: {terms: {expansion_id: expansion_ids}}) end def query_string if not_id.present? type_query.filter(not: { ids: { values: [not_id] } }) else type_query end end def type_query if type.present? platform_query.filter(type: { value: type }) else platform_query end end def platform_query if platform.present? index_query.filter(term: { platform_id: platform }) else index_query end end def index_query index.query(bool: { should: [ { multi_match: { fields: [:title], query: query, operator: 'AND' } }, { multi_match: { fields: [:title], query: query, fuzziness: 'AUTO', operator: 'AND' } } ] } ) if query.present? end end
internetvideogamelibrary/internetvideogamelibrary-website
app/searches/games_search.rb
Ruby
gpl-3.0
1,857
/* Copyright 2009-2016 EPFL, Lausanne */ package leon package xlang import purescala.Common._ import purescala.Types._ import purescala.Expressions._ import purescala.Extractors._ import purescala.{PrettyPrintable, PrinterContext} import utils._ object Expressions { import purescala.PrinterHelpers._ trait XLangExpr extends Expr case class Old(id: Identifier) extends XLangExpr with Terminal with PrettyPrintable { val getType = id.getType def printWith(implicit pctx: PrinterContext): Unit = { p"old($id)" } } case class OldThis(ct: ClassType) extends XLangExpr with Terminal with PrettyPrintable { val getType = ct def printWith(implicit pctx: PrinterContext): Unit = { p"old(this)" } } case class Block(exprs: Seq[Expr], last: Expr) extends XLangExpr with Extractable with PrettyPrintable { def extract: Option[(Seq[Expr], (Seq[Expr])=>Expr)] = { Some((exprs :+ last, exprs => Block(exprs.init, exprs.last))) } override def getPos = exprs.headOption match { case Some(head) => Position.between(head.getPos, last.getPos) case None => last.getPos } def printWith(implicit pctx: PrinterContext) { p"${nary(exprs :+ last, "\n")}" } val getType = last.getType override def isSimpleExpr = false } case class Assignment(varId: Identifier, expr: Expr) extends XLangExpr with Extractable with PrettyPrintable { val getType = UnitType def extract: Option[(Seq[Expr], Seq[Expr]=>Expr)] = { Some((Seq(expr), (es: Seq[Expr]) => Assignment(varId, es.head))) } def printWith(implicit pctx: PrinterContext) { p"$varId = $expr" } } case class FieldAssignment(obj: Expr, varId: Identifier, expr: Expr) extends XLangExpr with Extractable with PrettyPrintable { val getType = UnitType def extract: Option[(Seq[Expr], Seq[Expr]=>Expr)] = { Some((Seq(obj, expr), (es: Seq[Expr]) => FieldAssignment(es(0), varId, es(1)))) } def printWith(implicit pctx: PrinterContext) { p"${obj}.${varId} = ${expr}" } } case class While(cond: Expr, body: Expr) extends XLangExpr with Extractable with PrettyPrintable { val getType = UnitType var invariant: Option[Expr] = None def getInvariant: Expr = invariant.get def setInvariant(inv: Expr) = { invariant = Some(inv); this } def setInvariant(inv: Option[Expr]) = { invariant = inv; this } def extract: Option[(Seq[Expr], Seq[Expr]=>Expr)] = { Some((Seq(cond, body) ++ invariant, { (es:Seq[Expr]) => es match { case Seq(e1, e2) => While(e1, e2).setPos(this) case Seq(e1, e2, e3) => While(e1, e2).setInvariant(e3).setPos(this) }})) } def printWith(implicit pctx: PrinterContext) { invariant match { case Some(inv) => p"""|@invariant($inv) |""" case None => } p"""|while($cond) { | $body |}""" } } case class Epsilon(pred: Expr, tpe: TypeTree) extends XLangExpr with Extractable with PrettyPrintable { def extract: Option[(Seq[Expr], Seq[Expr]=>Expr)] = { Some((Seq(pred), (es: Seq[Expr]) => Epsilon(es.head, this.getType).setPos(this))) } def printWith(implicit pctx: PrinterContext) { p"epsilon(x${getPos.line}_${getPos.col} => $pred)" } val getType = tpe } case class EpsilonVariable(pos: Position, tpe: TypeTree) extends XLangExpr with Terminal with PrettyPrintable { def printWith(implicit pctx: PrinterContext) { p"x${pos.line}_${pos.col}" } val getType = tpe } //same as let, buf for mutable variable declaration case class LetVar(binder: Identifier, value: Expr, body: Expr) extends XLangExpr with Extractable with PrettyPrintable { val getType = body.getType def extract: Option[(Seq[Expr], Seq[Expr]=>Expr)] = { Some( Seq(value, body), (es:Seq[Expr]) => LetVar(binder, es(0), es(1)) ) } def printWith(implicit pctx: PrinterContext) { p"""|var $binder : ${binder.getType} = $value |$body""" } override def isSimpleExpr = false } case class ArrayUpdate(array: Expr, index: Expr, newValue: Expr) extends XLangExpr with Extractable with PrettyPrintable { val getType = UnitType def extract: Option[(Seq[Expr], (Seq[Expr])=>Expr)] = { val ArrayUpdate(t1, t2, t3) = this Some((Seq(t1,t2,t3), (as: Seq[Expr]) => ArrayUpdate(as(0), as(1), as(2)))) } def printWith(implicit pctx: PrinterContext) { p"$array($index) = $newValue" } } }
epfl-lara/leon
src/main/scala/leon/xlang/Expressions.scala
Scala
gpl-3.0
4,566
package com.github.xabgesagtx.mensa.bot.date; import lombok.AllArgsConstructor; import lombok.Getter; import java.time.LocalDate; import java.util.Optional; /** * Wrapper class to hold the search result for a specific date */ @Getter @AllArgsConstructor(staticName = "of") public class DateSearchResult { private final LocalDate date; private final Optional<LocalDate> alternativeDate; public LocalDate getDateToUse() { return alternativeDate.orElse(date); } }
xabgesagtx/mensa-api
mensa-telegram/src/main/java/com/github/xabgesagtx/mensa/bot/date/DateSearchResult.java
Java
gpl-3.0
493
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* 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/>. */ /* * AP_Compass_HMC5843.cpp - Arduino Library for HMC5843 I2C magnetometer * Code by Jordi Muñoz and Jose Julio. DIYDrones.com * * Sensor is conected to I2C port * Sensor is initialized in Continuos mode (10Hz) * */ #include <AP_HAL/AP_HAL.h> #ifdef HAL_COMPASS_HMC5843_I2C_ADDR #include <assert.h> #include <utility> #include <AP_Math/AP_Math.h> #include <AP_HAL/AP_HAL.h> #include <AP_HAL/utility/sparse-endian.h> #include "AP_Compass_HMC5843.h" #include <AP_InertialSensor/AP_InertialSensor.h> #include <AP_InertialSensor/AuxiliaryBus.h> extern const AP_HAL::HAL& hal; /* * Defaul address: 0x1E */ #define HMC5843_REG_CONFIG_A 0x00 // Valid sample averaging for 5883L #define HMC5843_SAMPLE_AVERAGING_1 (0x00 << 5) #define HMC5843_SAMPLE_AVERAGING_2 (0x01 << 5) #define HMC5843_SAMPLE_AVERAGING_4 (0x02 << 5) #define HMC5843_SAMPLE_AVERAGING_8 (0x03 << 5) // Valid data output rates for 5883L #define HMC5843_OSR_0_75HZ (0x00 << 2) #define HMC5843_OSR_1_5HZ (0x01 << 2) #define HMC5843_OSR_3HZ (0x02 << 2) #define HMC5843_OSR_7_5HZ (0x03 << 2) #define HMC5843_OSR_15HZ (0x04 << 2) #define HMC5843_OSR_30HZ (0x05 << 2) #define HMC5843_OSR_75HZ (0x06 << 2) // Sensor operation modes #define HMC5843_OPMODE_NORMAL 0x00 #define HMC5843_OPMODE_POSITIVE_BIAS 0x01 #define HMC5843_OPMODE_NEGATIVE_BIAS 0x02 #define HMC5843_OPMODE_MASK 0x03 #define HMC5843_REG_CONFIG_B 0x01 #define HMC5883L_GAIN_0_88_GA (0x00 << 5) #define HMC5883L_GAIN_1_30_GA (0x01 << 5) #define HMC5883L_GAIN_1_90_GA (0x02 << 5) #define HMC5883L_GAIN_2_50_GA (0x03 << 5) #define HMC5883L_GAIN_4_00_GA (0x04 << 5) #define HMC5883L_GAIN_4_70_GA (0x05 << 5) #define HMC5883L_GAIN_5_60_GA (0x06 << 5) #define HMC5883L_GAIN_8_10_GA (0x07 << 5) #define HMC5843_GAIN_0_70_GA (0x00 << 5) #define HMC5843_GAIN_1_00_GA (0x01 << 5) #define HMC5843_GAIN_1_50_GA (0x02 << 5) #define HMC5843_GAIN_2_00_GA (0x03 << 5) #define HMC5843_GAIN_3_20_GA (0x04 << 5) #define HMC5843_GAIN_3_80_GA (0x05 << 5) #define HMC5843_GAIN_4_50_GA (0x06 << 5) #define HMC5843_GAIN_6_50_GA (0x07 << 5) #define HMC5843_REG_MODE 0x02 #define HMC5843_MODE_CONTINUOUS 0x00 #define HMC5843_MODE_SINGLE 0x01 #define HMC5843_REG_DATA_OUTPUT_X_MSB 0x03 AP_Compass_HMC5843::AP_Compass_HMC5843(Compass &compass, AP_HMC5843_BusDriver *bus, bool force_external) : AP_Compass_Backend(compass) , _bus(bus) , _force_external(force_external) { } AP_Compass_HMC5843::~AP_Compass_HMC5843() { delete _bus; } AP_Compass_Backend *AP_Compass_HMC5843::probe(Compass &compass, AP_HAL::OwnPtr<AP_HAL::I2CDevice> dev, bool force_external) { AP_HMC5843_BusDriver *bus = new AP_HMC5843_BusDriver_HALDevice(std::move(dev)); if (!bus) { return nullptr; } AP_Compass_HMC5843 *sensor = new AP_Compass_HMC5843(compass, bus, force_external); if (!sensor || !sensor->init()) { delete sensor; return nullptr; } return sensor; } AP_Compass_Backend *AP_Compass_HMC5843::probe_mpu6000(Compass &compass) { AP_InertialSensor &ins = *AP_InertialSensor::get_instance(); AP_HMC5843_BusDriver *bus = new AP_HMC5843_BusDriver_Auxiliary(ins, HAL_INS_MPU60XX_SPI, HAL_COMPASS_HMC5843_I2C_ADDR); if (!bus) { return nullptr; } AP_Compass_HMC5843 *sensor = new AP_Compass_HMC5843(compass, bus, false); if (!sensor || !sensor->init()) { delete sensor; return nullptr; } return sensor; } bool AP_Compass_HMC5843::init() { hal.scheduler->suspend_timer_procs(); AP_HAL::Semaphore *bus_sem = _bus->get_semaphore(); if (!bus_sem || !bus_sem->take(HAL_SEMAPHORE_BLOCK_FOREVER)) { hal.console->printf("HMC5843: Unable to get bus semaphore\n"); goto fail_sem; } if (!_bus->configure()) { hal.console->printf("HMC5843: Could not configure the bus\n"); goto errout; } if (!_detect_version()) { hal.console->printf("HMC5843: Could not detect version\n"); goto errout; } if (!_calibrate()) { hal.console->printf("HMC5843: Could not calibrate sensor\n"); goto errout; } if (!_setup_sampling_mode()) { goto errout; } if (!_bus->start_measurements()) { hal.console->printf("HMC5843: Could not start measurements on bus\n"); goto errout; } _initialised = true; bus_sem->give(); hal.scheduler->resume_timer_procs(); // perform an initial read read(); _compass_instance = register_compass(); set_dev_id(_compass_instance, _product_id); if (_force_external) { set_external(_compass_instance, true); } return true; errout: bus_sem->give(); fail_sem: hal.scheduler->resume_timer_procs(); return false; } /* * Accumulate a reading from the magnetometer * * bus semaphore must not be taken */ void AP_Compass_HMC5843::accumulate() { if (!_initialised) { // someone has tried to enable a compass for the first time // mid-flight .... we can't do that yet (especially as we won't // have the right orientation!) return; } uint32_t tnow = AP_HAL::micros(); if (_accum_count != 0 && (tnow - _last_accum_time) < 13333) { // the compass gets new data at 75Hz return; } if (!_bus->get_semaphore()->take(1)) { // the bus is busy - try again later return; } bool result = _read_sample(); _bus->get_semaphore()->give(); if (!result) { return; } // the _mag_N values are in the range -2048 to 2047, so we can // accumulate up to 15 of them in an int16_t. Let's make it 14 // for ease of calculation. We expect to do reads at 10Hz, and // we get new data at most 75Hz, so we don't expect to // accumulate more than 8 before a read // get raw_field - sensor frame, uncorrected Vector3f raw_field = Vector3f(_mag_x, _mag_y, _mag_z); raw_field *= _gain_scale; // rotate to the desired orientation if (is_external(_compass_instance) && _product_id == AP_COMPASS_TYPE_HMC5883L) { raw_field.rotate(ROTATION_YAW_90); } // rotate raw_field from sensor frame to body frame rotate_field(raw_field, _compass_instance); // publish raw_field (uncorrected point sample) for calibration use publish_raw_field(raw_field, tnow, _compass_instance); // correct raw_field for known errors correct_field(raw_field, _compass_instance); _mag_x_accum += raw_field.x; _mag_y_accum += raw_field.y; _mag_z_accum += raw_field.z; _accum_count++; if (_accum_count == 14) { _mag_x_accum /= 2; _mag_y_accum /= 2; _mag_z_accum /= 2; _accum_count = 7; } _last_accum_time = tnow; } /* * Take accumulated reads from the magnetometer or try to read once if no * valid data * * bus semaphore must not be locked */ void AP_Compass_HMC5843::read() { if (!_initialised) { // someone has tried to enable a compass for the first time // mid-flight .... we can't do that yet (especially as we won't // have the right orientation!) return; } if (_accum_count == 0) { accumulate(); if (_retry_time != 0) { return; } } Vector3f field(_mag_x_accum * _scaling[0], _mag_y_accum * _scaling[1], _mag_z_accum * _scaling[2]); field /= _accum_count; _accum_count = 0; _mag_x_accum = _mag_y_accum = _mag_z_accum = 0; publish_filtered_field(field, _compass_instance); } bool AP_Compass_HMC5843::_setup_sampling_mode() { if (!_bus->register_write(HMC5843_REG_CONFIG_A, _base_config) || !_bus->register_write(HMC5843_REG_CONFIG_B, _gain_config) || !_bus->register_write(HMC5843_REG_MODE, HMC5843_MODE_CONTINUOUS)) { return false; } return true; } /* * Read Sensor data - bus semaphore must be taken */ bool AP_Compass_HMC5843::_read_sample() { struct PACKED { be16_t rx; be16_t ry; be16_t rz; } val; int16_t rx, ry, rz; if (_retry_time > AP_HAL::millis()) { return false; } if (!_bus->block_read(HMC5843_REG_DATA_OUTPUT_X_MSB, (uint8_t *) &val, sizeof(val))){ _retry_time = AP_HAL::millis() + 1000; return false; } rx = be16toh(val.rx); ry = be16toh(val.ry); rz = be16toh(val.rz); if (_product_id == AP_COMPASS_TYPE_HMC5883L) { std::swap(ry, rz); } if (rx == -4096 || ry == -4096 || rz == -4096) { // no valid data available return false; } _mag_x = -rx; _mag_y = ry; _mag_z = -rz; _retry_time = 0; return true; } bool AP_Compass_HMC5843::_detect_version() { _base_config = 0x0; uint8_t try_config = HMC5843_SAMPLE_AVERAGING_8 | HMC5843_OSR_75HZ | HMC5843_OPMODE_NORMAL; if (!_bus->register_write(HMC5843_REG_CONFIG_A, try_config) || !_bus->register_read(HMC5843_REG_CONFIG_A, &_base_config)) { return false; } if (_base_config == try_config) { /* a 5883L supports the sample averaging config */ _product_id = AP_COMPASS_TYPE_HMC5883L; _gain_config = HMC5883L_GAIN_1_30_GA; _gain_scale = (1.0f / 1090) * 1000; } else if (_base_config == (HMC5843_OPMODE_NORMAL | HMC5843_OSR_75HZ)) { _product_id = AP_COMPASS_TYPE_HMC5843; _gain_config = HMC5843_GAIN_1_00_GA; _gain_scale = (1.0f / 1300) * 1000; } else { /* not behaving like either supported compass type */ return false; } return true; } bool AP_Compass_HMC5843::_calibrate() { uint8_t calibration_gain; uint16_t expected_x; uint16_t expected_yz; int numAttempts = 0, good_count = 0; bool success = false; if (_product_id == AP_COMPASS_TYPE_HMC5883L) { calibration_gain = HMC5883L_GAIN_2_50_GA; /* * note that the HMC5883 datasheet gives the x and y expected * values as 766 and the z as 713. Experiments have shown the x * axis is around 766, and the y and z closer to 713. */ expected_x = 766; expected_yz = 713; } else { calibration_gain = HMC5843_GAIN_1_00_GA; expected_x = 715; expected_yz = 715; } uint8_t old_config = _base_config & ~(HMC5843_OPMODE_MASK); while (success == 0 && numAttempts < 25 && good_count < 5) { numAttempts++; // force positiveBias (compass should return 715 for all channels) if (!_bus->register_write(HMC5843_REG_CONFIG_A, old_config | HMC5843_OPMODE_POSITIVE_BIAS)) { // compass not responding on the bus continue; } hal.scheduler->delay(50); // set gains if (!_bus->register_write(HMC5843_REG_CONFIG_B, calibration_gain) || !_bus->register_write(HMC5843_REG_MODE, HMC5843_MODE_SINGLE)) { continue; } // read values from the compass hal.scheduler->delay(50); if (!_read_sample()) { // we didn't read valid values continue; } float cal[3]; // hal.console->printf("mag %d %d %d\n", _mag_x, _mag_y, _mag_z); cal[0] = fabsf(expected_x / (float)_mag_x); cal[1] = fabsf(expected_yz / (float)_mag_y); cal[2] = fabsf(expected_yz / (float)_mag_z); // hal.console->printf("cal=%.2f %.2f %.2f\n", cal[0], cal[1], cal[2]); // we throw away the first two samples as the compass may // still be changing its state from the application of the // strap excitation. After that we accept values in a // reasonable range if (numAttempts <= 2) { continue; } #define IS_CALIBRATION_VALUE_VALID(val) (val > 0.7f && val < 1.35f) if (IS_CALIBRATION_VALUE_VALID(cal[0]) && IS_CALIBRATION_VALUE_VALID(cal[1]) && IS_CALIBRATION_VALUE_VALID(cal[2])) { // hal.console->printf("car=%.2f %.2f %.2f good\n", cal[0], cal[1], cal[2]); good_count++; _scaling[0] += cal[0]; _scaling[1] += cal[1]; _scaling[2] += cal[2]; } #undef IS_CALIBRATION_VALUE_VALID #if 0 /* useful for debugging */ hal.console->printf("MagX: %d MagY: %d MagZ: %d\n", (int)_mag_x, (int)_mag_y, (int)_mag_z); hal.console->printf("CalX: %.2f CalY: %.2f CalZ: %.2f\n", cal[0], cal[1], cal[2]); #endif } if (good_count >= 5) { _scaling[0] = _scaling[0] / good_count; _scaling[1] = _scaling[1] / good_count; _scaling[2] = _scaling[2] / good_count; success = true; } else { /* best guess */ _scaling[0] = 1.0; _scaling[1] = 1.0; _scaling[2] = 1.0; } return success; } /* AP_HAL::I2CDevice implementation of the HMC5843 */ AP_HMC5843_BusDriver_HALDevice::AP_HMC5843_BusDriver_HALDevice(AP_HAL::OwnPtr<AP_HAL::I2CDevice> dev) : _dev(std::move(dev)) { } bool AP_HMC5843_BusDriver_HALDevice::block_read(uint8_t reg, uint8_t *buf, uint32_t size) { return _dev->read_registers(reg, buf, size); } bool AP_HMC5843_BusDriver_HALDevice::register_read(uint8_t reg, uint8_t *val) { return _dev->read_registers(reg, val, 1); } bool AP_HMC5843_BusDriver_HALDevice::register_write(uint8_t reg, uint8_t val) { return _dev->write_register(reg, val); } AP_HAL::Semaphore *AP_HMC5843_BusDriver_HALDevice::get_semaphore() { return _dev->get_semaphore(); } /* HMC5843 on an auxiliary bus of IMU driver */ AP_HMC5843_BusDriver_Auxiliary::AP_HMC5843_BusDriver_Auxiliary(AP_InertialSensor &ins, uint8_t backend_id, uint8_t addr) { /* * Only initialize members. Fails are handled by configure or while * getting the semaphore */ _bus = ins.get_auxiliary_bus(backend_id); if (!_bus) { return; } _slave = _bus->request_next_slave(addr); } AP_HMC5843_BusDriver_Auxiliary::~AP_HMC5843_BusDriver_Auxiliary() { /* After started it's owned by AuxiliaryBus */ if (!_started) { delete _slave; } } bool AP_HMC5843_BusDriver_Auxiliary::block_read(uint8_t reg, uint8_t *buf, uint32_t size) { if (_started) { /* * We can only read a block when reading the block of sample values - * calling with any other value is a mistake */ assert(reg == HMC5843_REG_DATA_OUTPUT_X_MSB); int n = _slave->read(buf); return n == static_cast<int>(size); } int r = _slave->passthrough_read(reg, buf, size); return r > 0 && static_cast<uint32_t>(r) == size; } bool AP_HMC5843_BusDriver_Auxiliary::register_read(uint8_t reg, uint8_t *val) { return _slave->passthrough_read(reg, val, 1) == 1; } bool AP_HMC5843_BusDriver_Auxiliary::register_write(uint8_t reg, uint8_t val) { return _slave->passthrough_write(reg, val) == 1; } AP_HAL::Semaphore *AP_HMC5843_BusDriver_Auxiliary::get_semaphore() { return _bus->get_semaphore(); } bool AP_HMC5843_BusDriver_Auxiliary::configure() { if (!_bus || !_slave) { return false; } return true; } bool AP_HMC5843_BusDriver_Auxiliary::start_measurements() { if (_bus->register_periodic_read(_slave, HMC5843_REG_DATA_OUTPUT_X_MSB, 6) < 0) { return false; } _started = true; return true; } #endif
roger-zhao/ardupilot-3.3
libraries/AP_Compass/AP_Compass_HMC5843.cpp
C++
gpl-3.0
16,360
package com.bitblocker.messenger.ui.view; import android.content.Context; import android.graphics.PointF; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.DisplayMetrics; public class SmoothLinearLayoutManager extends LinearLayoutManager { private static final float MILLISECONDS_PER_INCH = 50f; private Context mContext; public SmoothLinearLayoutManager(Context context) { super(context); mContext = context; } public SmoothLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); mContext = context; } public SmoothLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); mContext = context; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, final int position) { super.smoothScrollToPosition(recyclerView, state, position); LinearSmoothScroller smoothScroller = new LinearSmoothScroller(mContext) { //This controls the direction in which smoothScroll looks for your view @Override public PointF computeScrollVectorForPosition(int targetPosition) { return new PointF(0, 1); } //This returns the milliseconds it takes to scroll one pixel. @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { return MILLISECONDS_PER_INCH / displayMetrics.densityDpi; } }; smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); } }
Dato0011/btb-sms
QKSMS/src/main/java/com/bitblocker/messenger/ui/view/SmoothLinearLayoutManager.java
Java
gpl-3.0
1,903
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[5]; atomic_int atom_0_r1_1; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; int v2_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v3_r3 = v2_r1 ^ v2_r1; int v4_r3 = v3_r3 + 1; atomic_store_explicit(&vars[1], v4_r3, memory_order_seq_cst); int v18 = (v2_r1 == 1); atomic_store_explicit(&atom_0_r1_1, v18, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v6_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v7_r3 = v6_r1 ^ v6_r1; int v10_r4 = atomic_load_explicit(&vars[2+v7_r3], memory_order_seq_cst); int v11_cmpeq = (v10_r4 == v10_r4); if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[3], 1, memory_order_seq_cst); int v13_r8 = atomic_load_explicit(&vars[3], memory_order_seq_cst); int v14_cmpeq = (v13_r8 == v13_r8); if (v14_cmpeq) goto lbl_LC01; else goto lbl_LC01; lbl_LC01:; atomic_store_explicit(&vars[4], 1, memory_order_seq_cst); atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); int v19 = (v6_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v19, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[4], 0); atomic_init(&vars[1], 0); atomic_init(&vars[2], 0); atomic_init(&vars[0], 0); atomic_init(&atom_0_r1_1, 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v15 = atomic_load_explicit(&atom_0_r1_1, memory_order_seq_cst); int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v17_conj = v15 & v16; if (v17_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/LB+PPO0258.c
C
gpl-3.0
1,974
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>sctek Device Tools</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div id="sctek" class="container jk-leavetop"> <div> <div class="list-title">Device Lists:</div> <table class="table table-bordered table-dark"> <thead><td>Version</td><td>LastSend</td><td>IP</td><td>Mac</td><td>DevType</td><td>RemoteIP</td><td>ActionType</td><td>Online</td></thead> {{ range $k, $v := . }} <tr><td>{{ $v.Version }}</td> <td>{{ $v.Time }}</td> <td>{{ $v.IP }}</td> <td>{{ $v.Mac }}</td> <td>{{ $v.DevType }}</td> <td>{{ $v.RemoteIp }}</td> <td>{{ $v.ActionType }}</td> <td>{{ $v.Online }}</td> </tr> {{ end }} </table> </div> </body> </html>
jmdkina/jkgo
html/sctek/sctek_status.html
HTML
gpl-3.0
1,070
/* Copyright 2005 Simon Mieth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.kabeja.dxf.helpers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author <a href="mailto:simon.mieth@gmx.de>Simon Mieth</a> * */ public class TextDocument { protected List paragraphs = new ArrayList(); /** * Return the pure text content. * * @return the text content */ public String getText() { Iterator i = this.paragraphs.iterator(); StringBuffer buf = new StringBuffer(); while (i.hasNext()) { StyledTextParagraph para = (StyledTextParagraph) i.next(); buf.append(para.getText()); if (para.isNewline()) { buf.append('\n'); } } return buf.toString(); } public void addStyledParagraph(StyledTextParagraph para) { this.paragraphs.add(para); } public Iterator getStyledParagraphIterator() { return this.paragraphs.iterator(); } public int getParagraphCount() { return this.paragraphs.size(); } public StyledTextParagraph getStyleTextParagraph(int i) { return (StyledTextParagraph) this.paragraphs.get(i); } public int getLineCount() { int count = 1; Iterator i = this.paragraphs.iterator(); while (i.hasNext()) { StyledTextParagraph para = (StyledTextParagraph) i.next(); if (para.isNewline()) { count++; } } return count; } public int getMaximumLineLength() { int count = 0; int max = 0; Iterator i = paragraphs.iterator(); while (i.hasNext()) { StyledTextParagraph para = (StyledTextParagraph) i.next(); if (!para.isNewline()) { count += para.getLength(); } else { if (count > max) { max = count; } count = para.getLength(); } } return max; } }
winder/Universal-G-Code-Sender
ugs-platform/ugs-platform-plugin-designer/src/main/java/org/kabeja/dxf/helpers/TextDocument.java
Java
gpl-3.0
2,601
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct create_only_t</title> <link rel="stylesheet" href="../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.75.2"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../boost_interprocess_reference.html#header.boost.interprocess.creation_tags_hpp" title="Header &lt;boost/interprocess/creation_tags.hpp&gt;"> <link rel="prev" href="zero_memory.html" title="Global zero_memory"> <link rel="next" href="open_only_t.html" title="Struct open_only_t"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="zero_memory.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_interprocess_reference.html#header.boost.interprocess.creation_tags_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="open_only_t.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> <div class="refentry" title="Struct create_only_t"> <a name="boost.interprocess.create_only_t"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct create_only_t</span></h2> <p>boost::interprocess::create_only_t</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="emphasis"><em>// In header: &lt;<a class="link" href="../../boost_interprocess_reference.html#header.boost.interprocess.creation_tags_hpp" title="Header &lt;boost/interprocess/creation_tags.hpp&gt;">boost/interprocess/creation_tags.hpp</a>&gt; </em></span> <span class="bold"><strong>struct</strong></span> <a class="link" href="create_only_t.html" title="Struct create_only_t">create_only_t</a> { };</pre></div> <div class="refsect1" title="Description"> <a name="id1018286"></a><h2>Description</h2> <p>Tag to indicate that the resource must be only created </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005 - 2008 Ion Gaztanaga<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="zero_memory.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_interprocess_reference.html#header.boost.interprocess.creation_tags_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="open_only_t.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a> </div> </body> </html>
kelvindk/Video-Stabilization
boost_1_42_0/doc/html/boost/interprocess/create_only_t.html
HTML
gpl-3.0
3,908
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2013 Kai Reinhard (k.reinhard@micromata.de) // // ProjectForge is dual-licensed. // // This community edition 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 community edition 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.projectforge.plugins.todo; import org.apache.log4j.Logger; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.projectforge.web.mobile.AbstractMobileEditPage; import org.projectforge.web.mobile.AbstractMobileListPage; public class ToDoMobileEditPage extends AbstractMobileEditPage<ToDoDO, ToDoMobileEditForm, ToDoDao> { private static final long serialVersionUID = 3060701092253890337L; private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ToDoMobileEditPage.class); @SpringBean(name = "toDoDao") private ToDoDao toDoDao; public ToDoMobileEditPage(final PageParameters parameters) { super(parameters, "toDo"); init(); } @Override protected ToDoDao getBaseDao() { return toDoDao; } @Override protected Logger getLogger() { return log; } @Override protected ToDoMobileEditForm newEditForm(final AbstractMobileEditPage< ? , ? , ? > parentPage, final ToDoDO data) { return new ToDoMobileEditForm(this, data); } @Override protected Class< ? extends AbstractMobileListPage< ? , ? , ? >> getListPageClass() { return ToDoMobileListPage.class; } }
developerleo/ProjectForge-2nd
src/main/java/org/projectforge/plugins/todo/ToDoMobileEditPage.java
Java
gpl-3.0
2,214
{% extends "base.html" %} {% load staticfiles %} {% load i18n %} {% load thumbnail %} {% load votainteligente_extras %} {% load bootstrap3 %} {% block title %}- {% trans "Candidatos Chile 2017" %}{% endblock title %} {% block description %}{% trans "Conoce tus congresistas y sus compromisos" %}{% endblock description %} {% block everything %} <div class="container"> <h1 class="text-center">{% trans "Congresistas comprometidos" %}</h1> <p class="bajada text-center">{% trans "Encuentra aquí los nuevos/as diputados/as y senadores/as y sus compromisos con propuestas ciudadanas de votainteligente.cl" %}</p> </div> {% display_election_card default_election %} <div class="container"> {% for pos in positions %} <h2>{{pos.name}}</h2> <div class="row"> {% for candidate in pos.candidates %} {% include "_candidate_small.html" with candidate=candidate%} {% if forloop.counter|divisibleby:6 %} </div><div class="row"> {% endif %} {% endfor %} </div> {% endfor %} </div> {% endblock everything %}
ciudadanointeligente/votainteligente-portal-electoral
votai_general_theme/templates/know_your_candidates.html
HTML
gpl-3.0
1,027
/*************************************************************************************************** * * RunlessBASIC * Copyright 2013 Joshua Hawcroft <dev@joshhawcroft.com> * * test.h * (see C source file for details) * *************************************************************************************************** * * RunlessBASIC 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. * * RunlessBASIC 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 RunlessBASIC. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************************************/ #include <assert.h> #ifndef _TEST_H #define _TEST_H #ifdef DEBUG #define STRINGIZE(x) STRINGIZE2(x) #define STRINGIZE2(x) #x #define LINE_STRING STRINGIZE(__LINE__) #define CHECK(cond) if (!(cond)) return "Condition not satisfied at line " LINE_STRING; typedef const char* (*TestCaseRunner)(void *in_user, const char *in_file, int in_case_number, const char *in_input, const char *in_output); typedef void (*TestCaseResult)(void *in_user, const char *in_file, int in_case_number, long in_line_number, const char *in_error); const char* test_run_cases(const char *in_filename, TestCaseRunner in_case_runner, TestCaseResult in_result_handler, void *in_user); #endif #endif
jhawcroft/runlessbasic
Compiler/test.h
C
gpl-3.0
1,760
/* * mpu9150_l.c * * Created on: 2014/3/8 * Author: koyunbaba */ #include "mpu9150_l.h" #include "mpu9150_def.h" int MPU9150_WriteReg(XIicPs *i2c_drv, u8 addr, u8 *data, int len) { int status; int i; u8 packet[2]; // TODO: burst write packet[0] = addr; for(i = 0; i < len; i++) { packet[1] = data[i]; status = XIicPs_MasterSendPolled(i2c_drv, packet, 2, MPU9150_I2C_ADDR); while (XIicPs_BusIsBusy(i2c_drv)); if(status != XST_SUCCESS) break; } return status; } int MPU9150_ReadReg(XIicPs *i2c_drv, u8 addr, u8 *data, int len) { int status; status = XIicPs_MasterSendPolled(i2c_drv, &addr, 1, MPU9150_I2C_ADDR); while (XIicPs_BusIsBusy(i2c_drv)); if(status != XST_SUCCESS) return status; status = XIicPs_MasterRecvPolled(i2c_drv, data, len, MPU9150_I2C_ADDR); if(status != XST_SUCCESS) return status; return XST_SUCCESS; }
koyunbaba/zc702_mpu9150
hello_world/src/mpu9150_l.c
C
gpl-3.0
936
<?php get_header(); //include header.php ?> <main id="content"> <?php //THE LOOP if( have_posts() ): ?> <?php while( have_posts() ): the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_post_thumbnail( 'large' , array( 'class' => 'product-image alignright' ) ); ?> <h2 class="entry-title"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h2> <div class="entry-content"> <?php the_meta(); //list of all custom fields ?> <?php the_terms( $post->ID, 'brand', '<b>Brand:</b> ' ); ?> <?php the_terms( $post->ID, 'feature', '<br /><b>Features:</b> ' ); ?> <?php the_content(); ?> </div> </article><!-- end post --> <?php endwhile; ?> <div class="pagination"> <?php if( is_single() ){ //single pagination next_post_link('%link', '&larr; Newer Product: %title ' ); //newer post previous_post_link( '%link', ' Older Product: %title &rarr;' ); //older post }else{ //archive pagination //use pagenavi plugin if it exists if( function_exists('wp_pagenavi') ){ wp_pagenavi(); }else{ next_posts_link('&larr; Older Posts'); //older posts previous_posts_link('Newer Posts &rarr;'); //newer posts } } ?> </div> <?php else: ?> <h2>Sorry, no posts found</h2> <p>Try using the search bar instead</p> <?php endif; //end THE LOOP ?> </main><!-- end #content --> <?php get_sidebar( 'shop' ); //include sidebar.php ?> <?php get_footer(); //include footer.php ?>
melissacabral/awesome-theme-0514
single-product.php
PHP
gpl-3.0
1,554
/************************************************************************* * Copyright 2009-2014 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; 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/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, 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. ************************************************************************/ package com.eucalyptus.context; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.log4j.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.Channels; import org.mule.RequestContext; import org.mule.api.MuleMessage; import com.eucalyptus.BaseException; import com.eucalyptus.http.MappingHttpRequest; import com.eucalyptus.records.EventRecord; import com.eucalyptus.records.EventType; import com.eucalyptus.records.Logs; import com.eucalyptus.util.Consumer; import com.eucalyptus.util.Consumers; import com.eucalyptus.ws.util.ReplyQueue; import edu.ucsb.eucalyptus.msgs.BaseMessage; import edu.ucsb.eucalyptus.msgs.BaseMessageSupplier; import edu.ucsb.eucalyptus.msgs.ExceptionResponseType; import edu.ucsb.eucalyptus.msgs.HasRequest; import static com.eucalyptus.util.Parameters.checkParam; import static org.hamcrest.Matchers.notNullValue; public class Contexts { private static Logger LOG = Logger.getLogger( Contexts.class ); private static int MAX = 8192; private static int CONCUR = MAX / ( Runtime.getRuntime( ).availableProcessors( ) * 2 + 1 ); private static float THRESHOLD = 1.0f; private static ConcurrentMap<String, Context> uuidContexts = new ConcurrentHashMap<String, Context>( MAX, THRESHOLD, CONCUR ); private static ConcurrentMap<Channel, Context> channelContexts = new ConcurrentHashMap<Channel, Context>( MAX, THRESHOLD, CONCUR ); static boolean hasOutstandingRequests( ) { return uuidContexts.keySet( ).size( ) > 0; } public static Context create( MappingHttpRequest request, Channel channel ) { Context ctx = new Context( request, channel ); request.setCorrelationId( ctx.getCorrelationId( ) ); uuidContexts.put( ctx.getCorrelationId( ), ctx ); final Context previousContext = channelContexts.put( channel, ctx ); if ( previousContext != null && previousContext.getCorrelationId() != null ) { uuidContexts.remove( previousContext.getCorrelationId() ); } return ctx; } public static Context update ( Context ctx, final String correlationId) { final String oldId = ctx.getCorrelationId(); uuidContexts.remove(oldId); ctx.setCorrelationId(correlationId); uuidContexts.put( ctx.getCorrelationId( ), ctx ); return ctx; } public static boolean exists( ) { try { lookup( ); return true; } catch ( IllegalContextAccessException ex ) { return false; } } public static boolean exists( Channel channel ) { return channelContexts.containsKey( channel ); } public static Context lookup( Channel channel ) throws NoSuchContextException { if ( !channelContexts.containsKey( channel ) ) { throw new NoSuchContextException( "Found channel context " + channel + " but no corresponding context." ); } else { Context ctx = channelContexts.get( channel ); ctx.setMuleEvent( RequestContext.getEvent( ) ); return Context.maybeImpersonating( ctx ); } } public static boolean exists( String correlationId ) { return correlationId != null && uuidContexts.containsKey( correlationId ); } private static ThreadLocal<Context> tlContext = new ThreadLocal<Context>( ); public static void threadLocal( Context ctx ) {//GRZE: really unhappy these are public. tlContext.set( ctx ); } public static void removeThreadLocal( ) {//GRZE: really unhappy these are public. tlContext.remove( ); } public static <T> Consumer<T> consumerWithCurrentContext( final Consumer<T> consumer ) { return consumerWithContext( consumer, Contexts.lookup() ); } public static <T> Consumer<T> consumerWithContext( final Consumer<T> consumer, final Context context ) { return new Consumer<T>( ) { @Override public void accept( final T t ) { final Context previously = tlContext.get( ); threadLocal( context ); try { consumer.accept( t ); } finally { threadLocal( previously ); } } }; } public static Runnable runnableWithCurrentContext( final Runnable runnable ) { return runnableWithContext( runnable, Contexts.lookup( ) ); } public static Runnable runnableWithContext( final Runnable runnable, final Context context ) { return Consumers.partial( consumerWithContext( Consumers.forRunnable( runnable ), context ), null ); } public static Context lookup( String correlationId ) throws NoSuchContextException { checkParam( "BUG: correlationId is null.", correlationId, notNullValue() ); if ( !uuidContexts.containsKey( correlationId ) ) { throw new NoSuchContextException( "Found correlation id " + correlationId + " but no corresponding context." ); } else { Context ctx = uuidContexts.get( correlationId ); ctx.setMuleEvent( RequestContext.getEvent( ) ); return Context.maybeImpersonating( ctx ); } } public static final Context lookup( ) throws IllegalContextAccessException { Context ctx; if ( ( ctx = tlContext.get( ) ) != null ) { return Context.maybeImpersonating( ctx ); } BaseMessage parent = null; MuleMessage muleMsg = null; if ( RequestContext.getEvent( ) != null && RequestContext.getEvent( ).getMessage( ) != null ) { muleMsg = RequestContext.getEvent( ).getMessage( ); } else if ( RequestContext.getEventContext( ) != null && RequestContext.getEventContext( ).getMessage( ) != null ) { muleMsg = RequestContext.getEventContext( ).getMessage( ); } else { throw new IllegalContextAccessException( "Cannot access context implicitly using lookup(V) outside of a service." ); } Object o = muleMsg.getPayload( ); if ( o != null && o instanceof BaseMessage ) { try { return Contexts.lookup( ( ( BaseMessage ) o ).getCorrelationId( ) ); } catch ( NoSuchContextException e ) { Logs.exhaust( ).error( e, e ); throw new IllegalContextAccessException( "Cannot access context implicitly using lookup(V) when not handling a request.", e ); } } else if ( o != null && o instanceof HasRequest ) { try { return Contexts.lookup( ( ( HasRequest ) o ).getRequest( ).getCorrelationId( ) ); } catch ( NoSuchContextException e ) { Logs.exhaust( ).error( e, e ); throw new IllegalContextAccessException( "Cannot access context implicitly using lookup(V) when not handling a request.", e ); } } else { throw new IllegalContextAccessException( "Cannot access context implicitly using lookup(V) when not handling a request." ); } } public static void clear( String corrId ) { checkParam( "BUG: correlationId is null.", corrId, notNullValue() ); Context ctx = uuidContexts.remove( corrId ); Channel channel = null; if ( ctx != null && ( channel = ctx.getChannel( ) ) != null ) { channelContexts.remove( channel ); } else { LOG.trace( "Context.clear() failed for correlationId=" + corrId ); Logs.extreme( ).trace( "Context.clear() failed for correlationId=" + corrId, new RuntimeException( "Missing reference to channel for the request." ) ); } if ( ctx != null ) { ctx.clear( ); } } public static void clear( Context context ) { if ( context != null ) { clear( context.getCorrelationId( ) ); } } public static Context createWrapped( String dest, final BaseMessage msg ) { if ( uuidContexts.containsKey( msg.getCorrelationId( ) ) ) { return null; } else { Context ctx = new Context( dest, msg ); uuidContexts.put( ctx.getCorrelationId( ), ctx ); return Context.maybeImpersonating( ctx ); } } public static void response( BaseMessage responseMessage ) { response( responseMessage, responseMessage ); } /** * Respond with the given supplier. * * <p>This allows a response with associated details such as an HTTP status * code.</p> * * @param responseMessageSupplier The supplier to use */ public static void response( final BaseMessageSupplier responseMessageSupplier ) { response( responseMessageSupplier, responseMessageSupplier.getBaseMessage() ); } @SuppressWarnings( "unchecked" ) private static void response( final Object message, final BaseMessage responseMessage ) { if ( responseMessage instanceof ExceptionResponseType ) { Logs.exhaust( ).trace( responseMessage ); } String corrId = responseMessage.getCorrelationId( ); try { Context ctx = lookup( corrId ); EventRecord.here( ServiceContext.class, EventType.MSG_REPLY, responseMessage.getCorrelationId( ), responseMessage.getClass( ).getSimpleName( ), String.format( "%.3f ms", ( System.nanoTime( ) - ctx.getCreationTime( ) ) / 1000000.0 ) ).trace( ); Channel channel = ctx.getChannel( ); Channels.write( channel, message ); clear( ctx ); } catch ( NoSuchContextException e ) { LOG.warn( "Received a reply for absent client: No channel to write response message: " + e.getMessage( ) + " for " + responseMessage.getClass( ).getSimpleName( ) ); Logs.extreme( ).debug( responseMessage, e ); } catch ( Exception e ) { LOG.warn( "Error occurred while handling reply: " + responseMessage ); Logs.extreme( ).debug( responseMessage, e ); } } public static void responseError( Throwable cause ) { try { Contexts.responseError( lookup( ).getCorrelationId( ), cause ); } catch ( Exception e ) { LOG.error( e ); Logs.extreme( ).error( cause, cause ); } } public static void responseError( String corrId, Throwable cause ) { try { Context ctx = lookup( corrId ); EventRecord.here( ReplyQueue.class, EventType.MSG_REPLY, cause.getClass( ).getCanonicalName( ), cause.getMessage( ), String.format( "%.3f ms", ( System.nanoTime( ) - ctx.getCreationTime( ) ) / 1000000.0 ) ).trace( ); if (cause.getCause() != null) { Channel channel = ctx.getChannel( ); Channels.write( channel, new ExceptionResponseType( ctx.getRequest( ), cause.getCause( ).getMessage( ), cause.getCause( ) ) ); } if ( !( cause instanceof BaseException ) ) { clear( ctx ); } } catch ( Exception ex ) { LOG.error( ex, ex ); Logs.extreme( ).error( cause, cause ); } } }
davenpcj5542009/eucalyptus
clc/modules/msgs/src/main/java/com/eucalyptus/context/Contexts.java
Java
gpl-3.0
13,850
import logging import os import sys from logging import handlers sys.path.append(os.path.dirname(__file__) + '/../src/') sys.path.append(os.path.dirname(__file__) + '/../lib/') from vision import playlist from vision import playout from vision import playoutweb from vision.configuration import configuration def sanity_test(): # TODO: Create a proper sanity test if not os.path.isdir("cache/dailyplan"): print("The directory 'cache/dailyplan' has to exist in work directory") sys.exit(1) if not os.path.isdir("cache/logs"): print("The directory 'cache/logs' has to exist in work directory") sys.exit(1) """ # Not needed yet if not os.path.isdir("cache/screenshots"): print "The directory 'cache/screenshots' has to exist in work directory" sys.exit(1) if not os.path.isdir("cache/overlays"): print "The directory 'cache/screenhots' has to exist in work directory" sys.exit(1) """ def logging_excepthook(type, value, tb): "Exception handler that logs" logging.debug("Unhandled exception", exc_info=(type, value, tb)) # continue processing the exception sys.__excepthook__(type, value, tb) def setup_logging(): log_fmt = ("%(asctime)s %(levelname)s:%(name)s " "%(filename)s:%(lineno)d %(message)s") logging.basicConfig(level=logging.DEBUG, format=log_fmt) logger = logging.getLogger() #ch = logging.StreamHandler() #ch.setLevel(logging.DEBUG) handler = handlers.TimedRotatingFileHandler( "cache/logs/integrated_playout.log", when="D") handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter(log_fmt)) logger.addHandler(handler) sys.excepthook = logging_excepthook if __name__ == "__main__": sanity_test() setup_logging() logging.info("FK Integrated Playout started") logging.info("Configuration details:\n%s" % configuration.config_strings()) # Create today's schedule schedule = playlist.Schedule() schedule.update_from_pg_cache(days=14) # Start the player playout_service = playout.PlayoutService() playout = playout.Playout(service=playout_service) # Start Web playoutweb.start_web(None, playout_service, playout, schedule=schedule) # Setting the schedule starts playback playout.set_schedule(schedule) # Heat up the reactor from twisted.internet import reactor reactor.run()
Frikanalen/mltplayout
bin/integrated.py
Python
gpl-3.0
2,450
""" :copyright: (c) 2015 by OpenCredo. :license: GPLv3, see LICENSE for more details. """ import logging import json log = logging.getLogger(__name__) redis_server = None redis_master_server = None def get_redis_slave(): return redis_server def get_redis_master(): return redis_master_server class QueueIterator(object): def __init__(self, queue, start=0): self.q = queue self.iter = iter(range(start, len(self.q))) def __iter__(self): return self def next(self): """ Retrieve the next message in the queue. """ i = self.iter.next() return self.q.get_item(i) class Queue(object): def __init__(self, name, server=None): self.name = name self.server = server or redis_server def size(self): return sum([len(self.server.lindex(self.name, m)) for m in range(0, len(self))]) def put_raw(self, data): self.server.rpush(self.name, data) def get_raw(self): return self.server.lpop(self.name) def put(self, msg): json_msg = json.dumps(msg) self.server.rpush(self.name, json_msg) def get(self, timeout=None): if timeout: result = self.server.blpop(self.name, timeout) if result: result = result[1] else: result = self.server.lpop(self.name) if result: result = json.loads(result) return result def get_item(self, index): msg = self.server.lindex(self.name, index) if msg: msg = json.loads(msg) return msg def __len__(self): return self.server.llen(self.name) def __iter__(self): return QueueIterator(self) def delete(self): return self.server.delete(self.name) class String(object): def __init__(self, server=None, ttl=None): self.server = server or redis_server self.ttl = ttl or 24 * 7 * 3600 # 7 days def set_raw(self, key, msg): self.server.setex(key, msg, self.ttl) def get_raw(self, key): return self.server.get(key) def get(self, key): try: return json.loads(self.get_raw(key)) except TypeError: return None def set(self, key, msg): self.set_raw(key, json.dumps(msg)) def delete(self, key): return self.server.delete(key) class Hash(object): def __init__(self, server=None): self.server = server or redis_server def get(self, name, key): try: return json.loads(self.get_raw(name, key)) except TypeError: return None def set(self, name, key, msg): return self.set_raw(name, key, json.dumps(msg)) def set_raw(self, name, key, msg): return self.server.hset(name, key, msg) def incr(self, name, key, amount=1): return self.server.hincrby(name, key, amount=amount) def get_raw(self, name, key): return self.server.hget(name, key) def get_all_raw(self, name): return self.server.hgetall(name) def get_all(self, name): return dict((k, json.loads(v)) for k, v in self.server.hgetall( name).iteritems()) def keys(self, name): return self.server.hkeys(name) def values(self, name): return [json.loads(x) for x in self.server.hvals(name)] def delete(self, name, *keys): """ delete the hash key """ return self.server.hdel(name, *keys) def remove(self, name): """ delete the hash """ return self.server.delete(name) def exists(self, name, key): return self.server.hexists(name, key) def get_queue(q=None): q = q or Queue return q
rusenask/stubo-app
stubo/cache/queue.py
Python
gpl-3.0
3,776
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using PyTK; using PyTK.Extensions; using PyTK.PlatoUI; using PyTK.Types; using StardewModdingAPI; using StardewValley; using StardewValley.Menus; using System; using System.Collections.Generic; using System.Linq; namespace Portraiture { public class MenuLoader { const int listElementHeight = 128; const int numPortraits = 7; const int listElementWidth = (listElementHeight - margin * 2) * numPortraits + (margin * (numPortraits + 1)); const int elementsPerPage = 3; const int margin = 10; public static void OpenMenu(IClickableMenu prioMenu = null) { PlatoUIMenu menu = null; List<UIElement> folders = new List<UIElement>(); foreach (string folder in TextureLoader.folders) folders.AddOrReplace(GetElementForFolder(folder)); int f = folders.Count; Texture2D circle = PyDraw.getCircle(margin * 9, Color.White); UIElement container = UIElement.GetContainer("PortraitureMenu", 0, UIHelper.GetCentered(0, 0, listElementWidth + margin * 2, listElementHeight * elementsPerPage + margin * 3), 1); UIElement listbox = new UIElement("ListBox", UIHelper.GetCentered(0, 0, listElementWidth + margin * 2, listElementHeight * elementsPerPage + margin * 3), 0, UIHelper.PlainTheme, Color.Black * 0.5f, 1, false); UIElementList list = new UIElementList("PortraitFolders", true, 0, 1, 5, 0, true, UIHelper.GetCentered(0, 0, listElementWidth, listElementHeight * elementsPerPage + margin), UIHelper.GetFixed(0, 0, listElementWidth, listElementHeight), folders.ToArray()); UIElement closeBtn = UIElement.GetImage(circle, Color.White, "CloseBtn", 0.8f, 99, UIHelper.GetAttachedDiagonal(listbox, false, true, margin, -1 * margin, margin * 3, margin * 3)).WithInteractivity(click: (point, right, release, hold, element) => { if (release) menu?.exitThisMenu(); }, hover: (point, hoverIn, element) => { if (hoverIn != element.WasHover) Game1.playSound("smallSelect"); if (hoverIn) element.Opacity = 1f; else element.Opacity = 0.8f; }); closeBtn.Add(UIElement.GetImage(circle, Color.DarkCyan, "CloseBtn_Inner", 1, 0, UIHelper.GetCentered(0, 0, margin, margin))); container.Add(closeBtn); listbox.Add(list); container.Add(listbox); UIElement scrollBar = UIElement.GetContainer("ScrollBarContainer", 0, UIHelper.GetAttachedHorizontal(listbox, false, 1, margin, 0, margin * 2, listElementHeight * 2)); UIElement up = UIElement.GetImage(PyDraw.getFade(margin * 2, margin * 2, Color.White, Color.Gray, false), Color.DarkCyan, "ScrollUp", 1, 0, UIHelper.GetTopCenter()); UIElement down = UIElement.GetImage(PyDraw.getFade(margin * 2, margin * 2, Color.White, Color.Gray, false), Color.DarkCyan, "ScrollDown", 1, 0, UIHelper.GetBottomCenter()); UIElement bar = UIElement.GetImage(PyDraw.getFade(margin * 2, listElementHeight * 2 - margin * 4, Color.White, Color.Gray, false), Color.White, "ScrollBar", 1, 0, UIHelper.GetCentered()); UIElement scrollPoint = UIElement.GetImage(circle, Color.DarkCyan, "ScrollPoint", 1, 0, (t, p) => { int w = p.Bounds.Width; int h = p.Bounds.Height / (f - 2); int x = 0; int y = list.Position * h; return new Rectangle(p.Bounds.X + x, p.Bounds.Y + y, w, h); }); if (f > 3) { bar.Add(scrollPoint.WithBase(list)); scrollBar.Add(up.WithBase(list).WithInteractivity(click: clickScrollBar, hover: hoverScrollBar)); scrollBar.Add(down.WithBase(list).WithInteractivity(click: clickScrollBar, hover: hoverScrollBar)); scrollBar.Add(bar.WithBase(list).WithInteractivity(click: clickScrollBar)); listbox.Add(scrollBar); } menu = UIHelper.OpenMenu("PortraitureMenu", container); menu.exitFunction = new IClickableMenu.onExit(() => { if (prioMenu != null) Game1.activeClickableMenu = prioMenu; }); } public static void hoverScrollBar(Point point, bool hoverIn, UIElement element) { element.Color = hoverIn ? Color.Cyan : Color.DarkCyan; } public static void clickScrollBar(Point point, bool right, bool release, bool hold, UIElement element) { if (!right && release) { bool scrolled = false; if (element.Id == "ScrollUp") scrolled = (element.Base as UIElementList).ChangePosition(-1); if (element.Id == "ScrollDown") scrolled = (element.Base as UIElementList).ChangePosition(1); if (scrolled) Game1.playSound("smallSelect"); } } public static UIElement GetElementForFolder(string folder) { if (folder == null) folder = "Null"; bool active = TextureLoader.getFolderName() == folder; UIElement element = new UIElement(folder, UIHelper.Fill, 0, UIHelper.PlainTheme, Color.White, active ? 1f : 0.75f, false).AsSelectable("Folder", (s, e) => { e.Opacity = s ? 1f : 0.7f; e.GetElementById(e.Id + "_BgName").Color = s ? Color.DarkCyan : Color.Black; if (s) Game1.playSound("coin"); if (e.Base != null) { if (s) foreach (UIElement selected in e.Base.GetSelected()) if (selected != e) selected.Deselect(); if (!s) if ((new List<UIElement>(e.Base.GetSelected())).Count == 0) e.Select(); } if(s) setFolder(e.Id); }).WithInteractivity(hover:(point,hoverIn,e) => { if (e.IsSelected) return; if(hoverIn != e.WasHover) Game1.playSound("smallSelect"); if (hoverIn) e.Opacity = e.IsSelected ? 1f : 0.9f; else e.Opacity = e.IsSelected ? 1f : 0.75f; }); element.IsSelected = active; element.Overflow = true; int LastX = 0; float i = 0; bool scaled = false; if(folder == "Vanilla") { List<NPC> npcs = new List<NPC>(); for (int c = 0; c < numPortraits; c++) { NPC npc = null; while (npc == null || npcs.Contains(npc)) npc = Utility.getRandomTownNPC(); npcs.Add(npc); Texture2D p = Game1.content.Load<Texture2D>(@"Portraits/" + npc.Name); if (p is Texture2D portrait) { Texture2D t = portrait is ScaledTexture2D st ? st.STexture : portrait; int mx = Math.Max(t.Width / 2, 64); Rectangle s = new Rectangle(0, 0, mx, mx); int w = listElementHeight - margin * 2; int x = LastX + margin; LastX = x + w; i++; UIElement pic = UIElement.GetImage(portrait, Color.White, folder + "_Portrait_" + npc.Name, 1f / (i + 1), 0, UIHelper.GetTopLeft(x, margin, w)).WithSourceRectangle(s); element.Add(pic); } } } else foreach (var texture in TextureLoader.pTextures.Where(k => k.Key.StartsWith(folder))) if (texture.Value is Texture2D portrait) { if (i >= numPortraits) { i++; continue; } if (portrait is ScaledTexture2D || scaled) scaled = true; Texture2D t = portrait is ScaledTexture2D st ? st.STexture : portrait; int mx = Math.Max(t.Width / 2, 64); Rectangle s = new Rectangle(0, 0, mx, mx); int w = listElementHeight - margin * 2; int x = LastX + margin; LastX = x + w; i++; UIElement pic = UIElement.GetImage(portrait, Color.White, folder + "_Portrait_" + texture.Key, 1f / (i+1), 0, UIHelper.GetTopLeft(x, margin, w)).WithSourceRectangle(s); element.Add(pic); } UITextElement name = new UITextElement(folder, Game1.smallFont, Color.White,0.5f, 1f, folder + "_Name", 2, UIHelper.GetTopLeft(margin, margin)); UITextElement num = new UITextElement(folder == "Vanilla" ? " " : i.ToString(), Game1.tinyFont, Color.Black,1f, 1f, folder + "_Num", 2, UIHelper.GetBottomRight(-1* margin, -1* margin)); var size = (Game1.smallFont.MeasureString(folder) * 0.5f).toPoint(); var scaleText = scaled ? "128+" : "64"; var scaleSize = (Game1.smallFont.MeasureString("XX") * 0.5f).toPoint(); int sIBSize = Math.Max(scaleSize.X, scaleSize.Y) + margin * 2; Point bgSize = new Point(size.X + margin * 4, size.Y + margin * 2); Texture2D bgName = PyTK.PyDraw.getFade(bgSize.X * 4, bgSize.Y * 4, Color.White * 0.8f, Color.Transparent); UIElement nameBg = UIElement.GetImage(bgName, active ? Color.DarkCyan : Color.Black, folder + "_BgName", 1, 1, UIHelper.GetTopLeft(0, 0, bgSize.X)); UIElement scaleInfoText = new UITextElement(scaleText, Game1.smallFont, Color.White, 0.5f, 1, folder + "_Scale", 2, UIHelper.GetCentered()); UIElement scaleInfoBackground = UIElement.GetImage(PyDraw.getCircle((int)(sIBSize * (scaled ? 4 : 1)), Color.White), Color.LightGray,folder + "_ScaleBG",1,1, UIHelper.GetTopRight(-1 * margin, margin, sIBSize)); scaleInfoBackground.Add(scaleInfoText); element.Add(name); element.Add(num); element.Add(scaleInfoBackground); element.Add(nameBg); return element; } private static void setFolder(string folder) { string current = TextureLoader.getFolderName(); while (TextureLoader.getFolderName() != folder) { TextureLoader.nextFolder(); if (TextureLoader.getFolderName() == current) break; } } } }
Platonymous/Stardew-Valley-Mods
Portraiture/MenuLoader.cs
C#
gpl-3.0
11,359
package de.raptor2101.BattleWorldsKronos.Connector.Gui.Activities; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import de.raptor2101.BattleWorldsKronos.Connector.AbstractConnectorApp; import de.raptor2101.BattleWorldsKronos.Connector.Data.Entities.Message; import de.raptor2101.BattleWorldsKronos.Connector.Gui.R; import de.raptor2101.BattleWorldsKronos.Connector.Tasks.SendMessageTask; import de.raptor2101.BattleWorldsKronos.Connector.Tasks.SendMessageTask.Result; import de.raptor2101.BattleWorldsKronos.Connector.Tasks.ServerConnectionTask.ResultListener; public abstract class AbstractWriteMessageActivity extends Activity implements ResultListener<Result> { public final static String INTENT_EXTRA_MESSAGE_RESPOND_TO = "RESPONSE_MESSAGE"; private SendMessageTask mTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.message_write_activity); View view = (View) findViewById(R.id.text_write_message_respond_box); Message message = (Message) getIntent().getExtras().get(INTENT_EXTRA_MESSAGE_RESPOND_TO); if(message != null){ EditText editText = (EditText) findViewById(R.id.edit_write_message_receiver); editText.setText(message.getAuthorName()); TextView textView = (TextView) findViewById(R.id.text_write_message_respond_text); textView.setText(message.getMessageText()); view.setVisibility(View.VISIBLE); } else{ view.setVisibility(View.GONE); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item.getItemId() == R.id.action_send_message) { Message messageRespondTo = (Message) getIntent().getExtras().get(INTENT_EXTRA_MESSAGE_RESPOND_TO); SendMessageTask.Message message = new SendMessageTask.Message(); EditText editText = (EditText) findViewById(R.id.edit_write_message_receiver); if(messageRespondTo == null){ message.setReceiver(editText.getText().toString()); } else { message.setReceiver(messageRespondTo.getAuthorName()); message.setLastMessageId(messageRespondTo.getLastMessageId()); } editText = (EditText) findViewById(R.id.edit_write_message_text); message.setText(editText.getText().toString()); if (mTask != null) { mTask.cancel(true); } mTask = new SendMessageTask((AbstractConnectorApp) this.getApplication(), this); mTask.execute(message); ProgressBar progressBar = getProgressBar(); progressBar.setVisibility(View.VISIBLE); } return super.onMenuItemSelected(featureId, item); } @Override public void handleResult(Result result) { mTask = null; ProgressBar progressBar = getProgressBar(); progressBar.setVisibility(View.GONE); if (result.areAllMessagesSuccesfullySend()) { this.finish(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.alert_dialog_send_message_error_message); builder.setTitle(R.string.alert_dialog_send_message_error_title); builder.create().show(); } }; protected abstract ProgressBar getProgressBar(); }
raptor2101/BWKConnector.Library.Base
src/de/raptor2101/BattleWorldsKronos/Connector/Gui/Activities/AbstractWriteMessageActivity.java
Java
gpl-3.0
3,444
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Questionnaire and Consent</title> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <form name = "questionnaire_form" id = "questionnaire_form" action="questionnaire2.php" method="POST"> <fieldset> <legend><b>3. Questionnaire and Consent</b></legend> <br><br> <label>A. What <a href="explanations.html#interests">interests</a> do you have? (please select at least one)</label><br><br> <hr> <label><a href="explanations.html#arts_and_entertainment">Arts and Entertainment</a></label> <input type='hidden' class="interestsa" value='0' name="arts_and_entertainment"/> <input type='checkbox' class="interestsb" value='1' name="arts_and_entertainment"/><br> <hr> <label><a href="explanations.html#autos_and_vehicles">Autos and Vehicles</a></label> <input type='hidden' class="interestsa" value='0' name="autos_and_vehicles"/> <input type='checkbox' class="interestsb" value='1' name="autos_and_vehicles"/><br> <hr> <label><a href="explanations.html#beauty_and_fitness">Beauty and Fitness</a></label> <input type='hidden' class="interestsa" value='0' name="beauty_and_fitness"/> <input type='checkbox' class="interestsb" value='1' name="beauty_and_fitness"/><br> <hr> <label><a href="explanations.html#books_and_literature">Books and Literature</a></label> <input type='hidden' class="interestsa" value='0' name="books_and_literature"/> <input type='checkbox' class="interestsb" value='1' name="books_and_literature"/><br> <hr> <label><a href="explanations.html#business_and_industrial">Business and Industrial</a></label> <input type='hidden' class="interestsa" value='0' name="business_and_industrial"/> <input type='checkbox' class="interestsb" value='1' name="business_and_industrial"/><br> <hr> <label><a href="explanations.html#computers_and_electronics">Computers and Electronics</a></label> <input type='hidden' class="interestsa" value='0' name="computers_and_electronics"/> <input type='checkbox' class="interestsb" value='1' name="computers_and_electronics"/><br> <hr> <label><a href="explanations.html#finance">Finance</a></label> <input type='hidden' class="interestsa" value='0' name="finance"/> <input type='checkbox' class="interestsb" value='1' name="finance"/><br> <hr> <label><a href="explanations.html#food_and_drink">Food and Drink</a></label> <input type='hidden' class="interestsa" value='0' name="food_and_drink"/> <input type='checkbox' class="interestsb" value='1' name="food_and_drink"/><br> <hr> <label><a href="explanations.html#games">Games</a></label> <input type='hidden' class="interestsa" value='0' name="games"/> <input type='checkbox' class="interestsb" value='1' name="games"/><br> <hr> <label><a href="explanations.html#hobbies_and_leisure">Hobbies and Leisure</a></label> <input type='hidden' class="interestsa" value='0' name="hobbies_and_leisure"/> <input type='checkbox' class="interestsb" value='1' name="hobbies_and_leisure"/><br> <hr> <label><a href="explanations.html#home_and_garden">Home and Garden</a></label> <input type='hidden' class="interestsa" value='0' name="home_and_garden"/> <input type='checkbox' class="interestsb" value='1' name="home_and_garden"/><br> <hr> <label><a href="explanations.html#internet_and_telecom">Internet and Telecom</a></label> <input type='hidden' class="interestsa" value='0' name="internet_and_telecom"/> <input type='checkbox' class="interestsb" value='1' name="internet_and_telecom"/><br> <hr> <label><a href="explanations.html#jobs_and_education">Jobs and Education</a></label> <input type='hidden' class="interestsa" value='0' name="jobs_and_education"/> <input type='checkbox' class="interestsb" value='1' name="jobs_and_education"/><br> <hr> <label><a href="explanations.html#law_and_government">Law and Government</a></label> <input type='hidden' class="interestsa" value='0' name="law_and_government"/> <input type='checkbox' class="interestsb" value='1' name="law_and_government"/><br> <hr> <label><a href="explanations.html#news">News</a></label> <input type='hidden' class="interestsa" value='0' name="news"/> <input type='checkbox' class="interestsb" value='1' name="news"/><br> <hr> <label><a href="explanations.html#online_communities">Online Communities</a></label> <input type='hidden' class="interestsa" value='0' name="online_communities"/> <input type='checkbox' class="interestsb" value='1' name="online_communities"/><br> <hr> <label><a href="explanations.html#people_and_society">People and Society</a></label> <input type='hidden' class="interestsa" value='0' name="people_and_society"/> <input type='checkbox' class="interestsb" value='1' name="people_and_society"/><br> <hr> <label><a href="explanations.html#pets_and_animals">Pets and Animals</a></label> <input type='hidden' class="interestsa" value='0' name="pets_and_animals"/> <input type='checkbox' class="interestsb" value='1' name="pets_and_animals"/><br> <hr> <label><a href="explanations.html#real_estate">Real Estate</a></label> <input type='hidden' class="interestsa" value='0' name="real_estate"/> <input type='checkbox' class="interestsb" value='1' name="real_estate"/><br> <hr> <label><a href="explanations.html#reference">Reference</a></label> <input type='hidden' class="interestsa" value='0' name="reference"/> <input type='checkbox' class="interestsb" value='1' name="reference"/><br> <hr> <label><a href="explanations.html#science">Science</a></label> <input type='hidden' class="interestsa" value='0' name="science"/> <input type='checkbox' class="interestsb" value='1' name="science"/><br> <hr> <label><a href="explanations.html#shopping">Shopping</a></label> <input type='hidden' class="interestsa" value='0' name="shopping"/> <input type='checkbox' class="interestsb" value='1' name="shopping"/><br> <hr> <label><a href="explanations.html#sports">Sports</a></label> <input type='hidden' class="interestsa" value='0' name="sports"/> <input type='checkbox' class="interestsb" value='1' name="sports"/><br> <hr> <label><a href="explanations.html#travel">Travel</a></label> <input type='hidden' class="interestsa" value='0' name="travel"/> <input type='checkbox' class="interestsb" value='1' name="travel"/><br> <hr> <label><a href="explanations.html#world_localities">World Localities</a></label> <input type='hidden' class="interestsa" value='0' name="world_localities"/> <input type='checkbox' class="interestsb" value='1' name="world_localities"/><br> <hr> <br><br> <label>B. What type of <a href="explanations.html#personas">persona</a> are you? (please select at least one)</label><br><br> <hr> <label><a href="explanations.html#business_professionals">Business Professional</a></label> <input type='hidden' class="personasa" value='0' name="business_professionals"/> <input type='checkbox' class="personasb" value='1' name="business_professionals"/><br> <hr> <label><a href="explanations.html#personal_finance_geeks">Personal Finance Geek</a></label> <input type='hidden' class="personasa" value='0' name="personal_finance_geeks"/> <input type='checkbox' class="personasb" value='1' name="personal_finance_geeks"/><br> <hr> <label><a href="explanations.html#real_estate_followers">Real Estate Follower</a></label> <input type='hidden' class="personasa" value='0' name="real_estate_followers"/> <input type='checkbox' class="personasb" value='1' name="real_estate_followers"/><br> <hr> <label><a href="explanations.html#small_business_owners">Small Business Owner</a></label> <input type='hidden' class="personasa" value='0' name="small_business_ownwers"/> <input type='checkbox' class="personasb" value='1' name="small_business_ownwers"/><br> <hr> <label><a href="explanations.html#business_travelers">Business Traveler</a></label> <input type='hidden' class="personasa" value='0' name="business_travelers"/> <input type='checkbox' class="personasb" value='1' name="business_travelers"/><br> <hr> <label><a href="explanations.html#flight_intenders">Flight Intender</a></label> <input type='hidden' class="personasa" value='0' name="flight_intenders"/> <input type='checkbox' class="personasb" value='1' name="flight_intenders"/><br> <hr> <label><a href="explanations.html#leisure_travelers">Leisure Traveler</a></label> <input type='hidden' class="personasa" value='0' name="leisure_travelers"/> <input type='checkbox' class="personasb" value='1' name="leisure_travelers"/><br> <hr> <label><a href="explanations.html#catalog_shoppers">Catalog Shopper</a></label> <input type='hidden' class="personasa" value='0' name="catalog_shoppers"/> <input type='checkbox' class="personasb" value='1' name="catalog_shoppers"/><br> <hr> <label><a href="explanations.html#mobile_payment_makers">Mobile Payment Maker</a></label> <input type='hidden' class="personasa" value='0' name="mobile_payment_makers"/> <input type='checkbox' class="personasb" value='1' name="mobile_payment_makers"/><br> <hr> <label><a href="explanations.html#value_shoppers">Value Shopper</a></label> <input type='hidden' class="personasa" value='0' name="value_shoppers"/> <input type='checkbox' class="personasb" value='1' name="value_shoppers"/><br> <hr> <label><a href="explanations.html#american_football_fans">American Football Fan</a></label> <input type='hidden' class="personasa" value='0' name="american_football_fans"/> <input type='checkbox' class="personasb" value='1' name="american_football_fans"/><br> <hr> <label><a href="explanations.html#avid_runners">Avid Runner</a></label> <input type='hidden' class="personasa" value='0' name="avid_runners"/> <input type='checkbox' class="personasb" value='1' name="avid_runners"/><br> <hr> <label><a href="explanations.html#sports_fans">Sports Fan</a></label> <input type='hidden' class="personasa" value='0' name="sports_fans"/> <input type='checkbox' class="personasb" value='1' name="sports_fans"/><br> <hr> <label><a href="explanations.html#bookworms">Bookworm</a></label> <input type='hidden' class="personasa" value='0' name="bookworms"/> <input type='checkbox' class="personasb" value='1' name="bookworms"/><br> <hr> <label><a href="explanations.html#casual_and_social_gamers">Casual and Social Gamer</a></label> <input type='hidden' class="personasa" value='0' name="casual_and_social_gamers"/> <input type='checkbox' class="personasb" value='1' name="casual_and_social_gamers"/><br> <hr> <label><a href="explanations.html#entertainment_enthusiasts">Entertainment Enthusiast</a></label> <input type='hidden' class="personasa" value='0' name="entertainment_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="entertainment_enthusiasts"/><br> <hr> <label><a href="explanations.html#hardcore_gamers">Hardcore Gamer</a></label> <input type='hidden' class="personasa" value='0' name="hardcore_gamers"/> <input type='checkbox' class="personasb" value='1' name="hardcore_gamers"/><br> <hr> <label><a href="explanations.html#movie_lovers">Movie Lover</a></label> <input type='hidden' class="personasa" value='0' name="movie_lovers"/> <input type='checkbox' class="personasb" value='1' name="movie_lovers"/><br> <hr> <label><a href="explanations.html#music_lovers">Music Lover</a></label> <input type='hidden' class="personasa" value='0' name="music_lovers"/> <input type='checkbox' class="personasb" value='1' name="music_lovers"/><br> <hr> <label><a href="explanations.html#news_and_magazine_readers">News and Magazine Reader</a></label> <input type='hidden' class="personasa" value='0' name="news_and_magazine_readers"/> <input type='checkbox' class="personasb" value='1' name="news_and_magazine_readers"/><br> <hr> <label><a href="explanations.html#slots_players">Slots Player</a></label> <input type='hidden' class="personasa" value='0' name="slots_players"/> <input type='checkbox' class="personasb" value='1' name="slots_players"/><br> <hr> <label><a href="explanations.html#auto_enthusiasts">Auto Enthusiast</a></label> <input type='hidden' class="personasa" value='0' name="auto_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="auto_enthusiasts"/><br> <hr> <label><a href="explanations.html#fashionistas">Fashionista</a></label> <input type='hidden' class="personasa" value='0' name="fashionistas"/> <input type='checkbox' class="personasb" value='1' name="fashionistas"/><br> <hr> <label><a href="explanations.html#food_and_dining_lovers">Food and Dining Lover</a></label> <input type='hidden' class="personasa" value='0' name="food_and_dining_lovers"/> <input type='checkbox' class="personasb" value='1' name="food_and_dining_lovers"/><br> <hr> <label><a href="explanations.html#health_and_fitness_enthusiasts">Health and Fitness Enthusiast</a></label> <input type='hidden' class="personasa" value='0' name="health_and_fitness_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="health_and_fitness_enthusiasts"/><br> <hr> <label><a href="explanations.html#high_net_individuals">High Net Individual</a></label> <input type='hidden' class="personasa" value='0' name="high_net_individuals"/> <input type='checkbox' class="personasb" value='1' name="high_net_individuals"/><br> <hr> <label><a href="explanations.html#home_design_enthusiasts">Home Design Enthusiast</a></label> <input type='hidden' class="personasa" value='0' name="home_design_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="home_design_enthusiasts"/><br> <hr> <label><a href="explanations.html#home_and_garden_pros">Home and Garden Pro</a></label> <input type='hidden' class="personasa" value='0' name="home_and_garden_pros"/> <input type='checkbox' class="personasb" value='1' name="home_and_garden_pros"/><br> <hr> <label><a href="explanations.html#new_mothers">New Mother</a></label> <input type='hidden' class="personasa" value='0' name="new_mothers"/> <input type='checkbox' class="personasb" value='1' name="new_mothers"/><br> <hr> <label><a href="explanations.html#photo_and_video_enthusiasts">Photo and Video Enthusiast</a></label> <input type='hidden' class="personasa" value='0' name="photo_and_video_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="photo_and_video_enthusiasts"/><br> <hr> <label><a href="explanations.html#singles">Single</a></label> <input type='hidden' class="personasa" value='0' name="singles"/> <input type='checkbox' class="personasb" value='1' name="singles"/><br> <hr> <label><a href="explanations.html#social_influencers">Social Influencer</a> <input type='hidden' class="personasa" value='0' name="social_influencers"/> <input type='checkbox' class="personasb" value='1' name="social_influencers"/><br> <hr> <label><a href="explanations.html#tech_and_gadget_enthusiasts">Tech and Gadget Enthusiast</a> <input type='hidden' class="personasa" value='0' name="tech_and_gadget_enthusiasts"/> <input type='checkbox' class="personasb" value='1' name="tech_and_gadget_enthusiasts"/><br> <hr> <label><a href="explanations.html#mothers">Mother</a></label> <input type='hidden' class="personasa" value='0' name="mothers"/> <input type='checkbox' class="personasb" value='1' name="mothers"/><br> <hr> <label><a href="explanations.html#parenting_and_education">Parenting and Education</a> <input type='hidden' class="personasa" value='0' name="parenting_and_education"/> <input type='checkbox' class="personasb" value='1' name="parenting_and_education"/><br> <hr> <label><a href="explanations.html#pet_owners">Pet Owner</a></label> <input type='hidden' class="personasa" value='0' name="pet_owners"/> <input type='checkbox' class="personasb" value='1' name="pet_owners"/><br> <hr> <br><br> <label>C. Please enter your personal information.</label> <br><br> <input type="hidden" id="identifier" input name="identifier" value=" <?php echo $_COOKIE['user_id']; ?>"/> <label>First Name </label> <input type="text" name="first_name" id="first_name"/><br><br> <label>Last Name </label> <input type="text" name="last_name" id="last_name"/><br><br> <label>E-Mail </label> <input type="text" name="e_mail" id="e_mail"/><br><br> <label>Gender </label> <select name="gender" id="gender"> <option value="">Select...</option> <option value="female">Female</option> <option value="male">Male</option> </select><br><br> <label>Age </label> <input type="text" name="age" id="age"/><br><br> <label>Native Language</label> <input type="text" name="native_language" id="native_language"/><br><br> <hr> <br><br> <label>I consent to participate in this study and allow collection of data from the registered devices and browsers according to <a href="consent.pdf" target="_new">these terms</a>.</label><input type="checkbox" input name="consent" value="1"/> <br><br> <label></label><input type="submit" name="submit" value="Submit Questionnaire and Consent"/> </fieldset> </form> <p>Questionnaire and Consent Progress: 1/2</p> <!-- check for valid user input into the sign up form fields, especially, check if the user consented --> <script src="jquery-1.11.1.min.js"></script> <script src="jquery.validate.min.js"></script> <script src="additional-methods.min.js"></script> <script> $( "#questionnaire_form" ).validate({ errorClass: "message_color", groups: { interests: "arts_and_entertainment autos_and_vehicles beauty_and_fitness books_and_literature business_and_industrial computers_and_electronics finance food_and_drink games hobbies_and_leisure home_and_garden internet_and_telecom jobs_and_education law_and_government news online_communities people_and_society pets_and_animals real_estate reference science shopping sports travel world_localities", personas: "business_professionals personal_finance_geeks real_estate_followers small_business_owners business_travelers flight_intenders leisure_travelers catalog_shoppers mobile_payment_makers value_shoppers american_football_fans avid_runners sports_fans bookworms casual_and_social_gamers entertainment_enthusiasts hardcore_gamers movie_lovers music_lovers news_and_magazine_readers slots_players auto_enthusiasts fashionistas food_and_dining_lovers health_and_fitness_enthusiasts high_net_individuals home_design_enthusiasts home_and_garden_pros new_mothers photo_and_video_enthusiasts singles social_influencers tech_and_gadget_enthusiasts mothers parenting_and_education pet_owners" }, rules: { arts_and_entertainment: { require_from_group: [1, ".interestsb"] }, business_professionals: { require_from_group: [1, ".personasb"] }, first_name: { required: true, minlength: 2 }, last_name: { required: true, minlength: 2 }, e_mail: { required: true, email: true }, gender: { required: true }, age: { required: true, digits: true }, native_language: { required: true, minlength: 2 }, consent: { required: true } }, messages: { arts_and_entertainment: { require_from_group: "Please check at least one interest." }, business_professionals: { require_from_group: "Please check at least one persona." } } }); </script> </body> </html>
SebastianZimmeck/Cross_Device_Tracking
Software/Browser_History_Server_Files/questionnaire1.php
PHP
gpl-3.0
20,737
package cr0s.javara.render.map; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Point; import cr0s.javara.main.Main; import cr0s.javara.resources.ResourceManager; import cr0s.javara.util.Pos; public class ResourcesLayer { ResourceCell[][] resources; private TileMap map; public ResourcesLayer(TileMap aMap) { this.map = aMap; this.resources = new ResourceCell[this.map.getWidth()][this.map.getHeight()]; } int getAdjacentCellsWith(byte t, int i, int j) { int sum = 0; for (int u = -1; u < 2; u++) { for (int v = -1; v < 2; v++) { if (resources[i + u][j + v] != null && resources[i + u][j + v].type == t) { ++sum; } } } return sum; } public void setInitialDensity() { for (int x = 0; x < this.map.getWidth(); x++) { for (int y = 0; y < this.map.getHeight(); y++) { ResourceCell cell = resources[x][y]; if (cell != null) { int adjacent = getAdjacentCellsWith(cell.type, x, y); int density = lerp(0, cell.maxDensity, adjacent, 9); cell.density = (byte) (density & 0xFF); } } } } public static int lerp(int a, int b, int mul, int div ) { return a + (b - a) * mul / div; } public class ResourceCell { public ResourceCell (byte aType, byte aVariant) { this.type = aType; this.variant = aVariant; this.density = 0; this.maxDensity = (byte) ((aType == 1) ? 12 : 3); } public byte maxDensity; public byte density; public byte type; public byte variant; public String getSpriteName() { if (type == 1) { return "gold0" + (this.variant + 1) + ".tem"; } else if (type == 2) { return "gem0" + (this.variant + 1) + ".tem"; } return null; } public int getFrameIndex() { return lerp(0, maxDensity - 1, density - 1, maxDensity); } } public void renderAll(Graphics g) { // Draw tiles layer for (int y = 0; y < this.map.getHeight(); y++) { for (int x = 0; x < this.map.getWidth(); x++) { if (x < (int) -Main.getInstance().getCamera().offsetX / 24 - 1 || x > (int) -Main.getInstance().getCamera().offsetX / 24 + (int) Main.getInstance().getContainer().getWidth() / 24 + 1) { continue; } if (y < (int) -Main.getInstance().getCamera().offsetY / 24 - 1 || y > (int) -Main.getInstance().getCamera().offsetY / 24 + (int) Main.getInstance().getContainer().getHeight() / 24 + 1) { continue; } if (Main.getInstance().getPlayer().getShroud() != null && Main.getInstance().getPlayer().getShroud().isAreaShrouded(x, y, 2, 2)) { continue; } if (this.resources[x][y] != null) { byte index = (byte) (this.resources[x][y].getFrameIndex() & 0xFF); Point sheetPoint = map.getTheater().getShpTexturePoint(this.resources[x][y].getSpriteName()); int sX = (int) sheetPoint.getX(); int sY = (int) sheetPoint.getY(); if (sX != -1 && sY != -1) { this.map.getTheater().getSpriteSheet().renderInUse(x * 24, y * 24, sX / 24, (sY / 24) + index); } } } } } public void renderCell(int x, int y) { if (this.resources[x][y] != null) { byte index = (byte) (this.resources[x][y].getFrameIndex() & 0xFF); Point sheetPoint = map.getTheater().getShpTexturePoint(this.resources[x][y].getSpriteName()); int sX = (int) sheetPoint.getX(); int sY = (int) sheetPoint.getY(); if (sX != -1 && sY != -1) { this.map.getTheater().getSpriteSheet().renderInUse(x * 24, y * 24, sX / 24, (sY / 24) + index); } } } public boolean isCellEmpty(int x, int y) { return !Main.getInstance().getWorld().getMap().isInMap(x * 24, y * 24) || this.resources[x][y] == null; } public int harvestCell(int x, int y) { ResourceCell resource = this.resources[x][y]; if (resource != null) { if (resource.density >= 0) { resource.density--; if (resource.density <= 0) { this.resources[x][y] = null; } return resource.type; } } return -1; } public boolean isCellEmpty(Point targetCell) { return isCellEmpty((int) targetCell.getX(), (int) targetCell.getY()); } public int harvestCell(Point currentCell) { return harvestCell((int) currentCell.getX(), (int) currentCell.getY()); } public void destroy(Pos tile) { int x = (int) tile.getX(); int y = (int) tile.getY(); this.resources[x][y] = null; } }
Cr0s/JavaRA
src/cr0s/javara/render/map/ResourcesLayer.java
Java
gpl-3.0
4,627
<?php ## # index file ## require('inc/core.php'); ?>
digital-ghost/scanlab
index.php
PHP
gpl-3.0
54
<?php /* * Basic virtual vacation example plugin using the RESPONSE-PROJECT :-) * URL: http://feurix.org/projects/response/ * * WARNING: Check the permissions of this file after editing it! * No one except the user running roundcube (e.g. www-data, ...) * should be able to read it. */ $rcmail_config['driver'] = 'virtual'; $rcmail_config['virtual']['default_enabled'] = 0; $rcmail_config['virtual']['default_subject'] = "Out of Office"; $rcmail_config['virtual']['default_message'] = "Sorry, I'm on vacation this week."; /* please change this */ $rcmail_config['virtual']['dsn'] = 'mysql://responserc:FIXME@localhost/response'; $rcmail_config['virtual']['sql_read'] = "SELECT `config`.`enabled` AS `enabled`, " . "`config`.`expires` AS `expires`, " . "`config`.`subject` AS `subject`, " . "`config`.`message` AS `message` " . "FROM `autoresponse_config` `config` " . "WHERE `config`.`address` = '%address'"; /* TODO * As soon as we have a usable datetime widget the user may set an expiry date * on his own! For now, the hardcoded limit is one month in the future to * prevent lazy users forgetting about their autoresponse config. */ $rcmail_config['virtual']['sql_write'] = "INSERT INTO `autoresponse_config` " . "(`address`,`enabled`,`changed`,`expires`,`subject`,`message`) " . "VALUES ('%address', %enabled, NOW(), CURDATE() + INTERVAL 30 DAY, " . "'%subject', '%message') " . "ON DUPLICATE KEY UPDATE `enabled` = %enabled, `changed` = NOW(), " . "`expires` = CURDATE() + INTERVAL 30 DAY, `subject` = '%subject', " . "`message` = '%message'"; ?>
feurix/response
examples/roundcube-plugin/vacation/config.inc.php
PHP
gpl-3.0
1,723
#!/usr/bin/env bash mkdir -p bundle mkdir -p autoload mkdir -p colors # Install pathogen. pathogenFile='autoload/pathogen.vim' echo $pathogenFile if [ -f $pathogenFile ] then echo "Pathogen.vim exists, out with the old and in with the new." rm $pathogenFile fi wget -P autoload https://raw.githubusercontent.com/tpope/vim-pathogen/master/autoload/pathogen.vim curl -fLo ~/.config/nvim/autoload/plug.vim --create-dirs \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim # Install critical color scheme (vim does not work without this, I swear). molokai='colors/molokai.vim' if [ -f $molokai ] then echo $molokai"exists, out with the old and in with the new." rm $molokai fi # Install vim-plug magic. wget -P colors https://raw.githubusercontent.com/tomasr/molokai/master/colors/molokai.vim nvim +PlugInstall
dinnerTime/vimrc
setup_env.sh
Shell
gpl-3.0
856
#pragma once #include "vgBaseEntry.h" #include "vgBasedTabPage.h" #include "Resource.h" #include <string> #include "vgPlatform/vgPropList.h" using std::string; typedef struct PropertiesParam_t { unsigned int typeId; // ÊôÐÔÏîµÄÀàÐÍ string label; // ÊôÐÔÏîÃû³Æ string comment; // ÊôÐÔÏî×¢ÊÍ unsigned int dataType; // ÊôÐÔÊý¾ÝÀàÐÍ void* connectedPtr; // Ô­Êý¾ÝÖ¸Õë CBCGPProp* pProp; // Éú³ÉµÄÊôÐÔ¶ÔÏóÖ¸Õë } PropertiesParam; typedef std::vector<PropertiesParam> PropertiesParamVector; /** * vgPropertyPage ʵÏÖÊôÐÔÒ³µÄ×Ô¶¯Éú³É * ¿É¸ù¾Ý²»Í¬µÄPropertiesParam²úÉúÏàÓ¦ * µÄÊôÐÔÒ³. * * @see vgTestNode1 * @see vgCameraNode * * @author ZSC * @version VRGIS FrameWork RC * @since VRGIS 1.0+ */ // ×Ô¶¯»¯Property Page²»ÊÇBasedTabPageµÄÅÉÉúÀà class vgPropertyPage : public CDialog { DECLARE_DYNAMIC(vgPropertyPage) public: vgPropertyPage(CWnd* pParent = NULL); virtual ~vgPropertyPage(); enum { IDD = NIDD_PROPERTY }; string GetTitle() { return "ÊôÐÔ"; } CWnd* GetWnd() { return this; } // ¸ù¾ÝNode´«ÈëµÄPropertiesParamÉú³ÉÊôÐÔÒ³ // @see vgTestNode1::AddNodeTabs void ConnectNode(vgBaseEntry* node, PropertiesParam* propParam, int numOfProp); // ÖØÔØÐ°汾 ¶¯Ì¬VectorʵÏÖ void ConnectNode(vgBaseEntry* node, vector<PropertiesParam>* propParam); void AdjustLayout(); // ÊôÐÔ¸ü¸Ä»Øµ÷º¯Êý£¬¸ù¾ÝÔ­Êý¾ÝÖ¸Õë¸üÐÂÊý¾Ý virtual LRESULT OnPropertyChanged(WPARAM w, LPARAM l); // void OnChangeSelection(CBCGPProp*,CBCGPProp*); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV Ö§³Ö //CBCGPPropList m_wndPropList; PropList m_wndPropList; vgBaseEntry* m_pNode; PropertiesParam* m_pPropParam; int m_numOfParam; // modified by zsc @ 08/10/30 vector<PropertiesParam> *m_pPropVector; bool m_useVectorParam; DECLARE_MESSAGE_MAP() public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); };
xzy0008/sample_code
SAMPLE_CODE/include/vgSuperPlatform/vgPropertyPage.h
C
gpl-3.0
2,027
package se.idega.idegaweb.commune.school.presentation; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import se.idega.idegaweb.commune.presentation.CommuneBlock; import com.idega.block.school.business.SchoolBusiness; import com.idega.block.school.data.School; import com.idega.business.IBOLookup; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.IWContext; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.user.business.GroupBusiness; import com.idega.user.business.UserBusiness; import com.idega.user.data.Group; import com.idega.user.data.User; /** * @author aron * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class SchoolAdminDirector extends CommuneBlock { GroupBusiness grpBuiz; UserBusiness usrBuiz; SchoolBusiness schoolBuiz; Integer schoolChoiceApproverPageId = null; IWResourceBundle iwrb; public String getBundleIdentifier(){ return CommuneBlock.IW_BUNDLE_IDENTIFIER; } private void init(IWContext iwc) throws RemoteException{ usrBuiz =(UserBusiness) IBOLookup.getServiceInstance(iwc,UserBusiness.class); grpBuiz = (GroupBusiness) IBOLookup.getServiceInstance(iwc,GroupBusiness.class); schoolBuiz = (SchoolBusiness) IBOLookup.getServiceInstance(iwc,SchoolBusiness.class); } public void main(IWContext iwc) throws Exception{ iwrb = getResourceBundle(iwc); if(iwc.isLoggedOn() && schoolChoiceApproverPageId!=null){ init(iwc); int userId = iwc.getUserId(); User user = usrBuiz.getUser(userId); Group rootGroup = schoolBuiz.getRootSchoolAdministratorGroup(); // if user is a SchoolAdministrator if(user.hasRelationTo(rootGroup)){ Collection schools = schoolBuiz.getSchoolHome().findAllBySchoolGroup(user); if(!schools.isEmpty()){ Table T = new Table(); int row = 1; int col = 1; T.add(new Text(iwrb.getLocalizedString("school_choice.links_to_choice_approvers","Links to school choice approvers")),col,row++); Iterator iter = schools.iterator(); while(iter.hasNext()){ School school = (School) iter.next(); T.add(getApproverLink(school),col,row++); } add(T); } /* else add("no schools"); */ } /* else add("has no relation to School admin root group"); */ } /* else add("not logged on"); */ } public Link getApproverLink(School school) { Link L = new Link(school.getName()); L.setPage(this.schoolChoiceApproverPageId.intValue()); L.addParameter(SchoolChoiceApprover.prmSchoolId,school.getPrimaryKey().toString()); return L; } public void setSchoolChoiceApproverPage(int pageId){ this.schoolChoiceApproverPageId = new Integer(pageId); } }
idega/platform2
src/se/idega/idegaweb/commune/school/presentation/SchoolAdminDirector.java
Java
gpl-3.0
2,981
define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred", "dojo/on", "dojo/aspect", "dojo/query", "dojo/has", "./util/misc", "put-selector/put", "xstyle/has-class", "./Grid", "dojo/_base/sniff", "xstyle/css!./css/columnset.css"], function(kernel, declare, lang, Deferred, listen, aspect, query, has, miscUtil, put, hasClass, Grid){ has.add("event-mousewheel", function(global, document, element){ return typeof element.onmousewheel !== "undefined"; }); has.add("event-wheel", function(global, document, element){ var supported = false; // From https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel try{ WheelEvent("wheel"); supported = true; }catch(e){ // empty catch block; prevent debuggers from snagging } return supported; }); var colsetidAttr = "data-dgrid-column-set-id"; hasClass("safari", "ie-7"); function adjustScrollLeft(grid, row){ var scrollLefts = grid._columnSetScrollLefts; function doAdjustScrollLeft(){ query(".dgrid-column-set", row).forEach(function(element){ element.scrollLeft = scrollLefts[element.getAttribute(colsetidAttr)]; }); } if(has("ie") < 8 || has("quirks")){ setTimeout(doAdjustScrollLeft, 1); }else{ doAdjustScrollLeft(); } } function scrollColumnSetTo(grid, columnSetNode, offsetLeft){ var id = columnSetNode.getAttribute(colsetidAttr); var scroller = grid._columnSetScrollers[id]; scroller.scrollLeft = offsetLeft < 0 ? 0 : offsetLeft; } function getColumnSetSubRows(subRows, columnSetId){ // Builds a subRow collection that only contains columns that correspond to // a given column set id. if(!subRows || !subRows.length){ return; } var subset = []; var idPrefix = columnSetId + "-"; for(var i = 0, numRows = subRows.length; i < numRows; i++){ var row = subRows[i]; var subsetRow = []; subsetRow.className = row.className; for(var k = 0, numCols = row.length; k < numCols; k++){ var column = row[k]; // The column id begins with the column set id. if(column.id != null && column.id.indexOf(idPrefix) === 0){ subsetRow.push(column); } } subset.push(subsetRow); } return subset; } var horizMouseWheel = has("event-mousewheel") || has("event-wheel") ? function(grid){ return function(target, listener){ return listen(target, has("event-wheel") ? "wheel" : "mousewheel", function(event){ var node = event.target, deltaX; // WebKit will invoke mousewheel handlers with an event target of a text // node; check target and if it's not an element node, start one node higher // in the tree if(node.nodeType !== 1){ node = node.parentNode; } while(!query.matches(node, ".dgrid-column-set[" + colsetidAttr + "]", target)){ if(node === target || !(node = node.parentNode)){ return; } } // Normalize reported delta value: // wheelDeltaX (webkit, mousewheel) needs to be negated and divided by 3 // deltaX (FF17+, wheel) can be used exactly as-is deltaX = event.deltaX || -event.wheelDeltaX / 3; if(deltaX){ // only respond to horizontal movement listener.call(null, grid, node, deltaX); } }); }; } : function(grid){ return function(target, listener){ return listen(target, ".dgrid-column-set[" + colsetidAttr + "]:MozMousePixelScroll", function(event){ if(event.axis === 1){ // only respond to horizontal movement listener.call(null, grid, this, event.detail); } }); }; }; return declare(null, { // summary: // Provides column sets to isolate horizontal scroll of sets of // columns from each other. This mainly serves the purpose of allowing for // column locking. postCreate: function(){ var self = this; this.inherited(arguments); this.on(horizMouseWheel(this), function(grid, colsetNode, amount){ var id = colsetNode.getAttribute(colsetidAttr), scroller = grid._columnSetScrollers[id], scrollLeft = scroller.scrollLeft + amount; scroller.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft; }); this.on('.dgrid-column-set:dgrid-cellfocusin', function (event) { self._onColumnSetCellFocus(event, this); }); }, columnSets: [], createRowCells: function(tag, each, subRows, object){ var row = put("table.dgrid-row-table"); var tr = put(row, "tbody tr"); for(var i = 0, l = this.columnSets.length; i < l; i++){ // iterate through the columnSets var cell = put(tr, tag + ".dgrid-column-set-cell.dgrid-column-set-" + i + " div.dgrid-column-set[" + colsetidAttr + "=" + i + "]"); var subset = getColumnSetSubRows(subRows || this.subRows , i) || this.columnSets[i]; cell.appendChild(this.inherited(arguments, [tag, each, subset, object])); } return row; }, renderArray: function(){ var grid = this, rows = this.inherited(arguments); Deferred.when(rows, function(rows){ for(var i = 0; i < rows.length; i++){ adjustScrollLeft(grid, rows[i]); } }); return rows; }, renderHeader: function(){ // summary: // Setup the headers for the grid this.inherited(arguments); var columnSets = this.columnSets, domNode = this.domNode, scrollers = this._columnSetScrollers, scrollerContents = this._columnSetScrollerContents = {}, scrollLefts = this._columnSetScrollLefts = {}, grid = this, i, l; function reposition(){ grid._positionScrollers(); } if (scrollers) { // this isn't the first time; destroy existing scroller nodes first for(i in scrollers){ put(scrollers[i], "!"); } } else { // first-time-only operations: hook up event/aspected handlers aspect.after(this, "resize", reposition, true); aspect.after(this, "styleColumn", reposition, true); this._columnSetScrollerNode = put(this.footerNode, "+div.dgrid-column-set-scroller-container"); } // reset to new object to be populated in loop below scrollers = this._columnSetScrollers = {}; for(i = 0, l = columnSets.length; i < l; i++){ this._putScroller(columnSets[i], i); } this._positionScrollers(); }, styleColumnSet: function(colsetId, css){ // summary: // Dynamically creates a stylesheet rule to alter a columnset's style. var rule = this.addCssRule("#" + miscUtil.escapeCssIdentifier(this.domNode.id) + " .dgrid-column-set-" + miscUtil.escapeCssIdentifier(colsetId, "-"), css); this._positionScrollers(); return rule; }, _destroyColumns: function(){ var columnSetsLength = this.columnSets.length, i, j, k, subRowsLength, len, columnSet, subRow, column; for(i = 0; i < columnSetsLength; i++){ columnSet = this.columnSets[i]; for(j = 0, subRowsLength = columnSet.length; j < subRowsLength; j++){ subRow = columnSet[j]; for(k = 0, len = subRow.length; k < len; k++){ column = subRow[k]; if(typeof column.destroy === "function"){ column.destroy(); } } } } this.inherited(arguments); }, configStructure: function(){ // Squash the column sets together so the grid and other dgrid extensions and mixins can // configure the columns and create any needed subrows. this.columns = {}; this.subRows = []; for(var i = 0, l = this.columnSets.length; i < l; i++){ var columnSet = this.columnSets[i]; for(var j = 0; j < columnSet.length; j++){ columnSet[j] = this._configColumns(i + "-" + j + "-", columnSet[j]); } } this.inherited(arguments); }, _positionScrollers: function (){ var domNode = this.domNode, scrollers = this._columnSetScrollers, scrollerContents = this._columnSetScrollerContents, columnSets = this.columnSets, scrollerWidth = 0, numScrollers = 0, // tracks number of visible scrollers (sets w/ overflow) i, l, columnSetElement, contentWidth; for(i = 0, l = columnSets.length; i < l; i++){ // iterate through the columnSets columnSetElement = query('.dgrid-column-set[' + colsetidAttr + '="' + i +'"]', domNode)[0]; scrollerWidth = columnSetElement.offsetWidth; contentWidth = columnSetElement.firstChild.offsetWidth; scrollerContents[i].style.width = contentWidth + "px"; scrollers[i].style.width = scrollerWidth + "px"; if(has("ie") < 9){ // IE seems to need scroll to be set explicitly scrollers[i].style.overflowX = contentWidth > scrollerWidth ? "scroll" : "auto"; } // Keep track of how many scrollbars we're showing if(contentWidth > scrollerWidth){ numScrollers++; } } this._columnSetScrollerNode.style.bottom = this.showFooter ? this.footerNode.offsetHeight + "px" : "0"; // Align bottom of body node depending on whether there are scrollbars this.bodyNode.style.bottom = numScrollers ? (has("dom-scrollbar-height") + (has("ie") ? 1 : 0) + "px") : "0"; }, _putScroller: function (columnSet, i){ // function called for each columnSet var scroller = this._columnSetScrollers[i] = put(this._columnSetScrollerNode, "span.dgrid-column-set-scroller.dgrid-column-set-scroller-" + i + "[" + colsetidAttr + "=" + i +"]"); this._columnSetScrollerContents[i] = put(scroller, "div.dgrid-column-set-scroller-content"); listen(scroller, "scroll", lang.hitch(this, '_onColumnSetScroll')); }, _onColumnSetScroll: function (evt){ var scrollLeft = evt.target.scrollLeft, colSetId = evt.target.getAttribute(colsetidAttr), newScrollLeft; if(this._columnSetScrollLefts[colSetId] != scrollLeft){ query('.dgrid-column-set[' + colsetidAttr + '="' + colSetId + '"],.dgrid-column-set-scroller[' + colsetidAttr + '="' + colSetId + '"]', this.domNode). forEach(function(element, i){ element.scrollLeft = scrollLeft; if(!i){ // Compute newScrollLeft based on actual resulting // value of scrollLeft, which may be different than // what we assigned under certain circumstances // (e.g. Chrome under 33% / 67% / 90% zoom). // Only need to compute this once, as it will be the // same for every row. newScrollLeft = element.scrollLeft; } }); this._columnSetScrollLefts[colSetId] = newScrollLeft; } }, _setColumnSets: function(columnSets){ this._destroyColumns(); this.columnSets = columnSets; this._updateColumns(); }, setColumnSets: function(columnSets){ kernel.deprecated("setColumnSets(...)", 'use set("columnSets", ...) instead', "dgrid 0.4"); this.set("columnSets", columnSets); }, _onColumnSetCellFocus: function(event, columnSetNode){ var focusedNode = event.target; var columnSetId = columnSetNode.getAttribute(colsetidAttr); // columnSetNode's offsetLeft is not always correct, // so get the columnScroller to check offsetLeft against var columnScroller = this._columnSetScrollers[columnSetId]; var elementEdge = focusedNode.offsetLeft - columnScroller.scrollLeft + focusedNode.offsetWidth; if (elementEdge > columnSetNode.offsetWidth || columnScroller.scrollLeft > focusedNode.offsetLeft) { scrollColumnSetTo(this, columnSetNode, focusedNode.offsetLeft); } } }); });
spatialagent001/BlogExamples
example16/js/dojo/dgrid/ColumnSet.js
JavaScript
gpl-3.0
11,189
OpenCV Projects ============== This repository includes all the practices I wrote and projects I did in OpenCV. ##SOME NEW FACTS (OCT 2013)### * By this date (Oct 18th, 2013), in order to install OpenCV on Mac OS, it's still better to use version 2.4.3 instead of latest release since some compatible problems (not confirmed actually, but happened to my machine). * Hebrew is an awesome tool for completing Mac OS. * The process to install OpenCV in mac is like this: + First, download OpenCV and uncompress it locally, I recommend that you move it to home folder. + Second, install `cmake`, apparently, it's very important. You can in fact install it using Hebrew by using `ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"`. And then use `brew install cmake` to install `cmake` + Third, `cd` to your opencv folder and execute following commands: `mkdir build`, `cd build`, `cmake -G "Unix Makefiles"`, `make -j8`, `sudo make install`, and yes, you do need administrator access. + If everything moves correctly, now you can enjoy your fresh OpenCV installation. + If you want to remove it, go to `build` folder and run `sudo make uninstall`. This command will clear everything for you. * Eclipse+OpenCV is still my best choice + Sadly, you need to configure C++ build properties every time (as I know). + In MacOS C++ Linker/Libraries: include `/usr/local/lib/` in _Library search path (-L)_, include `opencv_core`, `opencv_imgproc`, `opencv_highgui`, `opencv_ml`, `opencv_video`, `opencv_features2d`, `opencv_calib3d`, `opencv_objdetect`, `opencv_contrib`, `opencv_legacy`, `opencv_flann` in _Libraries (-L)_ + In GCC C++ Compiler/Includes: include `/usr/local/include/` in _Include paths (-I)_ * Of course, system library are still working. * When you include a library from OpenCV, better use like `#include<opencv2/core/core.hpp>` * Read Image: `imread("argument", OPTION)` * Image type: `Mat` (not like old days) * Create a window object: `namedWindow("name", WINDOW_AUTOSIZE)`, if you are not using Qt, `WINDOW_AUTOSIZE` is the only option. * Show image: `imshow("window's name", image)`. * Waiting for key stroke: `waitKey(0)`. * Seems like you don't have to destroy and release resource anymore. * `cvtColor` is able to perform colour transformation, in this case, `CV_BGR2GRAY` specify that image is changed from BGR format to Grayscale format. And if you look at it, there are many of them. * Write image: `imwrite("address",image)` is the corresponding function for writing image to disk. * The function and data type mentioned above can be found in `cv` class. * Some interesting facts about `Mat` class + If you perform something like `A=C` or `Mat B(A)`, different `Mat` object will have certainly the different headers, but they are all pointing to the same data matrix. + Use `A.clone()` or `A.copyTo(B)` instead. + You don't need to worry about memory management. + Supporting storage format: RGB, HSV & HLS, YCrCb (JPEG) and CIE L*a*b* + There are some Matlab style function available to use `Mat::eye`, `Mat::ones`, `Mat::zeros` + Output formatting is pretty interesting. + Can format a vector to matrix * The channels of stored image is BGR instead of RGB. * use `cvCaptureFromCAM(0)` to open camera access, the function will return a `CvCapture` object. * `cvQueryFrame(capture)` will return a `IplImage` object by definition. But if you are using newer version of OpenCV, you can directly change it to a `Mat` image. * You need to call `cvReleaseCapture(capture)` after displaying the image, the function will release the resources allocated on the capturer. ###Contacts### Name: Hu Yuhuang (duguyue100) Email: duguyue100@gmail.com Address: _No. 42, North, Flatland_
duguyue100/opencvprojects
README.md
Markdown
gpl-3.0
3,772
/* * @author: jelathro * @date: 10/24/13 * * */ #ifndef __LIST_C__ #define __LIST_C__ #include <stdlib.h> #include "List.h" /* * Given list, Creates a new empty List_t and * returns its reference. */ List_t list_initialize(){ List_t list = { NULL }; return list; } /* * Given list, Creates a new ListItem_t and adds * it to the end of the List_t. This * returns an int accordingly if * successful or not. */ int list_add_item(List_t * list, ListItem_t * li){ // Temporary "iterator" on the list ListItem_t * nextItem = list->head; // No head yet if(!list->head){ list->head = li; return(1); } // Move to the end of the list while(nextItem->next){ nextItem = nextItem->next; } // Made it to the end of the list // add the new item to the list. if(!li->next){ nextItem->next = li; }else{ return(0); } return(1); } /* * Given list, Creates a new ListItem_t and adds * it after the index given. This returns * an int accordingly if successful * or not. */ int list_add_item_after(List_t * list, int idx, ListItem_t * li){ // Temporary "iterator" on the list ListItem_t * nextItem = list->head; // Move to list index or return 1 if no such index while(idx > 0){ // Insert after last item in list if(!nextItem->next){ // Index doesn't exist return(0); }else{ nextItem = nextItem->next; idx--; } } // Add item after current "nextItem" pointed too. if(nextItem->next){ // Middle of list if(!li->next){ ListItem_t * tmpItem = list_item_initialize(); // Save next item in list tmpItem = nextItem->next; // Attach new item to current item's next pointer nextItem->next = li; // Attach "old" next item pointer li->next = tmpItem; }else{ return(0); } }else if(!nextItem->next){ // End of list if(!li->next){ nextItem->next = li; }else{ return(0); } } return(1); } /* * Given list, Creates a new ListItem_t and adds * it before the index given. This returns * an int accordingly if successful * or not. */ int list_add_item_before(List_t * list, int idx, ListItem_t * li){ // Temporary "iterator" on the list ListItem_t * nextItem = list->head; // Move to right before list index or return 1 if no such index while(idx-1 > 0){ // Insert after last item in list if(!nextItem->next){ // Index doesn't exist return(0); }else{ nextItem = nextItem->next; idx--; } } // Add item after current "nextItem" pointed too. if(nextItem->next){ // Middle of list if(!li->next){ ListItem_t * tmpItem = list_item_initialize(); // Save next item in list tmpItem = nextItem->next; // Attach new item to current item's next pointer nextItem->next = li; // Attach "old" next item pointer li->next = tmpItem; return(1); }else{ return(0); } }else if(!nextItem->next){ // End of list if(!li->next){ nextItem->next = li; return(1); }else{ return(0); } } return(0); } /* * Given list, Free's and removes head from * the List_t. */ int list_remove_item_head(List_t * list, list_item_remove_callback_func cb){ if(list->head){ // Get current head of list ListItem_t * tmp = list->head; if(list_item_remove(tmp, cb)){ // Set next item in list to be head list->head = tmp->next; // Remove old list head free(tmp); return(1); }else{ return(0); } }else{ // List is already empty return(1); } } /* * Given list, Free's and removes tail from * List_t. */ int list_remove_item_tail(List_t * list, list_item_remove_callback_func cb){ // Temporary "iterator" on the list ListItem_t * nextItem = list->head; // Move to one before end of list while(nextItem->next){ if(!nextItem->next->next){ // Remove last list item if(list_item_remove(nextItem->next, cb)){ free(nextItem->next); }else{ return(0); } nextItem->next = 0; return(1); }else{ nextItem = nextItem->next; } } return(0); } /* * Given list, Free's and removes ListItem_t * and updates list "hole". */ int list_remove_item_at(List_t * list, int idx, list_item_remove_callback_func cb){ ListItem_t * nextItem, * lastItem; if(!list->head) return(1); if(idx == 0 && !list->head->next) return list_remove_item_head(list, cb); nextItem = list->head; lastItem = NULL; // Move to index while(idx-1 > 0){ // Index does not exist if(!nextItem->next){ return(0); }else{ // Move to next Item lastItem = nextItem; nextItem = nextItem->next; } idx--; } // Last Item if(!nextItem->next){ free(nextItem); return(1); }else{ // Middle Item // Connect item before and after index lastItem->next = nextItem->next; // Free unconnected item index free(nextItem); return(1); } } /* * Given list, Free's and removes list * and returns int according to success. */ int list_remove(List_t * list, list_item_remove_callback_func cb){ // Loop through entire list removing each item while(1){ if( list_remove_item_head(list, cb) ){ if(!list->head){ break; } }else{ return(0); } } return(1); } /* * Given list and callback function, list * will loop through all LitItem_t's and * call the function for it. */ int list_for_each(List_t * list, list_item_callback_func cb){ ListItem_t * nextItem; int idx; if(!list->head) return(0); nextItem = list->head; idx = 0; while(nextItem){ cb(idx, nextItem->data); nextItem = nextItem->next; idx++; } return(1); } /* * Given list and index to find and * return ListItem_t data (void *). */ void * list_get_at(List_t * list, int idx){ ListItem_t * nextItem; if(!list->head) return( (void *)1 ); if(idx == 0) return( (void *) list->head->data ); nextItem = list->head; // Iterate to list item at index given while(idx > 0){ if(!nextItem->next){ return( (void *) -1 ); }else{ nextItem = nextItem->next; } idx--; } return( nextItem->data ); } /* * Given list and index to find and * set ListItem_t data (void *), * returns int on success accordingly. */ int list_set_at(List_t * list, void * data, int idx){ ListItem_t * nextItem; if(!list->head) return(0); if(idx == 0){ list->head->data = data; return(0); } nextItem = list->head; // Iterate to list item at index given while(idx > 0){ if(!nextItem->next){ return(0); }else{ nextItem = nextItem->next; } idx--; } // Set the item's new/updated data if(list_item_add(nextItem, data)){ return(1); } return(0); } #endif
Eddyding/C
C-master/List/List.c
C
gpl-3.0
6,496
# Bot de alertas Esta aplicación permite crear un bot para alertas en Telegram ## Instalación ### Dependencias El desarrollo del bot se hará con python3. Así que lo primero es asegurarnos de que lo tenemos instalado: ```bash bash$ sudo apt-get install python3 python3-setuptools python3-dev bash$ sudo easy_install-3.4 pip ``` Se pueden instalar las dependencias en un subdirectorio o en el sistema. Se recomienda el primer método para evitar problemas: ```bash bash$ pip3 install -t dist -r requirements.txt ``` ### Alta de un bot Para desarrollar, cada miembro puede crear su propio bot para desarrollo. Para ello [seguir el tutorial oficial](https://core.telegram.org/bots#botfather) Es importante anotar el token de autorización de nuestro bot. Por ejemplo, consideremos que nuestro bot tiene el token ```110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw```. ### Configuración Antes de iniciar el bot, tenemos que configurar el token. Para ello copiaremos el fichero _config/parameters.yml.dist_ en _config/parameters.yml_ añadiendo el token que hemos obtenido en el paso anterior. El fichero debe quedar así (pero con nuestro token): ```yaml telegram: token: 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw ``` ### Inicio del bot Iniciamos el script de python _ucobot.py_. ### Demo Podemos hablarle a nuestro bot que responderá, por ahora, a las órdenes _/start_ y _/help_. ## Desarrollo Nos basaremos en dos APIs: * Para Telegram Bot: [pyTelegramBotAPI](https://github.com/eternnoir/pyTelegramBotAPI) * Para la base de datos: [ponyorm](http://ponyorm.com/) Cada grupo de órdenes tendrá un fichero independiente en el directorio _ucobot_ (ver commands.py como ejemplo). Si es necesario guardar datos, se usara el ORM de Python PonyORM para definir las clases.
aulasoftwarelibre/ucobot
README.md
Markdown
gpl-3.0
1,796
//--------------------------------------------- // FREQUENCY COUNTER // www.circuit-projects.com // Y.Erol //--------------------------------------------- #include <pic.h> #include <delay.c> __CONFIG(WDTDIS&PWRTEN&LVPDIS&XT); unsigned char kontrol; //--------------------------------------------- // CCP1 INTERRUPT //--------------------------------------------- void interrupt interrupt(void){ TMR1H=0; TMR1L=0; GIE=0; control=1; CCP1IF=0; GIE=1; } //--------------------------------------------- // MAIN PROGRAM //--------------------------------------------- main(void) { unsigned const char number[10]={0x3F,0x06,0x5B, 0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F}; unsigned char select[4]={1,2,4,8}; unsigned int counter,value,remainder1,remainder2; float frekans; unsigned char a,i,display[5],data; TRISA=0x00; TRISB=0x08; CMCON=0x07; cont=0; PORTA=0; PORTB=0 CCP1IE=1; CCP1CON=0b00000110; T1CON=0b00100001; GIE=1; PEIE=1; for(;;){ counter=256*CCPR1H+CCPR1L; if(control==1)frequency=100000000/counter; if(kontrol==0)frequency=0; if(counter<10000)frequency=0; control=0; for(a=0;a<25;a++){ value=(int)frequency; display[1]=value/1000; remainder1=value-display[1]*1000; display[2]=remainder1/100; remainder2=remainder1-display[2]*100; display[3]=remainder2/10; display[4]=remainder2-display[3]*10; for(i=0;i<4;i++){ PORTB=0; PORTA=0; data=number[display[i+1]]; PORTB=data&0x07; data=data<<1; PORTB=PORTB|(data&0xF0); PORTA=select[i]; DelayMs(3); } } } }
techdude101/code
PIC uC Projects/c/Samples/Frequency-Counter/Frequency-Counter-C.C
C++
gpl-3.0
1,528
@extends('main') @section('page') <div class="container-fluid page-container"> <div class="row"> <div class="col-xs-12"> <h1>ArchStrike Wiki</h1> <div class="breadcrumb"> @if($path == 'index') Home @elseif(preg_match('/\//', $path)) <a href="/wiki">Home</a> <span>&rarr;</span> @set('curr_path', '/wiki') @foreach(explode('/', preg_replace('/\/index$/', '', $path)) as $level) @if($loop->last) {{ ucfirst($level) }} @else @set('curr_path', $curr_path . '/' . $level) <a href="{{ $curr_path }}">{{ ucfirst($level) }}</a> <span>&rarr;</span> @endif @endforeach @else <a href="/wiki">Home</a> <span>&rarr;</span> {{ ucfirst(preg_replace('/\/index$/', '', $path)) }} @endif </div> </div> </div> <div class="row wiki-row"> <div class="col-xs-12"> @include('wiki.' . preg_replace('/\//', '.', $path)) </div> </div> </div> @endsection
ArchStrike/ArchStrike-Website
resources/views/website/wiki.blade.php
PHP
gpl-3.0
1,388
// sort_10_bit.cpp // #include <iostream> #include <ctime> #include <vector> #include "bitstrm/reg.hpp" #include "bitstrm/alloced_bref.hpp" #include "bitstrm/utility.hpp" #include "bitstrm/bit_int_itr.hpp" #include "bitstrm/TimeFixture.hpp" #include <boost/lexical_cast.hpp> using namespace bitstrm; using namespace std; unsigned bitstrm::TimeFixture::s_timer_number = 0; int main(int /*argc*/ , const char** /*argv*/){ const size_t testSize = 1024*1024; string message(string("sort ") + boost::lexical_cast<string>(testSize) + " signed random elements of size 10 bits"); TimeFixture fixture(message.c_str()); vector<reg> testSet64(testSize); vector<reg> ::iterator c64(testSet64.begin()); vector<short> testSet16(testSize); vector<short>::iterator c16(testSet16.begin()); const reg ten_bit_mask((1<<10) -1); alloced_bref buf(testSize*10); bit_int_itr<10,reg> b0(buf); bit_int_itr<10,reg> bc(b0); { string msg(string("created ") + boost::lexical_cast<string>(testSize) + " random elements storing as reg, short and 10 bit reg"); TimeFixture fixture(msg.c_str()); for(vector<reg>::iterator e = testSet64.end(); c64 < e; ++c64, ++c16, ++bc) { reg orig = rand() & ten_bit_mask; reg ten_bit_number = signextend<reg, 10>(orig); // we don't care what the orig number is, just what is interpreted // as when we take only ten bits of it. This should approximate an // even split of positive and negative numbers *bc = *c16 = *c64 = ten_bit_number; } } bit_int_itr<10,reg> be(bc); bc = b0; { TimeFixture fixture("sorting as reg", testSize); sort(testSet64.begin(), testSet64.end()); } { TimeFixture fixture("sorting as signed short", testSize); sort(testSet16.begin(), testSet16.end()); } { TimeFixture fixture("sorting as 10 bit signed integer", testSize); sort(bc, be); } }
chrisdursoorg/bitstrm
examples/sort_10_bit.cpp
C++
gpl-3.0
1,995
# This file is part of barrioSquare. # # barrioSquare 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. # # barrioSquare 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 barrioSquare. If not, see <http://www.gnu.org/licenses/>. # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. QPUSHBUTTON_DEFAULT = 'QPushButton { color: #000000; border-radius: 6px; border: 2px solid #8f8f91; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f6f7fa, stop: 1 #dadbde); } QPushButton:pressed {background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #7ec2cc, stop: 1 #defbff); }' QPUSHBUTTON_HIGHLIGHT = 'QPushButton { color: #000000; border-radius: 6px; border: 2px solid #8f8f91; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #7ec2cc, stop: 1 #defbff); } QPushButton:pressed {background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #cccccc, stop: 1 #f6f7fa); }' QLISTWIDGET_DEFAULT = 'QListWidget { color: #000000; background-color: #ffffff; } QListView { color: #000000; background-color: #ffffff; }' # '
chilitechno/barrioSquare
barrioStyles.py
Python
gpl-3.0
1,574
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### import json import bpy import mathutils import bmesh as bm import numpy as np from bpy.props import StringProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode callback_id = 'node.callback_execnodemod' lines = """\ for i, i2 in zip(V1, V2): append([x + y for x, y in zip(i, i2)]) """.strip().split('\n') def update_wrapper(self, context): try: updateNode(context.node, context) except: ... class SvExecNodeDynaStringItem(bpy.types.PropertyGroup): line = bpy.props.StringProperty(name="line to eval", default="", update=update_wrapper) class SvExecNodeModCallback(bpy.types.Operator): bl_idname = callback_id bl_label = "generic callback" cmd = bpy.props.StringProperty(default='') idx = bpy.props.IntProperty(default=-1) form = bpy.props.StringProperty(default='') def execute(self, context): getattr(context.node, self.cmd)(self) return {'FINISHED'} class SvExecNodeMod(bpy.types.Node, SverchCustomTreeNode): ''' Exec Node Mod''' bl_idname = 'SvExecNodeMod' bl_label = 'Exec Node Mod' bl_icon = 'CONSOLE' text = StringProperty(default='', update=updateNode) dynamic_strings = bpy.props.CollectionProperty(type=SvExecNodeDynaStringItem) def draw_buttons(self, context, layout): row = layout.row(align=True) # add() remove() clear() move() row.operator(callback_id, text='', icon='ZOOMIN').cmd = 'add_new_line' row.operator(callback_id, text='', icon='ZOOMOUT').cmd = 'remove_last_line' row.operator(callback_id, text='', icon='TRIA_UP').cmd = 'shift_up' row.operator(callback_id, text='', icon='TRIA_DOWN').cmd = 'shift_down' row.operator(callback_id, text='', icon='SNAP_ON').cmd = 'delete_blank' row.operator(callback_id, text='', icon='SNAP_OFF').cmd = 'insert_blank' if len(self.dynamic_strings) == 0: return if not context.active_node == self: b = layout.box() col = b.column(align=True) for idx, line in enumerate(self.dynamic_strings): col.prop(self.dynamic_strings[idx], "line", text="", emboss=False) else: col = layout.column(align=True) for idx, line in enumerate(self.dynamic_strings): row = col.row(align=True) row.prop(self.dynamic_strings[idx], "line", text="") # if UI , then opp = row.operator(callback_id, text='', icon='TRIA_DOWN_BAR') opp.cmd = 'insert_line' opp.form = 'below' opp.idx = idx opp2 = row.operator(callback_id, text='', icon='TRIA_UP_BAR') opp2.cmd = 'insert_line' opp2.form = 'above' opp2.idx = idx def draw_buttons_ext(self, context, layout): col = layout.column(align=True) col.operator(callback_id, text='copy to node').cmd = 'copy_from_text' col.prop_search(self, 'text', bpy.data, "texts", text="") row = layout.row() col.operator(callback_id, text='cc code to clipboard').cmd = 'copy_node_text_to_clipboard' def add_new_line(self, context): self.dynamic_strings.add().line = "" def remove_last_line(self, context): if len(self.dynamic_strings) > 1: self.dynamic_strings.remove(len(self.dynamic_strings)-1) def shift_up(self, context): sds = self.dynamic_strings for i in range(len(sds)): sds.move(i+1, i) def shift_down(self, context): sds = self.dynamic_strings L = len(sds) for i in range(L): sds.move(L-i, i-1) def delete_blank(self, context): sds = self.dynamic_strings Lines = [i.line for i in sds if i.line != ""] sds.clear() for i in Lines: sds.add().line = i def insert_blank(self, context): sds = self.dynamic_strings Lines = [i.line for i in sds] sds.clear() for i in Lines: sds.add().line = i if i != "": sds.add().line = "" def copy_from_text(self, context): """ make sure self.dynamic_strings has enough strings to do this """ slines = bpy.data.texts[self.text].lines while len(self.dynamic_strings) < len(slines): self.dynamic_strings.add() for i, i2 in zip(self.dynamic_strings, slines): i.line = i2.body def copy_node_text_to_clipboard(self, context): lines = [d.line for d in self.dynamic_strings] if not lines: return str_lines = "\n".join(lines) bpy.context.window_manager.clipboard = str_lines def insert_line(self, op_props): sds = self.dynamic_strings Lines = [i.line for i in sds] sds.clear() for tidx, i in enumerate(Lines): if op_props.form == 'below': sds.add().line = i if op_props.idx == tidx: sds.add().line = "" else: if op_props.idx == tidx: sds.add().line = "" sds.add().line = i def sv_init(self, context): self.inputs.new('StringsSocket', 'V1') self.inputs.new('StringsSocket', 'V2') self.inputs.new('StringsSocket', 'V3') self.outputs.new('StringsSocket', 'out') # add default strings self.dynamic_strings.add().line = lines[0] self.dynamic_strings.add().line = lines[1] self.dynamic_strings.add().line = "" self.width = 289 def process(self): v1, v2, v3 = self.inputs V1, V2, V3 = v1.sv_get(0), v2.sv_get(0), v3.sv_get(0) out = [] extend = out.extend append = out.append exec('\n'.join([j.line for j in self.dynamic_strings])) self.outputs[0].sv_set(out) def storage_set_data(self, storage): strings_json = storage['string_storage'] lines_list = json.loads(strings_json)['lines'] self.id_data.freeze(hard=True) self.dynamic_strings.clear() for line in lines_list: self.dynamic_strings.add().line = line self.id_data.unfreeze(hard=True) def storage_get_data(self, node_dict): local_storage = {'lines': []} for item in self.dynamic_strings: local_storage['lines'].append(item.line) node_dict['string_storage'] = json.dumps(local_storage) def register(): bpy.utils.register_class(SvExecNodeDynaStringItem) bpy.utils.register_class(SvExecNodeMod) bpy.utils.register_class(SvExecNodeModCallback) def unregister(): bpy.utils.unregister_class(SvExecNodeModCallback) bpy.utils.unregister_class(SvExecNodeMod) bpy.utils.unregister_class(SvExecNodeDynaStringItem)
elfnor/sverchok
nodes/script/multi_exec.py
Python
gpl-3.0
7,709
* vim: syn=asm6809 noexpandtab ts=8 * title micro forth 1.0 * * micro forth 1.0 * * this is a small fast implementation of a forth language for * the motorola 6809 microprocessor. it is unique in that there is * no interpreter, all words are directly executable. * * copyright 1984-2005 dave dunfield * all rights reserved. * * system equates * osram equ $8000 sysram equ $8030 width equ 65 terminal screen width margin rstack equ sysram+254 return stack dstack equ sysram+510 data stack aciasr equ $e100 aciadr equ $e101 * the Mirage has IRQ handlers and stuff at the start org osram beginning of forth code * system variables used by ROM fdccmd fcb 0 store FDC command byte fdcrtry fcb $09 FDC retries fdctrak fcb $0b FDC track fdcsect fcb $05 FDC sector fdcldad fdb $0000 used for OS loader address? fdcstat fcb $00 fdc status fdcerr fcb $00 error message for ROM routine * jump table, IRQs point to this irqj jmp irqhandler firqj jmp firqhandler osj jmp start sysvars equ * lstlok fdb 0 temp fdb 0 inpbuf equ * *lstlok equ sysvars pointer to last word processed from input buffer *temp equ lstlok+2 temporary storage *inpbuf equ temp+2 input buffer * the Mirage OS saves parameters from $8011 to $802e org sysram+$230 top of data stack *** set up FIRQ handler, runopsys configured the UART for us serialinit orcc #$55 disable interrupts ldx #aciabuffer stx aciain stx aciaout buffer is empty clra serial_loop1 sta ,x+ zero out 16 bytes cmpx #aciain bne serial_loop1 lda #$95 ACIA control = RX interrupt, 8n1, no TX interrupt sta aciasr rts *** test if a character is available serialchr pshs x ldx aciain cmpx aciaout puls x rts *** get a character from buffer serialget pshs x ldx aciaout ldb ,x+ cmpx #aciain bne serialgetend ldx #aciabuffer serialgetend stx aciaout puls x rts serialput pshs a serialput1 lda aciasr bita #$02 transmit flag? beq serialput1 stb aciadr puls a rts irqhandler rti dummy routine firqhandler pshs a,x save registers lda #$07 sta $e201 ldx aciain input pointer lda aciasr get ACIA status bita #$80 IRQ fired? beq firqend no, must have been an error but we don't care lda aciadr get the data from the ACIA sta ,x+ save and nudge the pointer cmpx #aciain ran off end? bne firqend ldx #aciabuffer firqend stx aciain save pointer puls x,a restore rti aciabuffer fcb 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00 aciain fdb aciabuffer aciaout fdb aciabuffer * initializations, start up forth start lda #$0 lds #rstack set up return stack ldu #dstack set up data stack lda #$18 turn off LEDs sta $e201 lda #$7f sta $e20e disable VIA interrupts jsr serialinit andcc #$bf enable interrupt ldx #strtmsg point to startup message lbsr pmsg1 display it jsr [boot+3] execute preset routine (usually 'quit') lbra bye exit forth * subroutine to obtain variables address on stack. * used by 'variable' type words variab ldx ,s++ get following address pshu x save rts return to caller * messages prompt fcb $0a,$0d new line fccz 'ok>' ; prompt ermsg1 fccz /error: '/ ;error prefix ermsg2 fccz /' / ;error suffix redmsg fccz 'redef: ' ;re-definition indicator delmsg fcb 8,32,8,0 bug when using strings? strtmsg fcb $0d,$0a fcc "Mirage micro forth" fcb $0d,$0a,0 ledval fdb 0 ledctr fdb 0 ledctr1 fdb 0 * * start of user dictionary * dictionary format: * 1) - word descriptor byte, format: * bit 7 - always set, indicates this is descriptor byte * bits 7-3 - currently not used * bit 2 - no-compile bit, word cannot be used in compiles * bit 1 - no-interactive bit, word cannot be used interactively * bit 0 - execute on compile bit, compiler executes word immediatly * instead of compiling into definition * 2) - word name, variable length, stored backwards * 3) - address of previous word in dictionary, address must point to first * byte of code which immediatly follows this field in the word * * * 'dropn' - drops a number of words from the stack fcb $80 fcc 'npord' fdb 0 ** end of dictionary ** dropn ldd ,u++ get operand aslb multiply by rola two for word stack entries leau d,u move user stack rts * 'drop' - drop one word from the stack fcb $80 fcc 'pord' fdb dropn drop leau 2,u move stack pointer rts * 'dup' - duplicate top of stack fcb $80 fcc 'pud' fdb drop dup ldd ,u get top of user stack std ,--u duplicate rts * 'over' duplicate one down from top of stack fcb $80 fcc 'revo' fdb dup over ldd 2,u get element std ,--u duplicate rts * 'rot' - rotate top three elements on stack fcb $80 fcc 'tor' fdb over rot ldd 4,u get bottom ldx 2,u get middle stx 4,u put on bottom bra swap1 do rest * 'swap' - swap top two elements on stack fcb $80 fcc 'paws' fdb rot swap ldd 2,u get lower one swap1 ldx ,u get top stx 2,u place top at lower std ,u place lower at top rts * '0=' - test for tos equal to zero fcb $80 fcc '=0' fdb swap zequ ldd ,u get top of stack beq ret1 equal to zero? bra ret0 no, return one * '=' - test for equality fcb $80 fcc '=' fdb zequ equals ldd ,u++ get top of stack cmpd ,u compare with next beq ret1 same, return 1 bra ret0 no, return zero * '<>' - test for not equal fcb $80 fcc '><' fdb equals notequ ldd ,u++ get tos cmpd ,u compare with next beq ret0 not same, return 1 bra ret1 no, return 0 * '>' - test for greater fcb $80 fcc '>' fdb notequ grtr ldd 2,u get lower element cmpd ,u++ compare with tos bgt ret1 greater, return 1 bra ret0 no, return false * '<' - test for less fcb $80 fcc '<' fdb grtr less ldd 2,u get lower element cmpd ,u++ compare with tos blt ret1 lower, return 1 bra ret0 no, return false * '>=' - test for greater or equal to fcb $80 fcc '=>' fdb less grequ ldd 2,u get lower cmpd ,u++ compare with tos blt ret0 less, return false ret1 ldb #1 get one bra rets return it * '<=' - test for less or equal to fcb $80 fcc '=<' fdb grequ lesequ ldd 2,u get lower cmpd ,u++ compare with tos ble ret1 lower or equal, return one ret0 clrb get zero result rets clra zero high byte std ,u save on stack rts * '$out' - output character to terminal fcb $80 fcc 'tuo$' fdb lesequ dolout ldb #$f1 jsr serialput ldd ,u++ get char from stack andb #$7f mask top bit jsr serialput rts * '$in' - input character from terminal fcb $80 fcc 'ni$' fdb dolout dolin jsr serialchr bne dolin1 dolin0 inc ledctr bne dolin inc ledctr1 lda ledctr1 cmpa #$0a bne dolin clr ledctr1 lda ledval inca cmpa #$6 bne dolin2 clra dolin2 sta ledval ora #$08 sta $e201 bra dolin dolin1 jsr serialget cmpb #$f1 bne dolin dolin9 jsr serialchr beq dolin9 jsr serialget clra std ,--u save on stack rts * 'emit' - output character to general output fcb $80 fcc 'time' fdb dolin emit jmp [disp+3] execute output routine in '(out)' variable * 'key' - get character from general input fcb $80 fcc 'yek' fdb emit key jmp [inpt+3] execute input routine in '(in)' variable * 'u.' - output unsigned number in current base fcb $80 fcc '.u' fdb key udot bra dot01 execute number output routine * '.' - output signed number in current base fcb $80 fcc '.' fdb udot dot ldd ,u get number from stack bpl dot01 is positive, its ok ldb #'-' get minus sign pshu a,b save on stack jsr emit output minus sign jsr neg negate number dot01 lda #$ff end if stream indicator pshs a save marker on return stack dot1 ldd base+3 get number base from 'base' variable pshu a,b save base jsr usmod perform division pulu a,b get remainder pshs b save for later ldd ,u get result bne dot1 if more, keep going leau 2,u skip last result on stack dot2 ldb ,s+ get character from stack lbmi space end of digits, output space and exit addb #$30 convert to decimal number cmpb #$39 in range? bls dot3 yes, its ok addb #7 convert to alpha dot3 pshu a,b save on stack bsr emit output character bra dot2 keep outputing * '-!' - subtract from self and reassign fcb $80 fcc '!-' fdb dot mstor ldx ,u++ get address ldd ,x get contents subd ,u++ subtract tos std ,x resave contents rts * '+!' - add to self and reassign fcb $80 fcc '!+' fdb mstor pstor ldx ,u++ get address ldd ,x get contents addd ,u++ add is tos std ,x resave contents rts * 'c!' - character (byte) store operation fcb $80 fcc '!c' fdb pstor vstorc ldx ,u++ get address ldd ,u++ get data from stack stb ,x save in variable rts * '!' - word store operation fcb $80 fcc '!' fdb vstorc vstor ldx ,u++ get address ldd ,u++ get data std ,x perform store rts * 'c@' - character read operation fcb $80 fcc '@c' fdb vstor vreadc ldb [,u] get character from address clra zero high byte bra savsd move to stack * '@' - word read operation fcb $80 fcc '@' fdb vreadc vread ldd [,u] get word from address bra savsd place on stack * '2/' - divide by two fcb $80 fcc '/2' fdb vread shr lsr ,u shift high ror 1,u shift low rts * '2*' - multiply by two fcb $80 fcc '*2' fdb shr shl lsl 1,u shift low rol ,u shift high rts * '+' - add operator fcb $80 fcc '+' fdb shl add ldd ,u++ get tos addd ,u add in next bra savsd place result on stack * '-' - subtract operator fcb $80 fcc '-' fdb add sub ldd 2,u get lower operand subd ,u++ subtract tos savsd std ,u place result on stack rts * 'd-' double precision subtraction fcb $80 fcc '-d' fdb sub dminus ldd 6,u get low word of lower operand subd 2,u subtract low word off higher operand std 6,u resave lower word of operand ldd 4,u get high word of lower operand sbcb 1,u subtract top of stack sbcb ,u with borrow from previous leau 4,u fix up stack std ,u place high word of result on stack rts * 'd+' - double precision addition fcb $80 fcc '+d' fdb dminus dplus ldd 2,u get low word of first operand addd 6,u add low word of second operand std 6,u resave ldd ,u get high word of first adcb 5,u add in high word of adca 4,u second with carry leau 4,u fix up stack std ,u resave rts * 'u*' - unsigned multiply fcb $80 fcc '*u' fdb dplus umult lda 1,u ldb 3,u mul pshs a,b lda ,u ldb 2,u mul pshs a,b lda 1,u ldb 2,u mul addd 1,s bcc umul1 inc ,s umul1 std 1,s lda ,u ldb 3,u mul addd 1,s bcc umul2 inc ,s umul2 std 1,s puls d,x std ,u stx 2,u rts * '*' - signed multiply fcb $80 fcc '*' fdb umult mult lda 1,u ldb 3,u mul pshs a,b lda ,u ldb 3,u mul addb ,s stb ,s lda 1,u ldb 2,u mul addb ,s stb ,s puls d leau 2,u std ,u rts * 'm/mod' - division with remainder fcb $80 fcc 'dom/m' fdb mult msmod clra clrb ldx #33 msmodl andcc #$fe msmodm rol 5,u rol 4,u rol 3,u rol 2,u leax -1,x beq msmodd rolb rola cmpd ,u blo msmodl subd ,u orcc #1 bra msmodm msmodd std ,u rts * 'u/mod' - unsigned division with remainder fcb $80 fcc 'dom/u' fdb msmod usmod ldd ,u++ clr ,-u clr ,-u std ,--u jsr msmod ldd ,u++ std ,u rts * '/mod' - division giving remainder fcb $80 fcc 'dom/' fdb usmod slmod lda 2,u pshs a bpl slmod2 clra clrb subd 2,u std 2,u lda ,s slmod2 eora ,u pshs a ldd ,u beq slmodr bpl slmod1 coma comb addd #1 std ,u slmod1 clra clrb ldx #17 slmodl andcc #$fe slmodm rol 3,u rol 2,u leax -1,x beq slmodd rolb rola cmpd ,u blo slmodl subd ,u orcc #1 bra slmodm slmodd tst 1,s bpl slmod3 coma comb addd #1 slmod3 std ,u tst ,s++ bpl slmodr clra clrb subd 2,u std 2,u slmodr rts * '/' - division fcb $80 fcc '/' fdb slmod slash bsr slmod leau 2,u rts * 'and' - logical and fcb $80 fcc 'dna' fdb slash and ldd ,u++ get top of stack anda ,u and high byte andb 1,u and low byte bra savds save result and exit * 'or' - logical or fcb $80 fcc 'ro' fdb and or ldd ,u++ get top of stack ora ,u or high byte orb 1,u or low byte bra savds save result and exit * 'xor' - logcal exclusive or fcb $80 fcc 'rox' fdb or xor ldd ,u++ get top of stack eora ,u xor high byte eorb 1,u xor low byte bra savds save result and exit * 'com' - complement operand fcb $80 fcc 'moc' fdb xor com com ,u complement high byte com 1,u complement low byte rts * 'neg' - negate operand fcb $80 fcc 'gen' fdb com neg bsr com complement operand bra onep increment (two's complement) * 'abs' - give absolute value of operand fcb $80 fcc 'sba' fdb neg abs ldd ,u get value from stack bmi neg negative, convert rts * '2-' - decrement by two fcb $80 fcc '-2' fdb abs twom ldd ,u get top of stack subd #2 decrement by two savds std ,u resave top of stack rts * '2+' - increment by two fcb $80 fcc '+2' fdb twom twop ldd ,u get top of stack addd #2 increment by two bra savds resave top of stack * '1-' - decrement by one fcb $80 fcc '-1' fdb twop onem ldd ,u get top of stack subd #1 decrement by one bra savds resave top of stack * '1+' - increment by one fcb $80 fcc '+1' fdb onem onep ldd ,u get top of stack addd #1 increment by one bra savds resave top of stack * 'skip' - advance input pointer to non-blank fcb $80 fcc 'piks' fdb onep qskip ldy inptr+3 get current position in input buffer qski1 lda ,y+ get character from input buffer cmpa #' ' is it a space beq qski1 yes, keep going leay -1,y backup to it sty inptr+3 resave input pointer tsta test for end of line rts * * subroutine to lookup words in dictionary from input line * on exit: 'z' is set if word not found * if word is found ('z'=0), its address is stacked on the * data stack, and the word descriptor byte is returned in * the 'a' accumulator * lookup pshs x,y save registers bsr qskip advance to word sty lstlok save incase error ldx here+3 get start of dictionary * scan dictionary, looking for word lok1 pshs x save current address leax -2,x backup past preceding address lok2 lda ,-x get character from name bmi lok3 decreiptor byte, start of word cmpa ,y+ does it match input buffer? beq lok2 yes, keep matching till end of word lok5 puls x restore pointer ldx ,--x get address of previous word beq lok4 end of dictionary, quit ldy inptr+3 restore input pointer bra lok1 try for this word lok3 ldb ,y get net char from input stream bsr tsterm is it a terminator? bne lok5 no, word does not match puls a,b restore address of word std ,--u save on stack bsr qski1 skip to next non-blank lda ,x get descriptor byte andcc #$fb clear 'z' flag lok4 puls x,y,pc * routine to test for terminator character tsterm cmpb #' ' is it a space? beq tster1 yes, its ok tstb is it null (end of line)? tster1 rts * ''' - tick: return address of a word fcb $81 fcc /'/ fdb qskip tick bsr lookup look up word bne tster1 found, return lbra lokerr word not found, cause error fcb $80 fcc 'cexe' fdb tick exec jmp [,u++] execute at address on [tos] * 'number' - get number from input stream in current base fdb $80 fcc 'rebmun' fdb exec number pshs x,y save regs lbsr qskip advance to next word in input stream cmpa #'-' is it a negative number? pshs cc save flags fo later test bne num4 no, not negative leay 1,y skip '-' sign num4 clra start off clrb with a zero result pshu a,b save on stack num2 ldb ,y+ get char from souce subb #'0' convert to binary cmpb #9 is it numeric digit? bls num1 yes, its ok andb #$df smash case subb #7 convert from alpha cmpb #$0a is it a valid number? blo num3 no, cause error num1 clra zero high byte cmpd base+3 are we within range of current base bhs num3 no, cause error pshs a,b save number ldd base+3 get base pshu a,b stack jsr mult perform multiply (old value already on data stack) puls a,b get new digit back addd ,u add to old value std ,u resave old value ldb ,y get next character from number lbsr tsterm is it a terminator bne num2 no, keep evaluating number sty inptr+3 resave input pointer puls cc,x,y restore registers bne num5 no negative, don't negate jsr neg negate value num5 lbra one return true (success) num3 puls cc,x,y clean up stack lbra zero return false (failure) * 'space' - display a space on general output fcb $80 fcc 'ecaps' fdb number space ldb #' ' get a space pshu a,b placeon data stack jmp emit output * 'cr' - display carriage-return, line-feed on general output fcb $80 fcc 'rc' fdb space cr ldd #$0d get carriage return pshu a,b place on stack jsr emit output to general output ldb #$0a get line-feed pshu a,b place on stack jmp emit output to general output * 'read' - read a line from input device fcb $80 fcc 'daer' fdb cr read bsr cr new line readnc ldy #inpbuf point to input buffer read1 jsr key get a key cmpb #$0d is it carriage return? beq rdcrlf yes, exit cmpb #$0a is it newline? beq rdcrlf cmpb #$08 is it backspace? beq rdbksp cmpb #$7f is it delete? beq rdbksp * normal key stb ,y+ save key in buffer jsr emit echo key bra read1 go back for another * delete key, delete previous character rdbksp leau 2,u remove keycode from stack leay -1,y backup up input buffer pointer cmpy #inpbuf past beginning? blo read if so, re-initiate read ldx #delmsg point to delete message bsr pmsg1 display bra read1 go back for next key * carriage return, terminate input rdcrlf leau 2,u remove keycode from stack clr ,y indicate end of input line ldy #inpbuf point to input buffer sty inptr+3 set up input buffer pointer pmsg2 rts * '.msg' - display message, address on stack fcb $80 fcc 'gsm.' fdb read pmsg ldx ,u++ get address pmsg1 ldb ,x+ get character from message beq pmsg2 end of message, exit pshu a,b save on stack jsr emit output to general output bra pmsg1 get next character * '.wrd' - display a word on general output (string) fcb $80 fcc 'drw.' fdb pmsg pwrd ldx ,u++ get address of word pwrd1 ldb ,x+ get character from word lbsr tsterm is it a terminator? beq pmsg2 yes, quit pshu a,b save data on stack jsr emit output to general output bra pwrd1 get next word * 'quit - general command interpreter, used to terminate words fcb $80 fcc 'tiuq' fdb pwrd quit jsr rpfix reset return stack ldx #prompt point to prompt bsr pmsg1 display prompt lbsr readnc read a line of input jsr space seperate by a space qui1 jsr qskip adance to non-blank beq quit null line, do nothing jsr lookup look up word beq qui2 not found, try number bita #$02 ok to execute interactivly? bne conerr no, force error jsr [,u++] execute word andcc #$bf FIXME EVIL HACK nmi routine comes back with FIRQ disabled cmpu #dstack did stack underflow? bls qui1 no, keep interpreting bsr error generate error message fccz 'stack empty' * not a word, try for number qui2 jsr number try for number ldd ,u++ get flag byte beq lokerr not a number. indicate not found bra qui1 keep interpreting * subroutine to generate error message, first displays 'error:' message, * then name of last word processed, then error message text error ldx #ermsg1 ; get pointer to error message prefix bsr pmsg1 display prefix ldx lstlok get address of last word from input buffer bsr pwrd1 display word ldx #ermsg2 ; point to error message suffix bsr pmsg1 display suffix ldx ,s++ get address of error message bsr pmsg1 display message jsr spfix reset data stack bra quit and enter command intrepreter * word was not found in the dictionary lokerr bsr error generate error message fccz 'not found' * word can not be executed interactively conerr bsr error generate error message fccz 'cannot execute' * '>r' - move word from data to return stack fcb $80 fcc 'r>' fdb quit tor ldx ,s get return address ldd ,u++ get data from data stack std ,s place on return stack tfr x,pc return to caller * '<r' - move word from return stack to data stack fcb $80 fcc 'r<' fdb tor fromr ldx ,s++ get return address ldd ,s++ get data from return stack std ,--u place on data stack tfr x,pc return to caller * 'rp!' - reset return stack fcb $80 fcc '!pr' fdb fromr rpfix puls a,b get return address lds #rstack reset return stack tfr d,pc return to caller * 'sp!' - reset data stack fcb $80 fcc '!ps' fdb rpfix spfix ldu #dstack reset data stack voc9 rts * ''s' - obtain stack address fcb $80 fcc /s'/ fdb spfix tics stu ,--u save data stack pointer rts * 'vlist' - display words in dictionary fcb $80 fcc 'tsilv' fdb tics voc ldx here+3 get address of start of dictionary voc1 jsr cr new line clra zero character count voc2 pshs a,x save count, current position leax -2,x backup to word name voc3 ldb ,-x get character from word name bmi voc4 descriptor byte, end of name pshu a,b save on data stack jsr emit output to general output inc ,s increment character count bra voc3 keep outputing voc4 jsr space seperate with a space puls a,x restore character count, position in dictionary inca advance character count for space ldx ,--x get address of next word beq voc9 end of dictionary, exit cmpa #width are we beyond terminal width? blo voc2 no, its ok bra voc1 continue on new line * 'bye' - exit forth fcb $80 fcc 'eyb' fdb voc bye nop * gjcp - fixme ssr * ssr 22 new line * ssr 0 exit to system jsr cr lda #$00 swi * 'forget' - remove one or more words from dictionary fcb $80 fcc 'tegrof' fdb bye forget jsr tick locate words address pulu x get address cmpx #usrspc is it in kernal dictionary? blo proerr if so, can't be forgotton ldd ,--x get address of previous word std here+3 new dictionary start forg1 lda ,-x get character from name bpl forg1 keep going till we find descriptor byte stx free+3 new free space for dictionary rts * word is protected, can't 'forget' it proerr lbsr error generate error message fccz 'protected' * 'create' - create new word in dictionary fdb $80 fcc 'etaerc' fdb forget create ldy inptr+3 get input buffer position lbsr lookup see if it already exists beq cre1 no, its ok leau 2,u remove address of existing word ldx #redmsg point to redefinition message lbsr pmsg1 output message tfr y,x point to word we are re-defining lbsr pwrd1 output word to general output cre1 lbsr qski1 advance to next non-blank, save pointer lda #$ff start with count of -1 cre3 ldb ,y+ get character from word inca advance word size count lbsr tsterm terminator character bne cre3 look till we find end leay -1,y backup to last char sty inptr+3 save new buffer position ldx free+3 get address of free dictionary space ldb #$80 get default descriptor byte stb ,x+ save in dictionary cre2 ldb ,-y get character from name stb ,x+ save in dictionary deca reduce count of name length bne cre2 move all of name into dictionary ldd here+3 get address of previous entry std ,x++ save in dictionary stx here+3 save new starting address stx free+3 save new free space address rts * 'allot' - allocate some space in the dictionary fcb $80 fcc 'tolla' fdb create allot ldd free+3 get address of free dictioanry space addd ,u++ offset by number of bytes requested std free+3 resave new free pointer rts * 'variable' - create a variable fcb $80 fcc 'elbairav' fdb allot var bsr create create the variable name lda #$bd get a 'jsr' extended instruction sta ,x+ insert into dictionary ldd #variab get address of variable subroutine std ,x++ insert into dictionary ldd ,u++ get default variable value std ,x++ save into dictionary stx free+3 set new free pointer rts * ';' - end a colon definition, terminate compiling fcb $83 fcc ';' fdb var semi ldd -2,x get last instruction complied cmpd #$3606 is it 'pshu a,b'? beq semi1 if so, its ok lda -3,x get instruction from dictionary cmpa #$bd is it 'jsr >'? bne semi1 no, its ok * convert 'jsr' followed by 'rts' to simple 'jmp' lda #$7e get 'jmp >' instruction sta -3,x save in dictionary bra semi2 terminate compiling semi1 lda #$39 get 'rts' instruction sta ,x+ save in dictionary semi2 stx free+3 resave free pointer jmp quit re-enter command interpreter * ':' - colon definition, begin compliing fcb $84 fcc ':' fdb semi colon jsr create create new word col1 jsr qskip advance to non-blank bne col11 not end of line, its ok jsr read read another line (no semicolon yet) bra col1 and continue scanning *we have a word, compile into present definition col11 lbsr lookup lookup word bne col2 found, we have it jsr number try it as a number ldd ,u++ get flag lbeq lokerr number failed, its an error * number to be compiled into dictionary col12 bsr brcl compile literal value bra col1 and keep scanning * word to be compiled into dictionary col2 bita #$04 is it ok to compile? bne interr no, force error bita #1 does it execute on compilation? beq col3 no, normal word stu temp save stack pointer ldx free+3 get free adress for ec functions jsr [,u++] execute word cmpu temp did it leave exactly one word on the stack? bne col1 no, continue scanning bra col12 special case, compile word as literal * normal word, compile as word call col3 bsr comp1 compile call to word bra col1 and keep scanning * non-compile word encountered interr lbsr error generate error mesage fccz 'cannot compile' * '[cr]' - compile a return instruction fcb $82 fcc ']rc[' fdb colon brcr ldx free+3 get free address ldb #$39 get 'rts' instruction bra brc11 place into dictionaty * '[cl]' - compile a literal value fcb $82 fcc ']lc[' fdb brcr brcl ldx free+3 get free addres lda #$cc get 'ldd #' instruction sta ,x+ place in dictionary ldd ,u++ get data value std ,x++ place in dictionat ldd #$3606 get 'pshu a,b' instruction bra comp3 place in dictionary * '[cw]' - compile call to a word into the dictionary fcb $82 fcc ']wc[' fdb brcl brcw ldx free+3 get free address bra comp1 compile into dictionry * '[c2]' - compile a two byte (word) value into the dictionary fcb $82 fcc ']2c[' fdb brcw brc2 ldx free+3 get free address bra comp3 compile two byte value * '[c1]' - compile a single byte value into the dictionary fcb $82 fcc ']1c[' fdb brc2 brc1 ldx free+3 get free address ldd ,u++ get value to compile brc11 stb ,x+ place in dictionary bra comp4 resave free pointer * '[fc]' - force compilation of next word, even if normaly auto-exec fcb $83 fcc ']cf[' fdb brc1 brcf jsr tick lookup word address bita #$04 can it be compiled? bne interr no, get upset * compile call to a word into dictionary comp1 lda #$bd get 'jsr >' instruction sta ,x+ write to dictionary comp2 ldd ,u++ get value from date stack comp3 std ,x++ write to dictionary comp4 stx free+3 resave free pointer rts * '[ni]' - cause last (or currently) compiled word to be non-interactive fcb $81 fcc ']in[' fdb brcf brni ldb #2 get [ni] bit bra setbit set bit in descriptor byte * '[nc]' - cause last (or currently) compiled word to be non-compiling fcb $81 fcc ']cn[' fdb brni brnc ldb #4 get [nc] bit bra setbit set bit in descriptor byte * '[ec]' - cause last (or currently) compiled word to execute when compiled fcb $81 fcc ']ce[' fdb brnc brec ldb #1 get [ec] bit * set a bit in the descriptor byte for last word in dictionary setbit ldy here+3 get address of last word in dictionary leay -2,y backup to name setb1 lda ,-y get char from name bpl setb1 keep reading till we get descriptor byte pshs b save bit to add ora ,s+ include bit in descriptor byte sta ,y resave new descriptor rts * 'exec>' - compile jump to remainder of this word into new word fcb $82 fcc '>cexe' fdb brec does ldx free+3 get address of free dictionary lda #$7e get 'jmp >' instruction sta ,x+ save in dictionary puls a,b get address of remainder of this word bra comp3 compile into dictionary * '(' - brace, start of comment fcb $81 fcc '(' fdb does brace ldy inptr+3 get input pointer brac1 lda ,y+ get data from buffer beq brac3 end of line cmpa #')' is it closing brace? beq brac2 yes, exit cmpa #'(' is it nested opening brace? bne brac1 no, its ok bsr brac1 recurse bra brac1 and keep looking * end of line, with no closing comment brac3 jsr read read another line bra brace and keep looking brac2 sty inptr+3 resave input pointer rts * 'leave' - exit innermost do loop fcb $82 fcc 'evael' fdb brace leave ldd 4,s get loop limit std 2,s set index to same value rts * '+loop' - loop with value to add fcb $83 fcc 'pool+' fdb leave ploop pulu a get structure type cmpa #$81 is it do loop? bne nsterr no, nesting error ldd #$ec62 'ldd 2,s' std ,x++ compile into dictionary ldd #$e3c1 'addd ,u++' std ,x++ compile lda #$ed 'std 2,s' sta ,x+ compile bra loop1 end terminate normally * 'loop' - normal do loop fcb $83 fcc 'pool' fdb ploop loop pulu a get structure type cmpa #$81 is it do loop? bne nsterr no, nesting error ldd #$ec62 'ldd 2,s' std ,x++ place in dictionary ldd #$c300 'addd #1' std ,x++ place in dictionary ldd #$01ed 'std 2,s' std ,x++ place in dictionary loop1 ldd #$6210 ; < catchup > (postbyte for std, prefix for cmpd) std ,x++ save in dictionary ldd #$a3e4 'cmpd ,s' std ,x++ compile ldd #$1025 'lblo' lbsr unt1 calculate offset value and compile ldd #$3264 'leas 4,s' std ,x++ compile comret stx free+3 save new free pointer rts * 'k' - third index value for do loop fcb $80 fcc 'k' fdb loop k ldd 12,s get index value bra ijk save it * 'j' - second indev value for do loop fcb $80 fcc 'j' fdb k j ldd 8,s get index value bra ijk save it * 'i' first index value for do loop fcb $80 fcc 'i' fdb j i ldd 4,s get index value ijk std ,--u save on stack rts * structure is nested improperly nsterr lbsr error generate error message fccz 'improper nesting' * 'do' - start of do loop construct fcb $83 fcc 'od' fdb i do lda #$bd get 'jsr >' instruction sta ,x+ compile into dictionary ldy #tor address of '>r' word sty ,x++ compile into dict sta ,x+ and another 'jsr >' sty ,x++ for another '>r' lda #$81 indicate do loop pshu a,x save pgm counter etc bra comret resave free pointer * 'forever' - begin loop forever fcb $83 fcc 'reverof' fdb do foreve pulu a,y get loop construct identifier cmpa #$80 was it a begin loop? bne nsterr no, improper nesting lda #$7e 'jmp >' instruction sta ,x+ place in dictionary sty ,x++ include address to loop to bra comret resave free pointer * 'until' - conditional begin loop fcb $83 fcc 'litnu' fdb foreve until pulu a get structure identifier cmpa #$80 is it a begin loop? bne nsterr no, bad nesting ldd #$ecc1 'ldd ,u++' std ,x++ save in dictionary ldd #$1027 'lbeq' * compile long branch, and calculate offset from address on stack unt1 std ,x++ save in dictionary leax 2,x get current address pshs x save on stack pulu a,b get address to jump to subd ,s++ calculate offset std -2,x compile into dictionary comr1 lbra comret resave free pointer * 'while' - conditional begin loop fcb $83 fcc 'elihw' fdb until while pulu a get structure identifier cmpa #$80 is it a begin loop? bne nsterr no, improper nesting ldd #$ecc1 'ldd ,u++' std ,x++ compile into dictionary ldd #$1026 'lbne' bra unt1 compile into dict with offset * 'begin' - start a begin loop fcb $83 fcc 'nigeb' fdb while begin lda #$80 begin loop identifier pshu a,x save it and current position rts * 'endif' - end an if statement fcb $83 fcc 'fidne' fdb begin endif pulu a get structure identifier cmpa #$82 is it 'if'? lbne nsterr no, bad nesting ldy ,u get address tfr x,d get current free address subd ,u++ calculate offset std -2,y save in branch operand rts * 'else' - else clause to an if statement fcb $83 fcc 'esle' fdb endif else lda #$16 'lbra' sta ,x+ compile into dictionary leax 2,x skip to next free pshs x save address bsr endif compile in branch puls x restore address bra if1 set up new if jumps * 'if' - if condition fcb $83 fcc 'fi' fdb else if ldd #$ecc1 'ldd ,u++' std ,x++ compile ldd #$1027 'lbeq' std ,x++ compile leax 2,x advance to free if1 lda #$82 indicate if structure pshu a,x save with address on stack comr2 lbra comret resave free pointer * '."' display message on terminal fcb $83 fcc '".' fdb if dotq bsr quote compile string lda #$bd 'jsr >' sta ,x+ compile into dict ldd #pmsg display message std ,x++ compile into dict bra comr2 resave free pointer * '"' - compile string into dictionary fcb $83 fcc '"' fdb dotq quote lda #$8d 'bsr' instruction sta ,x++ compile into dict jsr qskip advance to non-blank pshs x save pointer quo1 lda ,y+ get data from input buffer beq unterr end of line, error cmpa #'"' is it closing quote? beq quo2 yes, exit sta ,x+ save in string bra quo1 and keep processing quo2 sty inptr+3 save new input buffer pointer clr ,x+ indicate end of string ldy ,s get address of bsr operand tfr x,d get current address subd ,s++ calculate offset for bsr stb -1,y save in operand lda #$bd 'jsr >' sta ,x+ compile into dict ldd #fromr get '>r' address std ,x++ compile bra comr2 resave free pointer * unterminated string unterr lbsr error generate error message fccz 'unterminated' * '0' - quicker zero fcb $80 fcc '0' fdb quote zero clra zero high byte clrb zero low byte std ,--u save on data stack rts * '1' - quicker one fcb $80 fcc '1' fdb zero one ldd #1 get a value of one std ,--u save on stack rts * * variables * * '(out)' - address of general output driver fcb $80 fcc ')tuo(' fdb one disp jsr variab variable subroutine fdb dolout default is '$out' * '(in)' - address of general input driver fcb $80 fcc ')ni(' fdb disp inpt jsr variab variable subroutine fdb dolin default is '$in' * '(go)' - address of word to execute at startup fcb $80 fcc ')og(' fdb inpt boot jsr variab variable subroutine fdb quit default is 'quit' * '>in' - pointer to position in input buffer fcb $80 fcc 'ni>' fdb boot inptr jsr variab variable subroutine fdb inpbuf default is start of buffer * 'base' - current number conversion base fcb $80 fcc 'esab' fdb inptr base jsr variab variable subroutine fdb 16 default is base 10 * 'free' - address of free memory following dictionary fcb $80 fcc 'eerf' fdb base free jsr variab variable subroutine fdb usrspc default is end of dictionary * 'reboot' - reboot the system * 'ospanic' - show OS panic error and reboot fcb $80 fcc 'toober' fdb free reboot jmp $fc7f fcb $80 fcc 'cinapso' fdb reboot ospanic jmp $fc91 * 'setfilter' - take filter, cutoff, resonance and use ROM to poke filter fcb $80 fcc 'retliftes' fdb ospanic setfilter pshs x ldd ,u++ voice clra andb #$07 only eight of 'em pshs d puls x get it in X ldd ,u++ resonance stb $e408,x ldd ,u++ cutoff stb $e410,x puls x rts * motor fcb $80 fcc 'rotom' fdb setfilter motor ldd ,u++ ; on, off bitb #$01 beq motor1 jmp $f4c6 ; rom motor on motor1 jmp $f4d6 rts * seektrk fcb $80 fcc 'krtkees' fdb motor seektrk ldd ,u++ ; unstack track stb $8002 jsr $f06f andcc #$bf rts * loadsec fcb $80 fcc 'cesdaol' fdb seektrk loadsec ldd ,u++ std $8004 load address ldd ,u++ stb $8003 sector ldd ,u++ stb $8002 track orcc #$55 lda #$7f jsr $f06f jsr $f448 stx ,--u andcc #$bf rts * savesec fcb $80 fcc 'cesevas' fdb loadsec savesec ldd ,u++ std $8004 load address ldd ,u++ stb $8003 sector ldd ,u++ stb $8002 track orcc #$55 lda #$7f jsr $f06f jsr $f476 stx ,--u andcc #$bf rts fcb $80 fcc 'cdadr' fdb savesec rdadc pshs u ldu #$b050 ldx #$e418 ldb #$10 jsr $f571 puls u rts fcb $80 fcc 'enut' fdb rdadc tune pshs y ldd ,u++ ldx #$e418 ldy #$0 jsr $f5be sty ,--u * jsr $f5dc puls y rts * 'here' - address of last word in dictionary fcb $80 fcc 'ereh' fdb tune here jsr variab variable subroutine fdb here default is itself * dictionary grows from here usrspc equ *
gordonjcp/miragetools
asm/forth.asm
Assembly
gpl-3.0
37,571
package fr.xxiiteam.explorer.utils; import java.io.File; import java.io.Serializable; public final class Permissions implements Serializable { private static final long serialVersionUID = 2682238088276963741L; public final boolean ur; public final boolean uw; public final boolean ux; public final boolean gr; public final boolean gw; public final boolean gx; public final boolean or; public final boolean ow; public final boolean ox; public Permissions(String line) { if (line.length() != 10) { throw new IllegalArgumentException("Bad permission line"); } this.ur = line.charAt(1) == 'r'; this.uw = line.charAt(2) == 'w'; this.ux = line.charAt(3) == 'x'; this.gr = line.charAt(4) == 'r'; this.gw = line.charAt(5) == 'w'; this.gx = line.charAt(6) == 'x'; this.or = line.charAt(7) == 'r'; this.ow = line.charAt(8) == 'w'; this.ox = line.charAt(9) == 'x'; } public Permissions(boolean ur, boolean uw, boolean ux, boolean gr, boolean gw, boolean gx, boolean or, boolean ow, boolean ox) { this.ur = ur; this.uw = uw; this.ux = ux; this.gr = gr; this.gw = gw; this.gx = gx; this.or = or; this.ow = ow; this.ox = ox; } public static String toOctalPermission(final Permissions p) { byte user = 0; byte group = 0; byte other = 0; if (p.ur) { user += 4; } if (p.uw) { user += 2; } if (p.ux) { user += 1; } if (p.gr) { group += 4; } if (p.gw) { group += 2; } if (p.gx) { group += 1; } if (p.or) { other += 4; } if (p.ow) { other += 2; } if (p.ox) { other += 1; } return String.valueOf(user) + group + other; } // use this as alternative if no root is available public static String getBasicPermission(File file) { String per = ""; per += file.isDirectory() ? "d" : "-"; per += file.canRead() ? "r" : "-"; per += file.canWrite() ? "w" : "-"; per += file.canExecute() ? "x" : "-"; return per; } }
XXIITEAM/XXII-Explorer
explorer/src/main/java/fr/xxiiteam/explorer/utils/Permissions.java
Java
gpl-3.0
2,409
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>AtCore: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="atcore.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">AtCore &#160;<span id="projectnumber">1.0.0</span> </div> <div id="projectbrief">AtCore is a API to manage the serial connection between the computer and 3D Printers.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">MarlinPlugin Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_marlin_plugin.html">MarlinPlugin</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="class_i_firmware.html#a94415ab89871c20fc968a4953e020f46">checkCommand</a>(const QByteArray &amp;lastMessage)</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"><span class="mlabel">slot</span></td></tr> <tr><td class="entry"><a class="el" href="class_i_firmware.html#a4aa305b9b010e5c178eb69250e729952">core</a>() const</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_i_firmware.html#a9e98fbaf46e1a766633f003c3146ce9d">IFirmware</a>()</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_i_firmware.html#ab36cfc4d2de11096e81e5942229553ef">init</a>(AtCore *parent)</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_marlin_plugin.html#a767f51d4de4669581126d992ca2bfd89">MarlinPlugin</a>()</td><td class="entry"><a class="el" href="class_marlin_plugin.html">MarlinPlugin</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_marlin_plugin.html#a4757dc173f8305914c632308374e3617">name</a>() const override</td><td class="entry"><a class="el" href="class_marlin_plugin.html">MarlinPlugin</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_i_firmware.html#ae9ffc7fa1439b9c7bacc334af3f230fa">IFirmware::name</a></td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_i_firmware.html#abfcd63ee5029091908b12b4f3aa035f5">readyForCommand</a>(void)</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"><span class="mlabel">signal</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_i_firmware.html#a2c04ab38a72bc0e6c7dec38817598f5c">translate</a>(const QString &amp;command)</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="class_i_firmware.html#adbea813ff8f9bc989ca0395f433d0a92">validateCommand</a>(const QString &amp;lastMessage)</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_i_firmware.html#aa9d1eaace1749f63c04313e14d14b65a">~IFirmware</a>() override</td><td class="entry"><a class="el" href="class_i_firmware.html">IFirmware</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.14 </small></address> </body> </html>
lays147/WebAtelier
atelier/static/atcore_doc/class_marlin_plugin-members.html
HTML
gpl-3.0
6,166
<?php define('DB_HOST', 'localhost'); define('DB_NAME', 'u453794882_king'); define('DB_USER', 'u453794882_king'); define('DB_PASS', 'gamabeta'); define('DB_CHAR', 'utf8'); class DB { private static $instance; public static function getInstance(){ if(!isset(self::$instance)){ try { self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS); self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (PDOException $e) { echo $e->getMessage(); } } return self::$instance; } public static function prepare($sql){ return self::getInstance()->prepare($sql); } }
jeffersonmello/kingofeletroOficial
admin/class/DB.php
PHP
gpl-3.0
747
jQuery( function( $ ) { // wc_single_product_params is required to continue, ensure the object exists if ( typeof wc_single_product_params === 'undefined' ) { return false; } // Tabs $( '.woocommerce-tabs > .panel' ).hide(); $( '.woocommerce-tabs ul.tabs li a' ).click( function() { var $tab = $( this ), $tabs_wrapper = $tab.closest( '.woocommerce-tabs' ); $( 'ul.tabs li', $tabs_wrapper ).removeClass( 'active' ); $tabs_wrapper.children('div.panel').hide(); $( 'div' + $tab.attr( 'href' ), $tabs_wrapper).show(); $tab.parent().addClass( 'active' ); return false; }); $( '.woocommerce-tabs' ).each( function() { var hash = window.location.hash, url = window.location.href, tabs = $( this ); if ( hash.toLowerCase().indexOf( "comment-" ) >= 0 ) { $('ul.tabs li.reviews_tab a', tabs ).click(); } else if ( url.indexOf( "comment-page-" ) > 0 || url.indexOf( "cpage=" ) > 0 ) { $( 'ul.tabs li.reviews_tab a', $( this ) ).click(); } else { $( 'ul.tabs li:first a', tabs ).click(); } }); $( 'a.woocommerce-review-link' ).click( function() { $( '.reviews_tab a' ).click(); return true; }); // Star ratings for comments $( '#rating' ).hide().before( '<p class="stars"><span><a class="star-1" href="#">1</a><a class="star-2" href="#">2</a><a class="star-3" href="#">3</a><a class="star-4" href="#">4</a><a class="star-5" href="#">5</a></span></p>' ); $( 'body' ) .on( 'click', '#respond p.stars a', function() { var $star = $( this ), $rating = $( this ).closest( '#respond' ).find( '#rating' ); $rating.val( $star.text() ); $star.siblings( 'a' ).removeClass( 'active' ); $star.addClass( 'active' ); return false; }) .on( 'click', '#respond #submit', function() { var $rating = $( this ).closest( '#respond' ).find( '#rating' ), rating = $rating.val(); if ( $rating.size() > 0 && ! rating && wc_single_product_params.review_rating_required === 'yes' ) { alert( wc_single_product_params.i18n_required_rating_text ); return false; } }); // prevent double form submission $( 'form.cart' ).submit( function() { $( this ).find( ':submit' ).attr( 'disabled','disabled' ); }); });
shramee/test-ppb
js/wc-single-product.js
JavaScript
gpl-3.0
2,543
/* ColorCode, a free MasterMind clone with built in solver * Copyright (C) 2009 Dirk Laebisch * http://www.laebisch.com/ * * ColorCode 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. * * ColorCode 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 ColorCode. If not, see <http://www.gnu.org/licenses/>. */ #include "cellbtn.h" CellBtn::CellBtn(QWidget *parent) : QToolButton(parent) { setMouseTracking(true); setAttribute(Qt::WA_Hover, true); }
vakkov/ColorCode
cellbtn.cpp
C++
gpl-3.0
915
using System; using System.Collections.Generic; using System.Text; namespace RogueBasin.Triggers { /// <summary> /// When you enter the entrance square /// </summary> public class TreasureRoom : DungeonSquareTrigger { public TreasureRoom() { } public override bool CheckTrigger(int level, Point mapLocation) { //Check we are in the right place if (CheckLocation(level, mapLocation) == false) { return false; } //Otherwise in the right place if (!Triggered) { Game.Base.PlayMovie("treasureRoom", true); Triggered = true; //Teleport the player to the start location on the final level //Increment player level Player player = Game.Dungeon.Player; player.LocationLevel++; //Set vision player.SightRadius = 100; player.LocationMap = Game.Dungeon.Levels[player.LocationLevel].PCStartLocation; Game.Dungeon.MovePCAbsolute(player.LocationLevel, player.LocationMap.x, player.LocationMap.y); } return true; } } }
flend/roguelike
RogueBasin/RogueBasin/Triggers/TreasureRoom.cs
C#
gpl-3.0
1,323
<?php add_shortcode('style', 'style'); function style($options, $content) { return "<style> " . html_entity_decode($content) . "</style>"; }
cemc/cscircles-wp-content
plugins/pybox/shortcode-style.php
PHP
gpl-3.0
146
open(MAP, "> ucs_isdigit.map"); print MAP <<EOF; /* File generated from UnicodeData-4.1.0.txt. */ EOF for (<DATA>) { chop; ($name, $class) = split; @cp = (); open(UCD, "< private/UnicodeData-4.1.0.txt"); while(<UCD>) { chop; @entry = split(';'); last if $entry[0] =~ m/.{5,}/; if ($entry[2] eq $class) { push (@cp, $entry[0]); } } close UCD; @bs = (); $last = -1; $seq = -1; for my $e (@cp) { if (++$last != hex $e) { $seq = $e; $last = hex $e; push (@bs, $seq); } $end{$seq} = $e; } $nobs = @bs; print MAP <<EOF; #define N_ucs_${name}_map ${nobs} static wc_map ucs_${name}_map[ N_ucs_${name}_map ] = { EOF for (@bs) { print MAP " { 0x$_, 0x$end{$_} },\n"; } print MAP <<EOF }; EOF } __END__ isdigit Nd
chriskmanx/qmole
QMOLEDEV/w3m-0.5.3/libwc/map/mk_ucs_isdigit_map.pl
Perl
gpl-3.0
820
<?php /****************************************************************** * XLAgenda 4 par Xavier LE QUERE * Contact : support[at]xlagenda.fr * Web : http://www.xlagenda.fr * (C) Xavier LE QUERE, 2003-2013 * Version 4.3 - 16/06/13 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *********************************************************************/ echo "<div id=\"cadre_menu\"> <h2>".$lang['common_title_menu']."</h2> <p>\n"; //LIEN CALENDRIER if (!is_included($url_page,$page)) echo "&gt; <a href=\"$url_page\">".$lang['common_link_calendrier']."</a><br />\n"; else echo "&gt; ".$lang['common_link_calendrier']."<br />\n"; //LIEN RECHERCHER if (!is_included($url_recherche,$page)) echo "&gt; <a href=\"$url_recherche\">".$lang['common_link_rechercher']."</a><br />\n"; else echo "&gt; ".$lang['common_link_rechercher']."<br />\n"; //LIENS AJOUTER ET PROPOSER if (isSessionValide()) { echo "&gt; <a href=\"$repertoire_admin/ajouter.php\">".$lang['common_link_ajouter']."</a><br />\n"; } else { if ($menu_ajouter) echo "&gt; <a href=\"$repertoire_admin/index.php?add=yes\">".$lang['common_link_ajouter']."</a><br />\n"; if ($menu_proposer AND !is_included($url_proposition,$page)) echo "&gt; <a href=\"$url_proposition\">".$lang['common_link_proposer']."</a><br />\n"; elseif ($menu_proposer) echo "&gt; ".$lang['common_link_proposer']."<br />\n"; //LIEN DEMANDER UN COMPTE if ($menu_compte AND !is_included($url_compte,$page)) echo "&gt; <a href=\"$url_compte\">".$lang['common_link_compte']."</a><br />\n"; elseif ($menu_compte) echo "&gt; ".$lang['common_link_compte']."<br />\n"; } // LIEN ADMINISTRATION if ($menu_admin) echo "&gt; <a href=\"$repertoire_admin/index.php\">".$lang['common_link_admin']."</a><br />\n"; //LIEN DECONNEXION if (isSessionValide()) echo "&gt; <a href=\"$repertoire_admin/close.php\">".$lang['common_link_deconnexion']."</a>\n"; echo "</p> </div>\n" ?>
chrnoangel/xlagenda
menu.php
PHP
gpl-3.0
2,559
<div id="rewards-header" class="page-header"> <h1>奖惩情况</h1> </div> <!-- /rewards-header --> <div id="rewards-content" class="section"> <div id="rewards-content-header" style="overflow: auto;"> <div id="selector" style="float: left;"> <select id="available-years" class="span2"> <?php foreach ( $available_years as $available_year ) { $year = $available_year['school_year']; echo '<option value="'.$year.'">'.$year.'-'.($year + 1).'学年</option>'; } ?> </select> </div> <!-- /selector --> <div id="add-new" style="float: right; font-size: 13px;"> <img src="<?php echo base_url('/img/icon-add.png') ?>" alt="Icon" /> <a id="add-new-trigger" href="javascript:void(0);">添加记录</a> </div> <!-- /add-new --> </div> <!-- /rewards-content-header --> <div id="list"> <table id="reward-records" class="table table-striped"> <thead> <tr> <td>级别</td> <td>加/减分缘由</td> <td>加减分</td> </tr> </thead> <tbody></tbody> </table> </div> <!-- /list --> <div id="page-error" class="alert alert-error hide"><strong>温馨提示: </strong>未找到可用数据.</div> </div> <!-- /rewards-content --> <!-- New Rewards Modal --> <div id="new-rewards-dialog" class="modal hide dialog"> <div class="modal-header"> <button type="button" class="close">×</button> <h2 id="rewards-dialog-title">添加奖惩情况</h2> </div> <div class="modal-body"> <div id="rewards-notice-message" class="alert alert-warning"> <button type="button" class="close">×</button> <strong>提示: </strong>您正在为<?php echo $current_school_year; ?>-<?php echo ($current_school_year + 1); ?>学年添加奖惩情况记录. 请仔细确认后提交, 因为提交后的内容将无法修改! </div> <div id="rewards-error-message" class="alert alert-error hide"></div> <table id="new-rewards-table" class="table no-border"> <thead> <tr class="no-border"> <td>级别</td> <td>加/减分缘由</td> <td>加减分</td> </tr> </thead> <tbody></tbody> </table> <div id="new-record-trigger" style="padding-left: 8px; font-size: 13px;"> <img src="<?php echo base_url('/img/icon-add.png') ?>" alt="Icon" /> <a id="new-record-trigger" href="javascript:void(0);">添加一行</a> </div> <!-- /new-record-trigger --> </div> <div class="modal-footer"> <button id="add-rewards" class="btn btn-primary">确认</button> <button class="btn btn-cancel">取消</button> </div> </div> <!-- /New Rewards Modal --> <!-- JavaScript for the basic content --> <script type="text/javascript"> $('#available-years').change(function(){ var school_year = $(this).val(); get_reward_records(school_year); }); </script> <script type="text/javascript"> function get_reward_records(school_year) { $.ajax({ type: 'GET', async: true, url: "<?php echo base_url('home/get_reward_records/'); ?>" + school_year, dataType: 'JSON', success: function(result) { $('#reward-records tbody').empty(); if ( result['is_successful'] ) { var total_records = result['records'].length; for ( var i = 0; i < total_records; ++ i ) { $('#reward-records').append( '<tr class="table-datum">' + '<td>' + result['records'][i]['description'] + '</td>' + '<td>' + result['records'][i]['detail'] + '</td>' + '<td>' + result['records'][i]['additional_score'] + '</td>' + '</tr>' ); } set_visible('#page-error', false); set_visible('#list', true); } else { set_visible('#page-error', true); set_visible('#list', false); } } }); } </script> <script type="text/javascript"> function set_visible(element, is_visible) { if ( is_visible ) { $(element).css('display', 'block'); } else { $(element).css('display', 'none'); } set_footer_position(); // which is defined in index.php } </script> <script type="text/javascript"> function add_new_record() { $('#new-rewards-table').append( '<tr class="no-border">' + '<td>' + '<select name="level" style="width: 80px;">' + '<?php foreach ( $reward_levels as $reward_level ) { echo '<option value="'.$reward_level['reward_level_id'].'">'. $reward_level['description'].'</option>'; } ?>' + '</select>' + '</td>' + '<td><input type="text" name="detail" maxlength="255" /></td>' + '<td><input type="text" name="additional-score" /></td>' + '</tr>' ); } </script> <!-- JavaScript for New Rewards Model --> <script type="text/javascript"> $('#add-new-trigger').click(function() { $('#new-rewards-dialog').fadeIn(); }); </script> <script type="text/javascript"> $('#rewards-notice-message .close').click(function() { $('#rewards-notice-message').fadeOut(); }); </script> <script type="text/javascript"> $('.modal-header .close').click(function() { $('#new-rewards-dialog').fadeOut(); }); $('.btn-cancel').click(function() { $('#new-rewards-dialog').fadeOut(); }); </script> <script type="text/javascript"> $('#new-record-trigger').click(function() { add_new_record(); }) </script> <script type="text/javascript"> $('#new-rewards-table').delegate('input[name=additional-score]', 'change', function() { var number_string = $(this).val(); if ( !is_a_number(number_string) ) { $(this).val(''); } }); </script> <script type="text/javascript"> function is_a_number(number_string) { var number_regex = '^[-+]?[0-9]*\.?[0-9]+$'; return number_string.match(number_regex); } </script> <script type="text/javascript"> $('#add-rewards').click(function() { set_loading_mode(true); $('#new-rewards-table > tbody > tr').each(function() { var reward_level_id = $(this).find('select[name=level]').val(), detail = $(this).find('input[name=detail]').val(), additional_score = $(this).find('input[name=additional-score]').val(); if ( !is_empty(detail) && !is_empty(additional_score) ) { add_reward_record(reward_level_id, detail, additional_score); } }); // reload this page load('rewards'); }); </script> <script type="text/javascript"> function set_loading_mode(is_loading) { if ( is_loading ) { $('#new-rewards-dialog :input').attr('disabled', true); } else { $('#new-rewards-dialog :input').removeAttr('disabled'); } } </script> <script type="text/javascript"> function is_empty(str) { if ( !str || str.length == 0 ) { return true; } return !/[^\s]+/.test(str); } </script> <script type="text/javascript"> function add_reward_record(reward_level_id, detail, additional_score) { var post_data = 'reward_level_id=' + reward_level_id + '&detail=' + detail + '&additional_score=' + additional_score; $.ajax({ type: 'POST', async: true, url: "<?php echo base_url('home/add_reward_record/'); ?>", data: post_data, dataType: 'JSON', success: function(result) { }, error: function() { } }); } </script> <!-- Document Ready Function --> <script type="text/javascript"> $(document).ready(function() { // loading reward records var school_year = $('#available-years').val(); get_reward_records(school_year); // add three new lines in new rewards model var NUMBER_OF_LINES = 3; for ( i = 0; i < NUMBER_OF_LINES; ++ i ) { add_new_record(); } }); </script>
zjhzxhz/stumgr
application/views/home/rewards.php
PHP
gpl-3.0
8,887
package net.minecraft.src; import com.google.common.collect.Maps; import java.util.Iterator; import java.util.Map; import java.util.UUID; import java.util.Map.Entry; public class Potion { /** The array of potion types. */ public static final Potion[] potionTypes = new Potion[32]; public static final Potion field_76423_b = null; public static final Potion moveSpeed = (new Potion(1, false, 8171462)).setPotionName("potion.moveSpeed").setIconIndex(0, 0).func_111184_a(SharedMonsterAttributes.field_111263_d, "91AEAA56-376B-4498-935B-2F7F68070635", 0.20000000298023224D, 2); public static final Potion moveSlowdown = (new Potion(2, true, 5926017)).setPotionName("potion.moveSlowdown").setIconIndex(1, 0).func_111184_a(SharedMonsterAttributes.field_111263_d, "7107DE5E-7CE8-4030-940E-514C1F160890", -0.15000000596046448D, 2); public static final Potion digSpeed = (new Potion(3, false, 14270531)).setPotionName("potion.digSpeed").setIconIndex(2, 0).setEffectiveness(1.5D); public static final Potion digSlowdown = (new Potion(4, true, 4866583)).setPotionName("potion.digSlowDown").setIconIndex(3, 0); public static final Potion damageBoost = (new PotionAttackDamage(5, false, 9643043)).setPotionName("potion.damageBoost").setIconIndex(4, 0).func_111184_a(SharedMonsterAttributes.field_111264_e, "648D7064-6A60-4F59-8ABE-C2C23A6DD7A9", 3.0D, 2); public static final Potion heal = (new PotionHealth(6, false, 16262179)).setPotionName("potion.heal"); public static final Potion harm = (new PotionHealth(7, true, 4393481)).setPotionName("potion.harm"); public static final Potion jump = (new Potion(8, false, 7889559)).setPotionName("potion.jump").setIconIndex(2, 1); public static final Potion confusion = (new Potion(9, true, 5578058)).setPotionName("potion.confusion").setIconIndex(3, 1).setEffectiveness(0.25D); /** The regeneration Potion object. */ public static final Potion regeneration = (new Potion(10, false, 13458603)).setPotionName("potion.regeneration").setIconIndex(7, 0).setEffectiveness(0.25D); public static final Potion resistance = (new Potion(11, false, 10044730)).setPotionName("potion.resistance").setIconIndex(6, 1); /** The fire resistance Potion object. */ public static final Potion fireResistance = (new Potion(12, false, 14981690)).setPotionName("potion.fireResistance").setIconIndex(7, 1); /** The water breathing Potion object. */ public static final Potion waterBreathing = (new Potion(13, false, 3035801)).setPotionName("potion.waterBreathing").setIconIndex(0, 2); /** The invisibility Potion object. */ public static final Potion invisibility = (new Potion(14, false, 8356754)).setPotionName("potion.invisibility").setIconIndex(0, 1); /** The blindness Potion object. */ public static final Potion blindness = (new Potion(15, true, 2039587)).setPotionName("potion.blindness").setIconIndex(5, 1).setEffectiveness(0.25D); /** The night vision Potion object. */ public static final Potion nightVision = (new Potion(16, false, 2039713)).setPotionName("potion.nightVision").setIconIndex(4, 1); /** The hunger Potion object. */ public static final Potion hunger = (new Potion(17, true, 5797459)).setPotionName("potion.hunger").setIconIndex(1, 1); /** The weakness Potion object. */ public static final Potion weakness = (new PotionAttackDamage(18, true, 4738376)).setPotionName("potion.weakness").setIconIndex(5, 0).func_111184_a(SharedMonsterAttributes.field_111264_e, "22653B89-116E-49DC-9B6B-9971489B5BE5", 2.0D, 0); /** The poison Potion object. */ public static final Potion poison = (new Potion(19, true, 5149489)).setPotionName("potion.poison").setIconIndex(6, 0).setEffectiveness(0.25D); /** The wither Potion object. */ public static final Potion wither = (new Potion(20, true, 3484199)).setPotionName("potion.wither").setIconIndex(1, 2).setEffectiveness(0.25D); public static final Potion field_76434_w = (new PotionHealthBoost(21, false, 16284963)).setPotionName("potion.healthBoost").setIconIndex(2, 2).func_111184_a(SharedMonsterAttributes.field_111267_a, "5D6F0BA2-1186-46AC-B896-C61C5CEE99CC", 4.0D, 0); public static final Potion field_76444_x = (new PotionAbsoption(22, false, 2445989)).setPotionName("potion.absorption").setIconIndex(2, 2); public static final Potion field_76443_y = (new PotionHealth(23, false, 16262179)).setPotionName("potion.saturation"); public static final Potion field_76442_z = null; public static final Potion field_76409_A = null; public static final Potion field_76410_B = null; public static final Potion field_76411_C = null; public static final Potion field_76405_D = null; public static final Potion field_76406_E = null; public static final Potion field_76407_F = null; public static final Potion field_76408_G = null; /** The Id of a Potion object. */ public final int id; private final Map field_111188_I = Maps.newHashMap(); /** * This field indicated if the effect is 'bad' - negative - for the entity. */ private final boolean isBadEffect; /** Is the color of the liquid for this potion. */ private final int liquidColor; /** The name of the Potion. */ private String name = ""; /** The index for the icon displayed when the potion effect is active. */ private int statusIconIndex = -1; private double effectiveness; private boolean usable; protected Potion(int par1, boolean par2, int par3) { this.id = par1; potionTypes[par1] = this; this.isBadEffect = par2; if (par2) { this.effectiveness = 0.5D; } else { this.effectiveness = 1.0D; } this.liquidColor = par3; } /** * Sets the index for the icon displayed in the player's inventory when the status is active. */ protected Potion setIconIndex(int par1, int par2) { this.statusIconIndex = par1 + par2 * 8; return this; } /** * returns the ID of the potion */ public int getId() { return this.id; } public void performEffect(EntityLivingBase par1EntityLivingBase, int par2) { if (this.id == regeneration.id) { if (par1EntityLivingBase.func_110143_aJ() < par1EntityLivingBase.func_110138_aP()) { par1EntityLivingBase.heal(1.0F); } } else if (this.id == poison.id) { if (par1EntityLivingBase.func_110143_aJ() > 1.0F) { par1EntityLivingBase.attackEntityFrom(DamageSource.magic, 1.0F); } } else if (this.id == wither.id) { par1EntityLivingBase.attackEntityFrom(DamageSource.wither, 1.0F); } else if (this.id == hunger.id && par1EntityLivingBase instanceof EntityPlayer) { ((EntityPlayer)par1EntityLivingBase).addExhaustion(0.025F * (float)(par2 + 1)); } else if (this.id == field_76443_y.id && par1EntityLivingBase instanceof EntityPlayer) { if (!par1EntityLivingBase.worldObj.isRemote) { ((EntityPlayer)par1EntityLivingBase).getFoodStats().addStats(par2 + 1, 1.0F); } } else if ((this.id != heal.id || par1EntityLivingBase.isEntityUndead()) && (this.id != harm.id || !par1EntityLivingBase.isEntityUndead())) { if (this.id == harm.id && !par1EntityLivingBase.isEntityUndead() || this.id == heal.id && par1EntityLivingBase.isEntityUndead()) { par1EntityLivingBase.attackEntityFrom(DamageSource.magic, (float)(6 << par2)); } } else { par1EntityLivingBase.heal((float)Math.max(4 << par2, 0)); } } /** * Hits the provided entity with this potion's instant effect. */ public void affectEntity(EntityLivingBase par1EntityLivingBase, EntityLivingBase par2EntityLivingBase, int par3, double par4) { int var6; if ((this.id != heal.id || par2EntityLivingBase.isEntityUndead()) && (this.id != harm.id || !par2EntityLivingBase.isEntityUndead())) { if (this.id == harm.id && !par2EntityLivingBase.isEntityUndead() || this.id == heal.id && par2EntityLivingBase.isEntityUndead()) { var6 = (int)(par4 * (double)(6 << par3) + 0.5D); if (par1EntityLivingBase == null) { par2EntityLivingBase.attackEntityFrom(DamageSource.magic, (float)var6); } else { par2EntityLivingBase.attackEntityFrom(DamageSource.causeIndirectMagicDamage(par2EntityLivingBase, par1EntityLivingBase), (float)var6); } } } else { var6 = (int)(par4 * (double)(4 << par3) + 0.5D); par2EntityLivingBase.heal((float)var6); } } /** * Returns true if the potion has an instant effect instead of a continuous one (eg Harming) */ public boolean isInstant() { return false; } /** * checks if Potion effect is ready to be applied this tick. */ public boolean isReady(int par1, int par2) { int var3; if (this.id == regeneration.id) { var3 = 50 >> par2; return var3 > 0 ? par1 % var3 == 0 : true; } else if (this.id == poison.id) { var3 = 25 >> par2; return var3 > 0 ? par1 % var3 == 0 : true; } else if (this.id == wither.id) { var3 = 40 >> par2; return var3 > 0 ? par1 % var3 == 0 : true; } else { return this.id == hunger.id; } } /** * Set the potion name. */ public Potion setPotionName(String par1Str) { this.name = par1Str; return this; } /** * returns the name of the potion */ public String getName() { return this.name; } protected Potion setEffectiveness(double par1) { this.effectiveness = par1; return this; } public double getEffectiveness() { return this.effectiveness; } public boolean isUsable() { return this.usable; } /** * Returns the color of the potion liquid. */ public int getLiquidColor() { return this.liquidColor; } public Potion func_111184_a(Attribute par1Attribute, String par2Str, double par3, int par5) { AttributeModifier var6 = new AttributeModifier(UUID.fromString(par2Str), this.getName(), par3, par5); this.field_111188_I.put(par1Attribute, var6); return this; } public void func_111187_a(EntityLivingBase par1EntityLivingBase, BaseAttributeMap par2BaseAttributeMap, int par3) { Iterator var4 = this.field_111188_I.entrySet().iterator(); while (var4.hasNext()) { Entry var5 = (Entry)var4.next(); AttributeInstance var6 = par2BaseAttributeMap.func_111151_a((Attribute)var5.getKey()); if (var6 != null) { var6.func_111124_b((AttributeModifier)var5.getValue()); } } } public void func_111185_a(EntityLivingBase par1EntityLivingBase, BaseAttributeMap par2BaseAttributeMap, int par3) { Iterator var4 = this.field_111188_I.entrySet().iterator(); while (var4.hasNext()) { Entry var5 = (Entry)var4.next(); AttributeInstance var6 = par2BaseAttributeMap.func_111151_a((Attribute)var5.getKey()); if (var6 != null) { AttributeModifier var7 = (AttributeModifier)var5.getValue(); var6.func_111124_b(var7); var6.func_111121_a(new AttributeModifier(var7.func_111167_a(), this.getName() + " " + par3, this.func_111183_a(par3, var7), var7.func_111169_c())); } } } public double func_111183_a(int par1, AttributeModifier par2AttributeModifier) { return par2AttributeModifier.func_111164_d() * (double)(par1 + 1); } }
herpingdo/Hakkit
net/minecraft/src/Potion.java
Java
gpl-3.0
12,342
'use strict'; var obj = { a: 100, b: 200 }; var myVar = 10; console.log('Before delete'); console.log(obj); console.log(myVar); delete obj.a; //delete myVar;//ERROR console.log('After delete' + obj); console.log(obj); console.log(myVar);
ramezmagdy/NetPull
js/deletingStuff.js
JavaScript
gpl-3.0
242