code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#include "rtdef.h" #include "uip-conf.h" #include "uip.h" #include "uip_netif.h" #include "uip_arp.h" #include "rtconfig.h" #include "uip_pbuf.h" void netif_set_default(struct netif *netif) { } unsigned char mymac[6]={0xcc,0xbb,0xaa,0x99,0x88,0x02}; unsigned char ReadButton(); void netif_set_addr(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask, struct ip_addr *gw) { uip_ipaddr_t hipaddr; unsigned char tmp=0; //read button to differ mac/ip,fix me tmp=0x80 & ReadButton(); if(tmp) tmp=1; uip_ipaddr(hipaddr, RT_LWIP_IPADDR0,RT_LWIP_IPADDR1,RT_LWIP_IPADDR2,(RT_LWIP_IPADDR3+tmp)); uip_sethostaddr(hipaddr); uip_ipaddr(hipaddr, RT_LWIP_GWADDR0,RT_LWIP_GWADDR1,RT_LWIP_GWADDR2,RT_LWIP_GWADDR3); uip_setdraddr(hipaddr); uip_ipaddr(hipaddr, RT_LWIP_MSKADDR0,RT_LWIP_MSKADDR1,RT_LWIP_MSKADDR2,RT_LWIP_MSKADDR3); uip_setnetmask(hipaddr); uip_ethaddr.addr[0] = mymac[0]; uip_ethaddr.addr[1] = mymac[1]; uip_ethaddr.addr[2] = mymac[2]; uip_ethaddr.addr[3] = mymac[3]; uip_ethaddr.addr[4] = mymac[4]; uip_ethaddr.addr[5] = mymac[5]; uip_setethaddr(uip_ethaddr); return ; } struct netif * netif_add(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask, struct ip_addr *gw, void *state, err_t (* init)(struct netif *netif), err_t (* input)(struct pbuf *p, struct netif *netif)) { //if (netif_add(netif, IP_ADDR_ANY, IP_ADDR_BROADCAST, IP_ADDR_ANY, dev, //eth_init, eth_input) == RT_NULL) // netif->uip_hostaddr = ipaddr; //netif->uip_draddr = netmask; // netif->uip_netmask = gw; // netif_set_addr(netif,ipaddr,netmask,gw); // call user specified initialization function for netif if (init(netif) != 0) { return RT_NULL; } netif->input = input; netif->state = state; netif_set_addr(netif,ipaddr,netmask,gw); return netif; } err_t etharp_output(struct netif *netif, struct pbuf *q, struct ip_addr *ipaddr) { return 0; }
congallenwang/shdsl-bridge
components/net/uip/rt-thread/uip_netif.c
C
gpl-2.0
2,048
// This binary makes tar.gz files from directories, embedding and // deduping symlinked destinations. package main // QPov // // Copyright (C) Thomas Habets <thomas@habets.se> 2015 // https://github.com/ThomasHabets/qpov // // 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. import ( "flag" "io" "os" "path" "strings" "archive/tar" "compress/gzip" "fmt" "log" "path/filepath" ) var ( out = flag.String("out", "", "Output file.") in = flag.String("in", "", "Input directory.") packageLinks = flag.String("package_links", "_packagelinks", "Directory inside archive to store symlink destinations.") ) func countDirs(s string) int { s = path.Clean(s) n := 0 for { s, _ = path.Split(s) s = strings.TrimRight(s, fmt.Sprintf("%c", filepath.Separator)) if len(s) == 0 { return n } n++ } } func pkg(out *tar.Writer, dir string) error { linked := make(map[string]string) if err := filepath.Walk(dir, func(fn string, fi os.FileInfo, err error) error { if fi.Mode().IsRegular() { // Regular file: just store it as-is. if err := out.WriteHeader(&tar.Header{ Name: fn, Mode: 0644, Uid: 0, Gid: 0, Size: fi.Size(), ModTime: fi.ModTime(), Typeflag: tar.TypeReg, Uname: "qpov", Gname: "qpov", AccessTime: fi.ModTime(), ChangeTime: fi.ModTime(), }); err != nil { return err } t, err := os.Open(fn) if err != nil { return err } defer t.Close() if _, err := io.Copy(out, t); err != nil { return err } } else if 0 != (fi.Mode() & os.ModeSymlink) { dest, err := filepath.EvalSymlinks(fn) if err != nil { return err } if _, found := linked[dest]; !found { // If first occurence, store it. // Open real file. realFile, err := os.Open(fn) if err != nil { return err } defer realFile.Close() realStat, err := realFile.Stat() if err != nil { return err } // Write file to tarfile. newDest := path.Join(*packageLinks, fmt.Sprintf("d%08d%s", len(linked), path.Ext(fn))) // Write real file. if err := out.WriteHeader(&tar.Header{ Name: path.Join(dir, newDest), Mode: 0644, Uid: 0, Gid: 0, Size: realStat.Size(), ModTime: realStat.ModTime(), Typeflag: tar.TypeReg, Linkname: dest, Uname: "qpov", Gname: "qpov", AccessTime: fi.ModTime(), ChangeTime: fi.ModTime(), }); err != nil { return fmt.Errorf("writing linked dest: %v", err) } if _, err := io.Copy(out, realFile); err != nil { return fmt.Errorf("writing linked dest data (%q size %d): %v", fn, fi.Size(), err) } // Create relative path. var destPath []string for i := 0; i < countDirs(fn)-1; i++ { destPath = append(destPath, "..") } linked[dest] = path.Join(append(destPath, newDest)...) } if err := out.WriteHeader(&tar.Header{ Name: fn, Mode: 0644, Uid: 0, Gid: 0, Size: 0, ModTime: fi.ModTime(), Typeflag: tar.TypeSymlink, Linkname: linked[dest], Uname: "qpov", Gname: "qpov", AccessTime: fi.ModTime(), ChangeTime: fi.ModTime(), }); err != nil { log.Fatalf("Writing symlink header: %v", err) } } return nil }); err != nil { return err } return nil } func main() { flag.Parse() if len(flag.Args()) != 0 { log.Fatalf("Extra args on cmdline: %q", flag.Args()) } fo, err := os.Create(*out) if err != nil { log.Fatalf("Failed to open output file %q: %v", *out, err) } if err := func() (err error){ foz, err := gzip.NewWriterLevel(fo, gzip.BestCompression) if err != nil { return err } out := tar.NewWriter(foz) if err := pkg(out, *in); err != nil { return fmt.Errorf("writing package: %v", err) } if err := out.Close(); err != nil { return err } if err := foz.Close(); err != nil { return err } if err := fo.Close(); err != nil { return err } return nil }(); err != nil { if err2 := os.Remove(*out); err2 != nil { log.Fatalf("Error deleting failed write. Errors: %v and %v: ", err, err2) } log.Fatal(err) } }
ThomasHabets/qpov
cmd/package/package.go
GO
gpl-2.0
4,942
<?php die("Access Denied"); ?>#x#s:4516:" 1451556068 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw"> <head> <script type="text/javascript"> var siteurl='/'; var tmplurl='/templates/ja_mendozite/'; var isRTL = false; </script> <base href="http://www.zon.com.tw/zh/component/mailto/" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="榮憶橡膠工業股份有限公司" /> <title>榮憶橡膠工業股份有限公司 | 榮憶橡膠工業股份有限公司</title> <link href="http://www.zon.com.tw/zh/component/mailto/?tmpl=component&amp;template=ja_mendozite&amp;link=20000d9b7d49ba1a419c356277ea7f6dba822998" rel="canonical" /> <link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" /> <link rel="stylesheet" href="/t3-assets/css_31cec.css" type="text/css" /> <script src="/en/?jat3action=gzip&amp;jat3type=js&amp;jat3file=t3-assets%2Fjs_7f13c.js" type="text/javascript"></script> <script type="text/javascript"> function keepAlive() { var myAjax = new Request({method: "get", url: "index.php"}).send();} window.addEvent("domready", function(){ keepAlive.periodical(840000); }); </script> <script type="text/javascript"> var akoption = { "colorTable" : true , "opacityEffect" : true , "foldContent" : true , "fixingElement" : true , "smoothScroll" : false } ; var akconfig = new Object(); akconfig.root = 'http://www.zon.com.tw/' ; akconfig.host = 'http://'+location.host+'/' ; AsikartEasySet.init( akoption , akconfig ); </script> <link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-60602086-1', 'auto'); ga('send', 'pageview'); </script> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom-typo.css" type="text/css" /> <link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom.css" type="text/css" /> </head> <body id="bd" class="fs3 com_mailto contentpane"> <div id="system-message-container"> <div id="system-message"> </div> </div> <script type="text/javascript"> Joomla.submitbutton = function(pressbutton) { var form = document.getElementById('mailtoForm'); // do field validation if (form.mailto.value == "" || form.from.value == "") { alert('請提供正確的電子郵件。'); return false; } form.submit(); } </script> <div id="mailto-window"> <h2> 推薦此連結給朋友。 </h2> <div class="mailto-close"> <a href="javascript: void window.close()" title="關閉視窗"> <span>關閉視窗 </span></a> </div> <form action="http://www.zon.com.tw/index.php" id="mailtoForm" method="post"> <div class="formelm"> <label for="mailto_field">寄信給</label> <input type="text" id="mailto_field" name="mailto" class="inputbox" size="25" value=""/> </div> <div class="formelm"> <label for="sender_field"> 寄件者</label> <input type="text" id="sender_field" name="sender" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="from_field"> 您的郵件</label> <input type="text" id="from_field" name="from" class="inputbox" value="" size="25" /> </div> <div class="formelm"> <label for="subject_field"> 主旨</label> <input type="text" id="subject_field" name="subject" class="inputbox" value="" size="25" /> </div> <p> <button class="button" onclick="return Joomla.submitbutton('send');"> 送出 </button> <button class="button" onclick="window.close();return false;"> 取消 </button> </p> <input type="hidden" name="layout" value="default" /> <input type="hidden" name="option" value="com_mailto" /> <input type="hidden" name="task" value="send" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="link" value="20000d9b7d49ba1a419c356277ea7f6dba822998" /> <input type="hidden" name="875b7dd71770e1e6ca58b016f0a62a73" value="1" /> </form> </div> </body> </html>";
ForAEdesWeb/AEW32
cache/t3_pages/e8efe7956197beb28b5e158ad88f292e-cache-t3_pages-be0637f99e31d28bbb96f6fa8cd5fc49.php
PHP
gpl-2.0
4,524
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Marsyas: /home/hindle1/src/marsyas/src/marsyas/TempoHypotheses.h Source File</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="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Marsyas &#160;<span id="projectnumber">0.2</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </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_6680c0e66a1a8ddee45eaed69a14f44a.html">marsyas</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">TempoHypotheses.h</div> </div> </div><!--header--> <div class="contents"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="comment">/*</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="comment">** Copyright (C) 1998-2006 George Tzanetakis &lt;gtzan@cs.uvic.ca&gt;</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="comment">** </span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="comment">** This program is free software; you can redistribute it and/or modify</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="comment">** it under the terms of the GNU General Public License as published by</span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="comment">** the Free Software Foundation; either version 2 of the License, or</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="comment">** (at your option) any later version.</span></div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="comment">** </span></div> <div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;<span class="comment">** This program is distributed in the hope that it will be useful,</span></div> <div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160;<span class="comment">** but WITHOUT ANY WARRANTY; without even the implied warranty of</span></div> <div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;<span class="comment">** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span></div> <div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;<span class="comment">** GNU General Public License for more details.</span></div> <div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;<span class="comment">** </span></div> <div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="comment">** You should have received a copy of the GNU General Public License</span></div> <div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;<span class="comment">** along with this program; if not, write to the Free Software </span></div> <div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160;<span class="comment">** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</span></div> <div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160;<span class="comment">*/</span></div> <div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;</div> <div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;<span class="preprocessor">#ifndef MARSYAS_TEMPOHYPOTHESES_H</span></div> <div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define MARSYAS_TEMPOHYPOTHESES_H</span></div> <div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;<span class="preprocessor">#include &quot;MarSystem.h&quot;</span> </div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;</div> <div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160;<span class="keyword">namespace </span>Marsyas</div> <div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;{</div> <div class="line"><a name="l00060"></a><span class="lineno"><a class="code" href="classMarsyas_1_1TempoHypotheses.html"> 60</a></span>&#160;<span class="keyword">class </span><a class="code" href="classMarsyas_1_1TempoHypotheses.html" title="Organizes a NN x 3 matrix given NN = N x M raw {period, phase, periodSalience} hypotheses. (if no periods were retrieved some manually defined periods will be assumed)">TempoHypotheses</a>: <span class="keyword">public</span> <a class="code" href="classMarsyas_1_1MarSystem.html" title="MarSystem transforms a realvec.">MarSystem</a></div> <div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160;{</div> <div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160;<span class="keyword">private</span>: </div> <div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160; <span class="comment">//Add specific controls needed by this MarSystem.</span></div> <div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160; <span class="keywordtype">void</span> addControls();</div> <div class="line"><a name="l00065"></a><span class="lineno"> 65</span>&#160; MarControlPtr ctrl_nPhases_;</div> <div class="line"><a name="l00066"></a><span class="lineno"> 66</span>&#160; MarControlPtr ctrl_nPeriods_;</div> <div class="line"><a name="l00067"></a><span class="lineno"> 67</span>&#160; MarControlPtr ctrl_inductionTime_;</div> <div class="line"><a name="l00068"></a><span class="lineno"> 68</span>&#160; MarControlPtr ctrl_srcFs_;</div> <div class="line"><a name="l00069"></a><span class="lineno"> 69</span>&#160; MarControlPtr ctrl_hopSize_;</div> <div class="line"><a name="l00070"></a><span class="lineno"> 70</span>&#160; MarControlPtr ctrl_tickCount_;</div> <div class="line"><a name="l00071"></a><span class="lineno"> 71</span>&#160; MarControlPtr ctrl_dumbInduction_;</div> <div class="line"><a name="l00072"></a><span class="lineno"> 72</span>&#160; MarControlPtr ctrl_dumbInductionRequest_;</div> <div class="line"><a name="l00073"></a><span class="lineno"> 73</span>&#160; MarControlPtr ctrl_triggerInduction_;</div> <div class="line"><a name="l00074"></a><span class="lineno"> 74</span>&#160; MarControlPtr ctrl_accSize_;</div> <div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160; MarControlPtr ctrl_maxPeriod_;</div> <div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160; MarControlPtr ctrl_minPeriod_;</div> <div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160;</div> <div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160; mrs_natural maxPeriod_;</div> <div class="line"><a name="l00079"></a><span class="lineno"> 79</span>&#160; mrs_natural minPeriod_;</div> <div class="line"><a name="l00080"></a><span class="lineno"> 80</span>&#160; mrs_natural accSize_;</div> <div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160; mrs_bool triggerInduction_;</div> <div class="line"><a name="l00082"></a><span class="lineno"> 82</span>&#160; mrs_bool dumbInductionRequest_;</div> <div class="line"><a name="l00083"></a><span class="lineno"> 83</span>&#160; mrs_natural hopSize_;</div> <div class="line"><a name="l00084"></a><span class="lineno"> 84</span>&#160; mrs_real srcFs_;</div> <div class="line"><a name="l00085"></a><span class="lineno"> 85</span>&#160; mrs_natural inductionSize_;</div> <div class="line"><a name="l00086"></a><span class="lineno"> 86</span>&#160; mrs_natural timeElapsed_;</div> <div class="line"><a name="l00087"></a><span class="lineno"> 87</span>&#160; mrs_natural nPhases_;</div> <div class="line"><a name="l00088"></a><span class="lineno"> 88</span>&#160; mrs_natural nPeriods_;</div> <div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160; mrs_bool foundPeriods_;</div> <div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160; mrs_bool foundPhases_;</div> <div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160; mrs_natural manualBPMs_[10];</div> <div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160; <span class="keywordtype">void</span> myUpdate(MarControlPtr sender);</div> <div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160;</div> <div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160;<span class="keyword">public</span>:</div> <div class="line"><a name="l00095"></a><span class="lineno"> 95</span>&#160; <a class="code" href="classMarsyas_1_1TempoHypotheses.html" title="Organizes a NN x 3 matrix given NN = N x M raw {period, phase, periodSalience} hypotheses. (if no periods were retrieved some manually defined periods will be assumed)">TempoHypotheses</a>(std::string name);</div> <div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160; <a class="code" href="classMarsyas_1_1TempoHypotheses.html" title="Organizes a NN x 3 matrix given NN = N x M raw {period, phase, periodSalience} hypotheses. (if no periods were retrieved some manually defined periods will be assumed)">TempoHypotheses</a>(<span class="keyword">const</span> <a class="code" href="classMarsyas_1_1TempoHypotheses.html" title="Organizes a NN x 3 matrix given NN = N x M raw {period, phase, periodSalience} hypotheses. (if no periods were retrieved some manually defined periods will be assumed)">TempoHypotheses</a>&amp; a);</div> <div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160; ~<a class="code" href="classMarsyas_1_1TempoHypotheses.html" title="Organizes a NN x 3 matrix given NN = N x M raw {period, phase, periodSalience} hypotheses. (if no periods were retrieved some manually defined periods will be assumed)">TempoHypotheses</a>();</div> <div class="line"><a name="l00098"></a><span class="lineno"> 98</span>&#160; <a class="code" href="classMarsyas_1_1MarSystem.html" title="MarSystem transforms a realvec.">MarSystem</a>* clone() <span class="keyword">const</span>; </div> <div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160; </div> <div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160; <span class="keywordtype">void</span> myProcess(realvec&amp; in, realvec&amp; out);</div> <div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160;};</div> <div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160;</div> <div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160;}<span class="comment">//namespace Marsyas</span></div> <div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160;</div> <div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160;<span class="preprocessor">#endif</span></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Mar 24 2013 13:57:21 for Marsyas by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
abramhindle/marsyas-fork
doc/out-www/sourceDoc/html/TempoHypotheses_8h_source.html
HTML
gpl-2.0
13,102
<?php // // ------------------------------------------------------------------------ // // XOOPS - PHP Content Management System // // Copyright (c) 2000-2016 XOOPS.org // // <http://xoops.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. // // // // You may not change or alter any portion of this comment or credits // // of supporting developers from this source code or any supporting // // source code which is considered copyrighted (c) material of the // // original comment or credit authors. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // ------------------------------------------------------------------------ // // Author: Kazumi Ono (AKA onokazu) // // URL: http://www.myweb.ne.jp/, http://xoops.org/, http://jp.xoops.org/ // // Project: XOOPS Project // // ------------------------------------------------------------------------- // if (!is_object($xoopsUser) || !is_object($xoopsModule) || !$xoopsUser->isAdmin($xoopsModule->mid())) { exit('Access Denied'); } include_once XOOPS_ROOT_PATH . '/class/xoopsblock.php'; include XOOPS_ROOT_PATH . '/modules/system/admin/blocksadmin/blocksadmin.php'; $op = 'list'; if (!empty($_POST['op'])) { $op = $_POST['op']; } if (!empty($_POST['bid'])) { $bid = (int)$_POST['bid']; } if (isset($_GET['op'])) { if ($_GET['op'] === 'edit' || $_GET['op'] === 'delete' || $_GET['op'] === 'delete_ok' || $_GET['op'] === 'clone' /* || $_GET['op'] === 'previewpopup'*/) { $op = $_GET['op']; $bid = isset($_GET['bid']) ? (int)$_GET['bid'] : 0; } } if (isset($_POST['previewblock'])) { //if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { // exit('Invalid Referer'); //} if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } if (empty($bid)) { die('Invalid bid.'); } if (!empty($_POST['bside'])) { $bside = (int)$_POST['bside']; } else { $bside = 0; } if (!empty($_POST['bweight'])) { $bweight = (int)$_POST['bweight']; } else { $bweight = 0; } if (!empty($_POST['bvisible'])) { $bvisible = (int)$_POST['bvisible']; } else { $bvisible = 0; } if (!empty($_POST['bmodule'])) { $bmodule = $_POST['bmodule']; } else { $bmodule = array(); } if (!empty($_POST['btitle'])) { $btitle = $_POST['btitle']; } else { $btitle = ''; } if (!empty($_POST['bcontent'])) { $bcontent = $_POST['bcontent']; } else { $bcontent = ''; } if (!empty($_POST['bctype'])) { $bctype = $_POST['bctype']; } else { $bctype = ''; } if (!empty($_POST['bcachetime'])) { $bcachetime = (int)$_POST['bcachetime']; } else { $bcachetime = 0; } xoops_cp_header(); include_once XOOPS_ROOT_PATH . '/class/template.php'; $xoopsTpl = new XoopsTpl(); $xoopsTpl->xoops_setCaching(0); $block['bid'] = $bid; if ($op === 'clone_ok') { $block['form_title'] = _AM_CLONEBLOCK; $block['submit_button'] = _CLONE; $myblock = new XoopsBlock(); $myblock->setVar('block_type', 'C'); } else { $op = 'update'; $block['form_title'] = _AM_EDITBLOCK; $block['submit_button'] = _SUBMIT; $myblock = new XoopsBlock($bid); $block['name'] = $myblock->getVar('name'); } $myts = MyTextSanitizer::getInstance(); $myblock->setVar('title', $myts->stripSlashesGPC($btitle)); $myblock->setVar('content', $myts->stripSlashesGPC($bcontent)); // $dummyhtml = '<html><head><meta http-equiv="content-type" content="text/html; charset='._CHARSET.'" /><meta http-equiv="content-language" content="'._LANGCODE.'" /><title>'.$xoopsConfig['sitename'].'</title><link rel="stylesheet" type="text/css" media="all" href="'.getcss($xoopsConfig['theme_set']).'" /></head><body><table><tr><th>'.$myblock->getVar('title').'</th></tr><tr><td>'.$myblock->getContent('S', $bctype).'</td></tr></table></body></html>'; /* $dummyfile = '_dummyfile_'.time().'.html'; $fp = fopen(XOOPS_CACHE_PATH.'/'.$dummyfile, 'w'); fwrite($fp, $dummyhtml); fclose($fp);*/ $block['edit_form'] = false; $block['template'] = ''; $block['op'] = $op; $block['side'] = $bside; $block['weight'] = $bweight; $block['visible'] = $bvisible; $block['title'] = $myblock->getVar('title', 'E'); $block['content'] = $myblock->getVar('content', 'n'); $block['modules'] =& $bmodule; $block['ctype'] = isset($bctype) ? $bctype : $myblock->getVar('c_type'); $block['is_custom'] = true; $block['cachetime'] = (int)$bcachetime; echo '<a href="myblocksadmin.php">' . _AM_BADMIN . '</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;' . $block['form_title'] . '<br><br>'; include __DIR__ . '/../admin/myblockform.php'; //GIJ //echo '<a href="admin.php?fct=blocksadmin">'. _AM_BADMIN .'</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;'.$block['form_title'].'<br><br>'; //include XOOPS_ROOT_PATH.'/modules/system/admin/blocksadmin/blockform.php'; $xoopsGTicket->addTicketXoopsFormElement($form, __LINE__, 1800, 'myblocksadmin'); //GIJ $form->display(); $original_level = error_reporting(E_ALL); echo " <table width='100%' class='outer' cellspacing='1'> <tr> <th>" . $myblock->getVar('title') . "</th> </tr> <tr> <td class='odd'>" . $myblock->getContent('S', $bctype) . "</td> </tr> </table>\n"; error_reporting($original_level); xoops_cp_footer(); /* echo '<script type="text/javascript"> preview_window = openWithSelfMain("'.XOOPS_URL.'/modules/system/admin.php?fct=blocksadmin&op=previewpopup&file='.$dummyfile.'", "popup", 250, 200); </script>';*/ exit(); } /* if ($op == 'previewpopup') { if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { exit('Invalid Referer'); } $file = str_replace('..', '', XOOPS_CACHE_PATH.'/'.trim($_GET['file'])); if (file_exists($file)) { include $file; @unlink($file); } exit(); } */ /* if ($op == "list") { xoops_cp_header(); list_blocks(); xoops_cp_footer(); exit(); } */ if ($op === 'order') { //if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { // exit('Invalid Referer'); //} if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } if (!empty($_POST['side'])) { $side = $_POST['side']; } // if ( !empty($_POST['weight']) ) { $weight = $_POST['weight']; } if (!empty($_POST['visible'])) { $visible = $_POST['visible']; } // if ( !empty($_POST['oldside']) ) { $oldside = $_POST['oldside']; } // if ( !empty($_POST['oldweight']) ) { $oldweight = $_POST['oldweight']; } // if ( !empty($_POST['oldvisible']) ) { $oldvisible = $_POST['oldvisible']; } if (!empty($_POST['bid'])) { $bid = $_POST['bid']; } else { $bid = array(); } // GIJ start foreach (array_keys($bid) as $i) { if ($side[$i] < 0) { $visible[$i] = 0; $side[$i] = -1; } else { $visible[$i] = 1; } $bmodule = (isset($_POST['bmodule'][$i]) && is_array($_POST['bmodule'][$i])) ? $_POST['bmodule'][$i] : array(-1); myblocksadmin_update_block($i, $side[$i], $_POST['weight'][$i], $visible[$i], $_POST['title'][$i], null, null, $_POST['bcachetime'][$i], $bmodule, array()); // if ( $oldweight[$i] != $weight[$i] || $oldvisible[$i] != $visible[$i] || $oldside[$i] != $side[$i] ) // order_block($bid[$i], $weight[$i], $visible[$i], $side[$i]); } $query4redirect = '?dirname=' . urlencode(strip_tags(substr($_POST['query4redirect'], 9))); redirect_header("myblocksadmin.php$query4redirect", 1, _AM_DBUPDATED); // GIJ end } if ($op === 'order2') { if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } if (isset($_POST['addblock']) && is_array($_POST['addblock'])) { // addblock foreach ($_POST['addblock'] as $bid => $val) { myblocksadmin_update_blockinstance(0, 0, 0, 0, '', null, null, 0, array(), array(), (int)$bid); } } else { // else change order if (!empty($_POST['side'])) { $side = $_POST['side']; } if (!empty($_POST['visible'])) { $visible = $_POST['visible']; } if (!empty($_POST['id'])) { $id = $_POST['id']; } else { $id = array(); } foreach (array_keys($id) as $i) { // separate side and visible if ($side[$i] < 0) { $visible[$i] = 0; $side[$i] = -1; // for not to destroy the original position } else { $visible[$i] = 1; } $bmodule = (isset($_POST['bmodule'][$i]) && is_array($_POST['bmodule'][$i])) ? $_POST['bmodule'][$i] : array(-1); myblocksadmin_update_blockinstance($i, $side[$i], $_POST['weight'][$i], $visible[$i], $_POST['title'][$i], null, null, $_POST['bcachetime'][$i], $bmodule, array()); } } $query4redirect = '?dirname=' . urlencode(strip_tags(substr($_POST['query4redirect'], 9))); redirect_header("myblocksadmin.php$query4redirect", 1, _MD_AM_DBUPDATED); exit; } /* if ($op == 'save') { if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { exit('Invalid Referer'); } if ( ! $xoopsGTicket->check( true , 'myblocksadmin' ) ) { redirect_header(XOOPS_URL.'/',3,$xoopsGTicket->getErrors()); } if ( !empty($_POST['bside']) ) { $bside = (int)($_POST['bside']); } else { $bside = 0; } if ( !empty($_POST['bweight']) ) { $bweight = (int)($_POST['bweight']); } else { $bweight = 0; } if ( !empty($_POST['bvisible']) ) { $bvisible = (int)($_POST['bvisible']); } else { $bvisible = 0; } if ( !empty($_POST['bmodule']) ) { $bmodule = $_POST['bmodule']; } else { $bmodule = array(); } if ( !empty($_POST['btitle']) ) { $btitle = $_POST['btitle']; } else { $btitle = ""; } if ( !empty($_POST['bcontent']) ) { $bcontent = $_POST['bcontent']; } else { $bcontent = ""; } if ( !empty($_POST['bctype']) ) { $bctype = $_POST['bctype']; } else { $bctype = ""; } if ( !empty($_POST['bcachetime']) ) { $bcachetime = (int)($_POST['bcachetime']); } else { $bcachetime = 0; } save_block($bside, $bweight, $bvisible, $btitle, $bcontent, $bctype, $bmodule, $bcachetime); exit(); } */ if ($op === 'update') { //if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { // exit('Invalid Referer'); //} if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } /* if ( !empty($_POST['bside']) ) { $bside = (int)($_POST['bside']); } else { $bside = 0; } if ( !empty($_POST['bweight']) ) { $bweight = (int)($_POST['bweight']); } else { $bweight = 0; } if ( !empty($_POST['bvisible']) ) { $bvisible = (int)($_POST['bvisible']); } else { $bvisible = 0; } if ( !empty($_POST['btitle']) ) { $btitle = $_POST['btitle']; } else { $btitle = ""; } if ( !empty($_POST['bcontent']) ) { $bcontent = $_POST['bcontent']; } else { $bcontent = ""; } if ( !empty($_POST['bctype']) ) { $bctype = $_POST['bctype']; } else { $bctype = ""; } if ( !empty($_POST['bcachetime']) ) { $bcachetime = (int)($_POST['bcachetime']); } else { $bcachetime = 0; } if ( !empty($_POST['bmodule']) ) { $bmodule = $_POST['bmodule']; } else { $bmodule = array(); } if ( !empty($_POST['options']) ) { $options = $_POST['options']; } else { $options = array(); } update_block($bid, $bside, $bweight, $bvisible, $btitle, $bcontent, $bctype, $bcachetime, $bmodule, $options);*/ $bcachetime = isset($_POST['bcachetime']) ? (int)$_POST['bcachetime'] : 0; $options = isset($_POST['options']) ? $_POST['options'] : array(); $bcontent = isset($_POST['bcontent']) ? $_POST['bcontent'] : ''; $bctype = isset($_POST['bctype']) ? $_POST['bctype'] : ''; $bmodule = (isset($_POST['bmodule']) && is_array($_POST['bmodule'])) ? $_POST['bmodule'] : array(-1); // GIJ + $msg = myblocksadmin_update_block($_POST['bid'], $_POST['bside'], $_POST['bweight'], $_POST['bvisible'], $_POST['btitle'], $bcontent, $bctype, $bcachetime, $bmodule, $options); // GIJ ! redirect_header('myblocksadmin.php', 1, $msg); } if ($op === 'delete_ok') { //if ( !admin_refcheck("/modules/$admin_mydirname/admin/") ) { // exit('Invalid Referer'); //} if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } // delete_block_ok($bid); GIJ imported from blocksadmin.php $myblock = new XoopsBlock($bid); if ($myblock->getVar('block_type') !== 'D' && $myblock->getVar('block_type') !== 'C') { redirect_header('myblocksadmin.php', 4, 'Invalid block'); } $myblock->delete(); if ($myblock->getVar('template') != '' && !defined('XOOPS_ORETEKI')) { $tplfileHandler = xoops_getHandler('tplfile'); $btemplate =& $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $bid); if (count($btemplate) > 0) { $tplman->delete($btemplate[0]); } } redirect_header('myblocksadmin.php', 1, _AM_DBUPDATED); // end of delete_block_ok() GIJ } if ($op === 'delete') { xoops_cp_header(); // delete_block($bid); GIJ imported from blocksadmin.php $myblock = new XoopsBlock($bid); if ($myblock->getVar('block_type') === 'S') { $message = _AM_SYSTEMCANT; redirect_header('admin.php?fct=blocksadmin', 4, $message); } elseif ($myblock->getVar('block_type') === 'M') { $message = _AM_MODULECANT; redirect_header('admin.php?fct=blocksadmin', 4, $message); } else { xoops_confirm(array('fct' => 'blocksadmin', 'op' => 'delete_ok', 'bid' => $myblock->getVar('bid')) + $xoopsGTicket->getTicketArray(__LINE__, 1800, 'myblocksadmin'), 'admin.php', sprintf(_AM_RUSUREDEL, $myblock->getVar('title'))); } // end of delete_block() GIJ xoops_cp_footer(); exit(); } if ($op === 'edit') { xoops_cp_header(); // edit_block($bid); GIJ imported from blocksadmin.php $myblock = new XoopsBlock($bid); $db = XoopsDatabaseFactory::getDatabaseConnection(); $sql = 'SELECT module_id FROM ' . $db->prefix('block_module_link') . ' WHERE block_id=' . (int)$bid; $result = $db->query($sql); $modules = array(); while ($row = $db->fetchArray($result)) { $modules[] = (int)$row['module_id']; } $is_custom = ($myblock->getVar('block_type') === 'C' || $myblock->getVar('block_type') === 'E') ? true : false; $block = array( 'form_title' => _AM_EDITBLOCK, 'name' => $myblock->getVar('name'), 'side' => $myblock->getVar('side'), 'weight' => $myblock->getVar('weight'), 'visible' => $myblock->getVar('visible'), 'title' => $myblock->getVar('title', 'E'), 'content' => $myblock->getVar('content', 'n'), 'modules' => $modules, 'is_custom' => $is_custom, 'ctype' => $myblock->getVar('c_type'), 'cachetime' => $myblock->getVar('bcachetime'), 'op' => 'update', 'bid' => $myblock->getVar('bid'), 'edit_form' => $myblock->getOptions(), 'template' => $myblock->getVar('template'), 'options' => $myblock->getVar('options'), 'submit_button' => _SUBMIT ); echo '<a href="myblocksadmin.php">' . _AM_BADMIN . '</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;' . _AM_EDITBLOCK . '<br><br>'; include __DIR__ . '/../admin/myblockform.php'; //GIJ $xoopsGTicket->addTicketXoopsFormElement($form, __LINE__, 1800, 'myblocksadmin'); //GIJ $form->display(); // end of edit_block() GIJ xoops_cp_footer(); exit(); } if ($op === 'clone') { xoops_cp_header(); $myblock = new XoopsBlock($bid); $db = XoopsDatabaseFactory::getDatabaseConnection(); $sql = 'SELECT module_id FROM ' . $db->prefix('block_module_link') . ' WHERE block_id=' . (int)$bid; $result = $db->query($sql); $modules = array(); while ($row = $db->fetchArray($result)) { $modules[] = (int)$row['module_id']; } $is_custom = ($myblock->getVar('block_type') === 'C' || $myblock->getVar('block_type') === 'E') ? true : false; $block = array( 'form_title' => _AM_CLONEBLOCK, 'name' => $myblock->getVar('name'), 'side' => $myblock->getVar('side'), 'weight' => $myblock->getVar('weight'), 'visible' => $myblock->getVar('visible'), 'content' => $myblock->getVar('content', 'N'), 'title' => $myblock->getVar('title', 'E'), 'modules' => $modules, 'is_custom' => $is_custom, 'ctype' => $myblock->getVar('c_type'), 'cachetime' => $myblock->getVar('bcachetime'), 'op' => 'clone_ok', 'bid' => $myblock->getVar('bid'), 'edit_form' => $myblock->getOptions(), 'template' => $myblock->getVar('template'), 'options' => $myblock->getVar('options'), 'submit_button' => _CLONE ); echo '<a href="myblocksadmin.php">' . _AM_BADMIN . '</a>&nbsp;<span style="font-weight:bold;">&raquo;&raquo;</span>&nbsp;' . _AM_CLONEBLOCK . '<br><br>'; include __DIR__ . '/../admin/myblockform.php'; $xoopsGTicket->addTicketXoopsFormElement($form, __LINE__, 1800, 'myblocksadmin'); //GIJ $form->display(); xoops_cp_footer(); exit(); } if ($op === 'clone_ok') { // Ticket Check if (!$xoopsGTicket->check(true, 'myblocksadmin')) { redirect_header(XOOPS_URL . '/', 3, $xoopsGTicket->getErrors()); } $block = new XoopsBlock($bid); // block type check $block_type = $block->getVar('block_type'); if ($block_type !== 'C' && $block_type !== 'M' && $block_type !== 'D') { redirect_header('myblocksadmin.php', 4, 'Invalid block'); } if (empty($_POST['options'])) { $options = array(); } elseif (is_array($_POST['options'])) { $options = $_POST['options']; } else { $options = explode('|', $_POST['options']); } // for backward compatibility // $cblock =& $block->clone(); or $cblock =& $block->xoopsClone(); $cblock = new XoopsBlock(); foreach ($block->vars as $k => $v) { $cblock->assignVar($k, $v['value']); } $cblock->setNew(); $myts = MyTextSanitizer::getInstance(); $cblock->setVar('side', $_POST['bside']); $cblock->setVar('weight', $_POST['bweight']); $cblock->setVar('visible', $_POST['bvisible']); $cblock->setVar('title', $_POST['btitle']); $cblock->setVar('content', @$_POST['bcontent']); $cblock->setVar('c_type', @$_POST['bctype']); $cblock->setVar('bcachetime', $_POST['bcachetime']); if (isset($options) && (count($options) > 0)) { $options = implode('|', $options); $cblock->setVar('options', $options); } $cblock->setVar('bid', 0); $cblock->setVar('block_type', $block_type === 'C' ? 'C' : 'D'); $cblock->setVar('func_num', 255); $newid = $cblock->store(); if (!$newid) { xoops_cp_header(); $cblock->getHtmlErrors(); xoops_cp_footer(); exit(); } /* if ($cblock->getVar('template') != '') { $tplfileHandler = xoops_getHandler('tplfile'); $btemplate =& $tplfileHandler->find($GLOBALS['xoopsConfig']['template_set'], 'block', $bid); if (count($btemplate) > 0) { $tplclone =& $btemplate[0]->clone(); $tplclone->setVar('tpl_id', 0); $tplclone->setVar('tpl_refid', $newid); $tplman->insert($tplclone); } } */ $db = XoopsDatabaseFactory::getDatabaseConnection(); $bmodule = (isset($_POST['bmodule']) && is_array($_POST['bmodule'])) ? $_POST['bmodule'] : array(-1); // GIJ + foreach ($bmodule as $bmid) { $sql = 'INSERT INTO ' . $db->prefix('block_module_link') . ' (block_id, module_id) VALUES (' . $newid . ', ' . $bmid . ')'; $db->query($sql); } /* global $xoopsUser; $groups =& $xoopsUser->getGroups(); $count = count($groups); for ($i = 0; $i < $count; ++$i) { $sql = "INSERT INTO ".$db->prefix('group_permission')." (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES (".$groups[$i].", ".$newid.", 1, 'block_read')"; $db->query($sql); } */ $sql = 'SELECT gperm_groupid FROM ' . $db->prefix('group_permission') . " WHERE gperm_name='block_read' AND gperm_modid='1' AND gperm_itemid='$bid'"; $result = $db->query($sql); while (list($gid) = $db->fetchRow($result)) { $sql = 'INSERT INTO ' . $db->prefix('group_permission') . " (gperm_groupid, gperm_itemid, gperm_modid, gperm_name) VALUES ($gid, $newid, 1, 'block_read')"; $db->query($sql); } redirect_header('myblocksadmin.php', 1, _AM_DBUPDATED); } // import from modules/system/admin/blocksadmin/blocksadmin.php /** * @param $bid * @param $bside * @param $bweight * @param $bvisible * @param $btitle * @param $bcontent * @param $bctype * @param $bcachetime * @param $bmodule * @param array $options * @return string */ function myblocksadmin_update_block($bid, $bside, $bweight, $bvisible, $btitle, $bcontent, $bctype, $bcachetime, $bmodule, $options = array()) { global $xoopsConfig; /* if (empty($bmodule)) { xoops_cp_header(); xoops_error(sprintf(_AM_NOTSELNG, _AM_VISIBLEIN)); xoops_cp_footer(); exit(); } */ $myblock = new XoopsBlock($bid); // $myblock->setVar('side', $bside); GIJ - if ($bside >= 0) { $myblock->setVar('side', $bside); } // GIJ + $myblock->setVar('weight', $bweight); $myblock->setVar('visible', $bvisible); $myblock->setVar('title', $btitle); if (isset($bcontent)) { $myblock->setVar('content', $bcontent); } if (isset($bctype)) { $myblock->setVar('c_type', $bctype); } $myblock->setVar('bcachetime', $bcachetime); if (isset($options) && (count($options) > 0)) { $options = implode('|', $options); $myblock->setVar('options', $options); } if ($myblock->getVar('block_type') === 'C') { switch ($myblock->getVar('c_type')) { case 'H': $name = _AM_CUSTOMHTML; break; case 'P': $name = _AM_CUSTOMPHP; break; case 'S': $name = _AM_CUSTOMSMILE; break; default: $name = _AM_CUSTOMNOSMILE; break; } $myblock->setVar('name', $name); } $msg = _AM_DBUPDATED; if ($myblock->store() != false) { $db = XoopsDatabaseFactory::getDatabaseConnection(); $sql = sprintf('DELETE FROM %s WHERE block_id = %u', $db->prefix('block_module_link'), $bid); $db->query($sql); foreach ($bmodule as $bmid) { $sql = sprintf('INSERT INTO %s (block_id, module_id) VALUES (%u, %d)', $db->prefix('block_module_link'), $bid, (int)$bmid); $db->query($sql); } include_once XOOPS_ROOT_PATH . '/class/template.php'; $xoopsTpl = new XoopsTpl(); $xoopsTpl->xoops_setCaching(2); if ($myblock->getVar('template') != '') { if ($xoopsTpl->is_cached('db:' . $myblock->getVar('template'))) { if (!$xoopsTpl->clear_cache('db:' . $myblock->getVar('template'))) { $msg = 'Unable to clear cache for block ID' . $bid; } } } else { if ($xoopsTpl->is_cached('db:system_dummy.html', 'block' . $bid)) { if (!$xoopsTpl->clear_cache('db:system_dummy.html', 'block' . $bid)) { $msg = 'Unable to clear cache for block ID' . $bid; } } } } else { $msg = 'Failed update of block. ID:' . $bid; } // redirect_header('admin.php?fct=blocksadmin&amp;t='.time(),1,$msg); // exit(); GIJ - return $msg; // GIJ + } // update block instance for 2.2 /** * @param $id * @param $bside * @param $bweight * @param $bvisible * @param $btitle * @param $bcontent * @param $bctype * @param $bcachetime * @param $bmodule * @param array $options * @param null $bid * @return string */ function myblocksadmin_update_blockinstance($id, $bside, $bweight, $bvisible, $btitle, $bcontent, $bctype, $bcachetime, $bmodule, $options = array(), $bid = null) { global $xoopsDB; $instanceHandler = xoops_getHandler('blockinstance'); $blockHandler = xoops_getHandler('block'); if ($id > 0) { // update $instance =& $instanceHandler->get($id); if ($bside >= 0) { $instance->setVar('side', $bside); } if (!empty($options)) { $instance->setVar('options', $options); } } else { // insert $instance =& $instanceHandler->create(); $instance->setVar('bid', $bid); $instance->setVar('side', $bside); $block = $blockHandler->get($bid); $instance->setVar('options', $block->getVar('options')); if (empty($btitle)) { $btitle = $block->getVar('name'); } } $instance->setVar('weight', $bweight); $instance->setVar('visible', $bvisible); $instance->setVar('title', $btitle); // if( isset( $bcontent ) ) $instance->setVar('content', $bcontent); // if( isset( $bctype ) ) $instance->setVar('c_type', $bctype); $instance->setVar('bcachetime', $bcachetime); if ($instanceHandler->insert($instance)) { $GLOBALS['xoopsDB']->query('DELETE FROM ' . $GLOBALS['xoopsDB']->prefix('block_module_link') . ' WHERE block_id=' . $instance->getVar('instanceid')); foreach ($bmodule as $mid) { $page = explode('-', $mid); $mid = $page[0]; $pageid = $page[1]; $GLOBALS['xoopsDB']->query('INSERT INTO ' . $GLOBALS['xoopsDB']->prefix('block_module_link') . ' VALUES (' . $instance->getVar('instanceid') . ', ' . (int)$mid . ', ' . (int)$pageid . ')'); } return _MD_AM_DBUPDATED; } return 'Failed update of block instance. ID:' . $id; /* // NAME for CUSTOM BLOCK if ( $instance->getVar('block_type') == 'C') { switch ( $instance->getVar('c_type') ) { case 'H': $name = _AM_CUSTOMHTML; break; case 'P': $name = _AM_CUSTOMPHP; break; case 'S': $name = _AM_CUSTOMSMILE; break; default: $name = _AM_CUSTOMNOSMILE; break; } $instance->setVar('name', $name); } */ /* // CLEAR TEMPLATE CACHE include_once XOOPS_ROOT_PATH.'/class/template.php'; $xoopsTpl = new XoopsTpl(); $xoopsTpl->xoops_setCaching(2); if ($instance->getVar('template') != '') { if ($xoopsTpl->is_cached('db:'.$instance->getVar('template'))) { if (!$xoopsTpl->clear_cache('db:'.$instance->getVar('template'))) { $msg = 'Unable to clear cache for block ID'.$bid; } } } else { if ($xoopsTpl->is_cached('db:system_dummy.html', 'block'.$bid)) { if (!$xoopsTpl->clear_cache('db:system_dummy.html', 'block'.$bid)) { $msg = 'Unable to clear cache for block ID'.$bid; } } } */ } // TODO edit2, delete2, customblocks
XoopsModules25x/smartpartner
include/blocksadmin.inc.php
PHP
gpl-2.0
30,507
/* Simulator CPU header for m32r. THIS FILE IS MACHINE GENERATED WITH CGEN. Copyright 1996, 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc. This file is part of the GNU simulators. 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, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef M32R_CPUALL_H #define M32R_CPUALL_H /* Include files for each cpu family. */ #ifdef WANT_CPU_M32RBF #include "eng.h" #include "cgen-engine.h" #include "cpu.h" #include "decode.h" #endif #ifdef WANT_CPU_M32RXF #include "engx.h" #include "cgen-engine.h" #include "cpux.h" #include "decodex.h" #endif extern const MACH m32r_mach; extern const MACH m32rx_mach; #ifndef WANT_CPU /* The ARGBUF struct. */ struct argbuf { /* These are the baseclass definitions. */ IADDR addr; const IDESC *idesc; char trace_p; char profile_p; /* ??? Temporary hack for skip insns. */ char skip_count; char unused; /* cpu specific data follows */ }; #endif #ifndef WANT_CPU /* A cached insn. ??? SCACHE used to contain more than just argbuf. We could delete the type entirely and always just use ARGBUF, but for future concerns and as a level of abstraction it is left in. */ struct scache { struct argbuf argbuf; }; #endif #endif /* M32R_CPUALL_H */
durandj/devkitadv
insight-5.3/sim/m32r/cpuall.h
C
gpl-2.0
1,843
import * as React from "react"; import FollowButton from "../FollowButton"; import SimilarityScore from "../SimilarityScore"; import { SimilarUsersModalProps } from "./SimilarUsersModal"; export type UserListModalEntryProps = { mode: "follow-following" | "similar-users"; user: ListenBrainzUser | SimilarUser; loggedInUser: ListenBrainzUser | null; apiUrl: string; loggedInUserFollowsUser: boolean; updateFollowingList: ( user: ListenBrainzUser, action: "follow" | "unfollow" ) => void; }; const UserListModalEntry = (props: UserListModalEntryProps) => { const { mode, user, loggedInUserFollowsUser, loggedInUser, updateFollowingList, apiUrl, } = props; return ( <> <div key={user.name}> <div> <a href={`/user/${user.name}`} target="_blank" rel="noopener noreferrer" > {user.name} </a> {loggedInUser && mode === "similar-users" && ( <SimilarityScore similarityScore={(user as SimilarUser).similarityScore} user={user} type="compact" /> )} </div> {loggedInUser && ( <FollowButton type="block" user={user} apiUrl={apiUrl} loggedInUser={loggedInUser} loggedInUserFollowsUser={loggedInUserFollowsUser} updateFollowingList={updateFollowingList} /> )} </div> </> ); }; export default UserListModalEntry;
Freso/listenbrainz-server
listenbrainz/webserver/static/js/src/follow/UserListModalEntry.tsx
TypeScript
gpl-2.0
1,563
module.exports = require('./lib/moninode.js');
a70ma/moninode
index.js
JavaScript
gpl-2.0
46
# parser file class Parser def parse(problem_instance) @problem = ProblemDefinition.new @file = File.open(problem_instance) @marker = "" while !@file.eof? @current_line = @file.readline if @current_line.start_with?("discount") @problem.discount_factor = @current_line.strip.split(" ").last.to_f elsif not @current_line.start_with?("\r") if not @current_line.start_with?("\t") and @marker = @marker.empty? ? @current_line.strip : "" elsif suffix = @marker.split(" ").first send("new_#{suffix}") end end end return @problem end def new_states states = @current_line.strip.split(", ") states.each { |state_name| @problem.add_state(state_name) } end def new_action action_name = @marker.split(" ").last initial_state, final_state, probability = @current_line.strip.split(" ") @problem.add_action(action_name, initial_state, final_state, probability.to_f) end def new_reward state_name, reward = @current_line.strip.split(" ") @problem.add_reward(state_name, reward.to_f) end def new_cost action_name, cost = @current_line.strip.split(" ") @problem.add_cost(action_name, cost.to_f) end def new_initialstate state_name = @current_line.strip @problem.states[state_name].initial_state = true @problem.initial_state = state_name end def new_goalstate state_name = @current_line.strip @problem.states[state_name].goal_state = true @problem.goal_state = state_name end end
diegoamc/MAC5788-AI-Planning
probabilistic_planning/parser.rb
Ruby
gpl-2.0
1,567
/* * Copyright (C) 2004-2012 See the AUTHORS file for details. * * 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. */ #include <znc/znc.h> #include <znc/FileUtils.h> #include <sys/wait.h> #include <signal.h> using std::cout; using std::endl; using std::set; #ifdef HAVE_GETOPT_LONG #include <getopt.h> #else #define no_argument 0 #define required_argument 1 #define optional_argument 2 struct option { const char *a; int opt; int *flag; int val; }; static inline int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *, int *) { return getopt(argc, argv, optstring); } #endif static const struct option g_LongOpts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "debug", no_argument, 0, 'D' }, { "foreground", no_argument, 0, 'f' }, { "no-color", no_argument, 0, 'n' }, { "allow-root", no_argument, 0, 'r' }, { "makeconf", no_argument, 0, 'c' }, { "makepass", no_argument, 0, 's' }, { "makepem", no_argument, 0, 'p' }, { "datadir", required_argument, 0, 'd' }, { 0, 0, 0, 0 } }; static void GenerateHelp(const char *appname) { CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]"); CUtils::PrintMessage("Options are:"); CUtils::PrintMessage("\t-h, --help List available command line options (this page)"); CUtils::PrintMessage("\t-v, --version Output version information and exit"); CUtils::PrintMessage("\t-f, --foreground Don't fork into the background"); CUtils::PrintMessage("\t-D, --debug Output debugging information (Implies -f)"); CUtils::PrintMessage("\t-n, --no-color Don't use escape sequences in the output"); CUtils::PrintMessage("\t-r, --allow-root Don't complain if ZNC is run as root"); CUtils::PrintMessage("\t-c, --makeconf Interactively create a new config"); CUtils::PrintMessage("\t-s, --makepass Generates a password for use in config"); #ifdef HAVE_LIBSSL CUtils::PrintMessage("\t-p, --makepem Generates a pemfile for use with SSL"); #endif /* HAVE_LIBSSL */ CUtils::PrintMessage("\t-d, --datadir Set a different ZNC repository (default is ~/.znc)"); } static void die(int sig) { signal(SIGPIPE, SIG_DFL); CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]"); delete &CZNC::Get(); exit(sig); } static void signalHandler(int sig) { switch (sig) { case SIGHUP: CUtils::PrintMessage("Caught SIGHUP"); CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_REHASH); break; case SIGUSR1: CUtils::PrintMessage("Caught SIGUSR1"); CZNC::Get().SetConfigState(CZNC::ECONFIG_NEED_WRITE); break; default: CUtils::PrintMessage("WTF? Signal handler called for a signal it doesn't know?"); } } static bool isRoot() { // User root? If one of these were root, we could switch the others to root, too return (geteuid() == 0 || getuid() == 0); } static void seedPRNG() { struct timeval tv; unsigned int seed; // Try to find a seed which can't be as easily guessed as only time() if (gettimeofday(&tv, NULL) == 0) { seed = tv.tv_sec; // This is in [0:1e6], which means that roughly 20 bits are // actually used, let's try to shuffle the high bits. seed ^= (tv.tv_usec << 10) | tv.tv_usec; } else seed = time(NULL); seed ^= rand(); seed ^= getpid(); srand(seed); } int main(int argc, char** argv) { CString sConfig; CString sDataDir = ""; seedPRNG(); CDebug::SetStdoutIsTTY(isatty(1)); int iArg, iOptIndex = -1; bool bMakeConf = false; bool bMakePass = false; bool bAllowRoot = false; bool bForeground = false; #ifdef ALWAYS_RUN_IN_FOREGROUND bForeground = true; #endif #ifdef HAVE_LIBSSL bool bMakePem = false; #endif while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts, &iOptIndex)) != -1) { switch (iArg) { case 'h': GenerateHelp(argv[0]); return 0; case 'v': cout << CZNC::GetTag() << endl; cout << CZNC::GetCompileOptionsString() << endl; return 0; case 'n': CDebug::SetStdoutIsTTY(false); break; case 'r': bAllowRoot = true; break; case 'c': bMakeConf = true; break; case 's': bMakePass = true; break; case 'p': #ifdef HAVE_LIBSSL bMakePem = true; break; #else CUtils::PrintError("ZNC is compiled without SSL support."); return 1; #endif /* HAVE_LIBSSL */ case 'd': sDataDir = CString(optarg); break; case 'f': bForeground = true; break; case 'D': bForeground = true; CDebug::SetDebug(true); break; case '?': default: GenerateHelp(argv[0]); return 1; } } if (optind < argc) { CUtils::PrintError("Specifying a config file as an argument isn't supported anymore."); CUtils::PrintError("Use --datadir instead."); return 1; } CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir); #ifdef HAVE_LIBSSL if (bMakePem) { pZNC->WritePemFile(); delete pZNC; return 0; } #endif /* HAVE_LIBSSL */ if (bMakePass) { CString sSalt; CString sHash = CUtils::GetSaltedHashPass(sSalt); CUtils::PrintMessage("Use this in the <User> section of your config:"); CUtils::PrintMessage("Pass = " + CUtils::sDefaultHash + "#" + sHash + "#" + sSalt + "#"); delete pZNC; return 0; } { set<CModInfo> ssGlobalMods; set<CModInfo> ssUserMods; set<CModInfo> ssNetworkMods; CUtils::PrintAction("Checking for list of available modules"); pZNC->GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule); pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule); pZNC->GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule); if (ssGlobalMods.empty() && ssUserMods.empty() && ssNetworkMods.empty()) { CUtils::PrintStatus(false, ""); CUtils::PrintError("No modules found. Perhaps you didn't install ZNC properly?"); CUtils::PrintError("Read http://wiki.znc.in/Installation for instructions."); if (!CUtils::GetBoolInput("Do you really want to run ZNC without any modules?", false)) { delete pZNC; return 1; } } CUtils::PrintStatus(true, ""); } if (isRoot()) { CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid"); CUtils::PrintError("reasons for this and it can, in theory, cause great damage!"); if (!bAllowRoot) { delete pZNC; return 1; } CUtils::PrintError("You have been warned."); CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root."); CUtils::PrintError("ZNC will start in 30 seconds."); sleep(30); } if (bMakeConf) { if (!pZNC->WriteNewConfig(sConfig)) { delete pZNC; return 0; } /* Fall through to normal bootup */ } if (!pZNC->ParseConfig(sConfig)) { CUtils::PrintError("Unrecoverable config error."); delete pZNC; return 1; } if (!pZNC->OnBoot()) { CUtils::PrintError("Exiting due to module boot errors."); delete pZNC; return 1; } if (bForeground) { int iPid = getpid(); CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); CUtils::PrintMessage(CZNC::GetTag()); } else { CUtils::PrintAction("Forking into the background"); int iPid = fork(); if (iPid == -1) { CUtils::PrintStatus(false, strerror(errno)); delete pZNC; return 1; } if (iPid > 0) { // We are the parent. We are done and will go to bed. CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]"); pZNC->WritePidFile(iPid); CUtils::PrintMessage(CZNC::GetTag()); /* Don't destroy pZNC here or it will delete the pid file. */ return 0; } /* fcntl() locks don't necessarily propagate to forked() * children. Reacquire the lock here. Use the blocking * call to avoid race condition with parent exiting. */ if (!pZNC->WaitForChildLock()) { CUtils::PrintError("Child was unable to obtain lock on config file."); delete pZNC; return 1; } // Redirect std in/out/err to /dev/null close(0); open("/dev/null", O_RDONLY); close(1); open("/dev/null", O_WRONLY); close(2); open("/dev/null", O_WRONLY); CDebug::SetStdoutIsTTY(false); // We are the child. There is no way we can be a process group // leader, thus setsid() must succeed. setsid(); // Now we are in our own process group and session (no // controlling terminal). We are independent! } struct sigaction sa; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, (struct sigaction*) NULL); sa.sa_handler = signalHandler; sigaction(SIGHUP, &sa, (struct sigaction*) NULL); sigaction(SIGUSR1, &sa, (struct sigaction*) NULL); // Once this signal is caught, the signal handler is reset // to SIG_DFL. This avoids endless loop with signals. sa.sa_flags = SA_RESETHAND; sa.sa_handler = die; sigaction(SIGINT, &sa, (struct sigaction*) NULL); sigaction(SIGQUIT, &sa, (struct sigaction*) NULL); sigaction(SIGTERM, &sa, (struct sigaction*) NULL); int iRet = 0; try { pZNC->Loop(); } catch (CException e) { switch (e.GetType()) { case CException::EX_Shutdown: iRet = 0; break; case CException::EX_Restart: { // strdup() because GCC is stupid char *args[] = { strdup(argv[0]), strdup("--datadir"), strdup(pZNC->GetZNCPath().c_str()), NULL, NULL, NULL, NULL }; int pos = 3; if (CDebug::Debug()) args[pos++] = strdup("--debug"); else if (bForeground) args[pos++] = strdup("--foreground"); if (!CDebug::StdoutIsTTY()) args[pos++] = strdup("--no-color"); if (bAllowRoot) args[pos++] = strdup("--allow-root"); // The above code adds 3 entries to args tops // which means the array should be big enough delete pZNC; execvp(args[0], args); CUtils::PrintError("Unable to restart ZNC [" + CString(strerror(errno)) + "]"); } /* Fall through */ default: iRet = 1; } } delete pZNC; return iRet; }
kylef/znc
src/main.cpp
C++
gpl-2.0
10,070
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "StdAfx.h" #include "../Util/MemUtil.h" #include "../Util/StrUtil.h" #include "../Util/AppUtil.h" char* _StringToAnsi(const WCHAR* lpwString) { if(lpwString == NULL) { ASSERT(FALSE); return NULL; } const int nChars = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, lpwString, -1, NULL, 0, NULL, NULL); char* p = new char[nChars + 2]; p[0] = 0; p[1] = 0; p[nChars] = 0; p[nChars + 1] = 0; VERIFY(WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, lpwString, -1, p, nChars, NULL, NULL) == nChars); return p; } WCHAR* _StringToUnicode(const char* pszString) { if(pszString == NULL) { ASSERT(FALSE); return NULL; } const int nChars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszString, -1, NULL, 0); WCHAR* p = new WCHAR[nChars + 2]; p[0] = 0; p[1] = 0; p[nChars] = 0; p[nChars + 1] = 0; VERIFY(MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszString, -1, p, nChars) == nChars); return p; } std::basic_string<char> _StringToAnsiStl(const TCHAR* pszString) { std::basic_string<char> strA; #ifdef _UNICODE LPSTR lpA = _StringToAnsi(pszString); if(lpA != NULL) strA = (LPCSTR)lpA; SAFE_DELETE_ARRAY(lpA); #else if(pszString == NULL) { ASSERT(FALSE); return strA; } strA = pszString; #endif return strA; } std::basic_string<WCHAR> _StringToUnicodeStl(const TCHAR* pszString) { std::basic_string<WCHAR> strW; #ifdef _UNICODE if(pszString == NULL) { ASSERT(FALSE); return strW; } strW = pszString; #else LPWSTR lpW = _StringToUnicode(pszString); if(lpW != NULL) strW = (LPCWSTR)lpW; SAFE_DELETE_ARRAY(lpW); #endif return strW; } UTF8_BYTE *_StringToUTF8(const TCHAR *pszSourceString) { DWORD i, j = 0; DWORD dwLength, dwBytesNeeded; BYTE *p = NULL; WCHAR ut; const WCHAR *pUni = NULL; #ifndef _UNICODE WCHAR *pUniBuffer = NULL; DWORD dwUniBufferLength = 0; #endif ASSERT(pszSourceString != NULL); if(pszSourceString == NULL) return NULL; #ifdef _UNICODE dwLength = lstrlen(pszSourceString) + 1; // In order to be compatible with the code below, add 1 for the zero at the end of the buffer pUni = pszSourceString; #else // This returns the new length plus the zero byte - i.e. the whole buffer! dwLength = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszSourceString, -1, NULL, 0); dwUniBufferLength = dwLength + 2; pUniBuffer = new WCHAR[dwUniBufferLength]; pUniBuffer[0] = 0; pUniBuffer[1] = 0; pUni = pUniBuffer; MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszSourceString, -1, pUniBuffer, dwLength); #endif // Both counting and converting routines need update to support surrogates // count UTF-8 needed bytes dwBytesNeeded = 0; for(i = 0; i < dwLength; ++i) { ut = pUni[i]; if(ut == 0) break; if(ut < 0x80) dwBytesNeeded++; else if(ut < 0x0800) dwBytesNeeded += 2; else dwBytesNeeded += 3; } p = new BYTE[dwBytesNeeded + 2]; ASSERT(p != NULL); if(p == NULL) return NULL; j = 0; for(i = 0; i < dwLength; ++i) { ut = pUni[i]; // if(ut == 0) break; if(ut < 0x80) // 7-bit character, store as it is { p[j] = (BYTE)ut; j++; } else if(ut < 0x800) // Are 2 bytes enough? { p[j] = (BYTE)(0xC0 | (ut >> 6)); j++; p[j] = (BYTE)(0x80 | (ut & 0x3F)); j++; } else // Maximum bytes needed for UCS-2 is 3 bytes in UTF-8 { p[j] = (BYTE)(0xE0 | (ut >> 12)); j++; p[j] = (BYTE)(0x80 | ((ut >> 6) & 0x3F)); j++; p[j] = (BYTE)(0x80 | (ut & 0x3F)); j++; } } p[j] = 0; // Terminate string ASSERT(j == (dwBytesNeeded + 1)); #ifndef _UNICODE mem_erase(pUniBuffer, dwUniBufferLength * sizeof(WCHAR)); SAFE_DELETE_ARRAY(pUniBuffer); #endif return p; } DWORD _UTF8NumChars(const UTF8_BYTE *pUTF8String) { DWORD i = 0, dwLength = 0; BYTE bt; ASSERT(pUTF8String != NULL); if(pUTF8String == NULL) return 0; while(1) { bt = pUTF8String[i]; if(bt == 0) break; else if((bt & 0x80) == 0) dwLength++; else if((bt & 0xC0) == 0xC0) dwLength++; else if((bt & 0xE0) == 0xE0) dwLength++; i++; } return dwLength; } // This returns the needed bytes to represent the string, without terminating NULL character DWORD _UTF8BytesNeeded(const TCHAR *pszString) { DWORD i = 0; DWORD dwBytes = 0; USHORT us; // Don't use this function any more. The _StringToUTF8 function uses some pre-conversion // functions that makes a simple length calculation like in this function impossible. // If you really need this function, comment out the following ASSERT, but be careful! ASSERT(FALSE); ASSERT(pszString != NULL); if(pszString == NULL) return 0; while(1) { #ifdef _UNICODE us = (USHORT)pszString[i]; #else us = (USHORT)(((USHORT)((BYTE)pszString[i])) & 0x00FF); #endif if(us == 0) break; if(us < 0x0080) dwBytes++; else if(us < 0x0800) dwBytes += 2; else dwBytes += 3; i++; } return dwBytes; } TCHAR *_UTF8ToString(const UTF8_BYTE *pUTF8String) { DWORD i, j; DWORD dwNumChars, dwMoreBytes, dwPBufLength; BYTE b0, b1, b2; WCHAR *p; WCHAR tch; #ifndef _UNICODE WCHAR *pANSI; #endif ASSERT(pUTF8String != NULL); if(pUTF8String == NULL) return NULL; // Count the needed Unicode chars (right counterpart to _StringToUTF8) i = 0; dwNumChars = 0; while(1) { b0 = (BYTE)pUTF8String[i]; dwMoreBytes = 0; if(b0 == 0) break; else if(b0 < 0xC0) dwMoreBytes++; else if(b0 < 0xE0) dwMoreBytes++; else if(b0 < 0xF0) dwMoreBytes++; dwNumChars++; i += dwMoreBytes; if(dwMoreBytes == 0) return NULL; // Invalid UTF-8 string } // if(dwNumChars == 0) return NULL; dwPBufLength = dwNumChars + 2; p = new WCHAR[dwPBufLength]; ASSERT(p != NULL); if(p == NULL) return NULL; i = 0; j = 0; while(1) { b0 = pUTF8String[i]; i++; if(b0 < 0x80) { p[j] = (WCHAR)b0; j++; } else { b1 = pUTF8String[i]; i++; ASSERT((b1 & 0xC0) == 0x80); if((b1 & 0xC0) != 0x80) break; if((b0 & 0xE0) == 0xC0) { tch = (WCHAR)(b0 & 0x1F); tch <<= 6; tch |= (b1 & 0x3F); p[j] = tch; j++; } else { b2 = pUTF8String[i]; i++; ASSERT((b2 & 0xC0) == 0x80); if((b2 & 0xC0) != 0x80) break; tch = (WCHAR)(b0 & 0xF); tch <<= 6; tch |= (b1 & 0x3F); tch <<= 6; tch |= (b2 & 0x3F); p[j] = tch; j++; } } if(b0 == 0) break; } #ifdef _UNICODE return (TCHAR *)p; #else // Got Unicode, convert to ANSI dwNumChars = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, p, -1, NULL, 0, NULL, NULL); pANSI = new WCHAR[dwNumChars + 2]; pANSI[0] = 0; int nErr = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, p, -1, (LPSTR)pANSI, dwNumChars, NULL, NULL); if(dwNumChars != 122) { ASSERT(nErr != 122); } // ERROR_INSUFFICIENT_BUFFER is defined as 122... else { ASSERT(GetLastError() == 0); nErr = nErr; } if(p != NULL) mem_erase(p, dwPBufLength); SAFE_DELETE_ARRAY(p); return (TCHAR *)pANSI; #endif } BOOL _IsUTF8String(const UTF8_BYTE *pUTF8String) { DWORD i = 0; BYTE b0, b1, b2; ASSERT(pUTF8String != NULL); if(pUTF8String == NULL) return FALSE; if(pUTF8String[0] == 0xEF) if(pUTF8String[1] == 0xBB) if(pUTF8String[2] == 0xBF) i += 3; while(1) { b0 = pUTF8String[i]; i++; if(b0 >= 0x80) { b1 = pUTF8String[i]; i++; if((b1 & 0xC0) != 0x80) return FALSE; if((b0 & 0xE0) != 0xC0) { b2 = pUTF8String[i]; i++; if((b2 & 0xC0) != 0x80) return FALSE; } } if(b0 == 0) break; } return TRUE; } static HMODULE m_hShlWApi = NULL; static LPCWSTRCMPEX m_lpCmpNatural = NULL; #ifndef _WIN32_WCE void NSCAPI_Initialize() { NSCAPI_Exit(); // Free any previously loaded library // ShlWApi.dll is available on all Windows operating systems >= 98 m_hShlWApi = AU_LoadLibrary(_T("ShlWApi.dll")); if(m_hShlWApi == NULL) return; m_lpCmpNatural = (LPCWSTRCMPEX)GetProcAddress(m_hShlWApi, "StrCmpLogicalW"); if(m_lpCmpNatural == NULL) NSCAPI_Exit(); } void NSCAPI_Exit() { m_lpCmpNatural = NULL; if(m_hShlWApi != NULL) { FreeLibrary(m_hShlWApi); m_hShlWApi = NULL; } } bool NSCAPI_Supported() { return (m_lpCmpNatural != NULL); } #endif int StrCmpNaturalEx(LPCTSTR x, LPCTSTR y) { if(m_lpCmpNatural == NULL) { ASSERT(FALSE); return _tcsicmp(x, y); } CT2CW xw(x); CT2CW yw(y); return m_lpCmpNatural(xw, yw); } LPCTSTRCMPEX StrCmpGetNaturalMethodOrFallback() { return ((m_lpCmpNatural != NULL) ? StrCmpNaturalEx : _tcsicmp); }
joshuadugie/KeePass-1.x
KeePassLibCpp/SysSpec_Windows/StrUtilEx.cpp
C++
gpl-2.0
9,450
<?php /** * @package AcyMailing for Joomla! * @version 4.7.2 * @author acyba.com * @copyright (C) 2009-2014 ACYBA S.A.R.L. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php $name = 'Newspaper'; $thumb = 'media/com_acymailing/templates/newsletter-5/newsletter-5.png'; $body = JFile::read(dirname(__FILE__).DS.'index.html'); $styles['tag_h1'] = 'color:#454545 !important; font-size:24px; font-weight:bold; margin:0px;'; $styles['tag_h2'] = 'color:#b20000 !important; font-size:18px; font-weight:bold; margin:0px; margin-bottom:10px; padding-bottom:4px; border-bottom: 1px solid #d6d6d6;'; $styles['tag_h3'] = 'color:#b20101 !important; font-weight:bold; font-size:18px; margin:10px 0px;'; $styles['tag_h4'] = 'color:#e52323 !important; font-weight:bold; margin:0px; padding:0px'; $styles['tag_a'] = 'cursor:pointer; color:#9d0000; text-decoration:none; border:none;'; $styles['acymailing_readmore'] = 'cursor:pointer; color:#ffffff; background-color:#9d0000; border-top:1px solid #9d0000; border-bottom:1px solid #9d0000; padding:3px 5px; font-size:13px;'; $styles['acymailing_online'] = 'color:#dddddd; text-decoration:none; font-size:13px; margin:10px; text-align:center; font-family:Times New Roman, Times, serif; padding-bottom:10px;'; $styles['color_bg'] = '#454545'; $styles['acymailing_content'] = ''; $styles['acymailing_unsub'] = 'color:#dddddd; text-decoration:none; font-size:13px; text-align:center; font-family:Times New Roman, Times, serif; padding-top:10px'; $stylesheet = '.acyfooter a{ color:#454545; } .dark{ color:#454545; font-weight:bold; } div,table,p{font-family:"Times New Roman", Times, serif;font-size:13px;color:#575757;} @media (min-width:10px){ table[class=w600], td[class=w600] { width:320px !important; } table[class=w540], td[class=w540] { width:260px !important; } td[class=w30] { width:30px !important; } .w600 img {max-width:320px; height:auto !important; } .w540 img {max-width:260px; height:auto !important; } } @media (min-width: 480px){ table[class=w600], td[class=w600] { width:480px !important; } table[class=w540], td[class=w540] { width:420px !important; } td[class=w30] { width:30px !important; } .w600 img {max-width:480px; height:auto !important; } .w540 img {max-width:420px; height:auto !important; } } @media (min-width:600px){ table[class=w600], td[class=w600] { width:600px !important; } table[class=w540], td[class=w540] { width:540px !important; } td[class=w30] { width:30px !important; } .w600 img {max-width:600px; height:auto !important; } .w540 img {max-width:540px; height:auto !important; } } ';
unrealprojects/journal
media/com_acymailing/templates/newsletter-5/install.php
PHP
gpl-2.0
2,679
#include <unistd.h> #include "finder.h" int main (int argc, char** argv) { if (finder_init() == -1) return -1; usleep(1000*1000*3); finder_set_command(GRAB_DEBUG_SMALL_FOCUS); usleep(1000*1000*3); finder_close(); }
koudis/robot
kastelan/src/finder/ostreni.cpp
C++
gpl-2.0
232
/* * handle_request.c - Part of AFD, an automatic file distribution program. * Copyright (c) 1999 - 2013 Holger Kiehl <Holger.Kiehl@dwd.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. */ #include "afddefs.h" DESCR__S_M3 /* ** NAME ** handle_request - handles a TCP request ** ** SYNOPSIS ** void handle_request(int cmd_sd, ** int pos, ** int trusted_ip_pos, ** char *remote_ip_str) ** ** DESCRIPTION ** Handles all request from remote user in a loop. If user is inactive ** for AFDD_CMD_TIMEOUT seconds, the connection will be closed. ** ** RETURN VALUES ** ** AUTHOR ** H.Kiehl ** ** HISTORY ** 17.01.1999 H.Kiehl Created ** 06.04.2005 H.Kiehl Open FSA here and not in afdd.c. ** 23.11.2008 H.Kiehl Added danger_no_of_jobs. */ DESCR__E_M3 #include <stdio.h> /* fprintf() */ #include <string.h> /* memset() */ #include <stdlib.h> /* atoi(), strtoul() */ #include <time.h> /* time() */ #include <ctype.h> /* toupper() */ #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* close() */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #include <netdb.h> #include <errno.h> #include "afdddefs.h" #include "version.h" #include "logdefs.h" /* #define DEBUG_LOG_CMD */ /* Global variables. */ int cmd_sd, fra_fd = -1, fra_id, fsa_fd = -1, fsa_id, host_config_counter, in_log_child = NO, no_of_dirs, no_of_hosts; #ifdef HAVE_MMAP off_t fra_size, fsa_size; #endif char *line_buffer = NULL, log_dir[MAX_PATH_LENGTH], *log_buffer = NULL, *p_log_dir; unsigned char **old_error_history; FILE *p_data = NULL; struct filetransfer_status *fsa; struct fileretrieve_status *fra; /* External global variables. */ extern int *ip_log_defs, log_defs; extern long danger_no_of_jobs; extern char afd_name[], hostname[], *p_work_dir, *p_work_dir_end; extern struct logdata ld[]; extern struct afd_status *p_afd_status; /* Local global variables. */ static int report_changes = NO; static char *p_remote_ip; /* Local function prototypes. */ static void report_shutdown(void); /*########################### handle_request() ##########################*/ void handle_request(int sock_sd, int pos, int trusted_ip_pos, char *remote_ip_str) { register int i, j; int nbytes, status; long log_interval; time_t last, last_time_read, now, report_changes_interval = DEFAULT_CHECK_INTERVAL; char cmd[1024]; fd_set rset; struct timeval timeout; cmd_sd = sock_sd; if ((p_data = fdopen(cmd_sd, "r+")) == NULL) { system_log(ERROR_SIGN, __FILE__, __LINE__, _("fdopen() control error : %s"), strerror(errno)); exit(INCORRECT); } if (fsa_attach_passive(NO, AFDD) < 0) { system_log(FATAL_SIGN, __FILE__, __LINE__, _("Failed to attach to FSA.")); exit(INCORRECT); } host_config_counter = (int)*(unsigned char *)((char *)fsa - AFD_WORD_OFFSET + SIZEOF_INT); RT_ARRAY(old_error_history, no_of_hosts, ERROR_HISTORY_LENGTH, unsigned char); for (i = 0; i < no_of_hosts; i++) { (void)memcpy(old_error_history[i], fsa[i].error_history, ERROR_HISTORY_LENGTH); } if (fra_attach_passive() < 0) { system_log(FATAL_SIGN, __FILE__, __LINE__, _("Failed to attach to FRA.")); exit(INCORRECT); } status = 0; while (p_afd_status->amg_jobs & WRITTING_JID_STRUCT) { (void)my_usleep(100000L); status++; if ((status > 1) && ((status % 100) == 0)) { system_log(ERROR_SIGN, __FILE__, __LINE__, _("Timeout arrived for waiting for AMG to finish writting to JID structure.")); } } if (atexit(report_shutdown) != 0) { system_log(ERROR_SIGN, __FILE__, __LINE__, _("Could not register exit handler : %s"), strerror(errno)); } /* Give some information to the user where he is and what service */ /* is offered here. */ (void)fprintf(p_data, "220 %s AFD server %s (Version %s) ready.\r\n", hostname, afd_name, PACKAGE_VERSION); (void)fflush(p_data); p_remote_ip = remote_ip_str; init_get_display_data(); /* * Handle all request until the remote user has entered QUIT_CMD or * the connection was idle for AFDD_CMD_TIMEOUT seconds. */ now = last = last_time_read = time(NULL); FD_ZERO(&rset); for (;;) { now = time(NULL); nbytes = 0; if (report_changes == YES) { if ((now - last) >= report_changes_interval) { check_changes(p_data); timeout.tv_sec = report_changes_interval; last = now = time(NULL); } else { timeout.tv_sec = report_changes_interval - (now - last); last = now; } } else { if (in_log_child == YES) { timeout.tv_sec = log_interval; } else { timeout.tv_sec = AFDD_CMD_TIMEOUT; } } if ((in_log_child == NO) && ((now - last_time_read) > AFDD_CMD_TIMEOUT)) { (void)fprintf(p_data, "421 Timeout (%d seconds): closing connection.\r\n", AFDD_CMD_TIMEOUT); break; } FD_SET(cmd_sd, &rset); timeout.tv_usec = 0; /* Wait for message x seconds and then continue. */ status = select(cmd_sd + 1, &rset, NULL, NULL, &timeout); if (FD_ISSET(cmd_sd, &rset)) { if ((nbytes = read(cmd_sd, cmd, 1024)) <= 0) { if (nbytes == 0) { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Remote hangup by %s"), hostname); } else { #ifdef ECONNRESET if (errno == ECONNRESET) { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("read() error : %s"), strerror(errno)); } else { system_log(ERROR_SIGN, __FILE__, __LINE__, _("read() error : %s"), strerror(errno)); } #else system_log(ERROR_SIGN, __FILE__, __LINE__, _("read() error : %s"), strerror(errno)); #endif } break; } last_time_read = time(NULL); } else if (status == 0) { if (report_changes == YES) { /* * Check if there have been any changes. If no value has changed * just be silent and do nothing. */ check_changes(p_data); } else if (in_log_child == YES) { if (log_defs) { log_interval = check_logs(now + log_interval); } } else { (void)fprintf(p_data, "421 Timeout (%d seconds): closing connection.\r\n", AFDD_CMD_TIMEOUT); break; } } if (nbytes > 0) { i = 0; while ((cmd[i] != ' ') && (cmd[i] != '\r')) { cmd[i] = toupper((int)cmd[i]); i++; } cmd[nbytes] = '\0'; if (strcmp(cmd, QUIT_CMD) == 0) { (void)fprintf(p_data, "221 Goodbye.\r\n"); break; } else if (strcmp(cmd, HELP_CMD) == 0) { (void)fprintf(p_data, "214- The following commands are recognized (* =>'s unimplemented).\r\n\ *AFDSTAT *DISC HELP HSTAT ILOG *INFO *LDB LOG\r\n\ LRF NOP OLOG *PROC QUIT SLOG STAT TDLOG\r\n\ TLOG *TRACEF *TRACEI *TRACEO SSTAT\r\n\ 214 Direct comments to %s\r\n", AFD_MAINTAINER); } else if ((cmd[0] == 'H') && (cmd[1] == 'E') && (cmd[2] == 'L') && (cmd[3] == 'P') && (cmd[4] == ' ') && (cmd[5] != '\r')) { j = 5; while ((cmd[j] != ' ') && (cmd[j] != '\r')) { cmd[j] = toupper((int)cmd[j]); j++; } if (strcmp(&cmd[5], QUIT_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", QUIT_SYNTAX); } else if (strcmp(&cmd[5], HELP_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", HELP_SYNTAX); } else if (strcmp(&cmd[5], TRACEI_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", TRACEI_SYNTAX); } else if (strcmp(&cmd[5], TRACEO_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", TRACEO_SYNTAX); } else if (strcmp(&cmd[5], TRACEF_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", TRACEF_SYNTAX); } else if (strcmp(&cmd[5], ILOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", ILOG_SYNTAX); } else if (strcmp(&cmd[5], OLOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", OLOG_SYNTAX); } else if (strcmp(&cmd[5], SLOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", SLOG_SYNTAX); } else if (strcmp(&cmd[5], TLOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", TLOG_SYNTAX); } else if (strcmp(&cmd[5], TDLOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", TDLOG_SYNTAX); } else if (strcmp(&cmd[5], PROC_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", PROC_SYNTAX); } else if (strcmp(&cmd[5], DISC_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", DISC_SYNTAX); } else if (strcmp(&cmd[5], STAT_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", STAT_SYNTAX); } else if (strcmp(&cmd[5], HSTAT_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", HSTAT_SYNTAX); } else if (strcmp(&cmd[5], START_STAT_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", START_STAT_SYNTAX); } else if (strcmp(&cmd[5], LDB_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", LDB_SYNTAX); } else if (strcmp(&cmd[5], LRF_CMD) == 0) { (void)fprintf(p_data, "%s\r\n", LRF_SYNTAX); } else if (strcmp(&cmd[5], INFO_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", INFO_SYNTAX); } else if (strcmp(&cmd[5], AFDSTAT_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", AFDSTAT_SYNTAX); } else if (strcmp(&cmd[5], NOP_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", NOP_SYNTAX); } else if (strcmp(&cmd[5], LOG_CMDL) == 0) { (void)fprintf(p_data, "%s\r\n", LOG_SYNTAX); (void)fprintf(p_data, "%s\r\n", LOG_TYPES_SYNTAX); } else { *(cmd + nbytes - 2) = '\0'; (void)fprintf(p_data, "502 Unknown command %s\r\n", &cmd[5]); } } else if ((strncmp(cmd, ILOG_CMD, ILOG_CMD_LENGTH) == 0) || (strncmp(cmd, OLOG_CMD, OLOG_CMD_LENGTH) == 0) || (strncmp(cmd, SLOG_CMD, SLOG_CMD_LENGTH) == 0) || (strncmp(cmd, TLOG_CMD, TLOG_CMD_LENGTH) == 0) || (strncmp(cmd, TDLOG_CMD, TDLOG_CMD_LENGTH) == 0)) { int log_number; char *p_search_file, search_file[MAX_PATH_LENGTH]; /* * For now lets just disable the following code. */ (void)fprintf(p_data, "503 Service disabled.\r\n"); break; /* * First lets determine what file we want and then * create the full file name without the number. */ #ifdef HAVE_SNPRINTF p_search_file = search_file + snprintf(search_file, MAX_PATH_LENGTH, #else p_search_file = search_file + sprintf(search_file, #endif "%s%s/", p_work_dir, LOG_DIR); switch (cmd[0]) { #ifdef _INPUT_LOG case 'I' : /* Input log. */ (void)my_strncpy(p_search_file, INPUT_BUFFER_FILE, MAX_PATH_LENGTH - (p_search_file - search_file)); log_number = AFDD_ILOG_NO; break; #endif #ifdef _OUTPUT_LOG case 'O' : /* Output log. */ (void)my_strncpy(p_search_file, OUTPUT_BUFFER_FILE, MAX_PATH_LENGTH - (p_search_file - search_file)); log_number = AFDD_OLOG_NO; break; #endif case 'S' : /* System log. */ (void)my_strncpy(p_search_file, SYSTEM_LOG_NAME, MAX_PATH_LENGTH - (p_search_file - search_file)); log_number = AFDD_SLOG_NO; break; case 'T' : /* Transfer or transfer debug log */ if (cmd[1] == 'D') { (void)my_strncpy(p_search_file, TRANS_DB_LOG_NAME, MAX_PATH_LENGTH - (p_search_file - search_file)); log_number = AFDD_TDLOG_NO; } else { (void)my_strncpy(p_search_file, TRANSFER_LOG_NAME, MAX_PATH_LENGTH - (p_search_file - search_file)); log_number = AFDD_TLOG_NO; } break; default : /* Impossible!!! */ system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Unknown error!")); (void)fprintf(p_data, "500 Unknown error. (%s %d)\r\n", __FILE__, __LINE__); (void)fflush(p_data); (void)fclose(p_data); p_data = NULL; exit(INCORRECT); } if (cmd[i] == ' ') { if ((cmd[i + 1] == '-') || (cmd[i + 1] == '+') || (cmd[i + 1] == '#') || (cmd[i + 1] == '%')) { int k = 0, lines = EVERYTHING, show_time = EVERYTHING, start_line = NOT_SET, file_no = DEFAULT_FILE_NO, faulty = NO; char numeric_str[MAX_INT_LENGTH]; do { i += k; k = 0; while ((cmd[i + 1 + k] != ' ') && (cmd[i + 1 + k] != '\r') && (k < MAX_INT_LENGTH)) { if (isdigit((int)cmd[i + 1 + k])) { numeric_str[k] = cmd[i + 1 + k]; } else { faulty = YES; (void)fprintf(p_data, "500 Expecting numeric value after \'%c\'\r\n", cmd[i + 1]); break; } k++; } if (k > 0) { numeric_str[k] = '\0'; switch (cmd[i + 1]) { case '#' : /* File number. */ file_no = atoi(numeric_str); break; case '-' : /* Number of lines. */ lines = atoi(numeric_str); break; case '+' : /* Duration of displaying data. */ show_time = atoi(numeric_str); break; case '%' : /* Start at line number. */ start_line = atoi(numeric_str); break; default : /* Impossible!!! */ faulty = YES; system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Unknown error!")); (void)fprintf(p_data, "500 Unknown error. (%s %d)\r\n", __FILE__, __LINE__); break; } } else { faulty = YES; (void)fprintf(p_data, "500 No numeric value supplied after \'%c\'\r\n", cmd[i + 1]); } } while ((cmd[i + 1 + k] != '\r') && (faulty == NO)); if (faulty == NO) { get_display_data(search_file, log_number, NULL, start_line, lines, show_time, file_no); } } else if (isascii(cmd[i + 1])) { int k = 0; char *ptr, search_string[256]; /* User has supplied a search string. */ ptr = &cmd[i + 1]; while ((*ptr != ' ') && (*ptr != '\r') && (*ptr != '\n')) { search_string[k] = *ptr; ptr++; k++; } if (*ptr == ' ') { search_string[k] = '\0'; if ((cmd[i + k + 1] == '-') || (cmd[i + k + 1] == '+') || (cmd[i + k + 1] == '#') || (cmd[i + k + 1] == '%')) { int m = 0, lines = EVERYTHING, show_time = EVERYTHING, start_line = NOT_SET, file_no = DEFAULT_FILE_NO, faulty = NO; char numeric_str[MAX_INT_LENGTH]; do { i += m; m = 0; if (cmd[i + k + 1 + m] == '*') { if (cmd[i + k + 1] == '#') { file_no = EVERYTHING; } } else { while ((cmd[i + k + 1 + m] != ' ') && (cmd[i + k + 1 + m] != '\r') && (m < MAX_INT_LENGTH)) { if (isdigit((int)cmd[i + k + 1 + m])) { numeric_str[m] = cmd[i + k + 1 + m]; } else { faulty = YES; (void)fprintf(p_data, "500 Expecting numeric value after \'%c\'\r\n", cmd[i + k + 1]); break; } m++; } if (m > 0) { numeric_str[m] = '\0'; switch (cmd[i + k + 1]) { case '#' : /* File number. */ file_no = atoi(numeric_str); break; case '-' : /* Number of lines. */ lines = atoi(numeric_str); break; case '+' : /* Duration of displaying data. */ show_time = atoi(numeric_str); break; case '%' : /* Start at line number. */ start_line = atoi(numeric_str); break; default : /* Impossible!!! */ faulty = YES; system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Unknown error!")); (void)fprintf(p_data, "500 Unknown error. (%s %d)\r\n", __FILE__, __LINE__); break; } } else { faulty = YES; (void)fprintf(p_data, "500 No numeric value supplied after \'%c\'\r\n", cmd[i + k + 1]); } } } while ((cmd[i + k + 1 + m] != '\r') && (faulty == NO)); if (faulty == NO) { get_display_data(search_file, log_number, search_string, start_line, lines, show_time, file_no); } } else { *(cmd + nbytes - 2) = '\0'; (void)fprintf(p_data, "500 \'%s\': Syntax wrong (see HELP).\r\n", cmd); } } } else { *(cmd + nbytes - 2) = '\0'; (void)fprintf(p_data, "500 \'%s\': command not understood.\r\n", cmd); } } /* if (cmd[i] == ' ') */ else if (cmd[i] == '\r') { get_display_data(search_file, log_number, NULL, NOT_SET, EVERYTHING, EVERYTHING, DEFAULT_FILE_NO); } else { *(cmd + nbytes - 2) = '\0'; (void)fprintf(p_data, "500 \'%s\': command not understood.\r\n", cmd); } } else if (strncmp(cmd, STAT_CMD, STAT_CMD_LENGTH) == 0) { show_summary_stat(p_data); } else if (strncmp(cmd, HSTAT_CMD, HSTAT_CMD_LENGTH) == 0) { show_host_stat(p_data); } else if (strncmp(cmd, START_STAT_CMD, START_STAT_CMD_LENGTH) == 0) { show_summary_stat(p_data); show_host_list(p_data); show_dir_list(p_data); show_job_list(p_data); (void)fprintf(p_data, "LC %d\r\nWD %s\r\nAV %s\r\nDJ %ld\r\n", ip_log_defs[trusted_ip_pos], p_work_dir, PACKAGE_VERSION, danger_no_of_jobs); report_changes = YES; } else if (strncmp(cmd, NOP_CMD, NOP_CMD_LENGTH) == 0) { (void)fprintf(p_data, "200 OK\r\n"); } else if (strncmp(cmd, LRF_CMD, LRF_CMD_LENGTH) == 0) { #ifdef HAVE_SNPRINTF (void)snprintf(p_work_dir_end, MAX_PATH_LENGTH - (p_work_dir_end - p_work_dir), #else (void)sprintf(p_work_dir_end, #endif "%s%s", ETC_DIR, RENAME_RULE_FILE); display_file(p_data); *p_work_dir_end = '\0'; } else if (strncmp(cmd, LOG_CMD, LOG_CMD_LENGTH) == 0) { int complete_failure = NO, tmp_log_defs; char *log_type_ptr, *ptr; #ifdef DEBUG_LOG_CMD int cmd_buffer_length; char cmd_buffer[3 + 1 + 2 + 1 + (NO_OF_LOGS * (MAX_INT_LENGTH + 1 + MAX_LONG_LONG_LENGTH + 1 + MAX_LONG_LONG_LENGTH + 1))]; #endif tmp_log_defs = log_defs; log_defs = 0; #ifdef DEBUG_LOG_CMD (void)strcpy(cmd_buffer, LOG_CMD); cmd_buffer_length = LOG_CMD_LENGTH; #endif ptr = cmd + LOG_CMD_LENGTH; do { if ((*(ptr + 1) == 'L') && (*(ptr + 3) == ' ')) { char *p_start; log_type_ptr = ptr + 2; ptr += 4; p_start = ptr; while (isdigit((int)(*ptr))) { ptr++; } if (*ptr == ' ') { *ptr = '\0'; ptr++; ld[DUM_LOG_POS].options = (unsigned int)strtoul(p_start, NULL, 10); p_start = ptr; while (isdigit((int)(*ptr))) { ptr++; } if (*ptr == ' ') { *ptr = '\0'; ptr++; ld[DUM_LOG_POS].current_log_inode = (ino_t)str2inot(p_start, NULL, 10); p_start = ptr; while (isdigit((int)(*ptr))) { ptr++; } if ((*ptr == ' ') || ((*ptr == '\r') && (*(ptr + 1) == '\n'))) { int end_reached; if ((*ptr == ' ') && (*(ptr + 1) == 'L')) { end_reached = NO; } else { end_reached = YES; } *ptr = '\0'; ld[DUM_LOG_POS].offset = (off_t)str2offt(p_start, NULL, 10); ld[DUM_LOG_POS].flag = 0; if (end_reached == NO) { *ptr = ' '; } } } } #ifdef DEBUG_LOG_CMD # ifdef HAVE_SNPRINTF cmd_buffer_length += snprintf(&cmd_buffer[cmd_buffer_length], (3 + 1 + 2 + 1 + (NO_OF_LOGS * (MAX_INT_LENGTH + 1 + MAX_LONG_LONG_LENGTH + 1 + MAX_LONG_LONG_LENGTH + 1))) - cmd_buffer_length, # else cmd_buffer_length += sprintf(&cmd_buffer[cmd_buffer_length], # endif # if SIZEOF_INO_T == 4 # if SIZEOF_OFF_T == 4 " L%c %u %ld %ld", # else " L%c %u %ld %lld", # endif # else # if SIZEOF_OFF_T == 4 " L%c %u %lld %ld", # else " L%c %u %lld %lld", # endif # endif *log_type_ptr, ld[DUM_LOG_POS].options, (pri_ino_t)ld[DUM_LOG_POS].current_log_inode, (pri_off_t)ld[DUM_LOG_POS].offset); #endif switch (*log_type_ptr) { case 'S' : /* System Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_SYSTEM_LOG) { ld[SYS_LOG_POS].options = ld[DUM_LOG_POS].options; ld[SYS_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[SYS_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[SYS_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[SYS_LOG_POS].log_name, SYSTEM_LOG_NAME); ld[SYS_LOG_POS].log_name_length = SYSTEM_LOG_NAME_LENGTH; ld[SYS_LOG_POS].log_data_cmd[0] = 'L'; ld[SYS_LOG_POS].log_data_cmd[1] = 'S'; ld[SYS_LOG_POS].log_data_cmd[2] = '\0'; ld[SYS_LOG_POS].log_inode_cmd[0] = 'O'; ld[SYS_LOG_POS].log_inode_cmd[1] = 'S'; ld[SYS_LOG_POS].log_inode_cmd[2] = '\0'; ld[SYS_LOG_POS].log_flag = AFDD_SYSTEM_LOG; ld[SYS_LOG_POS].fp = NULL; ld[SYS_LOG_POS].current_log_no = 0; ld[SYS_LOG_POS].packet_no = 0; if ((log_defs & AFDD_SYSTEM_LOG) == 0) { log_defs |= AFDD_SYSTEM_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, SYSTEM_LOG_NAME); } break; case 'E' : /* Event Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_EVENT_LOG) { ld[EVE_LOG_POS].options = ld[DUM_LOG_POS].options; ld[EVE_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[EVE_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[EVE_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[EVE_LOG_POS].log_name, EVENT_LOG_NAME); ld[EVE_LOG_POS].log_name_length = EVENT_LOG_NAME_LENGTH; ld[EVE_LOG_POS].log_data_cmd[0] = 'L'; ld[EVE_LOG_POS].log_data_cmd[1] = 'E'; ld[EVE_LOG_POS].log_data_cmd[2] = '\0'; ld[EVE_LOG_POS].log_inode_cmd[0] = 'O'; ld[EVE_LOG_POS].log_inode_cmd[1] = 'E'; ld[EVE_LOG_POS].log_inode_cmd[2] = '\0'; ld[EVE_LOG_POS].log_flag = AFDD_EVENT_LOG; ld[EVE_LOG_POS].fp = NULL; ld[EVE_LOG_POS].current_log_no = 0; ld[EVE_LOG_POS].packet_no = 0; if ((log_defs & AFDD_EVENT_LOG) == 0) { log_defs |= AFDD_EVENT_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, EVENT_LOG_NAME); } break; case 'R' : /* Retrieve Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_RECEIVE_LOG) { ld[REC_LOG_POS].options = ld[DUM_LOG_POS].options; ld[REC_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[REC_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[REC_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[REC_LOG_POS].log_name, RECEIVE_LOG_NAME); ld[REC_LOG_POS].log_name_length = RECEIVE_LOG_NAME_LENGTH; ld[REC_LOG_POS].log_data_cmd[0] = 'L'; ld[REC_LOG_POS].log_data_cmd[1] = 'R'; ld[REC_LOG_POS].log_data_cmd[2] = '\0'; ld[REC_LOG_POS].log_inode_cmd[0] = 'O'; ld[REC_LOG_POS].log_inode_cmd[1] = 'R'; ld[REC_LOG_POS].log_inode_cmd[2] = '\0'; ld[REC_LOG_POS].log_flag = AFDD_RECEIVE_LOG; ld[REC_LOG_POS].fp = NULL; ld[REC_LOG_POS].current_log_no = 0; ld[REC_LOG_POS].packet_no = 0; if ((log_defs & AFDD_RECEIVE_LOG) == 0) { log_defs |= AFDD_RECEIVE_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, RECEIVE_LOG_NAME); } break; case 'T' : /* Transfer Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_TRANSFER_LOG) { ld[TRA_LOG_POS].options = ld[DUM_LOG_POS].options; ld[TRA_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[TRA_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[TRA_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[TRA_LOG_POS].log_name, TRANSFER_LOG_NAME); ld[TRA_LOG_POS].log_name_length = TRANSFER_LOG_NAME_LENGTH; ld[TRA_LOG_POS].log_data_cmd[0] = 'L'; ld[TRA_LOG_POS].log_data_cmd[1] = 'T'; ld[TRA_LOG_POS].log_data_cmd[2] = '\0'; ld[TRA_LOG_POS].log_inode_cmd[0] = 'O'; ld[TRA_LOG_POS].log_inode_cmd[1] = 'T'; ld[TRA_LOG_POS].log_inode_cmd[2] = '\0'; ld[TRA_LOG_POS].log_flag = AFDD_TRANSFER_LOG; ld[TRA_LOG_POS].fp = NULL; ld[TRA_LOG_POS].current_log_no = 0; ld[TRA_LOG_POS].packet_no = 0; if ((log_defs & AFDD_TRANSFER_LOG) == 0) { log_defs |= AFDD_TRANSFER_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, TRANSFER_LOG_NAME); } break; case 'B' : /* Transfer Debug Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_TRANSFER_DEBUG_LOG) { ld[TDB_LOG_POS].options = ld[DUM_LOG_POS].options; ld[TDB_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[TDB_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[TDB_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[TDB_LOG_POS].log_name, TRANS_DB_LOG_NAME); ld[TDB_LOG_POS].log_name_length = TRANS_DB_LOG_NAME_LENGTH; ld[TDB_LOG_POS].log_data_cmd[0] = 'L'; ld[TDB_LOG_POS].log_data_cmd[1] = 'B'; ld[TDB_LOG_POS].log_data_cmd[2] = '\0'; ld[TDB_LOG_POS].log_inode_cmd[0] = 'O'; ld[TDB_LOG_POS].log_inode_cmd[1] = 'B'; ld[TDB_LOG_POS].log_inode_cmd[2] = '\0'; ld[TDB_LOG_POS].log_flag = AFDD_TRANSFER_DEBUG_LOG; ld[TDB_LOG_POS].fp = NULL; ld[TDB_LOG_POS].current_log_no = 0; ld[TDB_LOG_POS].packet_no = 0; if ((log_defs & AFDD_TRANSFER_DEBUG_LOG) == 0) { log_defs |= AFDD_TRANSFER_DEBUG_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, TRANS_DB_LOG_NAME); } break; #ifdef _INPUT_LOG case 'I' : /* INPUT Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_INPUT_LOG) { ld[INP_LOG_POS].options = ld[DUM_LOG_POS].options; ld[INP_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[INP_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[INP_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[INP_LOG_POS].log_name, INPUT_BUFFER_FILE); ld[INP_LOG_POS].log_name_length = INPUT_BUFFER_FILE_LENGTH; ld[INP_LOG_POS].log_data_cmd[0] = 'L'; ld[INP_LOG_POS].log_data_cmd[1] = 'I'; ld[INP_LOG_POS].log_data_cmd[2] = '\0'; ld[INP_LOG_POS].log_inode_cmd[0] = 'O'; ld[INP_LOG_POS].log_inode_cmd[1] = 'I'; ld[INP_LOG_POS].log_inode_cmd[2] = '\0'; ld[INP_LOG_POS].log_flag = AFDD_INPUT_LOG; ld[INP_LOG_POS].fp = NULL; ld[INP_LOG_POS].current_log_no = 0; ld[INP_LOG_POS].packet_no = 0; if ((log_defs & AFDD_INPUT_LOG) == 0) { log_defs |= AFDD_INPUT_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, INPUT_BUFFER_FILE); } break; #endif #ifdef _DISTRIBUTION_LOG case 'U' : /* DISTRIBUTION Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_DISTRIBUTION_LOG) { ld[DIS_LOG_POS].options = ld[DUM_LOG_POS].options; ld[DIS_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[DIS_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[DIS_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[DIS_LOG_POS].log_name, DISTRIBUTION_BUFFER_FILE); ld[DIS_LOG_POS].log_name_length = DISTRIBUTION_BUFFER_FILE_LENGTH; ld[DIS_LOG_POS].log_data_cmd[0] = 'L'; ld[DIS_LOG_POS].log_data_cmd[1] = 'U'; ld[DIS_LOG_POS].log_data_cmd[2] = '\0'; ld[DIS_LOG_POS].log_inode_cmd[0] = 'O'; ld[DIS_LOG_POS].log_inode_cmd[1] = 'U'; ld[DIS_LOG_POS].log_inode_cmd[2] = '\0'; ld[DIS_LOG_POS].log_flag = AFDD_DISTRIBUTION_LOG; ld[DIS_LOG_POS].fp = NULL; ld[DIS_LOG_POS].current_log_no = 0; ld[DIS_LOG_POS].packet_no = 0; if ((log_defs & AFDD_DISTRIBUTION_LOG) == 0) { log_defs |= AFDD_DISTRIBUTION_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, DISTRIBUTION_BUFFER_FILE); } break; #endif #ifdef _PRODUCTION_LOG case 'P' : /* Production Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_PRODUCTION_LOG) { ld[PRO_LOG_POS].options = ld[DUM_LOG_POS].options; ld[PRO_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[PRO_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[PRO_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[PRO_LOG_POS].log_name, PRODUCTION_BUFFER_FILE); ld[PRO_LOG_POS].log_name_length = PRODUCTION_BUFFER_FILE_LENGTH; ld[PRO_LOG_POS].log_data_cmd[0] = 'L'; ld[PRO_LOG_POS].log_data_cmd[1] = 'P'; ld[PRO_LOG_POS].log_data_cmd[2] = '\0'; ld[PRO_LOG_POS].log_inode_cmd[0] = 'O'; ld[PRO_LOG_POS].log_inode_cmd[1] = 'P'; ld[PRO_LOG_POS].log_inode_cmd[2] = '\0'; ld[PRO_LOG_POS].log_flag = AFDD_PRODUCTION_LOG; ld[PRO_LOG_POS].fp = NULL; ld[PRO_LOG_POS].current_log_no = 0; ld[PRO_LOG_POS].packet_no = 0; if ((log_defs & AFDD_PRODUCTION_LOG) == 0) { log_defs |= AFDD_PRODUCTION_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, PRODUCTION_BUFFER_FILE); } break; #endif #ifdef _OUTPUT_LOG case 'O' : /* Output Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_OUTPUT_LOG) { ld[OUT_LOG_POS].options = ld[DUM_LOG_POS].options; ld[OUT_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[OUT_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[OUT_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[OUT_LOG_POS].log_name, OUTPUT_BUFFER_FILE); ld[OUT_LOG_POS].log_name_length = OUTPUT_BUFFER_FILE_LENGTH; ld[OUT_LOG_POS].log_data_cmd[0] = 'L'; ld[OUT_LOG_POS].log_data_cmd[1] = 'O'; ld[OUT_LOG_POS].log_data_cmd[2] = '\0'; ld[OUT_LOG_POS].log_inode_cmd[0] = 'O'; ld[OUT_LOG_POS].log_inode_cmd[1] = 'O'; ld[OUT_LOG_POS].log_inode_cmd[2] = '\0'; ld[OUT_LOG_POS].log_flag = AFDD_OUTPUT_LOG; ld[OUT_LOG_POS].fp = NULL; ld[OUT_LOG_POS].current_log_no = 0; ld[OUT_LOG_POS].packet_no = 0; if ((log_defs & AFDD_OUTPUT_LOG) == 0) { log_defs |= AFDD_OUTPUT_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, OUTPUT_BUFFER_FILE); } break; #endif #ifdef _DELETE_LOG case 'D' : /* Delete Log. */ if (ip_log_defs[trusted_ip_pos] & AFDD_DELETE_LOG) { ld[DEL_LOG_POS].options = ld[DUM_LOG_POS].options; ld[DEL_LOG_POS].current_log_inode = ld[DUM_LOG_POS].current_log_inode; ld[DEL_LOG_POS].offset = ld[DUM_LOG_POS].offset; ld[DEL_LOG_POS].flag = ld[DUM_LOG_POS].flag; (void)strcpy(ld[DEL_LOG_POS].log_name, DELETE_BUFFER_FILE); ld[DEL_LOG_POS].log_name_length = DELETE_BUFFER_FILE_LENGTH; ld[DEL_LOG_POS].log_data_cmd[0] = 'L'; ld[DEL_LOG_POS].log_data_cmd[1] = 'D'; ld[DEL_LOG_POS].log_data_cmd[2] = '\0'; ld[DEL_LOG_POS].log_inode_cmd[0] = 'O'; ld[DEL_LOG_POS].log_inode_cmd[1] = 'D'; ld[DEL_LOG_POS].log_inode_cmd[2] = '\0'; ld[DEL_LOG_POS].log_flag = AFDD_DELETE_LOG; ld[DEL_LOG_POS].fp = NULL; ld[DEL_LOG_POS].current_log_no = 0; ld[DEL_LOG_POS].packet_no = 0; if ((log_defs & AFDD_DELETE_LOG) == 0) { log_defs |= AFDD_DELETE_LOG; } } else { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("Host %s was denied access for %s"), p_remote_ip, DELETE_BUFFER_FILE); } break; #endif default : /* Unknown, lets just ignore it. */ (void)fprintf(p_data, "501- Unknown log type\n\n"); break; } } else { /* Unknown message type. We are unable to */ /* determine the end, so lets discard the */ /* complete message. */ (void)fprintf(p_data, "501- Unknown log type\r\n"); log_defs = 0; complete_failure = YES; break; } } while (*ptr == ' '); if (complete_failure == YES) { log_defs = tmp_log_defs; } else { (void)fprintf(p_data, "211- Command success (%u)\r\n", log_defs); in_log_child = YES; log_interval = 0; if (line_buffer == NULL) { if ((line_buffer = malloc(MAX_LOG_DATA_BUFFER)) == NULL) { system_log(ERROR_SIGN, __FILE__, __LINE__, _("Failed to malloc() %d bytes : %s"), MAX_LOG_DATA_BUFFER, strerror(errno)); exit(INCORRECT); } } if (log_buffer == NULL) { if ((log_buffer = malloc(MAX_LOG_DATA_BUFFER)) == NULL) { system_log(ERROR_SIGN, __FILE__, __LINE__, _("Failed to malloc() %d bytes : %s"), MAX_LOG_DATA_BUFFER, strerror(errno)); exit(INCORRECT); } } #ifdef HAVE_SNPRINTF p_log_dir = log_dir + snprintf(log_dir, MAX_PATH_LENGTH, #else p_log_dir = log_dir + sprintf(log_dir, #endif "%s%s/", p_work_dir, LOG_DIR); #ifdef DEBUG_LOG_CMD if (cmd_buffer_length > LOG_CMD_LENGTH) { system_log(DEBUG_SIGN, __FILE__, __LINE__, "R-> %s", cmd_buffer); } #endif /* * Since we are from now on only handling log * data lets release those resources we no longer * need. */ (void)fsa_detach(NO); (void)fra_detach(); } } else if (strncmp(cmd, TRACEI_CMD, TRACEI_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, TRACEO_CMD, TRACEO_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, TRACEF_CMD, TRACEF_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, PROC_CMD, PROC_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, DISC_CMD, DISC_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, LDB_CMD, LDB_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, INFO_CMD, INFO_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else if (strncmp(cmd, AFDSTAT_CMD, AFDSTAT_CMD_LENGTH) == 0) { (void)fprintf(p_data, "502 Service not implemented. See help for commands.\r\n"); } else { *(cmd + nbytes - 2) = '\0'; (void)fprintf(p_data, "500 \'%s\': command not understood.\r\n", cmd); } (void)fflush(p_data); } /* if (nbytes > 0) */ } /* for (;;) */ (void)fflush(p_data); if (fclose(p_data) == EOF) { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("fclose() error : %s"), strerror(errno)); } p_data = NULL; close_get_display_data(); exit(SUCCESS); } /*++++++++++++++++++++++++ report_shutdown() ++++++++++++++++++++++++++++*/ static void report_shutdown(void) { if (in_log_child == NO) { if (p_data != NULL) { if (report_changes == YES) { show_summary_stat(p_data); check_changes(p_data); } (void)fprintf(p_data, "%s\r\n", AFDD_SHUTDOWN_MESSAGE); (void)fflush(p_data); if (fclose(p_data) == EOF) { system_log(DEBUG_SIGN, __FILE__, __LINE__, _("fclose() error : %s"), strerror(errno)); } p_data = NULL; } } return; }
hfs/afd
src/afdd/handle_request.c
C
gpl-2.0
64,989
<?php /** * DokuWiki Spacious Template * Original Wordpress Theme URI: https://themegrill.com/themes/spacious * * @link https://www.dokuwiki.org/template:spacious * @author Simon DELAGE <sdelage@gmail.com> * @license GPL 3 (https://www.gnu.org/licenses/gpl-3.0.html) * * Template footer, included in the main and detail files */ // must be run from within DokuWiki if (!defined('DOKU_INC')) die(); ?> <!-- ********** FOOTER ********** --> <!-- <footer id="colophon" class="group"> --> <footer id="spacious__foot" class="group<?php print (strpos(tpl_getConf('print'), 'sitefooter') !== false) ? '' : ' noprint' ?>"> <div id="spacious__foot-widgets-container" class="group dark smaller"> <?php spacious_include("footerheader"); ?> <div class="inner-wrap"> <div id="spacious__foot-widgets-wrap" class="flex evenly start wrap"> <?php if ($conf['useacl'] && $ACT != "login" && $ACT != "denied"): ?> <aside id="spacious__userwidget" class="widget"> <?php //if (($conf['useacl']) and (empty($_SERVER['REMOTE_USER'])) and (strpos(tpl_getConf('widgets'), 'footer_login') !== false)) if (($conf['useacl']) && (empty($_SERVER['REMOTE_USER']))) { //<!-- LOGIN FORM --> spacious_loginform('widget'); //} elseif ($spacious['show']['tools']) { } else { print '<h6 class="widget-title title-block-wrap group"><span class="label">'.$lang['profile'].'</span></h6>'; if ($spacious['images']['avatar']['target'] != null) { if (strpos($spacious['images']['avatar']['target'], "debug") !== false) { print '<a href="/doku.php?id='.$ID.'&amp;do=media&amp;ns='.tpl_getConf('avatars').'&amp;tab_files=upload" title="'.tpl_getLang('upload_avatar').'"><img id="spacious__user-avatar" src="'.$spacious['images']['avatar']['target'].'" title="'.tpl_getLang('upload_avatar').'" alt="*'.tpl_getLang('upload_avatar').'*" width="64px" height="100%" /></a>'; } else { if ($spacious['images']['avatar']['thumbnail'] != null) { print '<a href="'.$spacious['images']['avatar']['target'].'" data-lity data-lity-desc="'.tpl_getLang('your_avatar').'" title="'.tpl_getLang('your_avatar').'"><img id="spacious__user-avatar" src="'.$spacious['images']['avatar']['thumbnail'].'" title="'.tpl_getLang('your_avatar').'" alt="*'.tpl_getLang('your_avatar').'*" width="64px" height="100%" /></a>'; } else { print '<a href="'.$spacious['images']['avatar']['target'].'" data-lity data-lity-desc="'.tpl_getLang('your_avatar').'" title="'.tpl_getLang('your_avatar').'"><img id="spacious__user-avatar" src="'.$spacious['images']['avatar']['target'].'" title="'.tpl_getLang('your_avatar').'" alt="*'.tpl_getLang('your_avatar').'*" width="64px" height="100%" /></a>'; } } } print '<ul>'; print '<li>'.$lang['fullname'].' : <em>'.$INFO['userinfo']['name'].'</em></li>'; print '<li>'.$lang['user'].' : <em>'.$_SERVER['REMOTE_USER'].'</em></li>'; print '<li>'.$lang['email'].' : <em>'.$INFO['userinfo']['mail'].'</em></li>'; print '</ul>'; echo '<p class="user">'; // If user has public page ID but no private space ID (most likely because UserHomePage plugin is not available) //if (($spacious['user']['private'] == null) && ($spacious['user']['public']['link'] != null)) { if (($spacious['user']['public']['id'] != null) && ($spacious['user']['private']['id'] != null)) { dbg("vérifier ces liens"); tpl_link(wl($spacious['user']['private']['id']),'<span>'.$spacious['user']['private']['title'].'</span>','title="'.$spacious['user']['private']['title'].'" class="'.$spacious['user']['private']['classes'].'"'); print " - "; tpl_link(wl($spacious['user']['public']['id']),'<span>'.$spacious['user']['public']['title'].'</span>','title="'.$spacious['user']['public']['title'].'" class="'.$spacious['user']['public']['classes'].'"'); } elseif (($spacious['user']['public']['id'] != null) && ($spacious['user']['private'] == null)) { //print $lang['loggedinas']." ".$spacious['user']['public']['link']; //print $lang['loggedinas']." "; // tpl_link(wl($spacious['user']['public']['id']),'<span>'.$spacious['user']['public']['string'].'</span>'.spacious_glyph('public-page', true),'title="'.$spacious['user']['public']['title'].'" class="'.$spacious['user']['public']['classes'].'"'); //tpl_link(wl($spacious['user']['public']['id']),'<span>'.$spacious['user']['public']['string'].'</span>','title="'.$spacious['user']['public']['title'].'" class="'.$spacious['user']['public']['classes'].'"'); print '<span title="'.$spacious['user']['public']['title'].'">'.$spacious['user']['public']['string'].'</span>'; // If user has both public page ID and private space ID // In any other case, use DW's default function //} else { // print $lang['loggedinas'].' '.userlink(); /* 'Logged in as ...' */ } echo '</p>'; echo '<p class="profile">'; print '<a href="/doku.php?id='.$ID.'&amp;do=profile" rel="nofollow" title="'.$lang['btn_profile'].'"><span>'.$lang['btn_profile'].'</span>'.spacious_glyph("profile", true).'</a>'; echo '</p>'; } ?> </aside><!-- /#spacious__usertools --> <?php endif; ?> <?php if (page_findnearest(tpl_getConf('links'), $useacl)): ?> <aside id="spacious__linkswidget" class="widget"> <h6 class="widget-title"><span class="label"><?php print tpl_getLang('links'); ?></span></h6> <?php tpl_include_page(tpl_getConf('links')) /* includes the wiki page "topbar" */ ?> </aside> <?php endif; ?> <?php spacious_include("footerwidget", true); ?> <aside id="spacious__licensewidget" class="widget"> <h6 class="widget-title"><span class="label"><?php print tpl_getLang('license'); ?></span></h6> <?php if ((isset($spacious['qrcode']['license'])) and ($spacious['qrcode']['license'] != null)) : ?> <img class="qrcode license" src="<?php print $spacious['qrcode']['license']; ?>" alt="*qrcode*" title="<?php print tpl_getLang('license'); ?>" /> <?php endif; ?> <?php tpl_license(tpl_getConf('licenseVisual')) /* content license, parameters: img=*badge|button|0, imgonly=*0|1, return=*0|1 */ ?> </aside> <?php if ((isset($spacious['qrcode']['id'])) and ($spacious['qrcode']['id'] != null)) : ?> <aside id="spacious__onlinewidget" class="widget"> <h6 class="widget-title"><span class="label"><?php print tpl_getLang('onlineversion'); ?></span></h6> <img class="qrcode url" src="<?php print $spacious['qrcode']['id']; ?>" alt="*qrcode*" title="<?php print tpl_getLang('onlineversion'); ?>" /> </aside> <?php endif; ?> </div><!-- /#spacious__foot-widgets-wrap --> </div><!-- /.inner-wrap --> <?php spacious_include("footer"); ?> </div><!-- /#spacious__foot-widgets-container --> <div class="footer-socket-wrapper group smallest<?php print (strpos(tpl_getConf('neutralize'), 'footersocket') !== false) ? ' neu' : '' ?>"> <div class="inner-wrap"> <div class="footer-socket-area flex between"> <div class="copyright"> <a href="https://themegrill.com/themes/spacious"<?php spacious_target(); ?> title="Spacious" ><span>Spacious</span><!-- <img src="/lib/tpl/spacious/images/Spacious_51x14.png" width="51" height="14" alt="*Spacious*" /> --></a> &copy; 2020 <a href="https://themegrill.com/"<?php spacious_target(); ?> title="ThemeGrill" rel="author"><span>ThemeGrill</span><!-- <img src="/lib/tpl/spacious/images/ThemeGrill_103x11.png" width="103" height="11" alt="*ThemeGrill*" /> --></a> </div><!-- /.copyright --> <nav class="small-menu group"> <ul class="menu buttons"> <li><a href="http://dokuwiki.org/" title="Driven by DokuWiki"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-dw.png" width="80" height="15" alt="Driven by DokuWiki" /></a></li> <li class="noprint"><a href="http://www.dokuwiki.org/donate" title="Donate to DokuWiki"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-donate.png" width="80" height="15" alt="Donate to DokuWiki" /></a></li> <li class="noprint"><a href="https://translate.dokuwiki.org/" title="Localized (you can help)"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-localized.png" width="80" height="15" alt="Localized" /></a></li> <li><a href="http://php.net" title="Powered by PHP"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-php.png" width="80" height="15" alt="Powered by PHP" /></a></li> <li><a href="http://validator.w3.org/check/referer" title="Check HTML5"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-html5.png" width="80" height="15" alt="Check HTML5" /></a></li> <li><a href="http://jigsaw.w3.org/css-validator/check/referer?profile=css3" title="Check CSS"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-css.png" width="80" height="15" alt="Check CSS" /></a></li> <li><a href="https://github.com/geekitude/dokuwiki-template-spacious" title="Spacious template"<?php spacious_target(); ?>><img src="<?php print tpl_basedir(); ?>images/button-spacious.png" width="80" height="15" alt="Spacious tmplate" /></a></li> </ul><!-- /.menu.buttons --> </nav><!-- /.small-menu --> </div><!-- /.footer-socket-area --> </div><!-- /.inner-wrap --> </div><!-- /.footer-socket-wrapper --> </footer><!-- /#spacious__foot --> <?php tpl_includeFile('footer.html');
geekitude/dokuwiki-template-spacious
tpl_footer.php
PHP
gpl-2.0
11,597
High Level To Do List ======= ## Expanded Error Handling and Reporting There's a lot of places where things might fail right now that are potentially poorly handled. For instance, if protractor doesn't detect any tests to run. These situations should be identified and handled cleanly. ## Reduce Noise and Provide Cleaner Reporting Right now all of the output of sauce-connect, webdriver, etc is simply piped through to stdout and stderr. Long-term it'd be ideal if this could be captured and cleaner, more legible output could be provided. ## Remove implicit use of console.log It's a little invasive. We should provide configurable logging.
allenai/pesto
TODO.md
Markdown
gpl-2.0
653
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.solr.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Admin JDK Logger level report and selection servlet. * * @version $Id: LogLevelSelection.java 1065312 2011-01-30 16:08:25Z rmuir $ * @since solr 1.3 */ public final class LogLevelSelection extends HttpServlet { @Override public void init() throws ServletException { } /** * Processes an HTTP GET request and changes the logging level as * specified. */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Output page response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write("<html><head>\n"); out.write("<title>Solr Admin: JDK Log Level Selector</title>\n"); out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"solr-admin.css\" />"); out.write("</head><body>\n"); out.write("<a href=\".\"><img border=\"0\" align=\"right\" height=\"78\" width=\"142\" src=\"solr_small.png\" alt=\"Solr\"></a>"); out.write("<h1>JDK Log Level Selector</h1>"); out.write("<p>Below is the complete JDK Log hierarchy with " + "intermediate logger/categories synthesized. " + "The effective logging level is shown to the " + "far right. If a logger has unset level, then " + "the effective level is that of the nearest ancestor " + "with a level setting. Note that this only shows " + "JDK Log levels.</p>\n"); out.write("<form method='POST'>\n"); out.write("<input type='submit' name='submit' value='set' " + "class='button'>\n"); out.write("<input type='submit' name='submit' value='cancel' " + "class='button'>\n"); out.write("<br><br>\n"); out.write("<table cellspacing='2' cellpadding='2'>"); out.write("<tr bgcolor='#CCCCFF'>" + "<th align=left>Logger/Category name<br>" + "<th colspan=9>Level</th>" + "</tr><tr bgcolor='#CCCCFF'>" + "<td bgcolor='#AAAAAA'>" + "(Dark rows don't yet exist.)</td>"); for (int j = 0; j < LEVELS.length; ++j) { out.write("<th align=left>"); if (LEVELS[j] != null) out.write(LEVELS[j].toString()); else out.write("unset"); out.write("</th>"); } out.write("<th align=left>Effective</th>\n"); out.write("</tr>\n"); Iterator iWrappers = buildWrappers().iterator(); while (iWrappers.hasNext()) { LogWrapper wrapper = (LogWrapper) iWrappers.next(); out.write("<tr"); if (wrapper.logger == null) { out.write(" bgcolor='#AAAAAA'"); } //out.write( ( wrapper.logger != null ) ? "#DDDDDD" : "#AAAAAA" ); out.write("><td>"); if ("".equals(wrapper.name)) { out.write("root"); } else { out.write(wrapper.name); } out.write("</td>\n"); for (int j = 0; j < LEVELS.length; ++j) { out.write("<td align=center>"); if (!wrapper.name.equals("root") || (LEVELS[j] != null)) { out.write("<input type='radio' name='"); if ("".equals(wrapper.name)) { out.write("root"); } else { out.write(wrapper.name); } out.write("' value='"); if (LEVELS[j] != null) out.write(LEVELS[j].toString()); else out.write("unset"); out.write('\''); if (LEVELS[j] == wrapper.level()) out.write(" checked"); out.write('>'); } out.write("</td>\n"); } out.write("<td align=center>"); if (wrapper.logger != null) { out.write(getEffectiveLevel(wrapper.logger).toString()); } out.write("</td></tr>\n"); } out.write("</table>\n"); out.write("<br>\n"); out.write("<input type='submit' name='submit' value='set' " + "class='button'>\n"); out.write("<input type='submit' name='submit' value='cancel' " + "class='button'>\n"); out.write("</form>\n"); out.write("</body></html>\n"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("submit").equals("set")) { Map paramMap = request.getParameterMap(); Iterator iParams = paramMap.entrySet().iterator(); while (iParams.hasNext()) { Map.Entry p = (Map.Entry) iParams.next(); String name = (String) p.getKey(); String value = ((String[]) p.getValue())[0]; if (name.equals("submit")) continue; Logger logger; LogManager logManager = LogManager.getLogManager(); if ("root".equals(name)) { logger = logManager.getLogger(""); } else logger = logManager.getLogger(name); if ("unset".equals(value)) { if ((logger != null) && (logger.getLevel() != null)) { logger.setLevel(null); log.info("Unset log level on '" + name + "'."); } } else { Level level = Level.parse(value); if (logger == null) logger = Logger.getLogger(name); if (logger.getLevel() != level) { logger.setLevel(level); log.info("Set '" + name + "' to " + level + " level."); } } } } else { log.fine("Selection form cancelled"); } // Redirect back to standard get page. response.sendRedirect(request.getRequestURI()); } private Collection buildWrappers() { // Use tree to get sorted results SortedSet<LogWrapper> roots = new TreeSet<LogWrapper>(); roots.add(LogWrapper.ROOT); LogManager logManager = LogManager.getLogManager(); Enumeration<String> loggerNames = logManager.getLoggerNames(); while (loggerNames.hasMoreElements()) { String name = loggerNames.nextElement(); Logger logger = Logger.getLogger(name); LogWrapper wrapper = new LogWrapper(logger); roots.remove(wrapper); // Make sure add occurs roots.add(wrapper); while (true) { int dot = name.lastIndexOf("."); if (dot < 0) break; name = name.substring(0, dot); roots.add(new LogWrapper(name)); // if not already } } return roots; } private Level getEffectiveLevel(Logger logger) { Level level = logger.getLevel(); if (level != null) { return level; } for (Level l : LEVELS) { if (l == null) { // avoid NPE continue; } if (logger.isLoggable(l)) { // return first level loggable return l; } } return Level.OFF; } private static class LogWrapper implements Comparable { public static LogWrapper ROOT = new LogWrapper(LogManager.getLogManager().getLogger("")); public LogWrapper(Logger logger) { this.logger = logger; this.name = logger.getName(); } public LogWrapper(String name) { this.name = name; } public int compareTo(Object other) { if (this.equals(other)) return 0; if (this == ROOT) return -1; if (other == ROOT) return 1; return name.compareTo(((LogWrapper) other).name); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LogWrapper other = (LogWrapper) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public Level level() { if (logger != null) return logger.getLevel(); return null; } public Logger logger = null; public String name; } private static Level[] LEVELS = { null, // aka unset Level.FINEST, Level.FINE, Level.CONFIG, Level.INFO, Level.WARNING, Level.SEVERE, Level.OFF // Level.ALL -- ignore. It is useless. }; private Logger log = Logger.getLogger(getClass().getName()); }
Lythimus/lptv
apache-solr-3.6.0/solr/core/src/java/org/apache/solr/servlet/LogLevelSelection.java
Java
gpl-2.0
9,568
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2012 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_VEGA_INTERNAL_HPP #define XCSOAR_VEGA_INTERNAL_HPP #include "Device/Driver.hpp" #include "Device/SettingsMap.hpp" #include "Atmosphere/Pressure.hpp" #include "Thread/Mutex.hpp" class NMEAInputLine; class VegaDevice : public AbstractDevice { private: Port &port; /** * The most recent QNH value, written by SetQNH(), read by * VarioWriteSettings(). */ AtmosphericPressure qnh; bool detected; DeviceSettingsMap<int> settings; public: VegaDevice(Port &_port) :port(_port), qnh(AtmosphericPressure::Standard()), detected(false) {} /** * Write an integer setting to the Vega. * * @return true if sending the command has succeeded (it does not * indicate whether the Vega has understood and processed it) */ bool SendSetting(const char *name, int value, OperationEnvironment &env); /** * Request an integer setting from the Vega. The Vega will send the * value, but this method will not wait for that. * * @return true if sending the command has succeeded (it does not * indicate whether the Vega has understood and processed it) */ bool RequestSetting(const char *name, OperationEnvironment &env); /** * Look up the given setting in the table of received values. The * first element is a "found" flag, and if that is true, the second * element is the value. */ gcc_pure std::pair<bool, int> GetSetting(const char *name) const; protected: void VarioWriteSettings(const DerivedInfo &calculated, OperationEnvironment &env) const; bool PDVSC(NMEAInputLine &line, NMEAInfo &info); public: virtual void LinkTimeout(); virtual bool ParseNMEA(const char *line, struct NMEAInfo &info); virtual bool PutQNH(const AtmosphericPressure& pres, OperationEnvironment &env); virtual void OnSysTicker(const DerivedInfo &calculated); }; #endif
damianob/xcsoar
src/Device/Driver/Vega/Internal.hpp
C++
gpl-2.0
2,795
/*************************************************************************** qgsauthimportcertdialog.h --------------------- begin : April 30, 2015 copyright : (C) 2015 by Boundless Spatial, Inc. USA author : Larry Shaffer email : lshaffer at boundlessgeo dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSAUTHIMPORTCERTDIALOG_H #define QGSAUTHIMPORTCERTDIALOG_H #include <QDialog> #include "ui_qgsauthimportcertdialog.h" #include <QSslCertificate> #include "qgis_gui.h" class QPushButton; /** \ingroup gui * Widget for importing a certificate into the authentication database */ class GUI_EXPORT QgsAuthImportCertDialog : public QDialog, private Ui::QgsAuthImportCertDialog { Q_OBJECT public: //! Type of filter to apply to dialog enum CertFilter { NoFilter = 1, CaFilter = 2, }; //! Type of inputs for certificates enum CertInput { AllInputs = 1, FileInput = 2, TextInput = 3, }; /** * Construct a dialog for importing certificates * @param parent Parent widget * @param filter Certificate type filter to apply to dialog * @param input Type of input(s) for certificates */ explicit QgsAuthImportCertDialog( QWidget *parent = nullptr, QgsAuthImportCertDialog::CertFilter filter = NoFilter, QgsAuthImportCertDialog::CertInput input = AllInputs ); //! Get list of certificate objects to import const QList<QSslCertificate> certificatesToImport(); //! Get the file path to a certificate to import const QString certFileToImport(); //! Get certificate text to import const QString certTextToImport(); //! Whether to allow importation of invalid certificates (so trust policy can be overridden) bool allowInvalidCerts(); //! Defined trust policy for imported certificates QgsAuthCertUtils::CertTrustPolicy certTrustPolicy(); private slots: void updateGui(); void validateCertificates(); void on_btnImportFile_clicked(); void on_chkAllowInvalid_toggled( bool checked ); private: QString getOpenFileName( const QString &title, const QString &extfilter ); QPushButton *okButton(); QList<QSslCertificate> mCerts; QgsAuthImportCertDialog::CertFilter mFilter; QgsAuthImportCertDialog::CertInput mInput; bool mDisabled; QVBoxLayout *mAuthNotifyLayout = nullptr; QLabel *mAuthNotify = nullptr; }; #endif // QGSAUTHIMPORTCERTDIALOG_H
myarjunar/QGIS
src/gui/auth/qgsauthimportcertdialog.h
C
gpl-2.0
3,179
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id: adler32.c,v 1.2 2005/08/15 16:11:23 johnmc Exp $ */ #define ZLIB_INTERNAL #include "zlib.h" #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); #ifdef NO_DIVIDE # define MOD(a) \ do { \ if (a >= (BASE << 16)) a -= (BASE << 16); \ if (a >= (BASE << 15)) a -= (BASE << 15); \ if (a >= (BASE << 14)) a -= (BASE << 14); \ if (a >= (BASE << 13)) a -= (BASE << 13); \ if (a >= (BASE << 12)) a -= (BASE << 12); \ if (a >= (BASE << 11)) a -= (BASE << 11); \ if (a >= (BASE << 10)) a -= (BASE << 10); \ if (a >= (BASE << 9)) a -= (BASE << 9); \ if (a >= (BASE << 8)) a -= (BASE << 8); \ if (a >= (BASE << 7)) a -= (BASE << 7); \ if (a >= (BASE << 6)) a -= (BASE << 6); \ if (a >= (BASE << 5)) a -= (BASE << 5); \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long s1 = adler & 0xffff; unsigned long s2 = (adler >> 16) & 0xffff; int k; if (buf == Z_NULL) return 1L; while (len > 0) { k = len < NMAX ? (int)len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); MOD(s1); MOD(s2); } return (s2 << 16) | s1; }
johngarvin/R-2.1.1rcc
src/extra/zlib/adler32.c
C
gpl-2.0
2,286
Practica-5 ========== Tabla 10x10
ulises-m/Practica-5
README.md
Markdown
gpl-2.0
35
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/php/showphp.asp?filename=demo_func_array_diff2 by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:06:20 GMT --> <head> <title>Tryit Editor v2.1 - Show PHP</title> <link rel="stylesheet" href="../trycss.css"> <!--[if lt IE 8]> <style> .textarea, .iframe {height:800px;} #iframeSource, #iframeResult {height:700px;} </style> <![endif]--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','../../www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-3855518-1', 'auto'); ga('require', 'displayfeatures'); ga('send', 'pageview'); </script> <script type='text/javascript'> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script type='text/javascript'> googletag.cmd.push(function() { googletag.defineSlot('/16833175/TryitLeaderboard', [[728, 90], [970, 90]], 'div-gpt-ad-1383036313516-0').addService(googletag.pubads()); googletag.pubads().setTargeting("content","tryphp"); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> </head> <body> <div style="position:relative;width:100%;margin-top:0px;margin-bottom:0px;"> <div style="width:974px;height:94px;position:relative;margin:0px;margin-left:auto;margin-right:auto;margin-top:5px;margin-bottom:5px;padding:0px;overflow:hidden;"> <!-- TryitLeaderboard --> <div id='div-gpt-ad-1383036313516-0' style='width:970px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1383036313516-0'); }); </script> </div> <div style="clear:both"></div> </div> </div> <div class="container"> <div class="textareacontainer"> <div class="textarea"> <div class="headerText">PHP Source:</div> <div class="iframewrapper"> <iframe id="iframeSource" frameborder="0" src="showphpcodebdac.html?source=demo_func_array_diff2"></iframe> </div> </div> </div> <div class="iframecontainer"> <div class="iframe"> <div class="headerText">Result:</div> <div class="iframewrapper"> <iframe id="iframeResult" frameborder="0" src="demo_func_array_diff2.html"></iframe> </div> <div class="footerText">Show PHP - &copy; <a href="../index.html">w3schools.com</a></div> </div> </div> </div> </body> <!-- Mirrored from www.w3schools.com/php/showphp.asp?filename=demo_func_array_diff2 by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:06:20 GMT --> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/php/showphp72a4.html
HTML
gpl-2.0
3,053
<?php // Authored by Skyler Moore. pb_backupbuddy::$ui->title( 'FTP' ); // FTP connection information $ftp_server = $destination['address']; $ftp_username = $destination['username']; $ftp_password = $destination['password']; $ftp_directory = $destination['path']; $ftps = $destination['ftps']; if ( !empty( $ftp_directory ) ) { $ftp_directory = $ftp_directory . '/'; } if ( isset( $destination['active_mode'] ) && ( $destination['active_mode'] == '0' ) ) { $active = false; } else { $active = true; } $port = '21'; if ( strstr( $ftp_server, ':' ) ) { $server_params = explode( ':', $ftp_server ); $ftp_server = $server_params[0]; $port = $server_params[1]; } // Delete ftp backups if ( !empty( $_POST['delete_file'] ) ) { pb_backupbuddy::verify_nonce(); $delete_count = 0; if ( !empty( $_POST['files'] ) && is_array( $_POST['files'] ) ) { // Connect to server. if ( $ftps == '1' ) { // Connect with FTPs. if ( function_exists( 'ftp_ssl_connect' ) ) { $conn_id = ftp_ssl_connect( $ftp_server, $port ); if ( $conn_id === false ) { pb_backupbuddy::status( 'details', 'Unable to connect to FTPS (check address/FTPS support).', 'error' ); return false; } else { pb_backupbuddy::status( 'details', 'Connected to FTPs.' ); } } else { pb_backupbuddy::status( 'details', 'Your web server doesnt support FTPS in PHP.', 'error' ); return false; } } else { // Connect with FTP (normal). if ( function_exists( 'ftp_connect' ) ) { $conn_id = ftp_connect( $ftp_server, $port ); if ( $conn_id === false ) { pb_backupbuddy::status( 'details', 'ERROR: Unable to connect to FTP (check address).', 'error' ); return false; } else { pb_backupbuddy::status( 'details', 'Connected to FTP.' ); } } else { pb_backupbuddy::status( 'details', 'Your web server doesnt support FTP in PHP.', 'error' ); return false; } } // login with username and password $login_result = ftp_login( $conn_id, $ftp_username, $ftp_password ); if ( $active === true ) { // do nothing, active is default. pb_backupbuddy::status( 'details', 'Active FTP mode based on settings.' ); } elseif ( $active === false ) { // Turn passive mode on. pb_backupbuddy::status( 'details', 'Passive FTP mode based on settings.' ); ftp_pasv( $conn_id, true ); } else { pb_backupbuddy::status( 'error', 'Unknown FTP active/passive mode: `' . $active . '`.' ); } ftp_chdir( $conn_id, $ftp_directory ); // loop through and delete ftp backup files foreach ( $_POST['files'] as $backup ) { // try to delete backup if ( ftp_delete( $conn_id, $backup ) ) { $delete_count++; } } // close this connection ftp_close( $conn_id ); } if ( $delete_count > 0 ) { pb_backupbuddy::alert( sprintf( _n( 'Deleted %d file.', 'Deleted %d files.', $delete_count, 'it-l10n-backupbuddy' ), $delete_count ) ); } else { pb_backupbuddy::alert( __('No backups were deleted.', 'it-l10n-backupbuddy' ) ); } } // Copy ftp backups to the local backup files if ( !empty( $_GET['copy_file'] ) ) { pb_backupbuddy::alert( sprintf( _x('The remote file is now being copied to your %1$slocal backups%2$s', '%1$s and %2$s are open and close <a> tags', 'it-l10n-backupbuddy' ), '<a href="' . pb_backupbuddy::page_url() . '">', '</a>.' ) ); pb_backupbuddy::status( 'details', 'Scheduling Cron for creating ftp copy.' ); pb_backupbuddy::$classes['core']->schedule_single_event( time(), pb_backupbuddy::cron_tag( 'process_ftp_copy' ), array( $_GET['copy_file'], $ftp_server, $ftp_username, $ftp_password, $ftp_directory, $port, $ftps ) ); spawn_cron( time() + 150 ); // Adds > 60 seconds to get around once per minute cron running limit. update_option( '_transient_doing_cron', 0 ); // Prevent cron-blocking for next item. } // Connect to server if ( $ftps == '1' ) { // Connect with FTPs. if ( function_exists( 'ftp_ssl_connect' ) ) { $conn_id = ftp_ssl_connect( $ftp_server, $port ); if ( $conn_id === false ) { pb_backupbuddy::status( 'details', 'Unable to connect to FTPS `' . $ftp_server . '` on port `' . $port . '` (check address/FTPS support and that server can connect to this address via this port).', 'error' ); return false; } else { pb_backupbuddy::status( 'details', 'Connected to FTPs.' ); } } else { pb_backupbuddy::status( 'details', 'Your web server doesnt support FTPS in PHP.', 'error' ); return false; } } else { // Connect with FTP (normal). if ( function_exists( 'ftp_connect' ) ) { $conn_id = ftp_connect( $ftp_server, $port ); if ( $conn_id === false ) { pb_backupbuddy::status( 'details', 'ERROR: Unable to connect to FTP server `' . $ftp_server . '` on port `' . $port . '` (check address and that server can connect to this address via this port).', 'error' ); return false; } else { pb_backupbuddy::status( 'details', 'Connected to FTP.' ); } } else { pb_backupbuddy::status( 'details', 'Your web server doesnt support FTP in PHP.', 'error' ); return false; } } // Login with username and password $login_result = ftp_login( $conn_id, $ftp_username, $ftp_password ); if ( $active === true ) { // do nothing, active is default. pb_backupbuddy::status( 'details', 'Active FTP mode based on settings.' ); } elseif ( $active === false ) { // Turn passive mode on. pb_backupbuddy::status( 'details', 'Passive FTP mode based on settings.' ); ftp_pasv( $conn_id, true ); } else { pb_backupbuddy::status( 'error', 'Unknown FTP active/passive mode: `' . $active . '`.' ); } // Get contents of the current directory ftp_chdir( $conn_id, $ftp_directory ); $contents = ftp_nlist( $conn_id, '' ); // Create array of backups and sizes $backups = array(); $got_modified = false; foreach ( $contents as $backup ) { // check if file is backup $pos = strpos( $backup, 'backup-' ); if ( $pos !== FALSE ) { $mod_time = ftp_mdtm( $conn_id, $ftp_directory . $backup ); if ( $mod_time > -1 ) { $got_modified = true; } $backups[] = array( 'file' => $backup, 'size' => ftp_size( $conn_id, $ftp_directory . $backup ), 'modified' => $mod_time, ); } } // close this connection ftp_close( $conn_id ); if ( $got_modified === true ) { // FTP server supports sorting by modified date. // Custom sort function for multidimension array usage. function backupbuddy_number_sort( $a,$b ) { return $a['modified']<$b['modified']; } // Sort by modified using custom sort function above. usort( $backups, 'backupbuddy_number_sort' ); } echo '<h3>', __('Viewing', 'it-l10n-backupbuddy' ), ' `' . $destination['title'] . '` (' . $destination['type'] . ')</h3>'; ?> <div style="max-width: 950px;"> <form id="posts-filter" enctype="multipart/form-data" method="post" action="<?php echo pb_backupbuddy::page_url() . '&custom=' . $_GET['custom'] . '&destination_id=' . $_GET['destination_id'];?>"> <div class="tablenav"> <div class="alignleft actions"> <input type="submit" name="delete_file" value="<?php _e('Delete from FTP', 'it-l10n-backupbuddy' );?>" class="button-secondary delete" /> </div> </div> <table class="widefat"> <thead> <tr class="thead"> <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th> <?php echo '<th>', __('Backup File', 'it-l10n-backupbuddy' ), '</th>', '<th>', __('File Size', 'it-l10n-backupbuddy' ), '</th>', '<th>', __('Modified', 'it-l10n-backupbuddy' ); if ( $got_modified === true ) { echo ' <img src="', pb_backupbuddy::plugin_url(), '/images/sort_down.png" style="vertical-align: 0px;" title="', __('Sorted by modified', 'it-l10n-backupbuddy' ), '" />'; } echo '</th>', '<th>', __('Actions', 'it-l10n-backupbuddy' ), '</th>'; ?> </tr> </thead> <tfoot> <tr class="thead"> <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th> <?php echo '<th>', __('Backup File', 'it-l10n-backupbuddy' ), '</th>', '<th>', __('File Size', 'it-l10n-backupbuddy' ), '</th>', '<th>', __('Modified', 'it-l10n-backupbuddy' ); if ( $got_modified === true ) { echo ' <img src="', pb_backupbuddy::plugin_url(), '/images/sort_down.png" style="vertical-align: 0px;" title="', __('Sorted by modified', 'it-l10n-backupbuddy' ), '" />'; } echo '</th><th>', __('Actions', 'it-l10n-backupbuddy' ), '</th>'; ?> </tr> </tfoot> <tbody> <?php // List FTP backups if ( empty( $backups ) ) { echo '<tr><td colspan="5" style="text-align: center;"><i>', __('This directory does not have any backups.', 'it-l10n-backupbuddy' ), '</i></td></tr>'; } else { $file_count = 0; foreach ( (array)$backups as $backup ) { $file_count++; ?> <tr class="entry-row alternate"> <th scope="row" class="check-column"><input type="checkbox" name="files[]" class="entries" value="<?php echo $backup; ?>" /></th> <td> <?php echo $backup['file']; ?> </td> <td style="white-space: nowrap;"> <?php if ( $backup['modified'] > -1 ) { echo pb_backupbuddy::$format->date( pb_backupbuddy::$format->localize_time( $backup['modified'] ) ); echo '<br /><span class="description">(' . pb_backupbuddy::$format->time_ago( $backup['modified'] ) . ' ', __('ago', 'it-l10n-backupbuddy' ), ')</span>'; } else { echo '<span class="description">Unknown</span>'; } ?> </td> <td style="white-space: nowrap;"> <?php echo pb_backupbuddy::$format->file_size( $backup['size'] ); ?> </td> <td> <?php echo '<a href="' . pb_backupbuddy::page_url() . '&custom=' . $_GET['custom'] . '&destination_id=' . $_GET['destination_id'] . '&#38;copy_file=' . $backup . '">Copy to local</a>'; ?> </td> </tr> <?php } } ?> </tbody> </table> <div class="tablenav"> <div class="alignleft actions"> <input type="submit" name="delete_file" value="<?php _e('Delete from FTP', 'it-l10n-backupbuddy' );?>" class="button-secondary delete" /> </div> </div> <?php pb_backupbuddy::nonce(); ?> </form><br /> </div>
lucasandcribb/scmusicguide
wp-content/plugins/backupbuddy/destinations/ftp/_manage.php
PHP
gpl-2.0
10,214
@media screen { *{ margin:0; padding:0; font-family:sans-serif; font-size:14px; } .analog-clock{ width:140px; height:140px; float:right; margin-top:20px; } #clock-face{ stroke:black; stroke-width:2px; fill:white; } #h-hand,#m-hand,#s-hand,#s-tail{ stroke:black; stroke-linecap:round; } #h-hand{ stroke-width:3px; } #m-hand{ stroke-width:2px; } #s-hand{ stroke-width:1px; } .time-text{ text-align:center; } }
iamstg/first-timer
public_html/clockstyle.css
CSS
gpl-2.0
421
using System; using System.Collections.Generic; using System.Reflection; namespace Polenter.Serialization.Advanced { ///<summary> ///</summary> internal class PropertyCache { private readonly Dictionary<Type, IList<PropertyInfo>> _cache = new Dictionary<Type, IList<PropertyInfo>>(); /// <summary> /// </summary> /// <returns>null if the key was not found</returns> public IList<PropertyInfo> TryGetPropertyInfos(Type type) { if (!this._cache.ContainsKey(type)) { return null; } return this._cache[type]; } public void Add(Type key, IList<PropertyInfo> value) { this._cache.Add(key, value); } } }
furesoft/POS
POS/POS/Internals/Serializer/Advanced/PropertyCache.cs
C#
gpl-2.0
775
package edu.courses.middleware.pubsub.events; /** * This Event is used to indicate an Event unsubscription along a path in the * Broker tree. * */ public class UnsubscriptionEvent extends Event { private static final long serialVersionUID = 6963303524174981529L; /** The Event being unsubscribed from. */ private Event event; public UnsubscriptionEvent(Event event) { this.event = event; } public Event getUnsubscription() { return event; } @Override public boolean matches(Event event) { // TODO Auto-generated method stub return false; } }
jonasrmichel/publish-subscribe-auction
src/edu/courses/middleware/pubsub/events/UnsubscriptionEvent.java
Java
gpl-2.0
570
<?php require_once('attachment.class.php'); /** * Fast Mime Mail parser Class using PHP's MailParse Extension * @author gabe@fijiwebdesign.com * @url http://www.fijiwebdesign.com/ * @license http://creativecommons.org/licenses/by-sa/3.0/us/ * @version $Id$ */ class MimeMailParser { /** * PHP MimeParser Resource ID */ public $resource; /** * A file pointer to email */ public $stream; /** * A text of an email */ public $data; /** * Stream Resources for Attachments */ public $attachment_streams; /** * Inialize some stuff * @return */ public function __construct() { $this->attachment_streams = array(); } /** * Free the held resouces * @return void */ public function __destruct() { // clear the email file resource if (is_resource($this->stream)) { fclose($this->stream); } // clear the MailParse resource if (is_resource($this->resource)) { mailparse_msg_free($this->resource); } // remove attachment resources foreach ($this->attachment_streams as $stream) { fclose($stream); } } /** * Set the file path we use to get the email text * @return Object MimeMailParser Instance * @param $mail_path Object */ public function setPath($path) { // should parse message incrementally from file $this->resource = mailparse_msg_parse_file($path); $this->stream = fopen($path, 'r'); $this->parse(); return $this; } /** * Set the Stream resource we use to get the email text * @return Object MimeMailParser Instance * @param $stream Resource */ public function setStream($stream) { // streams have to be cached to file first if (get_resource_type($stream) == 'stream') { $tmp_fp = tmpfile(); if ($tmp_fp) { while (!feof($stream)) { fwrite($tmp_fp, fread($stream, 2028)); } fseek($tmp_fp, 0); $this->stream = & $tmp_fp; } else { throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.'); return false; } fclose($stream); } else { $this->stream = $stream; } $this->resource = mailparse_msg_create(); // parses the message incrementally low memory usage but slower while (!feof($this->stream)) { mailparse_msg_parse($this->resource, fread($this->stream, 2082)); } $this->parse(); return $this; } /** * Set the email text * @return Object MimeMailParser Instance * @param $data String */ public function setText($data) { $this->resource = mailparse_msg_create(); // does not parse incrementally, fast memory hog might explode mailparse_msg_parse($this->resource, $data); $this->data = $data; $this->parse(); return $this; } /** * Parse the Message into parts * @return void */ protected function parse() { $structure = mailparse_msg_get_structure($this->resource); $this->parts = array(); foreach ($structure as $part_id) { $part = mailparse_msg_get_part($this->resource, $part_id); $this->parts[$part_id] = mailparse_msg_get_part_data($part); } } /** * Retrieve the Email Headers * @return Array */ public function getHeaders() { if (isset($this->parts[1])) { return $this->getPartHeaders($this->parts[1]); } else { throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.'); } return false; } /** * Retrieve the raw Email Headers * @return string */ public function getHeadersRaw() { if (isset($this->parts[1])) { return $this->getPartHeaderRaw($this->parts[1]); } else { throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.'); } return false; } /** * Retrieve a specific Email Header * @return String * @param $name String Header name */ public function getHeader($name) { if (isset($this->parts[1])) { $headers = $this->getPartHeaders($this->parts[1]); if (isset($headers[$name])) { return $this->_decodeHeader($headers[$name]); } } else { throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.'); } return false; } /** * Returns the email message body in the specified format. Assumes all body * parts are encoding in the same character encoding. * * @return Mixed String Body or False if not found * @param string $type The content type to fetch (text or html) * @see MimeMailParser::getMessageBodies() */ public function getMessageBody($type = 'text') { $bodies = $this->getMessageBodies($type); if (empty($bodies)) return false; $body = ""; foreach ($bodies as $elem) { $body .= $elem; } return $body; } /** * Returns the email message bodies in the specified format * @return Array * @param string $type The content type to fetch (text or html) */ public function getMessageBodies($type = 'text') { $body = array(); $mime_types = array( 'text' => 'text/plain', 'html' => 'text/html' ); $dispositions = array("attachment"); if (in_array($type, array_keys($mime_types))) { foreach ($this->parts as $part) { $disposition = $this->getPartContentDisposition($part); if (in_array($disposition, $dispositions)) continue; if ($this->getPartContentType($part) == $mime_types[$type]) { $headers = $this->getPartHeaders($part); $body[] = $this->decode($this->getPartBody($part), array_key_exists('content-transfer-encoding', $headers) ? $headers['content-transfer-encoding'] : ''); } } } else { throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.'); } return $body; } /** * get the headers for the message body parts. * @return Array * @param string $type The content type to fetch (text or html) */ public function getMessageBodyHeaders($type = 'text') { $headers = false; $mime_types = array( 'text' => 'text/plain', 'html' => 'text/html' ); $dispositions = array("attachment"); if (in_array($type, array_keys($mime_types))) { foreach ($this->parts as $part) { $disposition = $this->getPartContentDisposition($part); if (in_array($disposition, $dispositions)) continue; if ($this->getPartContentType($part) == $mime_types[$type]) { $headers[] = $this->getPartHeaders($part); } } } else { throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.'); } return $headers; } /** * Returns the attachments contents in order of appearance * @return Array */ public function getAttachments() { $attachments = array(); $dispositions = array("attachment", "inline"); foreach ($this->parts as $part) { $disposition = $this->getPartContentDisposition($part); if (in_array($disposition, $dispositions)) { $attachments[] = new MimeMailParser_attachment( $part['disposition-filename'], $this->getPartContentType($part), $this->getAttachmentStream($part), $disposition, $this->getPartHeaders($part) ); } } return $attachments; } /** * Return the Headers for a MIME part * @return Array * @param $part Array */ protected function getPartHeaders($part) { if (isset($part['headers'])) { return $part['headers']; } return false; } /** * Return a Specific Header for a MIME part * @return Array * @param $part Array * @param $header String Header Name */ protected function getPartHeader($part, $header) { if (isset($part['headers'][$header])) { return $part['headers'][$header]; } return false; } /** * Return the ContentType of the MIME part * @return String * @param $part Array */ protected function getPartContentType($part) { if (isset($part['content-type'])) { return $part['content-type']; } return false; } /** * Return the Content Disposition * @return String * @param $part Array */ protected function getPartContentDisposition($part) { if (isset($part['content-disposition'])) { return $part['content-disposition']; } return false; } /** * Retrieve the raw Header of a MIME part * @return String * @param $part Object */ protected function getPartHeaderRaw(&$part) { $header = ''; if ($this->stream) { $header = $this->getPartHeaderFromFile($part); } else if ($this->data) { $header = $this->getPartHeaderFromText($part); } else { throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.'); } return $header; } /** * Retrieve the Body of a MIME part * @return String * @param $part Object */ protected function getPartBody(&$part) { $body = ''; if ($this->stream) { $body = $this->getPartBodyFromFile($part); } else if ($this->data) { $body = $this->getPartBodyFromText($part); } else { throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.'); } return $body; } /** * Retrieve the Header from a MIME part from file * @return String Mime Header Part * @param $part Array */ protected function getPartHeaderFromFile(&$part) { $start = $part['starting-pos']; $end = $part['starting-pos-body']; if ($end - $start <= 0) return null; fseek($this->stream, $start, SEEK_SET); $header = fread($this->stream, $end - $start); return $header; } /** * Retrieve the Body from a MIME part from file * @return String Mime Body Part * @param $part Array */ protected function getPartBodyFromFile(&$part) { $start = $part['starting-pos-body']; $end = $part['ending-pos-body']; if ($end - $start <= 0) return null; fseek($this->stream, $start, SEEK_SET); $body = fread($this->stream, $end - $start); return $body; } /** * Retrieve the Header from a MIME part from text * @return String Mime Header Part * @param $part Array */ protected function getPartHeaderFromText(&$part) { $start = $part['starting-pos']; $end = $part['starting-pos-body']; $header = substr($this->data, $start, $end - $start); return $header; } /** * Retrieve the Body from a MIME part from text * @return String Mime Body Part * @param $part Array */ protected function getPartBodyFromText(&$part) { $start = $part['starting-pos-body']; $end = $part['ending-pos-body']; $body = substr($this->data, $start, $end - $start); return $body; } /** * Read the attachment Body and save temporary file resource * @return String Mime Body Part * @param $part Array */ protected function getAttachmentStream(&$part) { $temp_fp = tmpfile(); array_key_exists('content-transfer-encoding', $part['headers']) ? $encoding = $part['headers']['content-transfer-encoding'] : $encoding = ''; if ($temp_fp) { if ($this->stream) { $start = $part['starting-pos-body']; $end = $part['ending-pos-body']; fseek($this->stream, $start, SEEK_SET); $len = $end - $start; $written = 0; $write = 2028; $body = ''; while ($written < $len) { if (($written + $write < $len)) { $write = $len - $written; } $part = fread($this->stream, $write); fwrite($temp_fp, $this->decode($part, $encoding)); $written += $write; } } else if ($this->data) { $attachment = $this->decode($this->getPartBodyFromText($part), $encoding); fwrite($temp_fp, $attachment, strlen($attachment)); } fseek($temp_fp, 0, SEEK_SET); } else { throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.'); return false; } return $temp_fp; } /** * Decode the string depending on encoding type. * @return String the decoded string. * @param $encodedString The string in its original encoded state. * @param $encodingType The encoding type from the Content-Transfer-Encoding header of the part. */ protected function decode($encodedString, $encodingType) { if (strtolower($encodingType) == 'base64') { return base64_decode($encodedString); } else if (strtolower($encodingType) == 'quoted-printable') { return quoted_printable_decode($encodedString); } else { return $encodedString; } } /** * Copied from PEAR Mail_Mime class * http://pear.php.net/manual/en/package.mail.mail-mimedecode.php * http://svn.php.net/viewvc/pear/packages/Mail_Mime/trunk/mimeDecode.php?view=markup * * LICENSE: This LICENSE is in the BSD license style. * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org> * Copyright (c) 2003-2006, PEAR <pear-group@php.net> * All rights reserved. * * Uses imap_mime_header_decode() if available for faster decoding * * Given a header, this function will decode it * according to RFC2047. Probably not *exactly* * conformant, but it does pass all the given * examples (in RFC2047). * * @param string Input header value to decode * @return string Decoded header value * @access private */ private function mimeDecodeHeader($input) { // Use the faster impac_mime_header_decode function if it exists if (function_exists("imap_mime_header_decode")) { $parts = imap_mime_header_decode($input); $input = ""; for ($i=0; $i<count($parts); $i++) $input .= $parts[$i]->text; return $input; } // Remove white space between encoded-words $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input); // For each encoded-word... while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) { $encoded = $matches[1]; $charset = $matches[2]; $encoding = $matches[3]; $text = $matches[4]; switch (strtolower($encoding)) { case 'b': $text = base64_decode($text); break; case 'q': $text = str_replace('_', ' ', $text); preg_match_all('/=([a-f0-9]{2})/i', $text, $matches); foreach($matches[1] as $value) $text = str_replace('='.$value, chr(hexdec($value)), $text); break; } $input = str_replace($encoded, $text, $input); } return $input; } /** * $input can be a string or an array * @param string,array $input * @return string,array */ private function _decodeHeader($input) { if(is_array($input)) { $new = array(); foreach($input as $i) $new[] = $this->mimeDecodeHeader($i); return $new; } else return $this->mimeDecodeHeader($input); } }
rtdean93/engagepeeps
accounts/plugins/support_manager/vendors/mime_mail_parser/MimeMailParser.class.php
PHP
gpl-2.0
16,323
if (not gadgetHandler:IsSyncedCode()) then return end function gadget:GetInfo() return { name = "Typemap Options", desc = "Edit's the map's typemap at the start of the game.", author = "Google Frog", date = "Feb, 2010", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local terrainNameToIndex = {} local oldTerrain = {} local IMPASSIBLE_TERRAIN = 137 -- Hope that this does not conflict with any maps local NANOFRAMES_BLOCK = false -- Allows for LOS hax. local function Round(x) return math.floor((x + 4)/8)*8 end local function SetImpassibleTerrain(x1, z1, x2, z2) x1, z1, x2, z2 = Round(x1), Round(z1), Round(x2), Round(z2) -- Save old terrain for i = x1, x2, 8 do oldTerrain[i] = oldTerrain[i] or {} for j = z1, z2, 8 do if not oldTerrain[i][j] then local terrainType = Spring.GetGroundInfo(i, j) if terrainNameToIndex[terrainType] then oldTerrain[i][j] = terrainNameToIndex[terrainType] end end end end -- Override terrain for i = x1, x2, 8 do for j = z1, z2, 8 do Spring.SetMapSquareTerrainType(i, j, IMPASSIBLE_TERRAIN) end end end local function ResetTerrain(x1, z1, x2, z2) x1, z1, x2, z2 = Round(x1), Round(z1), Round(x2), Round(z2) for i = x1, x2, 8 do for j = z1, z2, 8 do Spring.SetMapSquareTerrainType(i, j, (oldTerrain[i] and oldTerrain[i][j]) or 0) end end end local function GetUnitBounds(unitID, unitDefID) local ud = UnitDefs[unitDefID] local ux,_,uz = Spring.GetUnitPosition(unitID, true) local xsize = ud.xsize*4 local zsize = ud.zsize*4 local minx = ux - xsize local minz = uz - zsize local maxx = ux + xsize - 8 local maxz = uz + zsize - 8 return minx, minz, maxx, maxz end local function CreateImpassibleFootprint(unitID, unitDefID) local minx, minz, maxx, maxz = GetUnitBounds(unitID, unitDefID) SetImpassibleTerrain(minx, minz, maxx, maxz) end local function DestroyImpassibleFootprint(unitID, unitDefID) local minx, minz, maxx, maxz = GetUnitBounds(unitID, unitDefID) ResetTerrain(minx, minz, maxx, maxz) end function gadget:UnitCreated(unitID, unitDefID) if NANOFRAMES_BLOCK and (Spring.Utilities.getMovetype(UnitDefs[unitDefID]) == 2) then local _, _, inBuild = Spring.GetUnitIsStunned(unitID) if inBuild then CreateImpassibleFootprint(unitID, unitDefID) end end end function gadget:UnitDestroyed(unitID, unitDefID) if NANOFRAMES_BLOCK and (Spring.Utilities.getMovetype(UnitDefs[unitDefID]) == 2) then DestroyImpassibleFootprint(unitID, unitDefID) end end function gadget:UnitFinished(unitID, unitDefID) if NANOFRAMES_BLOCK and (Spring.Utilities.getMovetype(UnitDefs[unitDefID]) == 2) then DestroyImpassibleFootprint(unitID, unitDefID) end end function gadget:Initialize() Spring.SetTerrainTypeData(IMPASSIBLE_TERRAIN, 0, 0, 0, 0) if (Spring.GetModOptions().typemapsetting == "1") then for i = 0, 255 do if i ~= IMPASSIBLE_TERRAIN then Spring.SetTerrainTypeData(i, 1, 1, 1, 1) end end else for i = 0, 255 do if i ~= IMPASSIBLE_TERRAIN then local name, _, t, k, h, s = Spring.GetTerrainTypeData(i) if name and not terrainNameToIndex[name] then terrainNameToIndex[name] = i end if not (t == k and k == h and h == s and t ~= 0) then Spring.SetTerrainTypeData(i, 1,1,1,1) end end end end end
Aquanim/Zero-K
LuaRules/Gadgets/typemap_options.lua
Lua
gpl-2.0
3,380
/* * @(#)FFileTag.java * * Copyright 2004 Java Frame Studio Corporation. * All Rights Reserved. * */ package org.mo.web.tag.page; import org.mo.com.lang.FFatalError; import org.mo.com.lang.RString; import org.mo.web.protocol.context.SPageItem; import org.mo.web.tag.base.FBaseFileTag; /** * <T>下拉列表标签</T> * <P>当格式化方式为指定时,格式化为HTML代码</P> * * @author MAOCY * @version 1.00 - 2008/08/05 CREATE BY MAOCY * @version 1.01 - 2009/01/05 UPDATE BY YANGH */ public class FFileTag extends FBaseFileTag { @Override public int onEnd(){ /// 返回执行结果 return EVAL_PAGE; } /** * <T>开始标签逻辑。</T> * * @return 逻辑执行后的状态 */ @Override public int onStart(){ /// 获得数据源的值 SPageItem item = _context.parseItem(_source); String name = RString.nvl(_name, item.name); if(RString.isEmpty(name)){ throw new FFatalError("Item name is null. (source={0})", _source); } // 生成内容 _writer.append("<INPUT type='FILE'"); _writer.append(" name=\"", name, "\""); if(!RString.isEmpty(_size)){ _writer.append(" size=\"", _context.parseString(_size), "\""); } if(!RString.isEmpty(_width)){ appendStyle("width", _width); } if(!RString.isEmpty(_height)){ appendStyle("height", _height); } appendHtml(); _writer.append(">"); _writer.flush(); return 0; } }
favedit/MoPlatform
mo-4-web/src/web-java/org/mo/web/tag/page/FFileTag.java
Java
gpl-2.0
1,529
/** * */ package org.solinari.analyzer.engine; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Mapper.Context; /** * @author solinari * */ /* * 输出时无key,数据自己组织 */ public class SearchMapper extends TableMapper<Text, Text> { private String[] columnFamilys; private final static String SEARCH_FAMILY = "search.columnfamilys"; private final static String SEARCH_COLUMN_STRING = "search.column"; private static String getColumnString(String column){ return SEARCH_COLUMN_STRING + column; } /* * 通过自定义子类Oerride后对row中的数据进行处理:) */ public void dataProcesser(String row, Context context) throws IOException, InterruptedException{ /* *MapperBaseClass *do things you want in Override:) */ } /* * 用来从config中取得search的family和column */ private void parseSearchConf(Configuration conf){ columnFamilys = conf.getStrings(SEARCH_FAMILY); } @Override /* * (non-Javadoc) 每次取Hbase里一个row * @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN, org.apache.hadoop.mapreduce.Mapper.Context) */ protected void map(ImmutableBytesWritable key, Result value, Context context) throws InterruptedException, IOException { Configuration conf = context.getConfiguration(); parseSearchConf(conf); int size = columnFamilys.length; for (int i=0; i<size; i++){ String familyString = columnFamilys[i]; String[] columns = conf.getStrings(getColumnString(familyString)); byte[] family = Bytes.toBytes(familyString); for (int j=0; j<columns.length; j++){ byte[] column = Bytes.toBytes(columns[j]); String searchResult = Text.decode(value.getValue(family, column)); dataProcesser(searchResult, context); //注意添加context的output 用于其他地方的分析 } } } }
PersonalBigDataAnalyticsTeam/myPersonalBusiness
src/org/solinari/analyzer/engine/SearchMapper.java
Java
gpl-2.0
2,124
<?php /** * Copyright 2019 Google LLC * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. */ namespace Drupal\customizer\EventSubscriber; use Drupal\customizer\CustomizerInterface; use Drupal\Core\Config\ConfigCrudEvent; use Drupal\Core\Config\ConfigEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * An event subscriber to re-create stylesheet when config is updated. */ class ConfigEventsSubscriber implements EventSubscriberInterface { /** * The customizer service. * * @var \Drupal\customizer\CustomizerInterface */ protected $customizer; /** * ConfigEventsSubscriber constructor. * * @param \Drupal\customizer\CustomizerInterface $customizer * The customizer service. */ public function __construct(CustomizerInterface $customizer) { $this->customizer = $customizer; } /** * Re-creates stylesheet for theme when config is updated. * * @param \Drupal\Core\Config\ConfigCrudEvent $event * The config event. */ public function onSave(ConfigCrudEvent $event) { if (preg_match('/^customizer\.theme\.([^\.]*)$/', $event->getConfig()->getName(), $matches)) { $this->customizer->updateStylesheetForTheme($matches[1]); } } /** * Removes stylesheet for theme when config is deleted. * * @param \Drupal\Core\Config\ConfigCrudEvent $event * The config event. */ public function onDelete(ConfigCrudEvent $event) { if (preg_match('/^customizer\.theme\.([^\.]*)$/', $event->getConfig()->getName(), $matches)) { $this->customizer->deleteStylesheetForTheme($matches[1]); } } /** * {@inheritdoc} */ public static function getSubscribedEvents() { $events[ConfigEvents::SAVE][] = ['onSave']; $events[ConfigEvents::DELETE][] = ['onDelete']; return $events; } }
apigee/customizer-drupal
src/EventSubscriber/ConfigEventsSubscriber.php
PHP
gpl-2.0
2,431
<?php /** * Part of Component Akquickicons files. * * @copyright Copyright (C) 2014 Asikart. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; include_once JPATH_LIBRARIES . '/windwalker/src/init.php'; JForm::addFieldPath(WINDWALKER_SOURCE . '/Form/Fields'); JFormHelper::loadFieldClass('Modal'); /** * Supports a modal picker. */ class JFormFieldPlugin_Modal extends JFormFieldModal { /** * The form field type. * * @var string * @since 1.6 */ protected $type = 'Plugin_Modal'; /** * List name. * * @var string */ protected $view_list = 'plugins'; /** * Item name. * * @var string */ protected $view_item = 'plugin'; /** * Extension name, eg: com_content. * * @var string */ protected $extension = 'com_akquickicons'; }
asukademy/akblog
administrator/components/com_akquickicons/model/field/plugin/modal.php
PHP
gpl-2.0
880
/** * @file resources/resource.c * @brief Functions for working with LCFG resources * @author Stephen Quinney <squinney@inf.ed.ac.uk> * @copyright 2014-2017 University of Edinburgh. All rights reserved. This project is released under the GNU Public License version 2. * $Date: 2018-10-26 09:31:35 +0100 (Fri, 26 Oct 2018) $ * $Revision: 35012 $ */ #define _GNU_SOURCE /* for asprintf */ #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <assert.h> #include "derivation.h" #include "context.h" #include "resources.h" #include "utils.h" /* The list of resource type names MUST match the ordering of the LCFGResourceType enum. */ static const char * lcfgresource_type_names[] = { "string", "integer", "boolean", "list", "publish", "subscribe" }; /** * @brief Create and initialise a new resource * * Creates a new @c LCFGResource and initialises the parameters to the * default values. * * If the memory allocation for the new structure is not successful * the @c exit() function will be called with a non-zero value. * * The reference count for the structure is initialised to 1. To avoid * memory leaks, when it is no longer required the * @c lcfgresource_relinquish() function should be called. * * @return Pointer to new @c LCFGResource * */ LCFGResource * lcfgresource_new(void) { LCFGResource * res = malloc( sizeof(LCFGResource) ); if ( res == NULL ) { perror( "Failed to allocate memory for LCFG resource" ); exit(EXIT_FAILURE); } /* Set default values */ res->name = NULL; res->value = NULL; res->type = LCFG_RESOURCE_DEFAULT_TYPE; res->template = NULL; res->context = NULL; res->derivation = NULL; res->comment = NULL; res->priority = LCFG_RESOURCE_DEFAULT_PRIORITY; res->_refcount = 1; return res; } /** * @brief Clone the resource * * Creates a new @c LCFGResource and copies the values of the * parameters from the specified resource. The values for the * parameters are copied (e.g. strings are duplicated using * @c strdup() ) so that a later change to a parameter in the source * resource does not affect the new clone resource. * * If the memory allocation for the new structure is not successful * the @c exit() function will be called with a non-zero value. * * @param[in] res Pointer to @c LCFGResource to be cloned. * * @return Pointer to new @c LCFGResource or @c NULL if copy fails. * */ LCFGResource * lcfgresource_clone(const LCFGResource * res) { assert( res != NULL ); LCFGResource * clone = lcfgresource_new(); if ( clone == NULL ) return NULL; /* To simplify memory management the string attributes are duplicated. */ bool ok = true; if ( !isempty(res->name) ) { char * new_name = strdup(res->name); ok = lcfgresource_set_name( clone, new_name ); if ( !ok ) free(new_name); } clone->type = res->type; if ( ok && !isempty(res->value) ) { char * new_value = strdup(res->value); ok = lcfgresource_set_value( clone, new_value ); if ( !ok ) free(new_value); } /* The template is a pointer to an LCFGTemplate so this needs to be cloned separately. The simplest approach is to serialise it into a string and then recreate a new structure using that as the source string. */ if ( ok && lcfgresource_has_template(res) ) { char * tmpl_as_str = NULL; size_t tmpl_size = 0; ssize_t tmpl_len = lcfgresource_get_template_as_string( res, LCFG_OPT_NONE, &tmpl_as_str, &tmpl_size ); if ( tmpl_len > 0 ) { char * tmpl_msg = NULL; ok = lcfgresource_set_template_as_string( clone, tmpl_as_str, &tmpl_msg ); /* Should be impossible to get an error since the template will have been previously validated so just throw away any error message */ free(tmpl_msg); } free(tmpl_as_str); } clone->priority = res->priority; if ( ok && !isempty(res->comment) ) { char * new_comment = strdup(res->comment); ok = lcfgresource_set_comment( clone, new_comment ); if ( !ok ) free(new_comment); } if ( ok && !isempty(res->context) ) { char * new_context = strdup(res->context); ok = lcfgresource_set_context( clone, new_context ); if ( !ok ) free(new_context); } /* Original and clone resources will share the derivation list */ if ( ok && lcfgresource_has_derivation(res) ) ok = lcfgresource_set_derivation( clone, lcfgresource_get_derivation(res)); /* Cloning should never fail */ if ( !ok ) { lcfgresource_destroy(clone); clone = NULL; } return clone; } /** * @brief Acquire reference to resource * * This is used to record a reference to the @c LCFGResource, it * does this by simply incrementing the reference count. * * To avoid memory leaks, once the reference to the structure is no * longer required the @c lcfgresource_relinquish() function should be * called. * * @param[in] res Pointer to @c LCFGResource * */ void lcfgresource_acquire( LCFGResource * res ) { assert( res != NULL ); res->_refcount += 1; } /** * @brief Release reference to resource * * This is used to release a reference to the @c LCFGResource, * it does this by simply decrementing the reference count. If the * reference count reaches zero the @c lcfgresource_destroy() function * will be called to clean up the memory associated with the structure. * * If the value of the pointer passed in is @c NULL then the function * has no affect. This means it is safe to call with a pointer to a * resource which has already been destroyed (or potentially was never * created). * * @param[in] res Pointer to @c LCFGResource * */ void lcfgresource_relinquish( LCFGResource * res ) { if ( res == NULL ) return; if ( res->_refcount > 0 ) res->_refcount -= 1; if ( res->_refcount == 0 ) lcfgresource_destroy(res); } /** * @brief Destroy the resource * * When the specified @c LCFGResource is no longer required this will * free all associated memory. There is support for reference counting * so typically the @c lcfgresource_relinquish() function should be used. * * This will call @c free() on each parameter of the structure (or * @c lcfgtemplate_destroy() for the template parameter ) and then set each * value to be @c NULL. * * If the value of the pointer passed in is @c NULL then the function * has no affect. This means it is safe to call with a pointer to a * resource which has already been destroyed (or potentially was never * created). * * @param[in] res Pointer to @c LCFGResource to be destroyed. * */ void lcfgresource_destroy(LCFGResource * res) { if ( res == NULL ) return; free(res->name); res->name = NULL; free(res->value); res->value = NULL; lcfgtemplate_destroy(res->template); res->template = NULL; free(res->context); res->context = NULL; lcfgderivlist_relinquish(res->derivation); res->derivation = NULL; free(res->comment); res->comment = NULL; free(res); res = NULL; } /* Names */ /** * @brief Check if a string is a valid LCFG resource name * * Checks the contents of a specified string against the specification * for an LCFG resource name. * * An LCFG resource name MUST be at least one character in length. The * first character MUST be in the class @c [A-Za-z] and all other * characters MUST be in the class @c [A-Za-z0-9_]. This means they * are safe to use as variable names for languages such as bash. * * @param[in] name String to be tested * * @return boolean which indicates if string is a valid resource name * */ bool lcfgresource_valid_name( const char * name ) { /* MUST NOT be a NULL. MUST have non-zero length. First character MUST be in [A-Za-z] set. */ bool valid = ( !isempty(name) && isalpha(*name) ); /* All other characters MUST be in [A-Za-z0-9_] set */ const char * ptr; for ( ptr = name + 1; valid && *ptr != '\0'; ptr++ ) if ( !isword(*ptr) ) valid = false; return valid; } /** * @brief Check validity of resource * * Checks the specified @c LCFGResource to ensure that it is valid. For a * resource to be considered valid the pointer must not be @c NULL and * the resource must have a name. * * @param[in] res Pointer to an @c LCFGResource * * @return Boolean which indicates if resource is valid * */ bool lcfgresource_is_valid( const LCFGResource * res ) { return ( res != NULL && !isempty(res->name) ); } /** * @brief Check if the resource has a name * * Checks if the specified @c LCFGResource currently has a value set * for the @e name attribute. Although a name is required for an LCFG * resource to be valid it is possible for the value of the name to be * set to @c NULL when the structure is first created. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean which indicates if a resource has a name * */ bool lcfgresource_has_name( const LCFGResource * res ) { assert( res != NULL ); return !isempty(res->name); } /** * @brief Get the name for the resource * * This returns the value of the @e name parameter for the * @c LCFGResource. If the resource does not currently have a @e * name then the pointer returned will be @c NULL. * * It is important to note that this is @b NOT a copy of the string, * changing the returned string will modify the @e name of the * resource. * * @param[in] res Pointer to an @c LCFGResource * * @return The @e name for the resource (possibly @c NULL). */ const char * lcfgresource_get_name( const LCFGResource * res ) { assert( res != NULL ); return res->name; } /** * @brief Set the name for the resource * * Sets the value of the @e name parameter for the @c LCFGResource * to that specified. It is important to note that this does * @b NOT take a copy of the string. Furthermore, once the value is set * the resource assumes "ownership", the memory will be freed if the * name is further modified or the resource is destroyed. * * Before changing the value of the @e name to be the new string it * will be validated using the @c lcfgresource_valid_name() * function. If the new string is not valid then no change will occur, * the @c errno will be set to @c EINVAL and the function will return * a @c false value. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_name String which is the new name * * @return boolean indicating success * */ bool lcfgresource_set_name( LCFGResource * res, char * new_name ) { assert( res != NULL ); bool ok = false; if ( lcfgresource_valid_name(new_name) ) { free(res->name); res->name = new_name; ok = true; } else { errno = EINVAL; } return ok; } /* Types */ /** * @brief Get the type for the resource as an integer * * This returns the value of the type parameter for the * @c LCFGResource. * * An LCFG resource will be one of several types (e.g. string, * integer, boolean, list) which controls what validation is done when * a value is set. Internally the type is stored as an integer, see * the @c LCFGResourceType enum for the full list of supported * values. If you require the type as a string then use @c * lcfgresource_get_type_as_string() * * @param[in] res Pointer to an @c LCFGResource * * @return The type of the resource as an integer */ LCFGResourceType lcfgresource_get_type( const LCFGResource * res ) { assert( res != NULL ); return res->type; } /** * @brief Set the type of the resource * * Changes the type of the resource to that specified. The type of the * resource controls what validation will be done when a new value is * set. By default a resource is considered to be a "string" which * means that any value is permitted. Changing the type to something * like "integer" or "boolean" will thus restrict the valid values. * If a resource already has a value then it is only possible to * change the type to something more restrictive if the value is valid * for the new type. For instance, if a resource of type "string" has * a value of "foo" the type could be changed to "list" but not * "integer". If it is not possible to change the type for a resource * then @c errno will be set to @c EINVAL and this function will * return false. * * To set the type for a resource using a string rather than an * integer use @c lcfgresource_set_type_as_string() * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_type The new resource type as an integer * * @return boolean indicating success */ bool lcfgresource_set_type( LCFGResource * res, LCFGResourceType new_type ) { assert( res != NULL ); if ( res->type == new_type ) return true; /* no-op */ /* If the type is to be changed then there either must not be an existing value or that value must be compatible with the new type. For example, if the current value is "fish" and the requested new type is "integer" then that change is illegal. */ bool ok = false; if ( res->value == NULL || lcfgresource_valid_value_for_type( new_type, res->value ) ) { res->type = new_type; ok = true; } else { errno = EINVAL; } return ok; } /** * @brief Set the type of the resource to the default * * Sets the value of the @e type parameter for the @c LCFGResource to * the value of @c LCFG_RESOURCE_DEFAULT_TYPE (which is @c string). If * the resource type was not previously @c string then any templates * or comments associated with the previous type will be erased. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating success */ bool lcfgresource_set_type_default( LCFGResource * res ) { assert( res != NULL ); bool ok = true; if ( lcfgresource_get_type(res) != LCFG_RESOURCE_DEFAULT_TYPE ) { ok = lcfgresource_set_type( res, LCFG_RESOURCE_DEFAULT_TYPE ); /* Clear any previous templates and comments */ if (ok) { bool tmpl_ok = lcfgresource_set_template( res, NULL ); bool cmt_ok = lcfgresource_set_comment( res, NULL ); if ( !tmpl_ok || !cmt_ok ) ok = false; } } return ok; } /** * @brief Set the type of the resource as a string * * Parses the specified type string and sets the type for the resource * (and optionally sets the comment and template parameters). The type * is actually set using @c lcfgresource_set_type() so see that * function for further details. * * If the specified type string is NULL or empty then the type * defaults to "string". Otherwise the type will be taken from the * initial part of the string (if the first character is the LCFG * marker '%%' (percent) it will be ignored). * * Currently supported types are: * + string * + integer * + boolean * + list * + publish * + subscribe * * The "publish" and "subscribe" types are effectively string * sub-types and are only relevant for spanning maps. If any other * unsupported type is specified then @c errno will be set to @c * EINVAL and the function will return false. * * Further to the type of the resource a comment may be specified. Any * comment will be enclosed in brackets - '(' .. ')'. Typically these * only appear with string resources which have additional validation * specified by the schema author, the comment then describes the * expected format of the value for the resource. For example a type * specification for a string resource might be `%%string (MAC * address)`. * * If a resource is a list then there may also be a set of templates * specified. These follow a ':' (colon) separator and are a * space-separated list of templates of the form @c foo_$_$ where the * '$' (dollar) symbols are placeholders which are used to be build the * names of sub-resources given the "tags" in the resource value. For * example, a type specification for a list resource might be `%%list: * foo_$_$ bar_$_$` * * @param[in] res Pointer to an @c LCFGResource * @param[in] type_str The new type as a string * @param[out] msg Pointer to any diagnostic messages * * @return boolean indicating success */ bool lcfgresource_set_type_as_string( LCFGResource * res, const char * type_str, char ** msg ) { assert( res != NULL ); bool ok = true; /* If the new type string is empty then the resource is considered to be the default string type */ LCFGResourceType new_type = LCFG_RESOURCE_DEFAULT_TYPE; /* Spin past any leading whitespace */ if ( !isempty(type_str) ) while ( *type_str != '\0' && isspace(*type_str) ) type_str++; if ( !isempty(type_str) ) { /* If the type string begins with the type symbol character '%' (percent) then step past it and start the subsequent comparisons from the next char */ if ( *type_str == LCFG_RESOURCE_SYMBOL_TYPE ) type_str++; /* It is intentional that only the start of the type string is compared. The type string could potentially contain more than we need (e.g. "list: foo_$ bar_$") */ if ( strncmp( type_str, "integer", 7 ) == 0 ) { new_type = LCFG_RESOURCE_TYPE_INTEGER; } else if ( strncmp( type_str, "boolean", 7 ) == 0 ) { new_type = LCFG_RESOURCE_TYPE_BOOLEAN; } else if ( strncmp( type_str, "list", 4 ) == 0 ) { new_type = LCFG_RESOURCE_TYPE_LIST; } else if ( strncmp( type_str, "publish", 7 ) == 0 ) { new_type = LCFG_RESOURCE_TYPE_PUBLISH; } else if ( strncmp( type_str, "subscribe", 9 ) == 0 ) { new_type = LCFG_RESOURCE_TYPE_SUBSCRIBE; } else if ( strncmp( type_str, "string", 6 ) != 0 ) { errno = EINVAL; lcfgutils_build_message( msg, "invalid resource type '%s'", type_str ); ok = false; } } if (ok) ok = lcfgresource_set_type( res, new_type ); /* Check if there is a comment string for the resource. This would be after the type string and enclosed in brackets - ( ) */ const char * posn = type_str; if ( ok && !isempty(type_str) ) { const char * comment_start = strchr( type_str, '(' ); if ( comment_start != NULL ) { const char * comment_end = strchr( comment_start, ')' ); if ( comment_end != NULL ) { posn = comment_end + 1; if ( comment_end - comment_start > 1 ) { char * comment = strndup( comment_start + 1, comment_end - 1 - comment_start ); ok = lcfgresource_set_comment( res, comment ); if ( !ok ) free(comment); } } } } /* List types might also have templates */ if ( ok && new_type == LCFG_RESOURCE_TYPE_LIST ) { const char * tmpl_start = strstr( posn, ": " ); if ( tmpl_start != NULL ) { tmpl_start += 2; /* Spin past any further whitespace */ while( *tmpl_start != '\0' && isspace(*tmpl_start) ) tmpl_start++; /* A list type might be declared like "list: " (i.e. with no templates) in which case it is a simple list of tags. */ if ( *tmpl_start != '\0' ) ok = lcfgresource_set_template_as_string( res, tmpl_start, msg ); } } return ok; } /** * @brief Check if the resource is a string * * Checks if the type parameter for the @c LCFGResource is one of: * * - @c LCFG_RESOURCE_TYPE_STRING * - @c LCFG_RESOURCE_TYPE_SUBSCRIBE * - @c LCFG_RESOURCE_TYPE_PUBLISH * * Since "publish" and "subscribe" resources can hold any value which * is to be mapped between profiles they are considered to be * string-like for most operations. This does mean that sometimes * extra care must be taken to handle them correctly. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if string-type */ bool lcfgresource_is_string( const LCFGResource * res ) { assert( res != NULL ); return ( res->type == LCFG_RESOURCE_TYPE_STRING || res->type == LCFG_RESOURCE_TYPE_SUBSCRIBE || res->type == LCFG_RESOURCE_TYPE_PUBLISH ); } /** * @brief Check if the resource is a integer * * Checks if the type parameter for the @c LCFGResource is * @c LCFG_RESOURCE_TYPE_INTEGER. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if integer-type */ bool lcfgresource_is_integer( const LCFGResource * res ) { assert( res != NULL ); return ( lcfgresource_get_type(res) == LCFG_RESOURCE_TYPE_INTEGER ); } /** * @brief Check if the resource is a boolean * * Checks if the type parameter for the @c LCFGResource is * @c LCFG_RESOURCE_TYPE_BOOLEAN. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if boolean-type */ bool lcfgresource_is_boolean( const LCFGResource * res ) { assert( res != NULL ); return ( lcfgresource_get_type(res) == LCFG_RESOURCE_TYPE_BOOLEAN ); } /** * @brief Check if the resource is a list * * Checks if the type parameter for the @c LCFGResource is * @c LCFG_RESOURCE_TYPE_LIST. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if list-type */ bool lcfgresource_is_list( const LCFGResource * res ) { assert( res != NULL ); return ( lcfgresource_get_type(res) == LCFG_RESOURCE_TYPE_LIST ); } /** * @brief Check if the resource value is true * * Checks if the value parameter for the @c LCFGResource can be * considered to be "true". This uses similar rules to Perl. For * resources of the boolean type the canonical value of "yes" is * considered to be true and anything else is false. For all other * types of resource if the value is @c NULL, "" (empty string), or "0" * (zero) it will considered to be false and otherwise true. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if the value is true */ bool lcfgresource_is_true( const LCFGResource * res ) { assert( res != NULL ); bool is_true = false; const char * value = res->value; if ( !isempty(value) ) { if ( lcfgresource_is_boolean(res) ) is_true = ( strcmp( value, "yes" ) == 0 ); else is_true = ( strcmp( value, "0" ) != 0 ); } return is_true; } /** * @brief Get the resource type as a string * * Generates a new LCFG type string based on the values for the @e * type, @e comment and @e template parameters. * * This converts the integer @e type parameter for the resource into * an LCFG type string which is formatted as described in @c * lcfgresource_set_type_as_string(). For a list resource type the * templates section can be disabled by specifying the @c * LCFG_OPT_NOTEMPLATES option. * * @param[in] res Pointer to an @c LCFGResource * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return New string containing resource type information (call @c free() when no longer required) * */ ssize_t lcfgresource_get_type_as_string( const LCFGResource * res, LCFGOption options, char ** result, size_t * size ) { assert( res != NULL ); const char * type_string = lcfgresource_type_names[res->type]; size_t type_len = strlen(type_string); size_t new_len = type_len; const char * comment = res->comment; size_t comment_len = 0; if ( !isempty(comment) ) { comment_len = strlen(comment); new_len += ( comment_len + 2 ); /* + 2 for enclosing ( ) */ } /* A list resource might have a template */ char * tmpl_as_str = NULL; ssize_t tmpl_len = 0; if ( lcfgresource_is_list(res) && !(options&LCFG_OPT_NOTEMPLATES) ) { /* Always adds the ': ' separator even when there are no templates */ new_len += 2; /* +2 for ': ' separator */ if ( lcfgresource_has_template(res) ) { size_t tmpl_size = 0; tmpl_len = lcfgresource_get_template_as_string( res, LCFG_OPT_NONE, &tmpl_as_str, &tmpl_size ); if ( tmpl_len > 0 ) /* Avoid adding negative number */ new_len += tmpl_len; } } if ( options&LCFG_OPT_NEWLINE ) new_len += 1; /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG type string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ char * to = *result; to = stpncpy( to, type_string, type_len ); if ( comment_len > 0 ) { *to = '('; to++; to = stpncpy( to, comment, comment_len ); *to = ')'; to++; } if ( lcfgresource_is_list(res) && !(options&LCFG_OPT_NOTEMPLATES) ) { to = stpncpy( to, ": ", 2 ); if ( tmpl_len > 0 ) to = stpncpy( to, tmpl_as_str, tmpl_len ); } free(tmpl_as_str); /* Optional newline at the end of the string */ if ( options&LCFG_OPT_NEWLINE ) to = stpncpy( to, "\n", 1 ); *to = '\0'; assert( ( *result + new_len ) == to ); return new_len; } /* Templates */ /** * @brief Check if the resource has a set of templates * * Checks if the specified @c LCFGResource currently has a value set * for the template attribute. This is only relevant for list * resources. The templates are used to convert the list of LCFG tags * into the names of associated sub-resources. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean which indicates if a resource has a template * */ bool lcfgresource_has_template( const LCFGResource * res ) { assert( res != NULL ); return ( res->template != NULL ); } /** * @brief Get the template for the resource * * This returns the value of the @e template parameter for the * @c LCFGResource. If the resource does not currently have a @e * template then the pointer returned will be @c NULL. * * Templates for a list resource are stored as a linked-list using the * @c LCFGTemplate. To get them as a formatted string use the * @c lcfgresource_get_template_as_string() function. * * @param[in] res Pointer to an @c LCFGResource * * @return A pointer to an @c LCFGTemplate (or a @c NULL value). */ LCFGTemplate * lcfgresource_get_template( const LCFGResource * res ) { assert( res != NULL ); return res->template; } /** * @brief Get the template for the resource as a string * * If the @c LCFGResource has a value for the @e template attribute it * will be transformed into a new string using the @c * lcfgtemplate_to_string() function. If the resource does not have a * template then zero will be returned and the buffer will not have * been modified. * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to an @c LCFGResource * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_get_template_as_string( const LCFGResource * res, LCFGOption options, char ** result, size_t * size ) { assert( res != NULL ); if ( lcfgresource_has_template(res) ) { return lcfgtemplate_to_string( lcfgresource_get_template(res), NULL, options, result, size ); } else { return 0; } } /** * @brief Set the template for the resource. * * Sets the specified @c LCFGTemplate as the value for the @e * template attribute in the @c LCFGResource. * * The use of templates is only relevant for list resources. They are * used to transform a list of tags into the names of associated * sub-resources. * * Usually the template will be specified as a string which needs to * be converted into an @c LCFGTemplate, in that situation use * the @c lcfgresource_set_template_as_string() function. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_tmpl Pointer to an @c LCFGTemplate * * @return boolean indicating success * */ bool lcfgresource_set_template( LCFGResource * res, LCFGTemplate * new_tmpl ) { assert( res != NULL ); /* Allow setting the template to NULL which is basically an "unset" */ bool ok = false; if ( new_tmpl == NULL || lcfgtemplate_is_valid(new_tmpl) ) { lcfgtemplate_destroy(res->template); res->template = new_tmpl; ok = true; } else { errno = EINVAL; } return ok; } /** * @brief Set the template for a resource as a string. * * Converts the specified string into a linked-list of @c LCFGTemplate * structures. The pointer to the head of the new template list is set as * the value for the @e template attribute in the @c LCFGResource. * * The templates string is expected to be a space-separated list of * parts of the form @c foo_$_$ where the '$' (dollar) placeholders * are replaced with tag names when the resource names are * generated. The string is parsed using the @c * lcfgtemplate_from_string() function, see that for full details. If * the string cannot be parsed then @c errno will be set to @c EINVAL * and a false value will be returned. * * The use of templates is only relevant for list resources. They are * used to transform a list of tags into the names of associated * sub-resources. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_tmpl_str String of LCFG resource templates * @param[out] msg Pointer to any diagnostic messages * * @return boolean indicating success * */ bool lcfgresource_set_template_as_string( LCFGResource * res, const char * new_tmpl_str, char ** msg ) { assert( res != NULL ); if ( new_tmpl_str == NULL ) { errno = EINVAL; return false; } if ( *new_tmpl_str == '\0' ) return lcfgresource_set_template( res, NULL ); LCFGTemplate * new_template = NULL; char * parse_msg = NULL; LCFGStatus rc = lcfgtemplate_from_string( new_tmpl_str, &new_template, &parse_msg ); bool ok = ( rc == LCFG_STATUS_OK && new_template != NULL ); if (ok) ok = lcfgresource_set_template( res, new_template ); if (!ok) { lcfgutils_build_message( msg, "Invalid template '%s': %s", new_tmpl_str, ( parse_msg != NULL ? parse_msg : "unknown error" ) ); lcfgtemplate_destroy(new_template); errno = EINVAL; } free(parse_msg); return ok; } /* Values */ /** * @brief Check if the resource has a value * * Checks to see if the @e value parameter for the @c LCFGResource * is considered to be a non-empty value. * * @param[in] res Pointer to an LCFGResource * * @return A boolean which indicates if the resource has a non-empty value */ bool lcfgresource_has_value( const LCFGResource * res ) { assert( res != NULL ); return !isempty(res->value); } /** * @brief Get the value for the resource * * This returns the value of the @e value parameter for the * @c LCFGResource. If the resource does not currently have a * @e value then the returned pointer will be @c NULL. * * It is important to note that this is NOT a copy of the string, * changing the returned string will modify the @e value for the * resource. * * @param[in] res Pointer to an @c LCFGResource * * @return The @e value string for the resource (possibly NULL). */ const char * lcfgresource_get_value( const LCFGResource * res ) { assert( res != NULL ); return res->value; } static const char unsafe_chars[] = "\r\n&"; /** * Test if the resource values needs encoding in status files * * This can be used to test if the @e value for the resource contains * any characters which need to be encoded before insertion into @e * status and @e hold files. This checks for significant whitespace * (e.g. newlines and carriage returns) as well as the @c '&' * (ampersand) character which is used when encoding characters. * * @param[in] res Pointer to an @c LCFGResource * * @return Boolean which indicates if encoding is required * */ bool lcfgresource_value_needs_encode( const LCFGResource * res ) { assert( res != NULL ); if ( !lcfgresource_has_value(res) ) return false; bool needs_encode = false; const char * value = lcfgresource_get_value(res); const char * ptr; for ( ptr = value; *ptr != '\0'; ptr++ ) { if ( strchr( unsafe_chars, *ptr ) ) { needs_encode = true; break; } } return needs_encode; } /** * @brief Get an encoded version of the value for the resource * * Generates a new string which is an encoded version of the @e value * parameter for the @c LCFGResource. The encoded value is made * safe for use in LCFG status files by escaping newline and * carriage-return characters (and also ampersands). Note that this is * NOT a general encoding function and it does not make the value safe * for direct inclusion in XML or HTML. * * If the current value for the @e value parameter is @c NULL then * this function will return a @c NULL value. * * When the returned string is no longer required the memory must be * freed. * * @param[in] res Pointer to an @c LCFGResource * * @return The encoded @e value string for the resource (call @c free() when no longer required) or a @c NULL value */ char * lcfgresource_enc_value( const LCFGResource * res ) { assert( res != NULL ); const char * value = lcfgresource_get_value(res); if ( value == NULL ) return NULL; size_t value_len = strlen(value); /* The following characters need to be encoded to ensure they do not corrupt the format of status files. */ static const char cr[] = "&#xD;"; /* \r */ static const char lf[] = "&#xA;"; /* \n */ static const char amp[] = "&#x26;"; /* & */ static const size_t cr_len = sizeof(cr) - 1; static const size_t lf_len = sizeof(lf) - 1; static const size_t amp_len = sizeof(amp) - 1; size_t extend = 0; const char * ptr; for ( ptr=value; *ptr!='\0'; ptr++ ) { switch(*ptr) { case '\r': extend += ( cr_len - 1 ); break; case '\n': extend += ( lf_len - 1 ); break; case '&': extend += ( amp_len - 1 ); break; } } if ( extend == 0 ) return strdup(value); /* Some characters need encoding */ size_t new_len = value_len + extend; char * enc_value = calloc( ( new_len + 1 ), sizeof(char) ); if ( enc_value == NULL ) { perror("Failed to allocate memory for LCFG resource value"); exit(EXIT_FAILURE); } char * to = enc_value; for ( ptr=value; *ptr!='\0'; ptr++ ) { switch(*ptr) { case '\r': to = stpncpy( to, cr, cr_len ); break; case '\n': to = stpncpy( to, lf, lf_len ); break; case '&': to = stpncpy( to, amp, amp_len ); break; default: *to = *ptr; to++; } } *to = '\0'; assert( ( enc_value + new_len ) == to ); return enc_value; } /** * @brief Check if a value is a valid boolean * * Checks whether the string contains a valid LCFG boolean * value. There are various acceptable forms for a value for a boolean * LCFG resource (see @c lcfgresource_canon_boolean() for details) but * only the empty string and "yes" are considered to be @e valid * boolean values. Anything else must be canonicalised from an * accepted form into the equivalent valid value. * * @param[in] value A string to be checked * * @return A boolean which indicates if the string contains a boolean */ bool lcfgresource_valid_boolean( const char * value ) { /* MUST NOT be NULL. MUST be empty string or "yes" */ return ( value != NULL && ( *value == '\0' || strcmp( value, "yes" ) == 0 ) ); } static char * valid_false_values[] = { "false", "no", "off", "0", "", NULL }; static char * valid_true_values[] = { "true", "yes", "on", "1", NULL }; /** * @brief Canonicalise a boolean value * * Converts various acceptable forms of the boolean value into the * equivalent valid forms. Input can be any of: * * + false, no, off, 0, "" * + true, yes, on, 1 * * the characters of the input string can be in any case (upper, lower * or mixed). The strings are canonicalised into "yes" for true values * and "" (empty string) for false values. * * A new string will be returned, the input will not be modified. When * no longer required the newly created string should be freed. If the * input cannot be canonicalised the function will return a @c NULL * value. * * @param[in] value The boolean value string to be canonicalised * * @return A new string (call @c free() when no longer required) or a @c NULL value if the input could not be canonicalised. */ char * lcfgresource_canon_boolean( const char * value ) { char * result = NULL; /* Nothing to do but return a copy of the value in most cases */ if ( lcfgresource_valid_boolean(value) ) { result = strdup(value); } else { /* Take a copy so that the string can be modified. Map a NULL onto an empty string (which will be considered as false). */ char * value2 = value != NULL ? strdup(value) : strdup(""); if ( value2 == NULL ) { perror( "Failed to allocate memory for LCFG resource value" ); exit(EXIT_FAILURE); } /* Lower case the value for comparison */ char * ptr; for ( ptr = value2; *ptr != '\0'; ptr++ ) *ptr = tolower(*ptr); char ** val_ptr; bool canon_value; bool valid = false; /* Compare with true values */ for ( val_ptr = valid_true_values; *val_ptr != NULL; val_ptr++ ) { if ( strcmp( value2, *val_ptr ) == 0 ) { valid = true; canon_value = true; break; } } /* If not found compare with false values */ if ( !valid ) { for ( val_ptr = valid_false_values; *val_ptr != NULL; val_ptr++ ) { if ( strcmp( value2, *val_ptr ) == 0 ) { valid = true; canon_value = false; break; } } } if (valid) { if (canon_value) { result = strdup("yes"); } else { result = strdup(""); } } free(value2); } return result; } /** * @brief Check if a value is a valid integer * * Checks whether the string contains a valid LCFG integer value. The * string may begin with a negative sign '-', otherwise all characters * MUST be digits - @c [0-9]. * * @param[in] value A string to be checked * * @return A boolean which indicates if the string contains an integer */ bool lcfgresource_valid_integer( const char * value ) { /* MUST NOT be a NULL. */ if ( value == NULL ) return false; /* First character may be a negative-sign, if so walk past */ const char * ptr = value; if ( *ptr == '-' ) ptr++; /* MUST be further characters. MUST not have leading zeroes unless it is just "0" */ bool valid = ( *ptr != '\0' && ( *ptr != '0' || strcmp( ptr, "0" ) == 0 ) ); /* All other characters MUST be digits */ for ( ; valid && *ptr != '\0'; ptr++ ) if ( !isdigit(*ptr) ) valid = false; return valid; } /** * @brief Check if a value is a valid list * * Checks whether the string contains a valid list of LCFG tags. An * LCFG tag is used to generate resource names along with a template, * consequently tags MUST only contain characters which are valid in * LCFG resource names (@c [A-Za-z0-9_]). Tags in a list are separated * using space characters. If any other characters are found the * string is not a valid tag list. * * @param[in] value A string to be checked * * @return A boolean which indicates if the string contains a list of tags */ bool lcfgresource_valid_list( const char * value ) { /* MUST NOT be a NULL */ bool valid = ( value != NULL ); /* Empty list is fine. Tags MUST be characters in [A-Za-z0-9_] set. Separators MUST be spaces */ const char * ptr; for ( ptr = value; valid && *ptr != '\0'; ptr++ ) if ( !isword(*ptr) && *ptr != ' ' ) valid = false; return valid; } /** * @brief Check if a value is valid for the type * * Checks whether a string contains a value which is valid for the * specified LCFG resource type. This will call the relevant * validation function for the specified type (e.g. @c * lcfgresource_valid_boolean), if there is one, and return the * result. If no validation function is available for the type this * will just return true. * * @param[in] type Integer LCFG resource type * @param[in] value A string to be checked * * @return A boolean which indicates if the string is valid for the type * */ bool lcfgresource_valid_value_for_type( LCFGResourceType type, const char * value ) { /* Check if the specified value is valid for the current type of the resource. */ if ( value == NULL ) return false; bool valid = true; switch(type) { case LCFG_RESOURCE_TYPE_INTEGER: valid = lcfgresource_valid_integer(value); break; case LCFG_RESOURCE_TYPE_BOOLEAN: valid = lcfgresource_valid_boolean(value); break; case LCFG_RESOURCE_TYPE_LIST: valid = lcfgresource_valid_list(value); break; case LCFG_RESOURCE_TYPE_STRING: case LCFG_RESOURCE_TYPE_PUBLISH: case LCFG_RESOURCE_TYPE_SUBSCRIBE: valid = true; break; } return valid; } /** * @brief Check if a value is valid for the resource * * It can often be useful to test the validity of a potential new * value for a resource before proceeding with further work. This * checks to see if the specified value is valid for the type of the * @c LCFGResource, this is done using the @c * lcfgresource_valid_value_for_type() function. * * @param[in] res Pointer to an @c LCFGResource * @param[in] value A string to be checked * * @return A boolean which indicates if the string is valid for the resource * */ bool lcfgresource_valid_value( const LCFGResource * res, const char * value ) { assert( res != NULL ); return lcfgresource_valid_value_for_type( lcfgresource_get_type(res), value ); } /** * @brief Set the value for the resource * * Sets the value of the @e value parameter for the @c LCFGResource * to that specified. It is important to note that this does * NOT take a copy of the string. Furthermore, once the value is set * the resource assumes "ownership", the memory will be freed if the * value is further modified or the resource is destroyed. * * Before changing the value of the @e value parameter to be the new * string it will be validated using the @c lcfgresource_valid_value() * function. If the new string is not valid then no change will occur, * the @c errno will be set to @c EINVAL and the function will return * a @c false value. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_value String which is the new value * * @return boolean indicating success * */ bool lcfgresource_set_value( LCFGResource * res, char * new_value ) { assert( res != NULL ); bool ok = false; if ( lcfgresource_valid_value( res, new_value ) ) { free(res->value); res->value = new_value; ok = true; } else { errno = EINVAL; } return ok; } /** * @brief Unset the value for the resource * * Sets the value for the @e value parameter of the @c LCFGResource * back to @c NULL and frees any memory associated with a * previous value. * * This is useful since it is not permitted to set the value for an * LCFG resource to be @c NULL via the @c lcfgresource_set_value * function. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating success * */ bool lcfgresource_unset_value( LCFGResource * res ) { assert( res != NULL ); free(res->value); res->value = NULL; return true; } /* Derivations */ /** * @brief Check if the resource has a derivation * * Checks if there is any derivation information stored in the * @c LCFGResource. * * Derivation information is typically a space-separated list of files * and line numbers where the resource value has been modified. * * @param[in] res Pointer to an @c LCFGResource * * @return Boolean which indicates if the resource has derivation information * */ bool lcfgresource_has_derivation( const LCFGResource * res ) { assert( res != NULL ); return ( res->derivation != NULL && !lcfgderivlist_is_empty(res->derivation)); } /** * @brief Get the derivation for the resource * * This returns the value of the @e derivation parameter for the @c * LCFGResource. This will be a pointer to an @c LCFGDerivationList * structure. If the resource does not currently have a @e derivation * then the pointer returned will be @c NULL. * * @param[in] res Pointer to an @c LCFGResource * * @return The @e derivation for the resource (possibly NULL). */ LCFGDerivationList * lcfgresource_get_derivation( const LCFGResource * res ) { assert( res != NULL ); return res->derivation; } /** * @brief Get the derivation for the resource as a string * * This returns the stringified value of the @e derivation parameter * for the @c LCFGResource. The serialisation is done using the @c * lcfgderivlist_to_string() function. If the resource does not * currently have a @e derivation then the pointer returned will be @c * NULL. * * This function uses a string buffer which may be pre-allocated if * necessary to improve efficiency. This makes it possible to reuse * the same buffer for generating many strings, this can be a huge * performance benefit. If the buffer is initially unallocated then it * MUST be set to @c NULL. The current size of the buffer must be * passed and should be specified as zero if the buffer is initially * unallocated. If the generated string would be too long for the * current buffer then it will be resized and the size parameter is * updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to an @c LCFGResource * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_get_derivation_as_string( const LCFGResource * res, LCFGOption options, char ** result, size_t * size ){ assert( res != NULL ); const LCFGDerivationList * drvlist = lcfgresource_get_derivation(res); return lcfgderivlist_to_string( drvlist, options, result, size ); } /** * @brief Get the length of the resource derivation string * * It is sometimes necessary to know the length of the derivation for * the @c LCFGResource as a string before it is actually stored. This * simply calls the @c lcfgderivlist_get_string_length() function on * the @c LCFGDerivationList structure for the resource. * * @param[in] res Pointer to an @c LCFGResource * * @return The length of the derivation string * */ size_t lcfgresource_get_derivation_length( const LCFGResource * res ) { assert( res != NULL ); if ( !lcfgresource_has_derivation(res) ) return 0; const LCFGDerivationList * drvlist = lcfgresource_get_derivation(res); return lcfgderivlist_get_string_length(drvlist); } /** * @brief Set the derivation for the resource * * Sets the value of the @e derivation parameter for the @c * LCFGResource to the specified @c LCFGDerivationList. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_deriv Pointer to new @c LCFGDerivationList structure * * @return boolean indicating success * */ bool lcfgresource_set_derivation( LCFGResource * res, LCFGDerivationList * new_deriv ) { lcfgderivlist_relinquish(res->derivation); if ( new_deriv != NULL ) /* Supports unsetting the derivation */ lcfgderivlist_acquire(new_deriv); res->derivation = new_deriv; return true; } /** * @brief Set the derivation for the resource as a string * * Sets the value of the @e derivation parameter for the @c * LCFGResource to that specified. The derivation string is parsed * using @c lcfgderivlist_from_string(). * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_deriv String which is the new derivation * * @return boolean indicating success * */ bool lcfgresource_set_derivation_as_string( LCFGResource * res, const char * new_deriv ) { assert( res != NULL ); bool ok = true; LCFGDerivationList * new_drvlist = NULL; if ( new_deriv != NULL ) { /* Supports unsetting the derivation */ char * msg = NULL; LCFGStatus status = lcfgderivlist_from_string( new_deriv, &new_drvlist, &msg ); if ( status == LCFG_STATUS_ERROR ) ok = false; free(msg); } if (ok) ok = lcfgresource_set_derivation( res, new_drvlist ); lcfgderivlist_relinquish(new_drvlist); return ok; } /** * @brief Merge derivations for one resource into another * * This can be used to merge the @c LCFGDerivationList from one @c * LCFGResource into another. There is support for Copy On Write so * that if a derivation list is shared between multiple resources it * will be cloned before the merging is done. This is used when * merging resource specifications by prefix. * * @param[in] res1 Pointer to @c LCFGResource into which derivation is merged * @param[in] res2 Pointer to @c LCFGResource from which derivation is merged * * @return boolean indicating success * */ bool lcfgresource_merge_derivation( LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); LCFGDerivationList * drvlist1 = lcfgresource_get_derivation(res1); if ( res2 == NULL || !lcfgresource_has_derivation(res2) ) return true; LCFGDerivationList * drvlist2 = lcfgresource_get_derivation(res2); if ( lcfgderivlist_is_empty(drvlist1) ) return lcfgresource_set_derivation( res1, drvlist2 ); /* The main aim of the cloning is to provide COW for shared derivations. Keeping it simple by doing the clone for all merges. This also provides extra safety against corruption. */ bool ok = false; LCFGDerivationList * clone = lcfgderivlist_clone(drvlist1); if ( clone != NULL ) { LCFGChange merge_rc = lcfgderivlist_merge_list( clone, drvlist2 ); if ( LCFGChangeOK(merge_rc) ) { /* Only keep the clone if it was modified */ if ( merge_rc == LCFG_CHANGE_NONE ) ok = true; else ok = lcfgresource_set_derivation( res1, clone ); } lcfgderivlist_relinquish(clone); } return ok; } /** * @brief Add extra derivation information for the resource * * Adds the extra derivation information to the value for the @e * derivation parameter in the @c LCFGResource if it is not already * found. This is done using the @c lcfgderivlist_merge_string_list() * function. There is support for Copy On Write so that if a * derivation list is shared between multiple resources it will be * cloned before the merging is done. * @param[in] res Pointer to an @c LCFGResource * @param[in] extra_deriv String which is the additional derivation * * @return boolean indicating success * */ bool lcfgresource_add_derivation_string( LCFGResource * res, const char * extra_deriv ) { assert( res != NULL ); if ( isempty(extra_deriv) ) return true; bool ok = true; LCFGDerivationList * drvlist = lcfgresource_get_derivation(res); LCFGDerivationList * clone = lcfgderivlist_clone(drvlist); if ( clone != NULL ) { char * merge_msg = NULL; LCFGChange merge_rc = lcfgderivlist_merge_string_list( clone, extra_deriv, &merge_msg ); free(merge_msg); if ( LCFGChangeOK(merge_rc) ) { /* Only keep the clone if it was modified */ if ( merge_rc == LCFG_CHANGE_NONE ) ok = true; else ok = lcfgresource_set_derivation( res, clone ); } lcfgderivlist_relinquish(clone); } return ok; } /** * @brief Add extra derivation information for the resource * * Adds the extra filename to the @c LCFGDerivationList for the @c * LCFGResource if it is not already found. If the specified line * number is non-negative it will be added to the list of line numbers * for the specified file. This is done using the @c * lcfgderivlist_merge_file_line() function. There is support for Copy * On Write so that if a derivation list is shared between multiple * resources it will be cloned before the merging is done. * * @param[in] res Pointer to an @c LCFGResource * @param[in] filename Name of derivation file * @param[in] line Line number of derivation * * @return boolean indicating success * */ bool lcfgresource_add_derivation_file_line( LCFGResource * res, const char * filename, int line ) { assert( res != NULL ); if ( isempty(filename) ) return true; bool ok = true; LCFGDerivationList * drvlist = lcfgresource_get_derivation(res); LCFGDerivationList * clone = lcfgderivlist_clone(drvlist); if ( clone != NULL ) { LCFGChange merge_rc = lcfgderivlist_merge_file_line( clone, filename, line ); if ( LCFGChangeOK(merge_rc) ) { /* Only keep the clone if it was modified */ if ( merge_rc == LCFG_CHANGE_NONE ) ok = true; else ok = lcfgresource_set_derivation( res, clone ); } lcfgderivlist_relinquish(clone); } return ok; } /* Context Expression */ /** * @brief Check if a string is a valid LCFG context expression * * Checks the contents of a specified string against the specification * for an LCFG context expression. See @c lcfgcontext_valid_expression * for details. * * @param[in] ctx String to be tested * * @return boolean which indicates if string is a valid context * */ bool lcfgresource_valid_context( const char * ctx ) { char * msg = NULL; bool valid = lcfgcontext_valid_expression( ctx, &msg ); free(msg); /* Just ignore any error message */ return valid; } /** * @brief Check if the resource has a context * * Checks if there is any context information associated with the * @c LCFGResource. * * @param[in] res Pointer to an @c LCFGResource * * @return Boolean which indicates if the resource has a context * */ bool lcfgresource_has_context( const LCFGResource * res ) { assert( res != NULL ); return !isempty(res->context); } /** * @brief Get the context for the resource * * This returns the value of the @e context parameter for the * @c LCFGResource. If the resource does not currently have a * value for the @e context then the pointer returned will be @c * NULL. * * It is important to note that this is NOT a copy of the string, * changing the returned string will modify the @e context for the * resource. * * @param[in] res Pointer to an @c LCFGResource * * @return The @e context for the resource (possibly NULL). */ const char * lcfgresource_get_context( const LCFGResource * res ) { assert( res != NULL ); return res->context; } /** * @brief Set the context for the resource * * Sets the value of the @e context parameter for the @c * LCFGResource to that specified. It is important to note that * this does NOT take a copy of the string. Furthermore, once the * value is set the resource assumes "ownership", the memory will be * freed if the context is further modified or the resource is * destroyed. * * Before changing the value of the @e context to be the new string it * will be validated using the @c lcfgresource_valid_context() * function. If the new string is not valid then no change will occur, * the @c errno will be set to @c EINVAL and the function will return * a @c false value. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_ctx String which is the new context * * @return boolean indicating success * */ bool lcfgresource_set_context( LCFGResource * res, char * new_ctx ) { assert( res != NULL ); bool ok = false; if ( new_ctx == NULL || lcfgresource_valid_context(new_ctx) ) { free(res->context); res->context = new_ctx; ok = true; } else { errno = EINVAL; } return ok; } /** * @brief Add extra context information for the resource * * Adds the extra context information to the value for the @e * context parameter in the @c LCFGResource if it is not * already found in the string. * * If not already present in the existing information a new context * string is built which is the combination of any existing string * with the new string appended, the strings are combined using @c * lcfgcontext_combine_expressions(). The new string is passed to @c * lcfgresource_set_context(), unlike that function this does NOT * assume "ownership" of the input string. * * @param[in] res Pointer to an @c LCFGResource * @param[in] extra_context String which is the additional context * * @return boolean indicating success * */ bool lcfgresource_add_context( LCFGResource * res, const char * extra_context ) { assert( res != NULL ); if ( isempty(extra_context) ) return true; char * new_context; if ( !lcfgresource_has_context(res) ) { new_context = strdup(extra_context); } else { new_context = lcfgcontext_combine_expressions( res->context, extra_context ); } bool ok = lcfgresource_set_context( res, new_context ); if ( !ok ) free(new_context); return ok; } /* Comments */ /** * @brief Check if the resource has a comment * * Checks if there is any comment stored in the @c LCFGResource. * * Typically only string resources with additional validation added by * the schema author will have a comment. The comment often describes * the expected format for the value (e.g. MAC address) so that a * helpful error can be printed when an invalid value is specified. * * @param[in] res Pointer to an @c LCFGResource * * @return Boolean which indicates if the resource has a comment * */ bool lcfgresource_has_comment( const LCFGResource * res ) { assert( res != NULL ); return !isempty(res->comment); } /** * @brief Get the comment for the resource * * This returns the value of the @e comment parameter for the @c * LCFGResource. If the resource does not currently have a * value for the @e comment then the pointer returned will be @c * NULL. * * It is important to note that this is NOT a copy of the string, * changing the returned string will modify the @e comment for the * resource. * * @param[in] res Pointer to an @c LCFGResource * * @return The @e comment for the resource (possibly NULL). */ const char * lcfgresource_get_comment( const LCFGResource * res ) { assert( res != NULL ); return res->comment; } /** * @brief Set the comment for the resource * * Sets the value of the @e comment parameter for the * @c LCFGResource to that specified. It is important to note that * this does NOT take a copy of the string. Furthermore, once the * value is set the resource assumes "ownership", the memory will be * freed if the comment is further modified or the resource is * destroyed. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_comment String which is the new comment * * @return boolean indicating success * */ bool lcfgresource_set_comment( LCFGResource * res, char * new_comment ) { assert( res != NULL ); free(res->comment); res->comment = new_comment; return true; } /* Priority */ /** * @brief Get the priority for the resource * * This returns the value of the integer @e priority parameter for the * @c LCFGResource. The priority is calculated using the context * expression for the resource (if any) along with the current active * set of contexts for the system. * * @param[in] res Pointer to an @c LCFGResource * * @return The priority for the resource as an integer * */ int lcfgresource_get_priority( const LCFGResource * res ) { assert( res != NULL ); return res->priority; } /** * @brief Get the priority for the resource as a string * * This returns the stringified value of the integer @e priority * parameter for the @c LCFGResource. The priority is calculated using * the context expression for the resource (if any) along with the * current active set of contexts for the system. * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to an @c LCFGResource * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_get_priority_as_string( const LCFGResource * res, LCFGOption options, char ** result, size_t * size ) { assert( res != NULL ); size_t new_len = 0; int priority = lcfgresource_get_priority(res); if ( priority < 0 ) { new_len++; priority *= -1; } while ( priority > 9 ) { new_len++; priority/=10; } new_len++; /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG priority string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ int rc = snprintf( *result, new_len + 1, "%d", lcfgresource_get_priority(res) ); assert( rc > 0 && (size_t) rc == new_len ); return new_len; } /** * @brief Set the priority for the resource * * Sets the value of the @e priority parameter for the @c LCFGResource * to that specified. * * @param[in] res Pointer to an @c LCFGResource * @param[in] new_prio Integer which is the new priority * * @return boolean indicating success * */ bool lcfgresource_set_priority( LCFGResource * res, int new_prio ) { assert( res != NULL ); res->priority = new_prio; return true; } /** * @brief Set the priority for the resource to the default value * * Sets the value of the @e priority parameter for the @c LCFGResource * to the value of @c LCFG_RESOURCE_DEFAULT_PRIORITY (which is zero). * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating success * */ bool lcfgresource_set_priority_default( LCFGResource * res ) { assert( res != NULL ); return lcfgresource_set_priority( res, LCFG_RESOURCE_DEFAULT_PRIORITY ); } /** * @brief Evaluate the priority for the resource for a list of contexts * * This will evaluate and update the value of the @e priority * attribute for the LCFG resource using the value set for the * @e context attribute (if any) and the list of LCFG contexts passed in * as an argument. The priority is evaluated using * @c lcfgctxlist_eval_expression(). * * The default value for the priority is zero, if the resource is * applicable for the specified list of contexts the priority will be * positive otherwise it will be negative. * * @param[in] res Pointer to an @c LCFGResource * @param[in] ctxlist List of LCFG contexts * @param[out] msg Pointer to any diagnostic messages * * @return boolean indicating success * */ bool lcfgresource_eval_priority( LCFGResource * res, const LCFGContextList * ctxlist, char ** msg ) { assert( res != NULL ); bool ok = true; int priority = LCFG_RESOURCE_DEFAULT_PRIORITY; if ( lcfgresource_has_context(res) ) { /* Calculate the priority using the context expression for this resource. */ ok = lcfgctxlist_eval_expression( ctxlist, lcfgresource_get_context(res), &priority, msg ); } if (ok) ok = lcfgresource_set_priority( res, priority ); return ok; } /** * @brief Check if the resource is considered to be active * * Checks if the current value for the @e priority attribute in the * @c LCFGResource is greater than or equal to zero. * * The priority is calculated using the value for the @e context * attribute and the list of currently active contexts, see * @c lcfgresource_eval_priority() for details. * * @param[in] res Pointer to an @c LCFGResource * * @return boolean indicating if the resource is active * */ bool lcfgresource_is_active( const LCFGResource * res ) { assert( res != NULL ); return ( lcfgresource_get_priority(res) >= 0 ); } /** * @brief Import a resource from the environment * * This checks the environment for variables which hold resource value * and type information for the given name and creates a new @c * LCFGResource. The variable names are a simple concatenation of the * resource name and any prefix specified. * * The value prefix will typically be like @c LCFG_comp_ and the type * prefix will typically be like @c LCFGTYPE_comp_ where @c comp is * the name of the component. If the type prefix is @c NULL then no * attempt will be made to load type information from the environment. * * If there is no variable for the resource value in the environment * an error will be returned unless the @c LCFG_OPT_ALLOW_NOEXIST * option is specified. When the option is specified and there is no * variable the value is assumed to be an empty string. Note that this * may not be a valid value for some resource types. * * To avoid memory leaks, when the newly created resource structure is * no longer required you should call the @c lcfgresource_relinquish() * function. * * @param[in] name The name of the resource * @param[in] compname The name of the component * @param[in] val_pfx The prefix for the value variable name * @param[in] type_pfx The prefix for the type variable name * @param[out] result Reference to the pointer for the @c LCFGResource * @param[in] options Integer which controls behaviour * @param[out] msg Pointer to any diagnostic messages * * @return Status value indicating success of the process * */ LCFGStatus lcfgresource_from_env( const char * name, const char * compname, const char * val_pfx, const char * type_pfx, LCFGResource ** result, LCFGOption options, char ** msg ) { /* Declared before any cleanups */ LCFGStatus status = LCFG_STATUS_OK; char * env_key = NULL; size_t env_key_size = 0; ssize_t env_key_len = -1; LCFGResource * res = lcfgresource_new(); char * resname = strdup(name); if ( !lcfgresource_set_name( res, resname ) ) { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, compname, "Invalid name '%s'", resname ); free(resname); goto cleanup; } /* Type */ env_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_TYPE_PFX, type_pfx, &env_key, &env_key_size ); if ( env_key_len <= 0 ) { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( type_pfx != NULL ? type_pfx : LCFG_RESOURCE_ENV_TYPE_PFX ) ); goto cleanup; } const char * type = getenv(env_key); if ( !isempty(type) ) { char * type_msg = NULL; if ( !lcfgresource_set_type_as_string( res, type, &type_msg ) ) { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, compname, "Invalid type '%s': %s", type, type_msg ); free(type_msg); goto cleanup; } free(type_msg); } /* Value */ env_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_VAL_PFX, val_pfx, &env_key, &env_key_size ); if ( env_key_len <= 0 ) { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( val_pfx != NULL ? val_pfx : LCFG_RESOURCE_ENV_VAL_PFX ) ); goto cleanup; } const char * value = getenv(env_key); if ( value == NULL ) { if ( options&LCFG_OPT_ALLOW_NOEXIST ) { value = ""; /* Assume it is an empty string */ } else { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, compname, "Could not find value in environment" ); } } if ( status != LCFG_STATUS_ERROR ) { char * res_value = strdup(value); if ( !lcfgresource_set_value( res, res_value ) ) { status = LCFG_STATUS_ERROR; *msg = lcfgresource_build_message( res, NULL, "Invalid value '%s'", res_value ); free(res_value); goto cleanup; } } cleanup: free(env_key); if ( status == LCFG_STATUS_ERROR ) { lcfgresource_destroy(res); res = NULL; } *result = res; return status; } /** * @brief Load resource from specification string * * This can be used to parse an LCFG resource specification string and * create a new @c LCFGResource using the information. * * As well as returning the new resource if the hostname or component * name are included in the key they will also be returned. * * All of these are valid resource specifications: * \verbatim host.client.ack=yes client.ack=yes ack=yes \endverbatim * * To avoid memory leaks, when the newly created resource structure is * no longer required you should call the @c lcfgresource_relinquish() * function. * * @param[in] spec The resource specification string * @param[out] result Reference to pointer to new @c LCFGResource * @param[out] hostname Reference to pointer to host name string (may be @c NULL) * @param[out] compname Reference to pointer to component name string (may be @c NULL) * @param[out] msg Pointer to any diagnostic messages * * @return Status value indicating success of the process * */ LCFGStatus lcfgresource_from_spec( const char * spec, LCFGResource ** result, char ** hostname, char ** compname, char ** msg ) { /* The input string is mangled by the spec parser so we need to use a copy */ char * input = strdup(spec); const char * spec_host = NULL; const char * spec_comp = NULL; const char * spec_res = NULL; const char * spec_val = NULL; char spec_type; LCFGStatus status = lcfgresource_parse_spec( input, &spec_host, &spec_comp, &spec_res, &spec_val, &spec_type, msg ); LCFGResource * res = NULL; /* Create new resource and set the name */ if ( status != LCFG_STATUS_ERROR ) { res = lcfgresource_new(); char * res_name = strdup(spec_res); if ( !lcfgresource_set_name( res, res_name ) ) { free(res_name); lcfgutils_build_message( msg, "invalid resource name '%s'", spec_res ); status = LCFG_STATUS_ERROR; } } /* Set the value for the attribute type */ if ( status != LCFG_STATUS_ERROR ) { char * set_msg = NULL; size_t val_len = strlen(spec_val); if ( !lcfgresource_set_attribute( res, spec_type, spec_val, val_len, &set_msg ) ) { lcfgutils_build_message( msg, "bad value for resource attribute (%s)", set_msg ); status = LCFG_STATUS_ERROR; } free(set_msg); } /* Return the results */ if ( status != LCFG_STATUS_ERROR ) { *hostname = isempty(spec_host) ? NULL : strdup(spec_host); *compname = isempty(spec_comp) ? NULL : strdup(spec_comp); *result = res; } else { lcfgresource_relinquish(res); res = NULL; } /* Free after making copies of any results from the parse */ free(input); return status; } /* Output */ /** * @brief Format the resource as a string * * Generates a new string representation of the @c LCFGResource in * various styles. The following styles are supported: * * - @c LCFG_RESOURCE_STYLE_SUMMARY - uses @c lcfgresource_to_summary() * - @c LCFG_RESOURCE_STYLE_STATUS - uses @c lcfgresource_to_status() * - @c LCFG_RESOURCE_STYLE_SPEC - uses @c lcfgresource_to_spec() * - @c LCFG_RESOURCE_STYLE_VALUE - uses @c lcfgresource_to_value() * * See the documentation for each function to see which options are * supported. * * These functions use a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (may be @c NULL) * @param[in] style Integer indicating required style of formatting * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_string( const LCFGResource * res, const char * prefix, LCFGResourceStyle style, LCFGOption options, char ** result, size_t * size ) { assert( res != NULL ); /* Select the appropriate string function */ LCFGResStrFunc str_func = NULL; switch (style) { case LCFG_RESOURCE_STYLE_VALUE: str_func = &lcfgresource_to_value; break; case LCFG_RESOURCE_STYLE_SUMMARY: str_func = &lcfgresource_to_summary; break; case LCFG_RESOURCE_STYLE_STATUS: str_func = &lcfgresource_to_status; break; case LCFG_RESOURCE_STYLE_SPEC: default: str_func = &lcfgresource_to_spec; } return (*str_func)( res, prefix, options, result, size ); } ssize_t lcfgresource_build_env_var( const char * resname, const char * compname, const char * default_base, const char * base, char ** result, size_t * size ) { *result = NULL; if ( base == NULL ) base = default_base; char * base2 = NULL; if ( compname != NULL && strstr( base, LCFG_RESOURCE_ENV_PHOLDER ) != NULL ) { base2 = lcfgutils_string_replace( base, LCFG_RESOURCE_ENV_PHOLDER, compname ); base = base2; } size_t base_len = strlen(base); size_t new_len = base_len; /* Optional resource name */ size_t res_len = 0; if ( resname != NULL ) { res_len = strlen(resname); new_len += res_len; } /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ char * to = *result; to = stpncpy( to, base, base_len ); if ( res_len > 0 ) to = stpncpy( to, resname, res_len ); *to = '\0'; free(base2); assert( ( *result + new_len ) == to ); return new_len; } /** * @brief Check if a string is a valid environment variable name * * This can be used to validate an environment variable name to ensure * it is safe for use. The specification requires that the first * character is in the set [a-zA-Z_] and that any subsequent * characters are in the set [a-zA-Z0-9_] (i.e. it does not start with * a digit). We go further by requiring that where there are leading * underscores there must be an additional character in the set * [a-zA-Z0-9]. For example '__foo' is allowed but '___' is not. * * @param[in] name String to be checked * * @return Boolean indicating validity of variable name * */ bool lcfgresource_valid_env_var( const char * name ) { if ( isempty(name) ) return false; bool valid = true; bool need_extra_char = false; bool found_extra_char = false; if ( !isalpha(*name) ) { if ( *name == '_' && *(name+1) != '\0' ) need_extra_char = true; else valid = false; } const char * ptr; for ( ptr=name+1; valid && *ptr!='\0'; ptr++ ) { if ( isalnum(*ptr) ) found_extra_char = true; else if ( *ptr != '_' ) valid = false; } if ( need_extra_char && !found_extra_char ) valid = false; return valid; } /** * @brief Export a resource to the environment * * This exports value and type information for the @c LCFGResource as * environment variables. The variable names are a combination of the * resource name and any prefix specified. * * The value prefix will typically be like @c LCFG_comp_ and the type * prefix will typically be like @c LCFGTYPE_comp_ where @c comp is * the name of the component. Often only the value variable is * required so, for efficiency, the type variable will only be set * when the @c LCFG_OPT_USE_META option is specified. * * @param[in] res Pointer to @c LCFGResource * @param[in] compname Optional component name (may be @c NULL) * @param[in] val_pfx The prefix for the value variable name * @param[in] type_pfx The prefix for the type variable name * @param[in] options Integer which controls behaviour * @return Status value indicating success of the process * */ LCFGStatus lcfgresource_to_env( const LCFGResource * res, const char * compname, const char * val_pfx, const char * type_pfx, LCFGOption options ) { assert( res != NULL ); /* Name is required */ if ( !lcfgresource_is_valid(res) ) return LCFG_STATUS_ERROR; const char * name = res->name; /* Declared before any cleanups */ LCFGStatus status = LCFG_STATUS_OK; char * env_key = NULL; size_t env_key_size = 0; ssize_t env_key_len = -1; char * type_as_str = NULL; char * msg = NULL; /* Value */ env_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_VAL_PFX, val_pfx, &env_key, &env_key_size ); if ( env_key_len <= 0 ) { status = LCFG_STATUS_ERROR; msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( val_pfx != NULL ? val_pfx : LCFG_RESOURCE_ENV_VAL_PFX ) ); goto cleanup; } else if ( !lcfgresource_valid_env_var(env_key) ) { status = LCFG_STATUS_ERROR; msg = lcfgresource_build_message( res, compname, "Invalid environment variable name '%s'", env_key ); goto cleanup; } const char * value = or_default( res->value, "" ); if ( setenv( env_key, value, 1 ) != 0 ) { status = LCFG_STATUS_ERROR; goto cleanup; } /* Type - optional */ if ( options&LCFG_OPT_USE_META ) { if ( lcfgresource_get_type(res) != LCFG_RESOURCE_TYPE_STRING || lcfgresource_has_comment(res) ) { size_t type_size = 0; ssize_t type_len = lcfgresource_get_type_as_string( res, LCFG_OPT_NONE, &type_as_str, &type_size ); if ( type_len <= 0 ) { free(type_as_str); type_as_str = NULL; } } if ( !isempty(type_as_str) ) { env_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_TYPE_PFX, type_pfx, &env_key, &env_key_size ); if ( env_key_len <= 0 ) { status = LCFG_STATUS_ERROR; msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( type_pfx != NULL ? type_pfx : LCFG_RESOURCE_ENV_TYPE_PFX ) ); goto cleanup; } else if ( !lcfgresource_valid_env_var(env_key) ) { status = LCFG_STATUS_ERROR; msg = lcfgresource_build_message( res, compname, "Invalid environment variable name '%s'", env_key ); goto cleanup; } if ( setenv( env_key, type_as_str, 1 ) != 0 ) { status = LCFG_STATUS_ERROR; goto cleanup; } } } cleanup: free(type_as_str); free(env_key); if ( status == LCFG_STATUS_ERROR && msg != NULL ) { fprintf( stderr, "%s\n", msg ); } free(msg); return status; } static const char env_fn_name[] = "export"; static const size_t env_fn_len = sizeof(env_fn_name) - 1; /** * @brief Format resource information for shell evaluation * * This generates a new string representation of the @e value and * @e type information for the @c LCFGResource as environment variables * which can be evaluated in the bash shell. The variable names are a * combination of the resource name and any prefix specified. * The output will look something like: * \verbatim export LCFG_client_ack='yes' export LCFGTYPE_client_ack='boolean' \endverbatim * * The value prefix will typically be like @c LCFG_comp_ and the type * prefix will typically be like @c LCFGTYPE_comp_ where @c comp is * the name of the component. Often only the value variable is * required so, for efficiency, the type variable will only be set * when the @c LCFG_OPT_USE_META option is specified. * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] compname Optional component name (may be @c NULL) * @param[in] val_pfx The prefix for the value variable name * @param[in] type_pfx The prefix for the type variable name * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_export( const LCFGResource * res, const char * compname, const char * val_pfx, const char * type_pfx, LCFGOption options, char ** result, size_t * size ) { assert( res != NULL ); /* Name is required */ if ( !lcfgresource_is_valid(res) ) return -1; const char * name = lcfgresource_get_name(res); /* Declare before jumps to cleanup */ bool ok = true; char * msg = NULL; char * val_key = NULL; char * type_key = NULL; char * type_as_str = NULL; /* Value */ size_t val_key_size = 0; ssize_t val_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_VAL_PFX, val_pfx, &val_key, &val_key_size ); if ( val_key_len <= 0 ) { ok = false; msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( val_pfx != NULL ? val_pfx : LCFG_RESOURCE_ENV_VAL_PFX ) ); goto cleanup; } else if ( !lcfgresource_valid_env_var(val_key) ) { ok = false; msg = lcfgresource_build_message( res, compname, "Invalid environment variable name '%s'", val_key ); goto cleanup; } static const char escaped[] = "'\"'\"'"; static const size_t escaped_len = sizeof(escaped) - 1; const char * value = NULL; size_t value_len = 0; if ( lcfgresource_has_value(res) ) { value = lcfgresource_get_value(res); value_len = strlen(value); const char * ptr; for ( ptr = value; *ptr != '\0'; ptr++ ) { if ( *ptr == '\'' ) value_len += ( escaped_len - 1 ); } } /* +1 space, +1 =, +2 '', +1 '\n' == 5 */ size_t new_len = ( env_fn_len + val_key_len + value_len + 5 ); /* Type - optional */ ssize_t type_len = 0; ssize_t type_key_len = 0; if ( options&LCFG_OPT_USE_META ) { if ( lcfgresource_get_type(res) != LCFG_RESOURCE_TYPE_STRING || lcfgresource_has_comment(res) ) { size_t type_size = 0; type_len = lcfgresource_get_type_as_string( res, LCFG_OPT_NONE, &type_as_str, &type_size ); if ( type_len <= 0 ) { free(type_as_str); type_as_str = NULL; } } if ( !isempty(type_as_str) ) { size_t type_key_size = 0; type_key_len = lcfgresource_build_env_var( name, compname, LCFG_RESOURCE_ENV_TYPE_PFX, type_pfx, &type_key, &type_key_size ); if ( type_key_len <= 0 ) { ok = false; msg = lcfgresource_build_message( res, compname, "Failed to build environment variable name from '%s'", ( type_pfx != NULL ? type_pfx : LCFG_RESOURCE_ENV_TYPE_PFX ) ); goto cleanup; } else if ( !lcfgresource_valid_env_var(type_key) ) { ok = false; msg = lcfgresource_build_message( res, compname, "Invalid environment variable name '%s'", type_key ); goto cleanup; } if ( strcmp( val_key, type_key ) == 0 ) { ok = false; msg = lcfgresource_build_message( res, compname, "Must not have identical environment variables for value and type information" ); goto cleanup; } const char * ptr; for ( ptr = type_as_str; *ptr != '\0'; ptr++ ) { if ( *ptr == '\'' ) type_len += ( escaped_len - 1 ); } /* +1 space, +1 =, +2 '', +1 '\n' == 5 */ new_len += ( env_fn_len + type_key_len + type_len + 5 ); } } /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ char * to = *result; /* Type - optional - emit this first so that when the exported stuff is evaluated any type information is loaded first */ if ( type_len > 0 ) { to = stpncpy( to, env_fn_name, env_fn_len ); *to = ' '; to++; to = stpncpy( to, type_key, type_key_len ); to = stpncpy( to, "='", 2 ); const char * ptr; for ( ptr = type_as_str; *ptr != '\0'; ptr++ ) { if ( *ptr == '\'' ) { to = stpncpy( to, escaped, escaped_len ); } else { *to = *ptr; to++; } } to = stpncpy( to, "'\n", 2 ); } /* Value */ to = stpncpy( to, env_fn_name, env_fn_len ); *to = ' '; to++; to = stpncpy( to, val_key, val_key_len ); to = stpncpy( to, "='", 2 ); if ( value != NULL ) { const char * ptr; for ( ptr = value; *ptr != '\0'; ptr++ ) { if ( *ptr == '\'' ) { to = stpncpy( to, escaped, escaped_len ); } else { *to = *ptr; to++; } } } to = stpncpy( to, "'\n", 2 ); *to = '\0'; assert( ( *result + new_len ) == to ); cleanup: if ( !ok && msg != NULL ) fprintf( stderr, "%s\n", msg ); free(type_as_str); free(val_key); free(type_key); free(msg); if (ok) return new_len; else return -1; } /** * @brief Summarise the resource information * * Summarises the @c LCFGResource as a string in the verbose key-value * style used by the qxprof tool. The output will look something like: * \verbatim client.ack: value=yes type=boolean derive=/var/lcfg/conf/server/defaults/client-4.def:47 \endverbatim * * The following options are supported: * - @c LCFG_OPT_USE_META - Include any derivation and context information. * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (may be @c NULL) * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_summary( LCFG_RES_TOSTR_ARGS ) { assert( res != NULL ); static const char format[] = " %7s=%s\n"; static const size_t base_len = 10; /* 1 for indent + 7 for key + 1 for '=' +1 for newline */ ssize_t key_len = lcfgresource_to_spec( res, prefix, LCFG_OPT_NOVALUE|LCFG_OPT_NOCONTEXT, result, size ); if ( key_len < 0 ) return key_len; size_t new_len = key_len + 2; /* for ':' (colon) and newline */ /* Value */ const char * value = or_default( res->value, "" ); size_t value_len = strlen(value); new_len += ( base_len + value_len ); /* Type */ const char * type = "default"; size_t type_len = 7; char * type_as_str = NULL; if ( lcfgresource_get_type(res) != LCFG_RESOURCE_TYPE_STRING || lcfgresource_has_comment(res) ) { size_t type_size = 0; ssize_t type_str_len = lcfgresource_get_type_as_string( res, LCFG_OPT_NONE, &type_as_str, &type_size ); if ( type_len > 0 ) { type = type_as_str; type_len = (size_t) type_str_len; } else { free(type_as_str); type_as_str = NULL; } } new_len += ( base_len + type_len ); /* Optional meta-data */ char * deriv_as_str = NULL; ssize_t deriv_len = 0; const char * context = NULL; size_t ctx_len = 0; if ( options&LCFG_OPT_USE_META ) { if ( lcfgresource_has_derivation(res) ) { size_t deriv_size = 0; deriv_len = lcfgresource_get_derivation_as_string( res, LCFG_OPT_NONE, &deriv_as_str, &deriv_size ); if ( deriv_len > 0 ) new_len += ( base_len + deriv_len ); } if ( lcfgresource_has_context(res) ) { context = lcfgresource_get_context(res); ctx_len = strlen(context); if ( ctx_len > 0 ) new_len += ( base_len + ctx_len ); } } /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Build the new string - start at offset from the value line which was put there using lcfgresource_to_spec */ char * to = *result + key_len; to = stpncpy( to, ":\n", 2 ); int rc; /* Value */ rc = sprintf( to, format, "value", value ); to += rc; /* Type */ rc = sprintf( to, format, "type", type ); to += rc; /* Derivation */ if ( deriv_len > 0 ) { rc = sprintf( to, format, "derive", deriv_as_str ); to += rc; } /* Context */ if ( ctx_len > 0 ) { rc = sprintf( to, format, "context", context ); to += rc; } *to = '\0'; free(type_as_str); free(deriv_as_str); assert( (*result + new_len ) == to ); return new_len; } /** * @brief Format the resource as @e status * * Generates an LCFG @e status representation of the @c LCFGResource. * This is used by the LCFG components when the current state of the * resources is stored in a file. For safety, the resource value will * have any newline and ampersand characters HTML-encoded. The various * information is keyed using the standard prefix characters: * * - type - @c '%' * - derivation - @c '#' * - value - no prefix * * The output will look something like: * \verbatim client.ack=yes %client.ack=boolean \endverbatim * * The following options are supported: * - @c LCFG_OPT_USE_META - Include any derivation information. * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (may be @c NULL) * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_status( LCFG_RES_TOSTR_ARGS ) { assert( res != NULL ); /* The entry for the value is the standard stringified form. This writes directly into the result buffer, often this is all that the to_status function needs to do (if there is no type or derivation information). */ ssize_t value_len = lcfgresource_to_spec( res, prefix, options|LCFG_OPT_NEWLINE|LCFG_OPT_ENCODE, result, size ); if ( value_len < 0 ) return value_len; size_t new_len = value_len; /* Resource Meta Data */ /* Type - Only output the type when the resource is NOT a string */ char * type_as_str = NULL; ssize_t type_len = 0; if ( lcfgresource_get_type(res) != LCFG_RESOURCE_TYPE_STRING || lcfgresource_has_comment(res) ) { size_t type_size = 0; type_len = lcfgresource_get_type_as_string( res, LCFG_OPT_NONE, &type_as_str, &type_size ); if ( type_len > 0 ) { ssize_t key_len = lcfgresource_compute_key_length( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_TYPE ); new_len += ( key_len + type_len + 2 ); /* +2 for '=' and newline */ } else { free(type_as_str); type_as_str = NULL; } } /* Derivation */ size_t deriv_len = 0; if ( options&LCFG_OPT_USE_META && lcfgresource_has_derivation(res) ) { deriv_len = lcfgresource_get_derivation_length(res); if ( deriv_len > 0 ) { ssize_t key_len = lcfgresource_compute_key_length( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_DERIVATION ); new_len += ( key_len + deriv_len + 2 ); /* +2 for '=' and newline */ } } /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Build the new string - start at offset from the value line which was put there using lcfgresource_to_spec */ char * to = *result + value_len; /* Type */ if ( type_as_str != NULL ) { ssize_t write_len = lcfgresource_insert_key( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_TYPE, to ); if ( write_len > 0 ) { to += write_len; *to = '='; to++; to = stpncpy( to, type_as_str, type_len ); to = stpcpy( to, "\n" ); } free(type_as_str); } /* Derivation */ if ( deriv_len > 0 ) { ssize_t write_len = lcfgresource_insert_key( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_DERIVATION, to ); if ( write_len > 0 ) { to += write_len; *to = '='; to++; deriv_len++; /* include nul-terminator */ ssize_t inserted_len = lcfgresource_get_derivation_as_string( res, LCFG_OPT_NONE, &to, &deriv_len ); if ( inserted_len > 0 ) to += inserted_len; to = stpcpy( to, "\n" ); } } *to = '\0'; assert( (*result + new_len ) == to ); return new_len; } /** * @brief Format the resource as an LCFG specification * * Generates a new string representation for the @c LCFGResource. This * is the standard @c key=value style used by tools such as qxprof. * * The following options are supported: * - @c LCFG_OPT_NOCONTEXT - do not include any context information * - @c LCFG_OPT_NOVALUE - do not include any value * - @c LCFG_OPT_ENCODE - encode any newline characters in the value * - @c LCFG_OPT_NEWLINE - append a final newline character * - @c LCFG_OPT_NOPREFIX - do not include prefix (usually component name) * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (may be @c NULL) * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_spec( LCFG_RES_TOSTR_ARGS ) { assert( res != NULL ); if ( options&LCFG_OPT_NOPREFIX ) prefix = NULL; ssize_t key_len = lcfgresource_compute_key_length( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_VALUE ); if ( key_len < 0 ) return key_len; size_t new_len = key_len; /* Value */ /* When the NOVALUE option is set then the string is assembled without a value and also without the '= separator. It will be just the resource name, possibly with a prefix, and possibly with a context. Normally if there is no value specified for the resource the '=' separator is still added. */ const char * value = NULL; char * value_enc = NULL; size_t value_len = 0; if ( !(options&LCFG_OPT_NOVALUE) ) { if ( options&LCFG_OPT_ENCODE && lcfgresource_value_needs_encode(res) ) { value_enc = lcfgresource_enc_value(res); value = value_enc; } else { value = lcfgresource_get_value(res); } value_len = value != NULL ? strlen(value) : 0; new_len += ( 1 + value_len ); /* +1 for '=' separator */ } /* Context */ const char * context = NULL; size_t context_len = 0; if ( !(options&LCFG_OPT_NOCONTEXT) && lcfgresource_has_context(res) ) { context = lcfgresource_get_context(res); context_len = strlen(context); if ( context_len > 0 ) new_len += ( 2 + context_len ); /* +2 for '[' and ']' */ } /* Optional newline at end of string */ if ( options&LCFG_OPT_NEWLINE ) new_len += 1; /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ char * to = *result; ssize_t write_len = lcfgresource_insert_key( res->name, prefix, NULL, LCFG_RESOURCE_SYMBOL_VALUE, to ); if ( write_len != key_len ) { free(value_enc); return -1; } to += write_len; /* Optional context */ if ( context_len > 0 ) { *to = '['; to++; to = stpncpy( to, context, context_len ); *to = ']'; to++; } /* Optional value string */ if ( !(options&LCFG_OPT_NOVALUE) ) { *to = '='; to++; if ( value_len > 0 ) to = stpncpy( to, value, value_len ); } free(value_enc); /* Optional newline at the end of the string */ if ( options&LCFG_OPT_NEWLINE ) to = stpcpy( to, "\n" ); assert( (*result + new_len ) == to ); return new_len; } /** * @brief Format the resource value * * Generates a new string representation for value of the @c LCFGResource. * * The following options are supported: * - @c LCFG_OPT_ENCODE - encode any newline characters in the value * - @c LCFG_OPT_NEWLINE - append a final newline character * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (not used) * @param[in] options Integer that controls formatting * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return The length of the new string (or -1 for an error). * */ ssize_t lcfgresource_to_value( LCFG_RES_TOSTR_ARGS ) { assert( res != NULL ); const char * value = NULL; char * value_enc = NULL; if ( options&LCFG_OPT_ENCODE && lcfgresource_value_needs_encode(res) ) { value_enc = lcfgresource_enc_value(res); value = value_enc; } else { value = lcfgresource_get_value(res); } size_t value_len = value != NULL ? strlen(value) : 0; size_t new_len = value_len; /* Optional newline at end of string */ if ( options&LCFG_OPT_NEWLINE ) new_len += 1; /* Allocate the required space */ if ( *result == NULL || *size < ( new_len + 1 ) ) { size_t new_size = new_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( new_buf == NULL ) { perror("Failed to allocate memory for LCFG resource string"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); /* Build the new string */ char * to = *result; if ( value_len > 0 ) to = stpncpy( to, value, value_len ); free(value_enc); /* Optional newline at the end of the string */ if ( options&LCFG_OPT_NEWLINE ) to = stpcpy( to, "\n" ); assert( (*result + new_len ) == to ); return new_len; } /** * @brief Write formatted resource to file stream * * This can be used to write out the resource in various formats to the * specified file stream which must have already been opened for * writing. The following styles are supported: * * - @c LCFG_RESOURCE_STYLE_SUMMARY - uses @c lcfgresource_to_summary() * - @c LCFG_RESOURCE_STYLE_STATUS - uses @c lcfgresource_to_status() * - @c LCFG_RESOURCE_STYLE_SPEC - uses @c lcfgresource_to_spec() * * See the documentation for each function to see which options are * supported. * * @param[in] res Pointer to @c LCFGResource * @param[in] prefix Prefix, usually the component name (may be @c NULL) * @param[in] style Integer indicating required style of formatting * @param[in] options Integer for any additional options * @param[in] out Stream to which the resource string should be written * * @return boolean indicating success * */ bool lcfgresource_print( const LCFGResource * res, const char * prefix, LCFGResourceStyle style, LCFGOption options, FILE * out ) { assert( res != NULL ); char * lcfgres = NULL; size_t buf_size = 0; options |= LCFG_OPT_NEWLINE; ssize_t rc = lcfgresource_to_string( res, prefix, style, options, &lcfgres, &buf_size ); bool ok = ( rc > 0 ); if ( ok ) { if ( fputs( lcfgres, out ) < 0 ) ok = false; } free(lcfgres); return ok; } /** * @brief Compare the resource names * * This compares the names for two resources, this is mostly useful * for sorting lists of resources. An integer value is returned which * indicates lesser than, equal to or greater than in the same way as * @c strcmp(3). * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return Integer (-1,0,+1) indicating lesser,equal,greater * */ int lcfgresource_compare_names( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); const char * name1 = or_default( res1->name, "" ); const char * name2 = or_default( res2->name, "" ); return strcmp( name1, name2 ); } /** * @brief Test if resources have same name * * Compares the @e name for the two resources using the * @c lcfgresource_compare_names() function. * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return boolean indicating equality of names * */ bool lcfgresource_same_name( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); return ( lcfgresource_compare_names( res1, res2 ) == 0 ); } /** * @brief Compare the resource values * * This compares the values for two resources, this is mostly useful * for sorting lists of resources. An integer value is returned which * indicates lesser than, equal to or greater than in the same way as * @c strcmp(3). * * Comparison rules are: * - True is greater than false if both are booleans * - Integers are compared numerically * - Fall back to simple @c strcmp(3) * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return Integer (-1,0,+1) indicating lesser,equal,greater * */ int lcfgresource_compare_values( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); const char * value1_str = or_default( res1->value, "" ); const char * value2_str = or_default( res2->value, "" ); int result = 0; if ( lcfgresource_is_boolean(res1) && lcfgresource_same_type( res1, res2 ) ) { bool value1_istrue = ( strcmp( value1_str, "yes" ) == 0 ); bool value2_istrue = ( strcmp( value2_str, "yes" ) == 0 ); /* true is greater than false */ if ( value1_istrue ) { if ( !value2_istrue ) result = 1; } else { if ( value2_istrue ) result = -1; } } else if ( lcfgresource_is_integer(res1) && lcfgresource_same_type( res1, res2 ) ) { /* If value cannot be converted to integer will return zero */ long int value1 = strtol( value1_str, NULL, 10 ); long int value2 = strtol( value2_str, NULL, 10 ); result = ( value1 == value2 ? 0 : ( value1 > value2 ? 1 : -1 ) ); } else { result = strcmp( value1_str, value2_str ); } return result; } /** * @brief Test if resource matches name * * This compares the @e name for the @c LCFGResource with the * specified string. * * @param[in] res Pointer to @c LCFGResource * @param[in] name The name to check for a match * * @return boolean indicating equality of values * */ bool lcfgresource_match( const LCFGResource * res, const char * name ) { assert( res != NULL ); assert( name != NULL ); const char * res_name = or_default( res->name, "" ); return ( strcmp( res_name, name ) == 0 ); } /** * @brief Compare resources * * This compares two resources using the values for the @e name, * @e priority, @e value and @e context attributes (in that order). This * is mostly useful for sorting lists of resources. Priorities are * compared as integers, all other comparisons are done simply using * strcmp(). * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return Integer (-1,0,+1) indicating lesser,equal,greater * */ int lcfgresource_compare( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); /* Name */ int result = lcfgresource_compare_names( res1, res2 ); /* Priority */ if ( result == 0 ) { int prio1 = res1->priority; int prio2 = res2->priority; result = prio1 == prio2 ? 0 : ( prio1 < prio2 ? -1 : 1 ); } /* Value - explicitly doing a string comparison rather than type-based */ if ( result == 0 ) { const char * value1 = or_default( res1->value, "" ); const char * value2 = or_default( res2->value, "" ); result = strcmp( value1, value2 ); } /* Context */ if ( result == 0 ) { const char * context1 = or_default( res1->value, "" ); const char * context2 = or_default( res2->value, "" ); result = strcmp( context1, context2 ); } /* The template, type and derivation are NOT compared */ return result; } /** * @brief Test if resources have same value * * Compares the @e value for the two resources using the * @c lcfgresource_compare_values() function. * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return boolean indicating equality of values * */ bool lcfgresource_same_value( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); return ( lcfgresource_compare_values( res1, res2 ) == 0 ); } /** * @brief Test if resources have same type * * Compares the @e type for the two resources. Note that this will * return true for two list resources which have the same type but * different sets of templates. * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return boolean indicating equality of types * */ bool lcfgresource_same_type( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); return ( lcfgresource_get_type(res1) == lcfgresource_get_type(res2) ); } /** * @brief Test if resources have same context * * Compares the @e context for the two resources. Note that this only * does a string comparison, it does NOT evaluate the context * expressions thus two logically equivalent expressions with * different string representations will be considered to be * different. * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return boolean indicating equality of contexts * */ bool lcfgresource_same_context( const LCFGResource * res1, const LCFGResource * res2 ) { return ( lcfgcontext_compare_expressions( res1->context, res2->context ) == 0 ); } /** * @brief Test if resources are considered equal * * Compares the two resources using the @c lcfgresource_compare() * function. * * @param[in] res1 Pointer to @c LCFGResource * @param[in] res2 Pointer to @c LCFGResource * * @return boolean indicating equality of resources * */ bool lcfgresource_equals( const LCFGResource * res1, const LCFGResource * res2 ) { assert( res1 != NULL ); assert( res2 != NULL ); return ( lcfgresource_compare( res1, res2 ) == 0 ); } /** * @brief Assemble a resource-specific message * * This can be used to assemble resource-specific message, typically * this is used for generating diagnostic error messages. * * @param[in] res Pointer to @c LCFGResource * @param[in] component Component name string (or @c NULL) * @param[in] fmt Format string for message (and any additional arguments) * * @return Pointer to message string (call @c free(3) when no longer required) * */ char * lcfgresource_build_message( const LCFGResource * res, const char * component, const char *fmt, ... ) { /* This is rather messy and probably somewhat inefficient. It is intended to be used primarily for generating error messages, usually just before failing entirely. */ char * result = NULL; /* First assemble the base of the message using the format string and any varargs passed in by the caller */ char * msg_base; va_list ap; va_start(ap, fmt); /* The BSD version apparently sets ptr to NULL on fail. GNU loses. */ if (vasprintf(&msg_base, fmt, ap) < 0) msg_base = NULL; va_end(ap); char * type_as_str = NULL; char * res_as_str = NULL; if ( res != NULL ) { /* Not interested in the resource type if it is the default 'string' */ if ( lcfgresource_get_type(res) != LCFG_RESOURCE_TYPE_STRING ) { size_t type_size = 0; ssize_t type_len = lcfgresource_get_type_as_string( res, LCFG_OPT_NOTEMPLATES, &type_as_str, &type_size ); if ( type_len <= 0 ) { free(type_as_str); type_as_str = NULL; } } if ( lcfgresource_has_name(res) ) { size_t buf_size = 0; ssize_t str_rc = lcfgresource_to_spec( res, component, LCFG_OPT_NOVALUE, &res_as_str, &buf_size ); if ( str_rc < 0 ) { perror("Failed to build LCFG resource message"); exit(EXIT_FAILURE); } } } int rc = 0; /* Build the most useful summary possible using all the available information for the resource. */ char * msg_mid = NULL; if ( type_as_str != NULL ) { if ( res_as_str != NULL ) { rc = asprintf( &msg_mid, "for %s resource '%s'", type_as_str, res_as_str ); } else { if ( component != NULL ) { rc = asprintf( &msg_mid, "for %s resource in component '%s'", type_as_str, component ); } else { rc = asprintf( &msg_mid, "for %s resource", type_as_str ); } } } else if ( res_as_str != NULL ) { rc = asprintf( &msg_mid, "for resource '%s'", res_as_str ); } else { if ( component != NULL ) { rc = asprintf( &msg_mid, "for resource in component '%s'", component ); } else { msg_mid = strdup("for resource"); } } if ( rc < 0 ) { perror("Failed to build LCFG resource message"); exit(EXIT_FAILURE); } /* Final string, possibly with derivation information */ char * deriv_as_str = NULL; ssize_t deriv_len = 0; if ( res != NULL && lcfgresource_has_derivation(res) ) { size_t deriv_size = 0; deriv_len = lcfgresource_get_derivation_as_string( res, LCFG_OPT_NONE, &deriv_as_str, &deriv_size ); } if ( deriv_len > 0 ) { rc = asprintf( &result, "%s %s at %s", msg_base, msg_mid, deriv_as_str ); } else { rc = asprintf( &result, "%s %s", msg_base, msg_mid ); } free(deriv_as_str); if ( rc < 0 ) { perror("Failed to build LCFG resource message"); exit(EXIT_FAILURE); } /* Tidy up */ free(msg_base); free(msg_mid); free(res_as_str); free(type_as_str); return result; } /** * @brief Calculate the required size for a resource key * * This calculates the size requirements for a resource key including * the optional component and namespace. * * The key is generated by combining the part using a @c '.' (period) * character so will be something like @c namespace.component.resname * with an optional single-character type symbol prefix (e.g. @c '%', * @c '#' or @c '^'). This is used by the @c lcfgresource_build_key() * function. * * Clearly care must be taken to ensure no strings are altered after * the key size has been calculated prior to allocating the space for * the key. * * @param[in] resource Name of resource (required) * @param[in] component Name of component (optional) * @param[in] namespace Namespace, typically a hostname (optional) * @param[in] type_symbol The symbol for the particular key type * * @return Size of required key * */ ssize_t lcfgresource_compute_key_length( const char * resource, const char * component, const char * namespace, char type_symbol ) { if ( isempty(resource) ) return -1; size_t length = 0; if ( type_symbol != '\0' ) length++; if ( !isempty(namespace) ) length += ( strlen(namespace) + 1 ); /* +1 for '.' (period) separator */ if ( !isempty(component) ) length += ( strlen(component) + 1 ); /* +1 for '.' (period) separator */ length += strlen(resource); return length; } /** * @brief Insert resource key into a string * * This inserts the resource key into a pre-allocated string which * must be sufficiently large (use the * @c lcfgresource_compute_key_length() function). * * The key is generated by combining the part using a @c '.' (period) * character so will be something like @c namespace.component.resname * with an optional single-character type symbol prefix (e.g. @c '%', * @c '#' or @c '^'). This is used by the @c lcfgresource_build_key() * function. * * If an error occurs this function will return -1. * * @param[in] resource Name of resource (required) * @param[in] component Name of component (optional) * @param[in] namespace Namespace, typically a hostname (optional) * @param[in] type_symbol The symbol for the particular key type * @param[out] result The string into which the key should be written * * @return Size of required key (or -1 for error) * */ ssize_t lcfgresource_insert_key( const char * resource, const char * component, const char * namespace, char type_symbol, char * result ) { if ( isempty(resource) ) return -1; char * to = result; if ( type_symbol != '\0' ) { *to = type_symbol; to++; } if ( !isempty(namespace) ) { to = stpcpy( to, namespace ); *to = '.'; to++; } if ( !isempty(component) ) { to = stpcpy( to, component ); *to = '.'; to++; } to = stpcpy( to, resource ); *to = '\0'; return ( to - result ); } /** * @brief Build a resource key * * Generates a new key for the @c LCFGResource. This key is used by * the client to generate unique keys for storing current resource * data into the DB. * * The key is generated by combining the part using a @c '.' (period) * character so will be something like @c namespace.component.resname * with an optional single-character type symbol prefix (e.g. @c '%', * @c '#' or @c '^'). * * This function uses a string buffer which may be pre-allocated if * nececesary to improve efficiency. This makes it possible to reuse * the same buffer for generating many resource strings, this can be a * huge performance benefit. If the buffer is initially unallocated * then it MUST be set to @c NULL. The current size of the buffer must * be passed and should be specified as zero if the buffer is * initially unallocated. If the generated string would be too long * for the current buffer then it will be resized and the size * parameter is updated. * * If the string is successfully generated then the length of the new * string is returned, note that this is distinct from the buffer * size. To avoid memory leaks, call @c free(3) on the buffer when no * longer required. If an error occurs this function will return -1. * * @param[in] resource Name of resource (required) * @param[in] component Name of component (optional) * @param[in] namespace Namespace, typically a hostname (optional) * @param[in] type_symbol The symbol for the particular key type * @param[in,out] result Reference to the pointer to the string buffer * @param[in,out] size Reference to the size of the string buffer * * @return Size of required key (or -1 for an error) * */ ssize_t lcfgresource_build_key( const char * resource, const char * component, const char * namespace, char type_symbol, char ** result, size_t * size ) { if ( isempty(resource) ) return -1; ssize_t need_len = lcfgresource_compute_key_length( resource, component, namespace, type_symbol ); if ( need_len < 0 ) return need_len; /* Allocate the required space */ if ( *result == NULL || *size < ( (size_t) need_len + 1 ) ) { size_t new_size = need_len + 1; char * new_buf = realloc( *result, ( new_size * sizeof(char) ) ); if ( *result == NULL ) { perror("Failed to allocate memory for LCFG resource key"); exit(EXIT_FAILURE); } else { *result = new_buf; *size = new_size; } } /* Always initialise the characters of the full space to nul */ memset( *result, '\0', *size ); ssize_t write_len = lcfgresource_insert_key( resource, component, namespace, type_symbol, *result ); return ( write_len == need_len ? write_len : -1 ); } /** * @brief Parse a resource specification * * This parses the given resource specification string into the * constituent (hostname, component name, resource name and value) * parts. Note that this function modifies the given string in-place * and returns pointers to the various chunks of interest. * * @param[in] spec Pointer to the resource spec (will be modified in place) * @param[out] hostname Reference to a pointer to the hostname part of the key (optional) * @param[out] compname Reference to a pointer to the component name part of the key (optional) * @param[out] resname Reference to a pointer to the resource name * @param[out] value Reference to a pointer to the resource value (might be empty) * @param[out] type The key type symbol * @param[out] msg Pointer to any diagnostic messages. * * @return Status value indicating success of the process * */ LCFGStatus lcfgresource_parse_spec( char * spec, const char ** hostname, const char ** compname, const char ** resname, const char ** value, char * type, char ** msg ) { assert( spec != NULL ); LCFGStatus status = LCFG_STATUS_OK; while ( *spec != '\0' && isspace(*spec) ) spec++; if ( isempty(spec) ) { lcfgutils_build_message( msg, "empty resource specification" ); status = LCFG_STATUS_ERROR; goto cleanup; } /* Search for the '=' which separates status keys and values */ char * sep = strchr( spec, '=' ); if ( sep == NULL ) { lcfgutils_build_message( msg, "missing '=' character" ); status = LCFG_STATUS_ERROR; goto cleanup; } /* Replace the '=' separator with a NULL so that can avoid unnecessarily dupping the string */ *sep = '\0'; /* The value is everything after the separator (could just be an empty string) */ *value = sep + 1; if ( !lcfgresource_parse_key( spec, hostname, compname, resname, type ) ) { lcfgutils_build_message( msg, "invalid resource key '%s'", spec ); status = LCFG_STATUS_ERROR; goto cleanup; } /* Validation */ if ( !lcfgresource_valid_name(*resname) ) { lcfgutils_build_message( msg, "invalid resource name '%s'", *resname ); status = LCFG_STATUS_ERROR; goto cleanup; } cleanup: return status; } /** * @brief Parse a resource key * * This parses the given resource key into the constituent (hostname, * component name and resource name) parts. Note that this function * modifies the given string in-place and returns pointers to the * various chunks of interest. * * @param[in] key Pointer to the resource key (will be modified in place) * @param[out] hostname Reference to a pointer to the hostname part of the key (optional) * @param[out] compname Reference to a pointer to the component name part of the key (optional) * @param[out] resname Reference to a pointer to the resource name * @param[out] type The key type symbol * * @return boolean indicating success * */ bool lcfgresource_parse_key( char * key, const char ** hostname, const char ** compname, const char ** resname, char * type ) { *hostname = NULL; *compname = NULL; *resname = NULL; *type = LCFG_RESOURCE_SYMBOL_VALUE; if ( isempty(key) ) return false; const char * start = key; /* Ignore any leading whitespace */ while ( *start != '\0' && isspace(*start) ) start++; if ( *start == '\0' ) return false; if ( *start == LCFG_RESOURCE_SYMBOL_DERIVATION || *start == LCFG_RESOURCE_SYMBOL_TYPE || *start == LCFG_RESOURCE_SYMBOL_PRIORITY ) { *type = *start; start++; } /* Resource name - finds the *last* separator */ char * sep = strrchr( start, '.' ); if ( sep != NULL ) { if ( *( sep + 1 ) != '\0' ) { *sep = '\0'; *resname = sep + 1; } else { return false; } } else { *resname = start; } /* Component name - finds the *last* separator */ if ( *resname != start ) { sep = strrchr( start, '.' ); if ( sep != NULL ) { if ( *( sep + 1 ) != '\0' ) { *sep = '\0'; *compname = sep + 1; } else { return false; } } else { *compname = start; } /* Anything left is the hostname / namespace */ if ( *compname != start ) *hostname = start; } return true; } /** * @brief Set a value for the required attribute * * This sets a value for the relevant resource attribute for a given * type symbol: * * - type - @c '%' * - context - @c '=' * - derivation - @c '#' * - priority - @c '^' * - value - nul * * This will take a copy of the new attribute value string where * necessary. * * @param[in] res Pointer to @c LCFGResource * @param[in] type_symbol The symbol for the required attribute type * @param[in] value The new value for the attribute * @param[in] value_len The length of the new value string for the attribute * @param[out] msg Pointer to any diagnostic messages * * @return boolean indicating success * */ bool lcfgresource_set_attribute( LCFGResource * res, char type_symbol, const char * value, size_t value_len, char ** msg ) { assert( res != NULL ); free(*msg); *msg = NULL; bool ok = false; /* Apply the action which matches with the symbol at the start of the status line or assume this is a simple specification of the resource value. */ /* Always take a copy to ensure the value string is null-terminated */ char * value_copy = NULL; if ( value_len > 0 ) value_copy = strndup( value, value_len ); bool free_copy = true; /* Will value_copy need freeing at end? */ const char * attr_name = NULL; /* used for error messages */ switch (type_symbol) { case LCFG_RESOURCE_SYMBOL_DERIVATION: ; attr_name = "derivation"; if ( value_len > 0 ) ok = lcfgresource_set_derivation_as_string( res, value_copy ); else ok = lcfgresource_set_derivation_as_string( res, NULL ); /* unset */ break; case LCFG_RESOURCE_SYMBOL_TYPE: ; attr_name = "type"; if ( value_len > 0 ) ok = lcfgresource_set_type_as_string( res, value_copy, msg ); else ok = lcfgresource_set_type_default(res); break; case LCFG_RESOURCE_SYMBOL_CONTEXT: ; attr_name = "context"; if ( value_len > 0 ) { ok = lcfgresource_set_context( res, value_copy ); if (ok) free_copy = false; } else { ok = lcfgresource_set_context( res, NULL ); /* unset */ } break; case LCFG_RESOURCE_SYMBOL_PRIORITY: ; attr_name = "priority"; if ( value_len > 0 ) { /* Be careful to only convert string to int if it looks safe */ ok = lcfgresource_valid_integer(value_copy); if (ok) { int priority = atoi(value_copy); ok = lcfgresource_set_priority( res, priority ); } } else { ok = lcfgresource_set_priority_default(res); } break; case LCFG_RESOURCE_SYMBOL_VALUE: default: /* value line */ ; attr_name = "value"; if ( value_len > 0 ) { /* Value strings may be html encoded as they can contain whitespace characters which would otherwise corrupt the status file formatting. */ lcfgutils_decode_html_entities_utf8( value_copy, NULL ); ok = lcfgresource_set_value( res, value_copy ); } else { value_copy = strdup(""); ok = lcfgresource_set_value( res, value_copy ); } if (ok) free_copy = false; break; } if ( !ok && *msg == NULL ) { lcfgutils_build_message( msg, "Invalid %s '%s'", attr_name, ( value_len > 0 ? value_copy : "(empty string)" )); } if (free_copy) free(value_copy); return ok; } /** * @brief Calculate the hash for a resource * * This will calculate the hash for the resource using the value for * the @e name parameter. It does this using the @c * lcfgutils_string_djbhash() function. * * @param[in] res Pointer to @c LCFGResource * * @return The hash for the resource name * */ unsigned long lcfgresource_hash( const LCFGResource * res ) { return lcfgutils_string_djbhash( res->name, NULL ); } /** * @brief Get a list of all child resources for a specific tag * * This generates an @c LCFGTagList of all possible child resource * names for an @c LCFGResource. Note that no test is done to see if * the resources actually exist. The tags passed in are applied to * each template for the resource to generate the names. It thus only * makes sense to call this on a @e list resource which has a set of * templates. * * @param[in] res Pointer to @c LCFGResource * @param[in] tags Pointer to @c LCFGTagList of tags * @param[out] result Reference to pointer to @c LCFGTagList of child names * @param[out] msg Pointer to any diagnostic messages * * @return Status value indicating success * */ LCFGStatus lcfgresource_child_names( const LCFGResource * res, LCFGTagList * tags, LCFGTagList ** result, char ** msg ) { assert( res != NULL ); size_t size = 64; char * child_name = calloc( size, sizeof(char) ); if ( child_name == NULL ) { perror("Failed to allocate memory for LCFG resource name"); exit(EXIT_FAILURE); } LCFGTagList * child_list = lcfgtaglist_new(); LCFGStatus status = LCFG_STATUS_OK; const LCFGTemplate * cur_tmpl = NULL; for ( cur_tmpl = lcfgresource_get_template(res); cur_tmpl != NULL && status != LCFG_STATUS_ERROR; cur_tmpl = cur_tmpl->next ) { ssize_t len = lcfgtemplate_substitute( cur_tmpl, tags, &child_name, &size, msg ); if ( len > 0 ) { LCFGChange rc = lcfgtaglist_mutate_append( child_list, child_name, msg ); if ( rc == LCFG_CHANGE_ERROR ) status = LCFG_STATUS_ERROR; } else { status = LCFG_STATUS_ERROR; } } free(child_name); if ( status == LCFG_STATUS_ERROR ) { lcfgtaglist_relinquish(child_list); child_list = NULL; } *result = child_list; return status; } /* eof */
sjquinney/lcfg-core
resources/resource.c
C
gpl-2.0
139,733
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="it"> <head> <!-- Generated by javadoc (version 1.7.0_03) on Tue Dec 09 10:56:11 CET 2014 --> <title>SubscriptionResponder.SubscriptionManager (JADE v4.3.3 API)</title> <meta name="date" content="2014-12-09"> <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="SubscriptionResponder.SubscriptionManager (JADE v4.3.3 API)"; } //--> </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 class="navBarCell1Rev">Class</li> <li><a href="class-use/SubscriptionResponder.SubscriptionManager.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto"><span class="strong">Prev Class</span></a></li> <li><a href="../../jade/proto/TwoPh0Initiator.html" title="class in jade.proto"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?jade/proto/SubscriptionResponder.SubscriptionManager.html" target="_top">Frames</a></li> <li><a href="SubscriptionResponder.SubscriptionManager.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">jade.proto</div> <h2 title="Interface SubscriptionResponder.SubscriptionManager" class="title">Interface SubscriptionResponder.SubscriptionManager</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../jade/proto/SubscriptionResponder.html" title="class in jade.proto">SubscriptionResponder</a></dd> </dl> <hr> <br> <pre>public static interface <span class="strong">SubscriptionResponder.SubscriptionManager</span></pre> <div class="block">Inner interface SubscriptionManager. <p> A <code>SubscriptionResponder</code>, besides enforcing and controlling the sequence of messages in a subscription conversation, also stores current subscriptions into an internal table. In many cases however it is desirable to manage Subscription objects in an application specific way (e.g. storing them to a persistent support such as a DB). To enable that, it is possible to pass a SubscriptionManager implementation to the SubscriptionResponder. The SubscriptionManager is notified about subscription and cancellation events by means of the register() and deregister() methods. <p></div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../jade/proto/SubscriptionResponder.SubscriptionManager.html#deregister(jade.proto.SubscriptionResponder.Subscription)">deregister</a></strong>(<a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto">SubscriptionResponder.Subscription</a>&nbsp;s)</code> <div class="block">Deregister a Subscription object</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../jade/proto/SubscriptionResponder.SubscriptionManager.html#register(jade.proto.SubscriptionResponder.Subscription)">register</a></strong>(<a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto">SubscriptionResponder.Subscription</a>&nbsp;s)</code> <div class="block">Register a new Subscription object</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="register(jade.proto.SubscriptionResponder.Subscription)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>register</h4> <pre>boolean&nbsp;register(<a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto">SubscriptionResponder.Subscription</a>&nbsp;s) throws <a href="../../jade/domain/FIPAAgentManagement/RefuseException.html" title="class in jade.domain.FIPAAgentManagement">RefuseException</a>, <a href="../../jade/domain/FIPAAgentManagement/NotUnderstoodException.html" title="class in jade.domain.FIPAAgentManagement">NotUnderstoodException</a></pre> <div class="block">Register a new Subscription object</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>s</code> - The Subscription object to be registered</dd> <dt><span class="strong">Returns:</span></dt><dd>The boolean value returned by this method provides an indication to the <code>SubscriptionResponder</code> about whether or not an AGREE message should be sent back to the initiator. The default implementation of the <code>handleSubscription()</code> method of the <code>SubscriptionResponder</code> ignores this indication, but programmers can override it.</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../jade/domain/FIPAAgentManagement/RefuseException.html" title="class in jade.domain.FIPAAgentManagement">RefuseException</a></code></dd> <dd><code><a href="../../jade/domain/FIPAAgentManagement/NotUnderstoodException.html" title="class in jade.domain.FIPAAgentManagement">NotUnderstoodException</a></code></dd></dl> </li> </ul> <a name="deregister(jade.proto.SubscriptionResponder.Subscription)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>deregister</h4> <pre>boolean&nbsp;deregister(<a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto">SubscriptionResponder.Subscription</a>&nbsp;s) throws <a href="../../jade/domain/FIPAAgentManagement/FailureException.html" title="class in jade.domain.FIPAAgentManagement">FailureException</a></pre> <div class="block">Deregister a Subscription object</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The boolean value returned by this method provides an indication to the <code>SubscriptionResponder</code> about whether or not an INFORM message should be sent back to the initiator. The default implementation of the <code>handleCancel()</code> method of the <code>SubscriptionResponder</code> ignores this indication, but programmers can override it.</dd> <dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../jade/domain/FIPAAgentManagement/FailureException.html" title="class in jade.domain.FIPAAgentManagement">FailureException</a></code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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 class="navBarCell1Rev">Class</li> <li><a href="class-use/SubscriptionResponder.SubscriptionManager.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../jade/proto/SubscriptionResponder.Subscription.html" title="class in jade.proto"><span class="strong">Prev Class</span></a></li> <li><a href="../../jade/proto/TwoPh0Initiator.html" title="class in jade.proto"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?jade/proto/SubscriptionResponder.SubscriptionManager.html" target="_top">Frames</a></li> <li><a href="SubscriptionResponder.SubscriptionManager.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><center>These are the official <i><a href=http://jade.tilab.com target=top>JADE</a></i> API. For these API backward compatibility is guaranteed accross JADE versions</center></small></p> </body> </html>
LeeboyOver9000/TCC
doc/api/jade/proto/SubscriptionResponder.SubscriptionManager.html
HTML
gpl-2.0
11,664
#ifndef TSP_TSP_H #define TSP_TSP_H #include <pthread.h> /* dernier minimum trouvé */ extern int minimum; /********************************************/ struct arg_struct { int hops; /* Nb de ville dans le chemin path */ int len; /* Longueur du chemin path */ tsp_path_t path; /* Chemin */ int pere; }; /*********************************************/ int present (int city, int hops, tsp_path_t path); void* tsp (void* arguments); /*********************************************/ typedef struct Cell{ pthread_t thread; int occupe; } Cell; /********************************************/ int getTID (void); #endif
darkrossi/SEPC-Threads
src/tsp-tsp.h
C
gpl-2.0
628
#!/bin/sh dir=`echo "$0" | sed 's,[^/]*$,,'` test "x${dir}" = "x" && dir='.' if test "x`cd "${dir}" 2>/dev/null && pwd`" != "x`pwd`" then echo "this script must be executed directly from the source directory." exit 1 fi # this might not be necessary with newer autotools: rm -f config.cache # older crap way #aclocal #autoconf #autoheader #automake -a -c echo "Running:" echo "- libtoolize" && \ libtoolize --copy --force --automake && \ echo "- aclocal" && \ aclocal-1.4 && \ echo "- autoconf" && \ autoconf && \ echo "- autoheader" && \ autoheader && \ echo "- automake" && \ automake-1.4 --add-missing --gnu && \ echo && \ echo "Now run ./configure [options] and then make." && \ echo && \ exit 0 #echo "Running ./configure ..." && \ #./configure "$@" exit 1
OpenedHand/grandr-applet
autogen.sh
Shell
gpl-2.0
1,037
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-} module PGIP.GraphQL.Result.LocIdReference where import Data.Data newtype LocIdReference = LocIdReference { locId :: String } deriving (Show, Typeable, Data)
spechub/Hets
PGIP/GraphQL/Result/LocIdReference.hs
Haskell
gpl-2.0
255
import requests import yaml class RequestsApi: def __init__(self): 'init' self.config = yaml.load(open("config/request_settings.yml", "r")) def get_objects(self, sector): 'request to get objects' objects_points = [] url = self.config['host'] + self.config['object_path'] % sector response = requests.get(url) if not response.status_code == 200 : return [] for line in response.text.splitlines(): objects_points.append([int(num) for num in line.split(' ')]) return objects_points def get_roots(self, sector): 'request to get roots' roots = [] url = self.config['host'] + self.config['root_path'] % sector response = requests.get(url) if not response.status_code == 200 : return [] for line in response.text.splitlines(): roots.append(int(line)) return roots def send_trajectory(self, sector, paths): 'requets to send trajectory' url = self.config['host'] + self.config['trajectory_path'] % sector requests.post(url, params = {'trajectory' : paths})
veskopos/VMWare
api/requests_api.py
Python
gpl-2.0
1,010
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.model; import edu.cmu.tetrad.data.*; import edu.cmu.tetrad.graph.*; import edu.cmu.tetrad.search.*; import edu.cmu.tetrad.session.DoNotAddOldModel; import edu.cmu.tetrad.util.TetradSerializableUtils; import edu.cmu.tetrad.util.Unmarshallable; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DecimalFormat; import java.util.*; /** * Extends AbstractAlgorithmRunner to produce a wrapper for the GES algorithm. * * @author Ricardo Silva */ public class FgsRunner extends AbstractAlgorithmRunner implements IFgsRunner, GraphSource, PropertyChangeListener, IGesRunner, Indexable, DoNotAddOldModel, Unmarshallable { static final long serialVersionUID = 23L; private LinkedHashMap<String, String> allParamSettings; public enum Type {CONTINUOUS, DISCRETE, GRAPH} private transient List<PropertyChangeListener> listeners; private List<ScoredGraph> topGraphs; private int index; private transient Fgs2 fgs; private transient Graph initialGraph; //============================CONSTRUCTORS============================// public FgsRunner(DataWrapper dataWrapper, FgsParams params, KnowledgeBoxModel knowledgeBoxModel) { super(new MergeDatasetsWrapper(dataWrapper), params, knowledgeBoxModel); } public FgsRunner(DataWrapper dataWrapper, FgsParams params) { super(new MergeDatasetsWrapper(dataWrapper), params, null); } public FgsRunner(DataWrapper dataWrapper, GraphSource graph, FgsParams params) { super(new MergeDatasetsWrapper(dataWrapper), params, null); // if (graph == dataWrapper) throw new IllegalArgumentException(); if (graph == this) throw new IllegalArgumentException(); this.initialGraph = graph.getGraph(); } public FgsRunner(DataWrapper dataWrapper, GraphSource graph, FgsParams params, KnowledgeBoxModel knowledgeBoxModel) { super(new MergeDatasetsWrapper(dataWrapper), params, knowledgeBoxModel); if (graph == this) throw new IllegalArgumentException(); this.initialGraph = graph.getGraph(); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, DataWrapper dataWrapper6, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5, dataWrapper6 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, DataWrapper dataWrapper6, DataWrapper dataWrapper7, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5, dataWrapper6, dataWrapper7 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, DataWrapper dataWrapper6, DataWrapper dataWrapper7, DataWrapper dataWrapper8, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5, dataWrapper6, dataWrapper7, dataWrapper8 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, DataWrapper dataWrapper6, DataWrapper dataWrapper7, DataWrapper dataWrapper8, DataWrapper dataWrapper9, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5, dataWrapper6, dataWrapper7, dataWrapper8, dataWrapper9 ), params, null); } public FgsRunner(DataWrapper dataWrapper1, DataWrapper dataWrapper2, DataWrapper dataWrapper3, DataWrapper dataWrapper4, DataWrapper dataWrapper5, DataWrapper dataWrapper6, DataWrapper dataWrapper7, DataWrapper dataWrapper8, DataWrapper dataWrapper9, DataWrapper dataWrapper10, FgsParams params) { super(new MergeDatasetsWrapper( dataWrapper1, dataWrapper2, dataWrapper3, dataWrapper4, dataWrapper5, dataWrapper6, dataWrapper7, dataWrapper8, dataWrapper9, dataWrapper10 ), params, null); } public FgsRunner(GraphWrapper graphWrapper, FgsParams params, KnowledgeBoxModel knowledgeBoxModel) { super(graphWrapper.getGraph(), params, knowledgeBoxModel); } public FgsRunner(GraphWrapper graphWrapper, FgsParams params) { super(graphWrapper.getGraph(), params, null); } /** * Generates a simple exemplar of this class to test serialization. * * @see TetradSerializableUtils */ public static FgsRunner serializableInstance() { return new FgsRunner(DataWrapper.serializableInstance(), FgsParams.serializableInstance(), KnowledgeBoxModel.serializableInstance()); } //============================PUBLIC METHODS==========================// /** * Executes the algorithm, producing (at least) a result workbench. Must be * implemented in the extending class. */ public void execute() { System.out.println("A"); Object model = getDataModel(); if (model == null && getSourceGraph() != null) { model = getSourceGraph(); } if (model == null) { throw new RuntimeException("Data source is unspecified. You may need to double click all your data boxes, \n" + "then click Save, and then right click on them and select Propagate Downstream. \n" + "The issue is that we use a seed to simulate from IM's, so your data is not saved to \n" + "file when you save the session. It can, however, be recreated from the saved seed."); } FgsParams params = (FgsParams) getParams(); if (model instanceof Graph) { GraphScore gesScore = new GraphScore((Graph) model); fgs = new Fgs2(gesScore); fgs.setKnowledge(getParams().getKnowledge()); fgs.setVerbose(true); } else { double penaltyDiscount = params.getComplexityPenalty(); if (model instanceof DataSet) { DataSet dataSet = (DataSet) model; if (dataSet.isContinuous()) { SemBicScore gesScore = new SemBicScore(new CovarianceMatrixOnTheFly((DataSet) model)); // SemBicScore2 gesScore = new SemBicScore2(new CovarianceMatrixOnTheFly((DataSet) model)); // SemGpScore gesScore = new SemGpScore(new CovarianceMatrixOnTheFly((DataSet) model)); // SvrScore gesScore = new SvrScore((DataSet) model); gesScore.setPenaltyDiscount(penaltyDiscount); System.out.println("Score done"); fgs = new Fgs2(gesScore); } else if (dataSet.isDiscrete()) { double samplePrior = ((FgsParams) getParams()).getSamplePrior(); double structurePrior = ((FgsParams) getParams()).getStructurePrior(); BDeuScore score = new BDeuScore(dataSet); score.setSamplePrior(samplePrior); score.setStructurePrior(structurePrior); fgs = new Fgs2(score); } else { throw new IllegalStateException("Data set must either be continuous or discrete."); } } else if (model instanceof ICovarianceMatrix) { SemBicScore gesScore = new SemBicScore((ICovarianceMatrix) model); gesScore.setPenaltyDiscount(penaltyDiscount); gesScore.setPenaltyDiscount(penaltyDiscount); fgs = new Fgs2(gesScore); } else if (model instanceof DataModelList) { DataModelList list = (DataModelList) model; for (DataModel dataModel : list) { if (!(dataModel instanceof DataSet || dataModel instanceof ICovarianceMatrix)) { throw new IllegalArgumentException("Need a combination of all continuous data sets or " + "covariance matrices, or else all discrete data sets, or else a single initialGraph."); } } if (list.size() != 1) { throw new IllegalArgumentException("FGS takes exactly one data set, covariance matrix, or initialGraph " + "as input. For multiple data sets as input, use IMaGES."); } FgsParams FgsParams = (FgsParams) getParams(); FgsIndTestParams indTestParams = (FgsIndTestParams) FgsParams.getIndTestParams(); if (allContinuous(list)) { double penalty = ((FgsParams) getParams()).getComplexityPenalty(); if (indTestParams.isFirstNontriangular()) { SemBicScoreImages fgsScore = new SemBicScoreImages(list); fgsScore.setPenaltyDiscount(penalty); fgs = new Fgs2(fgsScore); } else { SemBicScoreImages fgsScore = new SemBicScoreImages(list); fgsScore.setPenaltyDiscount(penalty); fgs = new Fgs2(fgsScore); } } else if (allDiscrete(list)) { double structurePrior = ((FgsParams) getParams()).getStructurePrior(); double samplePrior = ((FgsParams) getParams()).getSamplePrior(); BdeuScoreImages fgsScore = new BdeuScoreImages(list); fgsScore.setSamplePrior(samplePrior); fgsScore.setStructurePrior(structurePrior); if (indTestParams.isFirstNontriangular()) { fgs = new Fgs2(fgsScore); } else { fgs = new Fgs2(fgsScore); } } else { throw new IllegalArgumentException("Data must be either all discrete or all continuous."); } } else { System.out.println("No viable input."); } } // fgs.setInitialGraph(initialGraph); // fgs.setKnowledge(getParams().getKnowledge()); fgs.setNumPatternsToStore(params.getIndTestParams().getNumPatternsToSave()); fgs.setVerbose(true); // fgs.setHeuristicSpeedup(true); // fgs.setDepth(3); fgs.setFaithfulnessAssumed(((FgsIndTestParams) params.getIndTestParams()).isFaithfulnessAssumed()); Graph graph = fgs.search(); if (getSourceGraph() != null) { GraphUtils.arrangeBySourceGraph(graph, getSourceGraph()); } else if (getParams().getKnowledge().isDefaultToKnowledgeLayout()) { SearchGraphUtils.arrangeByKnowledgeTiers(graph, getParams().getKnowledge()); } else { GraphUtils.circleLayout(graph, 200, 200, 150); } setResultGraph(graph); this.topGraphs = new ArrayList<>(fgs.getTopGraphs()); if (topGraphs.isEmpty()) { topGraphs.add(new ScoredGraph(getResultGraph(), Double.NaN)); } setIndex(topGraphs.size() - 1); } /** * Executes the algorithm, producing (at least) a result workbench. Must be * implemented in the extending class. */ public Type getType() { Object model = getDataModel(); if (model == null && getSourceGraph() != null) { model = getSourceGraph(); } if (model == null) { throw new RuntimeException("Data source is unspecified. You may need to double click all your data boxes, \n" + "then click Save, and then right click on them and select Propagate Downstream. \n" + "The issue is that we use a seed to simulate from IM's, so your data is not saved to \n" + "file when you save the session. It can, however, be recreated from the saved seed."); } Type type; if (model instanceof Graph) { type = Type.GRAPH; } else if (model instanceof DataSet) { DataSet dataSet = (DataSet) model; if (dataSet.isContinuous()) { type = Type.CONTINUOUS; } else if (dataSet.isDiscrete()) { type = Type.DISCRETE; } else { throw new IllegalStateException("Data set must either be continuous or discrete."); } } else if (model instanceof ICovarianceMatrix) { type = Type.CONTINUOUS; } else if (model instanceof DataModelList) { DataModelList list = (DataModelList) model; if (allContinuous(list)) { type = Type.CONTINUOUS; } else if (allDiscrete(list)) { type = Type.DISCRETE; } else { throw new IllegalArgumentException("Data must be either all discrete or all continuous."); } } else { throw new IllegalArgumentException("Unrecognized data type."); } return type; } private boolean allContinuous(List<DataModel> dataModels) { for (DataModel dataModel : dataModels) { if (dataModel instanceof DataSet) { if (!((DataSet) dataModel).isContinuous() || dataModel instanceof ICovarianceMatrix) { return false; } } } return true; } private boolean allDiscrete(List<DataModel> dataModels) { for (DataModel dataModel : dataModels) { if (dataModel instanceof DataSet) { if (!((DataSet) dataModel).isDiscrete()) { return false; } } } return true; } public void setIndex(int index) { if (index < -1) { throw new IllegalArgumentException("Must be in >= -1: " + index); } this.index = index; } public int getIndex() { return index; } public Graph getGraph() { if (getIndex() >= 0) { return getTopGraphs().get(getIndex()).getGraph(); } else { return getResultGraph(); } } /** * @return the names of the triple classifications. Coordinates with */ public List<String> getTriplesClassificationTypes() { return new ArrayList<String>(); } /** * @return the list of triples corresponding to <code>getTripleClassificationNames</code>. */ public List<List<Triple>> getTriplesLists(Node node) { return new ArrayList<List<Triple>>(); } public boolean supportsKnowledge() { return true; } public ImpliedOrientation getMeekRules() { MeekRules rules = new MeekRules(); rules.setKnowledge(getParams().getKnowledge()); return rules; } @Override public Map<String, String> getParamSettings() { super.getParamSettings(); FgsParams params = (FgsParams) getParams(); paramSettings.put("Penalty Discount", new DecimalFormat("0.0").format(params.getComplexityPenalty())); return paramSettings; } @Override public String getAlgorithmName() { return "FGS"; } public void propertyChange(PropertyChangeEvent evt) { firePropertyChange(evt); } private void firePropertyChange(PropertyChangeEvent evt) { for (PropertyChangeListener l : getListeners()) { l.propertyChange(evt); } } private List<PropertyChangeListener> getListeners() { if (listeners == null) { listeners = new ArrayList<PropertyChangeListener>(); } return listeners; } public void addPropertyChangeListener(PropertyChangeListener l) { if (!getListeners().contains(l)) getListeners().add(l); } public List<ScoredGraph> getTopGraphs() { return this.topGraphs; } public String getBayesFactorsReport(Graph dag) { if (fgs == null) { return "Please re-run IMaGES."; } else { return fgs.logEdgeBayesFactorsString(dag); } } public GraphScorer getGraphScorer() { return fgs; } }
ajsedgewick/tetrad
tetrad-gui/src/main/java/edu/cmu/tetradapp/model/FgsRunner.java
Java
gpl-2.0
21,781
DontEatHere =========== An online and WPF application for viewing Food Safety Violations at Houston Restaurants
jabbrass/DontEatHere
README.md
Markdown
gpl-2.0
113
# Makefile.in generated by automake 1.13.1 from Makefile.am. # src/libz/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994-2012 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/gtkwave pkgincludedir = $(includedir)/gtkwave pkglibdir = $(libdir)/gtkwave pkglibexecdir = $(libexecdir)/gtkwave am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : subdir = src/libz DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp README ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) AR = ar ARFLAGS = cru AM_V_AR = $(am__v_AR_$(V)) am__v_AR_ = $(am__v_AR_$(AM_DEFAULT_VERBOSITY)) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = libz_a_AR = $(AR) $(ARFLAGS) libz_a_LIBADD = am_libz_a_OBJECTS = adler32.$(OBJEXT) gzread.$(OBJEXT) trees.$(OBJEXT) \ zutil.$(OBJEXT) compress.$(OBJEXT) example.$(OBJEXT) \ gzwrite.$(OBJEXT) inflate.$(OBJEXT) crc32.$(OBJEXT) \ gzclose.$(OBJEXT) infback.$(OBJEXT) uncompr.$(OBJEXT) \ inffast.$(OBJEXT) inftrees.$(OBJEXT) deflate.$(OBJEXT) \ gzlib.$(OBJEXT) libz_a_OBJECTS = $(am_libz_a_OBJECTS) AM_V_P = $(am__v_P_$(V)) am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY)) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libz_a_SOURCES) DIST_SOURCES = $(libz_a_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /e/gtkspy/gtkspy/missing aclocal-1.13 AET2_CFLAGS = AET2_LDADD = ALLOCA = AMTAR = $${TAR-tar} AM_DEFAULT_VERBOSITY = 1 AUTOCONF = ${SHELL} /e/gtkspy/gtkspy/missing autoconf AUTOHEADER = ${SHELL} /e/gtkspy/gtkspy/missing autoheader AUTOMAKE = ${SHELL} /e/gtkspy/gtkspy/missing automake-1.13 AWK = gawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 -DFST_WRITER_PARALLEL COCOA_GTK_CFLAGS = COCOA_GTK_LDADD = COCOA_GTK_LDFLAGS = CPP = gcc -E CPPFLAGS = -DWAVE_USE_GTK2 CXX = g++ CXXDEPMODE = depmode=gcc3 CXXFLAGS = -g -O2 CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = .exe EXTDEBUG = notfound EXTDEBUG2 = notfound EXTDEBUG3 = notfound EXTDEBUG4 = notfound EXTLOAD_CFLAGS = FASTTREE_CFLAGS = FSDB_CFLAGS = FSDB_LDADD = GCONF_CFLAGS = GCONF_LIBS = GEDITTEST = notfound GEDIT_CFLAGS = GPERF = /c/MinGW/bin/gperf GREP = /bin/grep GTK_CFLAGS = -mms-bitfields -Ic:/MinGW/include/gtk-2.0 -Ic:/MinGW/lib/gtk-2.0/include -Ic:/MinGW/include/atk-1.0 -Ic:/MinGW/include/cairo -Ic:/MinGW/include/gdk-pixbuf-2.0 -Ic:/MinGW/include/pango-1.0 -Ic:/MinGW/include/glib-2.0 -Ic:/MinGW/lib/glib-2.0/include -Ic:/MinGW/include -Ic:/MinGW/include/pixman-1 -Ic:/MinGW/include/freetype2 -Ic:/MinGW/include/libpng15 GTK_CONFIG = GTK_LIBS = -Wl,-luuid -Lc:/MinGW/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -limm32 -lshell32 -lole32 -latk-1.0 -lpangocairo-1.0 -lgio-2.0 -lgdk_pixbuf-2.0 -lpangoft2-1.0 -lpangowin32-1.0 -lgdi32 -lfreetype -lfontconfig -lpango-1.0 -lm -lcairo -lgobject-2.0 -lglib-2.0 -lintl GTK_MAC_CFLAGS = GTK_MAC_LIBS = GTK_UNIX_PRINT_CFLAGS = GTK_UNIX_PRINT_LIBS = INSTALL = /bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LDFLAGS = LEX = flex LEXLIB = LEX_OUTPUT_ROOT = lex.yy LIBBZ2_CFLAGS = -I$(top_srcdir)/src/libbz2 LIBBZ2_DIR = libbz2 LIBBZ2_LDADD = $(top_builddir)/src/libbz2/libbz2.a LIBJUDY_CFLAGS = LIBJUDY_LDADD = LIBOBJS = ${LIBOBJDIR}error$U.o ${LIBOBJDIR}lstat$U.o LIBS = -lm -ldl LIBXZ_CFLAGS = LIBXZ_LDADD = LIBZ_CFLAGS = LIBZ_DIR = LIBZ_LDADD = -lz LTLIBOBJS = ${LIBOBJDIR}error$U.lo ${LIBOBJDIR}lstat$U.lo MAINT = # MAKEINFO = ${SHELL} /e/gtkspy/gtkspy/missing makeinfo MINGW_LDADD = -lcomdlg32 MKDIR_P = /bin/mkdir -p OBJEXT = o PACKAGE = gtkwave PACKAGE_BUGREPORT = bybell@rocketmail.com PACKAGE_NAME = gtkwave PACKAGE_STRING = gtkwave 3.3.64 PACKAGE_TARNAME = gtkwave PACKAGE_URL = PACKAGE_VERSION = 3.3.64 PATH_SEPARATOR = : PKG_CONFIG = /c/MinGW/bin/pkg-config POW_LIB = RANLIB = ranlib SET_MAKE = SHELL = /bin/sh STRIP = STRUCT_PACK = TCL_DEFADD = -DHAVE_LIBTCL TCL_INCLUDE_SPEC = -I/mingw/include TCL_LDADD = -L/mingw/lib -ltcl86 TCL_LIB_SPEC = -L/mingw/lib -ltcl86 TCL_MAJOR_VERSION = 8 TCL_MINOR_VERSION = 6 TK_INCLUDE_SPEC = TK_LDADD = -L/mingw/lib -ltk86 TK_LIB_SPEC = -L/mingw/lib -ltk86 UPDATE_DESKTOP_DATABASE = no UPDATE_MIME_DATABASE = no VERSION = 3.3.64 XDGDATADIR = ${datadir} abs_builddir = /e/gtkspy/gtkspy/src/libz abs_srcdir = /e/gtkspy/gtkspy/src/libz abs_top_builddir = /e/gtkspy/gtkspy abs_top_srcdir = /e/gtkspy/gtkspy ac_ct_CC = gcc ac_ct_CXX = g++ am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build_alias = builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host_alias = htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /e/gtkspy/gtkspy/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = $(MKDIR_P) oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../../ top_builddir = ../.. top_srcdir = ../.. noinst_LIBRARIES = libz.a AM_CFLAGS = -DNO_VIZ libz_a_SOURCES = adler32.c deflate.h gzread.c inffixed.h trees.c zutil.c \ compress.c example.c gzwrite.c inflate.c trees.h zutil.h \ crc32.c gzclose.c infback.c inflate.h uncompr.c \ crc32.h gzguts.h inffast.c inftrees.c zconf.h \ deflate.c gzlib.c inffast.h inftrees.h zlib.h EXTRA_DIST = README all: all-am .SUFFIXES: .SUFFIXES: .c .o .obj $(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/libz/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/libz/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: # $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): # $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) libz.a: $(libz_a_OBJECTS) $(libz_a_DEPENDENCIES) $(EXTRA_libz_a_DEPENDENCIES) $(AM_V_at)-rm -f libz.a $(AM_V_AR)$(libz_a_AR) libz.a $(libz_a_OBJECTS) $(libz_a_LIBADD) $(AM_V_at)$(RANLIB) libz.a mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/adler32.Po include ./$(DEPDIR)/compress.Po include ./$(DEPDIR)/crc32.Po include ./$(DEPDIR)/deflate.Po include ./$(DEPDIR)/example.Po include ./$(DEPDIR)/gzclose.Po include ./$(DEPDIR)/gzlib.Po include ./$(DEPDIR)/gzread.Po include ./$(DEPDIR)/gzwrite.Po include ./$(DEPDIR)/infback.Po include ./$(DEPDIR)/inffast.Po include ./$(DEPDIR)/inflate.Po include ./$(DEPDIR)/inftrees.Po include ./$(DEPDIR)/trees.Po include ./$(DEPDIR)/uncompr.Po include ./$(DEPDIR)/zutil.Po .c.o: $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c $< .c.obj: $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # $(AM_V_CC)source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(AM_V_CC_no)$(COMPILE) -c `$(CYGPATH_W) '$<'` ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-noinstLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-noinstLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
jazonk/gtkspy
src/libz/Makefile
Makefile
gpl-2.0
17,098
xpartsoft =========
xpartkamrul/xpartsoft
README.md
Markdown
gpl-2.0
20
Scholdoc ======== ### Converts [ScholarlyMarkdown][scholmd] documents into HTML5, LaTeX, or Docx **Current stable version:** 0.1.4 **Development build status** [![build status][scholarly-devel-travisimage]][travis_stat] **Stable build status** [![build status][scholarly-travisimage]][travis_stat] **Scholdoc** is a command-line utility that converts [ScholarlyMarkdown][scholmd] documents into the HTML5, LaTeX, and Docx (OOML) formats. It is intended to facilitate academic writing in a cross-platform, semantic-aware, plaintext format that can be quickly used in modern publishing pipelines. You can test the HTML and LaTeX output of Scholdoc on small (limited to 10,000 characters) [ScholarlyMarkdown][scholmd] snippets using the online [Dingus][dingus]. Scholdoc is implemented as fork of [Pandoc][pandoc], and mostly retains the same user interface (including the custom [template][pandocTemplate] and [filter][pandocFilters] system). It essentially understands a new input format `markdown_scholarly` (implemented in the markdown reader a superset of `markdown_pandoc` features), and limits itself to HTML5/LaTeX/Docx output. Scholdoc defaults to `standalone` output and has its own [custom templates][scholdoc-templates] to ensure output compatibility with [ScholarlyMarkdown][scholmd]. See the [Pandoc Guide][pandocReadme] for more about Pandoc, its usage, and the Markdown dialect that Pandoc (and hence Scholdoc) [understands][pandocMarkdown]. Scholdoc is currently up to date with [Pandoc][pandoc] version 1.13.2 (up to commit fb7a03dcda) ### Installing Scholdoc #### Via Homebrew (OS X only) On OS X, the easiest way to obtain Scholdoc is from the official [Homebrew][Homebrew] [tap][homebrew-scholdoc]. First make sure you have [Homebrew][Homebrew] set-up correctly on your system, and that running `brew doctor` gives you no serious warnings. After that, run the following: brew tap timtylin/scholdoc brew update brew install scholdoc scholdoc-citeproc To upgrade to the latest release, just run brew update brew upgrade scholdoc scholdoc-citeproc #### Via pre-built binary distribution Pre-built binary distributions exist for some platforms. Check the [download][scholdoc-download] page to see the list of available builds. #### Compile via Hackage (all operating systems) Scholdoc is written in pure Haskell. It requires the [GHC] compiler and the [cabal-install] build system. The easiest way to get it on all platforms is by installing the [Haskell platform] for your operating system. Please make sure you are using GHC version 7.4 or above. If you are using Ubuntu, Herbert V. Riedel have conveniently provided a [PPA of pre-compiled GHC and cabal-install][hvr-PPA] for recent Ubuntu systems. Here's an example of how to get recommended versions of [GHC] and [cabal-install] using `apt-get` sudo add-apt-repository ppa:hvr/ghc sudo apt-get update && sudo apt-get install ghc-7.8.3 cabal-install-1.20 Once you have GHC and `cabal-install` on your system, run the following cabal update cabal install scholdoc cabal install scholdoc-citeproc To upgrade to the latest release of Scholdoc, just run the above three commands again. ### HTML output ***Important:*** *A ScholarlyMarkdown [core CSS][corecss] is required for proper formatting of most HTML files output by Scholdoc.* Scholdoc's HTML output is strictly limited to HTML5 due to its enhanced semantic capabilities (such as the `figure` and `figcaption` element), and relies on some CSS3 features for layout (mostly for multi-image figures with subcaptions). It adheres to a fairly straightforward [schema][html-schema]. No formatting information is written to the HTML by Scholdoc, so a ScholarlyMarkdown [core CSS][corecss] is required for bare minimum proper formatting. You can also write your own CSS that target the schema. By default, the `html` output format generates a complete (but bare-bones) HTML5 document that can be used immediately. To have Scholdoc generate just the bare content (everything inside [`scholmd-content`][html-schema-content]), use the `html_bodyonly` output format. By default, Scholdoc will always include proper [MathJax] settings for the way [ScholarlyMarkdown][scholmd] prescribes math content in HTML. ### Docx output The Docx writer currently isn't fully functional yet. It does not yet output structures specific to ScholarlyMarkdown (such as figures). [scholmd]: http://scholarlymarkdown.com [scholdoc]: https://github.com/timtylin/scholdoc [scholdoc-types]: https://github.com/timtylin/scholdoc-types [texmath]: https://github.com/jgm/texmath [pandoc]: http://johnmacfarlane.net/pandoc/ [pandocReadme]: http://johnmacfarlane.net/pandoc/README.html [pandocMarkdown]: http://johnmacfarlane.net/pandoc/README.html#pandocs-markdown [pandocTemplate]: http://johnmacfarlane.net/pandoc/README.html#templates [pandocFilters]: https://github.com/jgm/pandocfilters [pandocWriters]: http://johnmacfarlane.net/pandoc/README.html#custom-writers [pandoc-types]: https://github.com/jgm/pandoc-types [travis_stat]: https://travis-ci.org/timtylin/scholdoc [scholarly-devel-travisimage]: https://travis-ci.org/timtylin/scholdoc.svg?branch=master [scholarly-travisimage]: https://travis-ci.org/timtylin/scholdoc.svg?branch=stable [scholdoc-templates]: https://github.com/timtylin/scholdoc-templates [html-schema]: http://scholarlymarkdown.com/Scholarly-Markdown-HTML-Schema.html [html-schema-content]: http://scholarlymarkdown.com/Scholarly-Markdown-HTML-Schema.html#content [corecss]: http://scholarlymarkdown.com/scholdoc-distribution/css/core/scholmd-core-latest.css [mathjax]: http://www.mathjax.org [GHC]: http://www.haskell.org/ghc/ [Haskell platform]: http://hackage.haskell.org/platform/ [cabal-install]: http://hackage.haskell.org/trac/hackage/wiki/CabalInstall [zip-archive]: http://hackage.haskell.org/package/zip-archive [highlighting-kate]: http://hackage.haskell.org/package/highlighting-kate [blaze-html]: http://hackage.haskell.org/package/blaze-html [Cabal User's Guide]: http://www.haskell.org/cabal/release/latest/doc/users-guide/builders.html#setup-configure-paths [Homebrew]: http://brew.sh [hvr-PPA]: https://launchpad.net/~hvr/+archive/ubuntu/ghc [homebrew-scholdoc]: https://github.com/timtylin/homebrew-scholdoc/ [dingus]: http://scholarlymarkdown.com/dingus/ [scholdoc-download]: http://scholdoc.scholarlymarkdown.com/download/
timtylin/scholdoc
README.md
Markdown
gpl-2.0
6,425
# Copyright © 2007 Raphaël Hertzog <hertzog@debian.org> # Copyright © 2009-2010 Modestas Vainius <modax@debian.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, see <http://www.gnu.org/licenses/>. package Dpkg::Shlibs::SymbolFile; use strict; use warnings; our $VERSION = "0.01"; use Dpkg::Gettext; use Dpkg::ErrorHandling; use Dpkg::Version; use Dpkg::Control::Fields; use Dpkg::Shlibs::Symbol; use Dpkg::Arch qw(get_host_arch); use base qw(Dpkg::Interface::Storable); my %blacklist = ( '__bss_end__' => 1, # arm '__bss_end' => 1, # arm '_bss_end__' => 1, # arm '__bss_start' => 1, # ALL '__bss_start__' => 1, # arm '__data_start' => 1, # arm '__do_global_ctors_aux' => 1, # ia64 '__do_global_dtors_aux' => 1, # ia64 '__do_jv_register_classes' => 1,# ia64 '_DYNAMIC' => 1, # ALL '_edata' => 1, # ALL '_end' => 1, # ALL '__end__' => 1, # arm '__exidx_end' => 1, # armel '__exidx_start' => 1, # armel '_fbss' => 1, # mips, mipsel '_fdata' => 1, # mips, mipsel '_fini' => 1, # ALL '_ftext' => 1, # mips, mipsel '_GLOBAL_OFFSET_TABLE_' => 1, # hppa, mips, mipsel '__gmon_start__' => 1, # hppa '__gnu_local_gp' => 1, # mips, mipsel '_gp' => 1, # mips, mipsel '_init' => 1, # ALL '_PROCEDURE_LINKAGE_TABLE_' => 1, # sparc, alpha '_SDA2_BASE_' => 1, # powerpc '_SDA_BASE_' => 1, # powerpc ); for (my $i = 14; $i <= 31; $i++) { # Many powerpc specific symbols $blacklist{"_restfpr_$i"} = 1; $blacklist{"_restfpr_$i\_x"} = 1; $blacklist{"_restgpr_$i"} = 1; $blacklist{"_restgpr_$i\_x"} = 1; $blacklist{"_savefpr_$i"} = 1; $blacklist{"_savegpr_$i"} = 1; } # Many armel-specific symbols $blacklist{"__aeabi_$_"} = 1 foreach (qw(cdcmpeq cdcmple cdrcmple cfcmpeq cfcmple cfrcmple d2f d2iz d2lz d2uiz d2ulz dadd dcmpeq dcmpge dcmpgt dcmple dcmplt dcmpun ddiv dmul dneg drsub dsub f2d f2iz f2lz f2uiz f2ulz fadd fcmpeq fcmpge fcmpgt fcmple fcmplt fcmpun fdiv fmul fneg frsub fsub i2d i2f idiv idivmod l2d l2f lasr lcmp ldivmod llsl llsr lmul ui2d ui2f uidiv uidivmod ul2d ul2f ulcmp uldivmod unwind_cpp_pr0 unwind_cpp_pr1 unwind_cpp_pr2 uread4 uread8 uwrite4 uwrite8)); sub new { my $this = shift; my %opts=@_; my $class = ref($this) || $this; my $self = \%opts; bless $self, $class; $self->{arch} = get_host_arch() unless defined $self->{arch}; $self->clear(); if (exists $self->{file}) { $self->load($self->{file}) if -e $self->{file}; } return $self; } sub get_arch { my ($self) = @_; return $self->{arch}; } sub clear { my ($self) = @_; $self->{objects} = {}; } sub clear_except { my ($self, @ids) = @_; my %has; $has{$_} = 1 foreach (@ids); foreach my $objid (keys %{$self->{objects}}) { delete $self->{objects}{$objid} unless exists $has{$objid}; } } sub get_sonames { my ($self) = @_; return keys %{$self->{objects}}; } sub get_symbols { my ($self, $soname) = @_; if (defined $soname) { my $obj = $self->get_object($soname); return (defined $obj) ? values %{$obj->{syms}} : (); } else { my @syms; foreach my $soname ($self->get_sonames()) { push @syms, $self->get_symbols($soname); } return @syms; } } sub get_patterns { my ($self, $soname) = @_; my @patterns; if (defined $soname) { my $obj = $self->get_object($soname); foreach my $alias (values %{$obj->{patterns}{aliases}}) { push @patterns, values %$alias; } return (@patterns, @{$obj->{patterns}{generic}}); } else { foreach my $soname ($self->get_sonames()) { push @patterns, $self->get_patterns($soname); } return @patterns; } } # Create a symbol from the supplied string specification. sub create_symbol { my ($self, $spec, %opts) = @_; my $symbol = (exists $opts{base}) ? $opts{base} : Dpkg::Shlibs::Symbol->new(); my $ret = $opts{dummy} ? $symbol->parse_symbolspec($spec, default_minver => 0) : $symbol->parse_symbolspec($spec); if ($ret) { $symbol->initialize(arch => $self->get_arch()); return $symbol; } return undef; } sub add_symbol { my ($self, $symbol, $soname) = @_; my $object = $self->get_object($soname); if ($symbol->is_pattern()) { if (my $alias_type = $symbol->get_alias_type()) { unless (exists $object->{patterns}{aliases}{$alias_type}) { $object->{patterns}{aliases}{$alias_type} = {}; } # Alias hash for matching. my $aliases = $object->{patterns}{aliases}{$alias_type}; $aliases->{$symbol->get_symbolname()} = $symbol; } else { # Otherwise assume this is a generic sequential pattern. This # should be always safe. push @{$object->{patterns}{generic}}, $symbol; } return 'pattern'; } else { # invalidate the minimum version cache $object->{minver_cache} = []; $object->{syms}{$symbol->get_symbolname()} = $symbol; return 'sym'; } } # Parameter seen is only used for recursive calls sub parse { my ($self, $fh, $file, $seen, $obj_ref, $base_symbol) = @_; sub new_symbol { my $base = shift || 'Dpkg::Shlibs::Symbol'; return (ref $base) ? $base->clone(@_) : $base->new(@_); } if (defined($seen)) { return if exists $seen->{$file}; # Avoid include loops } else { $self->{file} = $file; $seen = {}; } $seen->{$file} = 1; if (not ref($obj_ref)) { # Init ref to name of current object/lib $$obj_ref = undef; } while (defined($_ = <$fh>)) { chomp($_); if (/^(?:\s+|#(?:DEPRECATED|MISSING): ([^#]+)#\s*)(.*)/) { if (not defined ($$obj_ref)) { error(_g("symbol information must be preceded by a header (file %s, line %s)"), $file, $.); } # Symbol specification my $deprecated = ($1) ? $1 : 0; my $sym = new_symbol($base_symbol, deprecated => $deprecated); if ($self->create_symbol($2, base => $sym)) { $self->add_symbol($sym, $$obj_ref); } else { warning(_g("Failed to parse line in %s: %s"), $file, $_); } } elsif (/^(\(.*\))?#include\s+"([^"]+)"/) { my $tagspec = $1; my $filename = $2; my $dir = $file; my $new_base_symbol; if (defined $tagspec) { $new_base_symbol = new_symbol($base_symbol); $new_base_symbol->parse_tagspec($tagspec); } $dir =~ s{[^/]+$}{}; # Strip filename $self->load("$dir$filename", $seen, $obj_ref, $new_base_symbol); } elsif (/^#|^$/) { # Skip possible comments and empty lines } elsif (/^\|\s*(.*)$/) { # Alternative dependency template push @{$self->{objects}{$$obj_ref}{deps}}, "$1"; } elsif (/^\*\s*([^:]+):\s*(.*\S)\s*$/) { # Add meta-fields $self->{objects}{$$obj_ref}{fields}{field_capitalize($1)} = $2; } elsif (/^(\S+)\s+(.*)$/) { # New object and dependency template $$obj_ref = $1; if (exists $self->{objects}{$$obj_ref}) { # Update/override infos only $self->{objects}{$$obj_ref}{deps} = [ "$2" ]; } else { # Create a new object $self->create_object($$obj_ref, "$2"); } } else { warning(_g("Failed to parse a line in %s: %s"), $file, $_); } } delete $seen->{$file}; } # Beware: we reuse the data structure of the provided symfile so make # sure to not modify them after having called this function sub merge_object_from_symfile { my ($self, $src, $objid) = @_; if (not $self->has_object($objid)) { $self->{objects}{$objid} = $src->get_object($objid); } else { warning(_g("tried to merge the same object (%s) twice in a symfile"), $objid); } } sub output { my ($self, $fh, %opts) = @_; $opts{template_mode} = 0 unless exists $opts{template_mode}; $opts{with_deprecated} = 1 unless exists $opts{with_deprecated}; $opts{with_pattern_matches} = 0 unless exists $opts{with_pattern_matches}; my $res = ""; foreach my $soname (sort $self->get_sonames()) { my @deps = $self->get_dependencies($soname); my $dep = shift @deps; $dep =~ s/#PACKAGE#/$opts{package}/g if exists $opts{package}; print $fh "$soname $dep\n" if defined $fh; $res .= "$soname $dep\n" if defined wantarray; foreach $dep (@deps) { $dep =~ s/#PACKAGE#/$opts{package}/g if exists $opts{package}; print $fh "| $dep\n" if defined $fh; $res .= "| $dep\n" if defined wantarray; } my $f = $self->{objects}{$soname}{fields}; foreach my $field (sort keys %{$f}) { my $value = $f->{$field}; $value =~ s/#PACKAGE#/$opts{package}/g if exists $opts{package}; print $fh "* $field: $value\n" if defined $fh; $res .= "* $field: $value\n" if defined wantarray; } my @symbols; if ($opts{template_mode}) { # Exclude symbols matching a pattern, but include patterns themselves @symbols = grep { not $_->get_pattern() } $self->get_symbols($soname); push @symbols, $self->get_patterns($soname); } else { @symbols = $self->get_symbols($soname); } foreach my $sym (sort { $a->get_symboltempl() cmp $b->get_symboltempl() } @symbols) { next if $sym->{deprecated} and not $opts{with_deprecated}; # Do not dump symbols from foreign arch unless dumping a template. next if not $opts{template_mode} and not $sym->arch_is_concerned($self->get_arch()); # Dump symbol specification. Dump symbol tags only in template mode. print $fh $sym->get_symbolspec($opts{template_mode}), "\n" if defined $fh; $res .= $sym->get_symbolspec($opts{template_mode}) . "\n" if defined wantarray; # Dump pattern matches as comments (if requested) if ($opts{with_pattern_matches} && $sym->is_pattern()) { for my $match (sort { $a->get_symboltempl() cmp $b->get_symboltempl() } $sym->get_pattern_matches()) { print $fh "#MATCH:", $match->get_symbolspec(0), "\n" if defined $fh; $res .= "#MATCH:" . $match->get_symbolspec(0) . "\n" if defined wantarray; } } } } return $res; } # Tries to match a symbol name and/or version against the patterns defined. # Returns a pattern which matches (if any). sub find_matching_pattern { my ($self, $refsym, $sonames, $inc_deprecated) = @_; $inc_deprecated = 0 unless defined $inc_deprecated; my $name = (ref $refsym) ? $refsym->get_symbolname() : $refsym; my $pattern_ok = sub { my $p = shift; return defined $p && ($inc_deprecated || !$p->{deprecated}) && $p->arch_is_concerned($self->get_arch()); }; foreach my $soname ((ref($sonames) eq 'ARRAY') ? @$sonames : $sonames) { my $obj = $self->get_object($soname); my ($type, $pattern); next unless defined $obj; my $all_aliases = $obj->{patterns}{aliases}; for my $type (Dpkg::Shlibs::Symbol::ALIAS_TYPES) { if (exists $all_aliases->{$type} && keys(%{$all_aliases->{$type}})) { my $aliases = $all_aliases->{$type}; my $converter = $aliases->{(keys %$aliases)[0]}; if (my $alias = $converter->convert_to_alias($name)) { if ($alias && exists $aliases->{$alias}) { $pattern = $aliases->{$alias}; last if &$pattern_ok($pattern); $pattern = undef; # otherwise not found yet } } } } # Now try generic patterns and use the first that matches if (not defined $pattern) { for my $p (@{$obj->{patterns}{generic}}) { if (&$pattern_ok($p) && $p->matches_rawname($name)) { $pattern = $p; last; } } } if (defined $pattern) { return (wantarray) ? ( symbol => $pattern, soname => $soname ) : $pattern; } } return (wantarray) ? () : undef; } # merge_symbols($object, $minver) # Needs $Objdump->get_object($soname) as parameter # Don't merge blacklisted symbols related to the internal (arch-specific) # machinery sub merge_symbols { my ($self, $object, $minver) = @_; my $soname = $object->{SONAME} || error(_g("cannot merge symbols from objects without SONAME")); my %dynsyms; foreach my $sym ($object->get_exported_dynamic_symbols()) { my $name = $sym->{name} . '@' . ($sym->{version} ? $sym->{version} : "Base"); my $symobj = $self->lookup_symbol($name, $soname); if (exists $blacklist{$sym->{name}}) { next unless (defined $symobj and $symobj->has_tag("ignore-blacklist")); } $dynsyms{$name} = $sym; } unless ($self->has_object($soname)) { $self->create_object($soname, ''); } # Scan all symbols provided by the objects my $obj = $self->get_object($soname); # invalidate the minimum version cache - it is not sufficient to # invalidate in add_symbol, since we might change a minimum # version for a particular symbol without adding it $obj->{minver_cache} = []; foreach my $name (keys %dynsyms) { my $sym; if ($sym = $self->lookup_symbol($name, $obj, 1)) { # If the symbol is already listed in the file $sym->mark_found_in_library($minver, $self->get_arch()); } else { # The exact symbol is not present in the file, but it might match a # pattern. my $pattern = $self->find_matching_pattern($name, $obj, 1); if (defined $pattern) { $pattern->mark_found_in_library($minver, $self->get_arch()); $sym = $pattern->create_pattern_match(symbol => $name); } else { # Symbol without any special info as no pattern matched $sym = Dpkg::Shlibs::Symbol->new(symbol => $name, minver => $minver); } $self->add_symbol($sym, $obj); } } # Process all symbols which could not be found in the library. foreach my $sym ($self->get_symbols($soname)) { if (not exists $dynsyms{$sym->get_symbolname()}) { $sym->mark_not_found_in_library($minver, $self->get_arch()); } } # Deprecate patterns which didn't match anything for my $pattern (grep { $_->get_pattern_matches() == 0 } $self->get_patterns($soname)) { $pattern->mark_not_found_in_library($minver, $self->get_arch()); } } sub is_empty { my ($self) = @_; return scalar(keys %{$self->{objects}}) ? 0 : 1; } sub has_object { my ($self, $soname) = @_; return exists $self->{objects}{$soname}; } sub get_object { my ($self, $soname) = @_; return ref($soname) ? $soname : $self->{objects}{$soname}; } sub create_object { my ($self, $soname, @deps) = @_; $self->{objects}{$soname} = { syms => {}, fields => {}, patterns => { aliases => {}, generic => [], }, deps => [ @deps ], minver_cache => [] }; } sub get_dependency { my ($self, $soname, $dep_id) = @_; $dep_id = 0 unless defined($dep_id); return $self->get_object($soname)->{deps}[$dep_id]; } sub get_smallest_version { my ($self, $soname, $dep_id) = @_; $dep_id = 0 unless defined($dep_id); my $so_object = $self->get_object($soname); return $so_object->{minver_cache}[$dep_id] if(defined($so_object->{minver_cache}[$dep_id])); my $minver; foreach my $sym ($self->get_symbols($so_object)) { next if $dep_id != $sym->{dep_id}; $minver = $sym->{minver} unless defined($minver); if (version_compare($minver, $sym->{minver}) > 0) { $minver = $sym->{minver}; } } $so_object->{minver_cache}[$dep_id] = $minver; return $minver; } sub get_dependencies { my ($self, $soname) = @_; return @{$self->get_object($soname)->{deps}}; } sub get_field { my ($self, $soname, $name) = @_; if (my $obj = $self->get_object($soname)) { if (exists $obj->{fields}{$name}) { return $obj->{fields}{$name}; } } return undef; } # Tries to find a symbol like the $refsym and returns its descriptor. # $refsym may also be a symbol name. sub lookup_symbol { my ($self, $refsym, $sonames, $inc_deprecated) = @_; $inc_deprecated = 0 unless defined($inc_deprecated); my $name = (ref $refsym) ? $refsym->get_symbolname() : $refsym; foreach my $so ((ref($sonames) eq 'ARRAY') ? @$sonames : $sonames) { if (my $obj = $self->get_object($so)) { my $sym = $obj->{syms}{$name}; if ($sym and ($inc_deprecated or not $sym->{deprecated})) { return (wantarray) ? ( symbol => $sym, soname => $so ) : $sym; } } } return (wantarray) ? () : undef; } # Tries to find a pattern like the $refpat and returns its descriptor. # $refpat may also be a pattern spec. sub lookup_pattern { my ($self, $refpat, $sonames, $inc_deprecated) = @_; $inc_deprecated = 0 unless defined($inc_deprecated); # If $refsym is a string, we need to create a dummy ref symbol. $refpat = $self->create_symbol($refpat, dummy => 1) if ! ref($refpat); if ($refpat && $refpat->is_pattern()) { foreach my $soname ((ref($sonames) eq 'ARRAY') ? @$sonames : $sonames) { if (my $obj = $self->get_object($soname)) { my $pat; if (my $type = $refpat->get_alias_type()) { if (exists $obj->{patterns}{aliases}{$type}) { $pat = $obj->{patterns}{aliases}{$type}{$refpat->get_symbolname()}; } } elsif ($refpat->get_pattern_type() eq "generic") { for my $p (@{$obj->{patterns}{generic}}) { if (($inc_deprecated || !$p->{deprecated}) && $p->equals($refpat, versioning => 0)) { $pat = $p; last; } } } if ($pat && ($inc_deprecated || !$pat->{deprecated})) { return (wantarray) ? (symbol => $pat, soname => $soname) : $pat; } } } } return (wantarray) ? () : undef; } # Get symbol object reference either by symbol name or by a reference object. sub get_symbol_object { my ($self, $refsym, $soname) = @_; my $sym = $self->lookup_symbol($refsym, $soname, 1); if (! defined $sym) { $sym = $self->lookup_pattern($refsym, $soname, 1); } return $sym; } sub get_new_symbols { my ($self, $ref, %opts) = @_; my $with_optional = (exists $opts{with_optional}) ? $opts{with_optional} : 0; my @res; foreach my $soname ($self->get_sonames()) { next if not $ref->has_object($soname); # Scan raw symbols first. foreach my $sym (grep { ($with_optional || ! $_->is_optional()) && $_->is_legitimate($self->get_arch()) } $self->get_symbols($soname)) { my $refsym = $ref->lookup_symbol($sym, $soname, 1); my $isnew; if (defined $refsym) { # If the symbol exists in the $ref symbol file, it might # still be new if $refsym is not legitimate. $isnew = not $refsym->is_legitimate($self->get_arch()); } else { # If the symbol does not exist in the $ref symbol file, it does # not mean that it's new. It might still match a pattern in the # symbol file. However, due to performance reasons, first check # if the pattern that the symbol matches (if any) exists in the # ref symbol file as well. $isnew = not ( ($sym->get_pattern() and $ref->lookup_pattern($sym->get_pattern(), $soname, 1)) or $ref->find_matching_pattern($sym, $soname, 1) ); } push @res, { symbol => $sym, soname => $soname } if $isnew; } # Now scan patterns foreach my $p (grep { ($with_optional || ! $_->is_optional()) && $_->is_legitimate($self->get_arch()) } $self->get_patterns($soname)) { my $refpat = $ref->lookup_pattern($p, $soname, 0); # If reference pattern was not found or it is not legitimate, # considering current one as new. if (not defined $refpat or not $refpat->is_legitimate($self->get_arch())) { push @res, { symbol => $p , soname => $soname }; } } } return @res; } sub get_lost_symbols { my ($self, $ref, %opts) = @_; return $ref->get_new_symbols($self, %opts); } sub get_new_libs { my ($self, $ref) = @_; my @res; foreach my $soname ($self->get_sonames()) { push @res, $soname if not $ref->get_object($soname); } return @res; } sub get_lost_libs { my ($self, $ref) = @_; return $ref->get_new_libs($self); } 1;
nevali/dpkg
scripts/Dpkg/Shlibs/SymbolFile.pm
Perl
gpl-2.0
20,443
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; namespace InfinityScript { public class ScriptDynamics : DynamicObject { private int _entRef; public ScriptDynamics(int entRef) { _entRef = entRef; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var functionName = binder.Name; try { // convert arguments to Parameter var parameters = new Parameter[args.Length]; for (int i = 0; i < args.Length; i++) { parameters[i] = new Parameter(args[i]); } Function.SetEntRef(_entRef); result = Function.Call(functionName, typeof(object), parameters); return true; } catch (Exception ex) { Log.Error(ex); result = null; return false; } } } }
FreeTheTech101/lightning
InfinityScript/ScriptProcessor/ScriptDynamics.cs
C#
gpl-2.0
1,114
<?php /** * @file * Lightweight implementation of the Twitter API in PHP. * * This code does the heavy lifting behind the Drupal twitter_block module. It * does not aim to authenticate users nor provide complex integration. We only * need to grab public feeds, and as such we use the Twitter Search API. For * more information on the twitter search API, @see * @link http://dev.twitter.com/doc/get/search */ /** * TwitterSearch provides the class for using the Twitter Search API. * * For mor information on the API, see http://dev.twitter.com/doc/get/search */ class TwitterSearch { // HTTP status code returned private $http_status; // Search parameters as defined by the API to be used w/ http_build_query private $query_parameters = array(); // Determines which getter to use. private $search_type; // What were we looking for again? private $search_string; private $twitter_name; public function __construct($config = array()) { $this->search_type = $config['search_type']; if ( $config['search_type'] == 'searchHashtag' ) { // We presume the search string is already validated. $this->search_string = $config['search_string']; } else { $this->twitter_name = $config['search_string']; } // The number of tweets to return per page, up to a max of 100. if (isset( $config['rpp'])) { $this->query_parameters['rpp'] = $config['rpp']; } else { $this->query_parameters['rpp'] = variable_get('twitter_block_default_rpp', 10); } } /** * Retrieve JSON encoded search results */ public function getJSON() { return call_user_func(array($this, $this->search_type)); } /** * Returns the most recent tweets from $twittername * @param string $twittername to search. Note: begins with @ * @return string $json JSON encoded search response */ private function getTweetsFrom() { $this->options['q'] = "from$this->twitter_name"; $json = $this->search(); return $json; } /** * Returns the most recent mentions (status containing @twittername) * @param string $twittername to search. Note: begins with @ * @return string $json JSON encoded search response */ private function getMentions() { $this->options['q'] = $this->twitter_name; $json = $this->search(); return $json; } /** * Returns the most recent @replies to $twittername. * @param string $twittername to search. Note: begins with @. * @return string JSON encoded search response */ private function getReplies() { $this->options['q'] = "to$this->twitter_name"; $json = $this->search(); return $json; } /** * Returns the most recent tweets containing a string or hashtag. * @param string $hashtag to search. May or may not begin with #. * @return string JSON encoded search response */ private function searchHashtag() { $this->options['q'] = ($this->search_string); $json = $this->search(); return $json; } /** * Returns the last HTTP status code * @return integer */ public function lastStatusCode() { return $this->http_status; } /** * Executes a Twitter Search API call * @return string JSON encoded search response. */ function search() { $url = 'http://search.twitter.com/search.json?' . http_build_query($this->options); $ch = curl_init($url); // Applications must have a meaningful and unique User Agent. curl_setopt($ch, CURLOPT_USERAGENT, "Drupal Twitter Block Module"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); $twitter_data = curl_exec($ch); $this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $twitter_data; } } ?>
perandre/3-16
sites/all/modules/twitter_block/twitter.class.php
PHP
gpl-2.0
3,814
--- title: XSEDE tags: [single-sourcing] keywords: includes, conref, dita, transclusion, transclude, inclusion, reference last_updated: August 12, 2015 summary: "Information about the compute clusters at XSEDE." --- ## Stampede: the Caterpillar work horse As per [XSEDE website](https://www.xsede.org/tacc-stampede). The TACC Stampede system is a 10 PFLOPS (PF) Dell Linux Cluster based on 6,400+ Dell PowerEdge server nodes, each outfitted with 2 Intel Xeon E5 (Sandy Bridge) processors and an Intel Xeon Phi Coprocessor (MIC Architecture). The aggregate peak performance of the Xeon E5 processors is 2+PF, while the Xeon Phi processors deliver an additional aggregate peak performance of 7+PF. The system also includes a set of login nodes, large-memory nodes, graphics nodes (for both remote visualization and computation), and dual-coprocessor nodes. Additional nodes (not directly accessible to users) provide management and file system services. One of the important design considerations for Stampede was to create a multi-use cyberinfrastructure resource, offering large memory, large data transfer, and GPU capabilities for data-intensive, accelerated or visualization computing. By augmenting some of the compute-intensive nodes within the system with very large memory and GPUs there is no need to move data for data-intensive computing, remote visualization and GPGPU computing. For those situations requiring large-data transfers from other sites, 4 high-speed data servers have been integrated into the Lustre file systems. * Compute Nodes: The majority of the 6400 nodes are configured with two Xeon E5-2680 processors and one Intel Xeon Phi SE10P Coprocessor (on a PCIe card). These compute nodes are configured with 32GB of "host" memory with an additional 8GB of memory on the Xeon Phi coprocessor card. A smaller number of compute nodes are configured with two Xeon Phi Coprocessors -- the specific number of nodes available in each configuration at any time will be available from the batch queue summary. * Large Memory Nodes: There are an additional 16 large-memory nodes with 32 cores/node and 1TB of memory for data-intense applications requiring disk caching to memory and large-memory methods. Visualization Nodes: For visualization and GPGPU processing 128 compute nodes are augmented with a single NVIDIA K20 GPU on each node with 5GB of on-board GDDR5 memory. * File Systems: The Stampede system supports a 14PB global, parallel file storage managed as three Lustre file systems. Each node contains a local 250GB disk. Also, the TACC Ranch tape archival system (60 PB capacity) is accessible from Stampede. * Interconnect: Nodes are interconnected with Mellanox FDR InfiniBand technology in a 2-level (cores and leafs) fat-tree topology. **Notes about running Caterpillar halos on stampede:** You need to specify a minimum 512 cores (-N 32 -n 512) to get started. Depending on the error you should change the following parameters in order and try again. * Config.sh: `DOUBLEPRECISION_FFTW` * Config.sh: `MULTIPLEDOMAINS` 16 -> 32 * param.txt.: `Buffersize` 100 -> 50 * param.txt: `MaxMemSize` 3300
caterpillarproject/wiki
doc_xsede.md
Markdown
gpl-2.0
3,138
/* USB support for the Cyberjack family of readers. * * Previous version were (C) 2004-2005 by Harald Welte <laforge@gnumonks.org> * This version is a rewrite (asynchronous USB is no longer needed). * * (C) 2007 Martin Preuss <martin@libchipcard.de> * * Distributed and licensed under the terms of GNU LGPL, Version 2.1 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <inttypes.h> #include "ausb_l.h" #include "ausb_libusb0_l.h" #include "ausb_libusb1_l.h" #include <string.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <signal.h> #include <errno.h> #include <sys/ioctl.h> #include <time.h> #include <assert.h> #ifdef HAVE_HAL # include <hal/libhal.h> # include <dbus/dbus.h> #endif #define DEBUGP(ah, format, ...) {\ char dbg_buffer[256]; \ \ snprintf(dbg_buffer, sizeof(dbg_buffer)-1,\ __FILE__":%5d: " format , __LINE__ , ##__VA_ARGS__); \ dbg_buffer[sizeof(dbg_buffer)-1]=0; \ ausb_log(ah, dbg_buffer, NULL, 0);\ } #define DEBUGL(ah, text, pData, ulDataLen) {\ char dbg_buffer[256]; \ \ snprintf(dbg_buffer, sizeof(dbg_buffer)-1,\ __FILE__":%5d: %s", __LINE__ , text); \ dbg_buffer[sizeof(dbg_buffer)-1]=0; \ ausb_log(ah, dbg_buffer, pData, ulDataLen);\ } static AUSB_LOG_FN ausb_log_fn=NULL; void ausb_set_log_fn(AUSB_LOG_FN fn) { ausb_log_fn=fn; } void ausb_log(ausb_dev_handle *ah, const char *text, const void *pData, uint32_t ulDataLen) { if (ausb_log_fn) ausb_log_fn(ah, text, pData, ulDataLen); } int ausb_register_callback(ausb_dev_handle *ah, AUSB_CALLBACK callback, void *userdata){ DEBUGP(ah, "registering callback:%p\n", callback); ah->cb.handler=callback; ah->cb.userdata=userdata; return 0; } int ausb_claim_interface(ausb_dev_handle *ah, int interface){ DEBUGP(ah, "ausb_claim_interface\n"); if (ah->claimInterfaceFn) return ah->claimInterfaceFn(ah, interface); DEBUGP(ah, "callback for ausb_claim_interface not set\n"); return -1; } int ausb_release_interface(ausb_dev_handle *ah, int interface){ DEBUGP(ah, "ausb_release_interface\n"); if (ah->releaseInterfaceFn) return ah->releaseInterfaceFn(ah, interface); DEBUGP(ah, "callback for ausb_release_interface not set\n"); return -1; } int ausb_set_configuration(ausb_dev_handle *ah, int configuration){ DEBUGP(ah, "ausb_set_configuration\n"); if (ah->setConfigurationFn) return ah->setConfigurationFn(ah, configuration); DEBUGP(ah, "callback for ausb_set_configuration not set\n"); return -1; } ausb_dev_handle *ausb_open(rsct_usbdev_t *dev, int t) { ausb_dev_handle *ah=NULL; int rv; /*fprintf(stderr, "Opening device...\n");*/ ah=malloc(sizeof *ah); if (ah==0) { DEBUGP(ah, "memory full\n"); return 0; } memset(ah, 0, sizeof(*ah)); ah->pid=dev->productId; ah->device=*dev; switch(t) { case 1: #ifdef USE_USB1 rv=ausb11_extend(ah); #else rv=ausb1_extend(ah); #endif break; case 2: DEBUGP(ah, "This type is no longer supported.\n"); rv=-1; break; case 3: #ifdef USE_USB1 rv=ausb31_extend(ah); #else rv=ausb3_extend(ah); #endif break; default: DEBUGP(ah, "Invalid type %d\n", t); rv=-1; break; } if (rv) { DEBUGP(ah, "Could not extend as type %d (%d)\n", t, rv); free(ah); return 0; } return ah; } int ausb_close(ausb_dev_handle *ah) { DEBUGP(ah, "ausb_close\n"); if (ah->closeFn) ah->closeFn(ah); free(ah); return 0; } int ausb_start_interrupt(ausb_dev_handle *ah, int ep) { DEBUGP(ah, "ausb_start_interrupt\n"); if (ah->startInterruptFn) return ah->startInterruptFn(ah, ep); return 0; } int ausb_stop_interrupt(ausb_dev_handle *ah) { DEBUGP(ah, "ausb_stop_interrupt\n"); if (ah->stopInterruptFn) return ah->stopInterruptFn(ah); return 0; } int ausb_bulk_write(ausb_dev_handle *ah, int ep, char *bytes, int size, int timeout) { DEBUGL(ah, "Write:", bytes, size); if (ah->bulkWriteFn) return ah->bulkWriteFn(ah, ep, bytes, size, timeout); return -1; } int ausb_bulk_read(ausb_dev_handle *ah, int ep, char *bytes, int size, int timeout) { if (ah->bulkReadFn) { int rv; DEBUGP(ah, "Reading up to %d bytes", size); rv=ah->bulkReadFn(ah, ep, bytes, size, timeout); if (rv>=0) { DEBUGL(ah, "Read:", bytes, rv); } return rv; } return -1; } int ausb_reset(ausb_dev_handle *ah){ DEBUGP(ah, "ausb_reset\n"); if (ah->resetFn) return ah->resetFn(ah); else return -1; } int ausb_reset_endpoint(ausb_dev_handle *ah, unsigned int ep){ DEBUGP(ah, "ausb_reset_endpoint\n"); if (ah->resetEndpointFn) return ah->resetEndpointFn(ah, ep); else return -1; } int ausb_clear_halt(ausb_dev_handle *ah, unsigned int ep){ DEBUGP(ah, "ausb_clear_halt\n"); if (ah->clearHaltFn) return ah->clearHaltFn(ah, ep); else return -1; } int ausb_reset_pipe(ausb_dev_handle *ah, int ep){ DEBUGP(ah, "ausb_reset_pipe\n"); if (ah->resetPipeFn) return ah->resetPipeFn(ah, ep); else return -1; } int ausb_get_kernel_driver_name(ausb_dev_handle *ah, int interface, char *name, unsigned int namelen){ DEBUGP(ah, "ausb_get_kernel_driver_name\n"); if (ah->getKernelDriverNameFn) return ah->getKernelDriverNameFn(ah, interface, name, namelen); return -1; } int ausb_detach_kernel_driver(ausb_dev_handle *ah, int interface){ DEBUGP(ah, "ausb_detach_kernel_driver\n"); if (ah->detachKernelDriverFn) return ah->detachKernelDriverFn(ah, interface); return -1; } int ausb_reattach_kernel_driver(ausb_dev_handle *ah, int interface){ DEBUGP(ah, "ausb_reattach_kernel_driver\n"); if (ah->reattachKernelDriverFn) return ah->reattachKernelDriverFn(ah, interface); return -1; } int ausb_init(void) { #ifdef USE_USB1 return ausb_libusb1_init(); #else return ausb_libusb0_init(); #endif } int ausb_fini(void){ #ifdef USE_USB1 return ausb_libusb1_fini(); #else return ausb_libusb0_fini(); #endif }
larskanis/ctapi-cyberjack
cjeca32/ausb/ausb.c
C
gpl-2.0
6,043
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Sales\Test\Unit\Model; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Sales\Api\Data\OrderInterface; use Magento\Sales\Api\Data\OrderSearchResultInterfaceFactory as SearchResultFactory; use Magento\Sales\Model\ResourceModel\Metadata; use Magento\Tax\Api\OrderTaxManagementInterface; use Magento\Payment\Api\Data\PaymentAdditionalInfoInterfaceFactory; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class OrderRepositoryTest extends \PHPUnit\Framework\TestCase { /** * @var \Magento\Sales\Model\OrderRepository */ private $orderRepository; /** * @var Metadata|\PHPUnit_Framework_MockObject_MockObject */ private $metadata; /** * @var SearchResultFactory|\PHPUnit_Framework_MockObject_MockObject */ private $searchResultFactory; /** * @var ObjectManager */ private $objectManager; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $collectionProcessor; /** * @var OrderTaxManagementInterface|\PHPUnit_Framework_MockObject_MockObject */ private $orderTaxManagementMock; /** * @var PaymentAdditionalInfoInterfaceFactory|\PHPUnit_Framework_MockObject_MockObject */ private $paymentAdditionalInfoFactory; /** * Setup the test * * @return void */ protected function setUp() { $this->objectManager = new ObjectManager($this); $className = \Magento\Sales\Model\ResourceModel\Metadata::class; $this->metadata = $this->createMock($className); $className = \Magento\Sales\Api\Data\OrderSearchResultInterfaceFactory::class; $this->searchResultFactory = $this->createPartialMock($className, ['create']); $this->collectionProcessor = $this->createMock( \Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface::class ); $orderExtensionFactoryMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderExtensionFactory::class) ->disableOriginalConstructor() ->getMock(); $this->orderTaxManagementMock = $this->getMockBuilder(OrderTaxManagementInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $this->paymentAdditionalInfoFactory = $this->getMockBuilder(PaymentAdditionalInfoInterfaceFactory::class) ->disableOriginalConstructor()->setMethods(['create'])->getMockForAbstractClass(); $this->orderRepository = $this->objectManager->getObject( \Magento\Sales\Model\OrderRepository::class, [ 'metadata' => $this->metadata, 'searchResultFactory' => $this->searchResultFactory, 'collectionProcessor' => $this->collectionProcessor, 'orderExtensionFactory' => $orderExtensionFactoryMock, 'orderTaxManagement' => $this->orderTaxManagementMock, 'paymentAdditionalInfoFactory' => $this->paymentAdditionalInfoFactory ] ); } /** * Test for method getList. * * @return void */ public function testGetList() { $searchCriteriaMock = $this->createMock(\Magento\Framework\Api\SearchCriteria::class); $collectionMock = $this->createMock(\Magento\Sales\Model\ResourceModel\Order\Collection::class); $itemsMock = $this->getMockBuilder(OrderInterface::class)->disableOriginalConstructor() ->getMockForAbstractClass(); $orderTaxDetailsMock = $this->getMockBuilder(\Magento\Tax\Api\Data\OrderTaxDetailsInterface::class) ->disableOriginalConstructor() ->setMethods(['getAppliedTaxes', 'getItems'])->getMockForAbstractClass(); $paymentMock = $this->getMockBuilder(\Magento\Sales\Api\Data\OrderPaymentInterface::class) ->disableOriginalConstructor()->getMockForAbstractClass(); $paymentAdditionalInfo = $this->getMockBuilder(\Magento\Payment\Api\Data\PaymentAdditionalInfoInterface::class) ->disableOriginalConstructor()->setMethods(['setKey', 'setValue'])->getMockForAbstractClass(); $extensionAttributes = $this->createPartialMock( \Magento\Sales\Api\Data\OrderExtension::class, [ 'getShippingAssignments', 'setShippingAssignments', 'setConvertingFromQuote', 'setAppliedTaxes', 'setItemAppliedTaxes', 'setPaymentAdditionalInfo' ] ); $shippingAssignmentBuilder = $this->createMock( \Magento\Sales\Model\Order\ShippingAssignmentBuilder::class ); $itemsMock->expects($this->atLeastOnce())->method('getEntityId')->willReturn(1); $this->collectionProcessor->expects($this->once()) ->method('process') ->with($searchCriteriaMock, $collectionMock); $itemsMock->expects($this->atLeastOnce())->method('getExtensionAttributes')->willReturn($extensionAttributes); $itemsMock->expects($this->atleastOnce())->method('getPayment')->willReturn($paymentMock); $paymentMock->expects($this->atLeastOnce())->method('getAdditionalInformation') ->willReturn(['method' => 'checkmo']); $this->paymentAdditionalInfoFactory->expects($this->atLeastOnce())->method('create') ->willReturn($paymentAdditionalInfo); $paymentAdditionalInfo->expects($this->atLeastOnce())->method('setKey')->willReturnSelf(); $paymentAdditionalInfo->expects($this->atLeastOnce())->method('setValue')->willReturnSelf(); $this->orderTaxManagementMock->expects($this->atLeastOnce())->method('getOrderTaxDetails') ->willReturn($orderTaxDetailsMock); $extensionAttributes->expects($this->any()) ->method('getShippingAssignments') ->willReturn($shippingAssignmentBuilder); $this->searchResultFactory->expects($this->once())->method('create')->willReturn($collectionMock); $collectionMock->expects($this->once())->method('getItems')->willReturn([$itemsMock]); $this->assertEquals($collectionMock, $this->orderRepository->getList($searchCriteriaMock)); } /** * Test for method save. * * @return void */ public function testSave() { $mapperMock = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order::class) ->disableOriginalConstructor() ->getMock(); $orderEntity = $this->createMock(\Magento\Sales\Model\Order::class); $extensionAttributes = $this->createPartialMock( \Magento\Sales\Api\Data\OrderExtension::class, ['getShippingAssignments'] ); $shippingAssignment = $this->getMockBuilder(\Magento\Sales\Model\Order\ShippingAssignment::class) ->disableOriginalConstructor() ->setMethods(['getShipping']) ->getMock(); $shippingMock = $this->getMockBuilder(\Magento\Sales\Model\Order\Shipping::class) ->disableOriginalConstructor() ->setMethods(['getAddress', 'getMethod']) ->getMock(); $orderEntity->expects($this->once())->method('getExtensionAttributes')->willReturn($extensionAttributes); $orderEntity->expects($this->once())->method('getIsNotVirtual')->willReturn(true); $extensionAttributes ->expects($this->any()) ->method('getShippingAssignments') ->willReturn([$shippingAssignment]); $shippingAssignment->expects($this->once())->method('getShipping')->willReturn($shippingMock); $shippingMock->expects($this->once())->method('getAddress'); $shippingMock->expects($this->once())->method('getMethod'); $this->metadata->expects($this->once())->method('getMapper')->willReturn($mapperMock); $mapperMock->expects($this->once())->method('save'); $orderEntity->expects($this->any())->method('getEntityId')->willReturn(1); $this->orderRepository->save($orderEntity); } }
kunj1988/Magento2
app/code/Magento/Sales/Test/Unit/Model/OrderRepositoryTest.php
PHP
gpl-2.0
8,137
/** * @file */ /* Copyright (C) 1997-2001 Id Software, 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; 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "bsp.h" #include "textures.h" static int nummiptex = 0; textureref_t textureref[MAX_MAP_TEXTURES]; /** * @brief * @return -1 means that the texture was not found * @sa TexinfoForBrushTexture * @sa ParseBrush */ int FindMiptex (const char *name) { int i; /* search through textures that have already been loaded. */ for (i = 0; i < nummiptex; i++) if (Q_streq(name, textureref[i].name)) { return i; } if (nummiptex == MAX_MAP_TEXTURES) Sys_Error("MAX_MAP_TEXTURES"); Q_strncpyz(textureref[i].name, name, sizeof(textureref[i].name)); return i; } static const vec3_t baseaxis[18] = { {0,0,1}, {1,0,0}, {0,-1,0}, /* floor */ {0,0,-1}, {1,0,0}, {0,-1,0}, /* ceiling */ {1,0,0}, {0,1,0}, {0,0,-1}, /* west wall */ {-1,0,0}, {0,1,0}, {0,0,-1}, /* east wall */ {0,1,0}, {1,0,0}, {0,0,-1}, /* south wall */ {0,-1,0}, {1,0,0}, {0,0,-1} /* north wall */ }; static void TextureAxisFromPlane (plane_t *pln, vec3_t xv, vec3_t yv, bool isTerrain) { int bestaxis, numaxis, i; vec_t best; /* Knightmare- terrain support, use floor/ceiling axis only */ numaxis = (isTerrain) ? 2 : 6; best = 0; bestaxis = 0; for (i = 0; i < numaxis; i++) { const vec_t dot = DotProduct(pln->normal, baseaxis[i * 3]); if (dot > best) { best = dot; bestaxis = i; } } VectorCopy(baseaxis[bestaxis * 3 + 1], xv); VectorCopy(baseaxis[bestaxis * 3 + 2], yv); } /** * @sa BaseLightForFace */ int TexinfoForBrushTexture (plane_t *plane, brush_texture_t *bt, const vec3_t origin, bool isTerrain) { vec3_t vecs[2]; int sv, tv; vec_t ang, sinv, cosv; dBspTexinfo_t tx, *tc; int i, j, k; float shift[2]; vec3_t scaledOrigin; if (!bt->name[0]) return 0; OBJZERO(tx); Q_strncpyz(tx.texture, bt->name, sizeof(tx.texture)); TextureAxisFromPlane(plane, vecs[0], vecs[1], isTerrain); /* dot product of a vertex location with the [4] part will produce a * texcoord (s or t depending on the first index) */ VectorScale(origin, 1.0 / bt->scale[0], scaledOrigin); shift[0] = DotProduct(scaledOrigin, vecs[0]); VectorScale(origin, 1.0 / bt->scale[1], scaledOrigin); shift[1] = DotProduct(scaledOrigin, vecs[1]); if (!bt->scale[0]) bt->scale[0] = 1; if (!bt->scale[1]) bt->scale[1] = 1; /* rotate axis */ if (bt->rotate == 0) { sinv = 0; cosv = 1; } else if (bt->rotate == 90) { sinv = 1; cosv = 0; } else if (bt->rotate == 180) { sinv = 0; cosv = -1; } else if (bt->rotate == 270) { sinv = -1; cosv = 0; } else { ang = bt->rotate * torad; sinv = sin(ang); cosv = cos(ang); } shift[0] = cosv * shift[0] - sinv * shift[1]; shift[1] = sinv * shift[0] + cosv * shift[1]; if (vecs[0][0]) sv = 0; else if (vecs[0][1]) sv = 1; else sv = 2; if (vecs[1][0]) tv = 0; else if (vecs[1][1]) tv = 1; else tv = 2; for (i = 0; i < 2; i++) { const vec_t ns = cosv * vecs[i][sv] - sinv * vecs[i][tv]; const vec_t nt = sinv * vecs[i][sv] + cosv * vecs[i][tv]; vecs[i][sv] = ns; vecs[i][tv] = nt; } for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) tx.vecs[i][j] = vecs[i][j] / bt->scale[i]; /* texture offsets */ tx.vecs[0][3] = bt->shift[0] + shift[0]; tx.vecs[1][3] = bt->shift[1] + shift[1]; tx.surfaceFlags = bt->surfaceFlags; tx.value = bt->value; /* find the texinfo */ tc = curTile->texinfo; for (i = 0; i < curTile->numtexinfo; i++, tc++) { if (tc->surfaceFlags != tx.surfaceFlags) continue; if (tc->value != tx.value) continue; if (!Q_streq(tc->texture, tx.texture)) continue; for (j = 0; j < 2; j++) { for (k = 0; k < 4; k++) { if (tc->vecs[j][k] != tx.vecs[j][k]) goto skip; } } return i; skip:; } if (curTile->numtexinfo >= MAX_MAP_TEXINFO) Sys_Error("MAX_MAP_TEXINFO overflow"); *tc = tx; curTile->numtexinfo++; return i; }
Qazzian/ufoai_suspend
src/tools/ufo2map/textures.cpp
C++
gpl-2.0
4,539
/* * File: TProgression.cpp * Author: boutina * * Created on 19 décembre 2015, 12:21 */ #include "tprogression.h" #include <QJsonObject> TProgression::TProgression() : lastExerciseIndex_(0) { } TProgression::TProgression(const TProgression& orig): lastExerciseIndex_(orig.lastExerciseIndex_){ } TProgression::~TProgression() { } void TProgression::read(const QJsonObject &json) { lastExerciseIndex_ = json["lastExerciseIndex"].toInt(); } void TProgression::write(QJsonObject &json) const { json["lastExerciseIndex"] = lastExerciseIndex_; } bool operator==(const TProgression &prog1,const TProgression &prog2){ return prog1.getLastExericeIndex() == prog2.getLastExericeIndex(); }
AzariasB/QTypingTest
src/Data/tprogression.cpp
C++
gpl-2.0
714
<div class='teaser--slim'/> <content-row class="activation-form"> <form name="activation.form" class="box" novalidate> <div class="row"> <div class="small-12 columns"> <h1 ng-if="::activation.isRegistrationFlow" translate="ACTIVATION_HEADLINE">Registrierung - letzte Schritte</h1> <h1 ng-if="::activation.isPasswordRecoveryFlow" translate="PASSWORD_RESET_HEADLINE">Passwort neu setzen</h1> <div class="info-text margin-bottom-small" ng-if="::activation.isRegistrationFlow" translate="ACTIVATION_DESC">Bitte vergib ein Passwort, um die Aktivierung Deines Kontos abzuschließen.</div> <div class="info-text margin-bottom-small" ng-if="::activation.isPasswordRecoveryFlow" translate="PASSWORD_RESET_DESC">Bitte vergib jetzt ein neues Passwort.</div> </div> </div> <div class="general-error alert-box alert" ng-messages="activation.generalErrors" ng-if="activation.generalErrors"> <span ng-message="remote_already_activated"> <span ng-if="::activation.isRegistrationFlow" translate="ACTIVATION_ERROR_ALREADY_ACTIVE" translate-value-link="<a href='#/login' translate='ACTIVATION_ERROR_ALREADY_ACTIVE_LINK'></a>"></span> <span ng-if="::activation.isPasswordRecoveryFlow" translate="PASSWORD_RESET_ERROR_ALREADY_RESET" translate-value-link="<a href='#/login/password-recovery' translate='PASSWORD_RESET_ERROR_ALREADY_RESET_LINK'></a>"></span> </span> <div ng-message="remote_activation_token_invalid"><span translate="ACTIVATION_ERROR_INVALID_LINK">Der Aktivierungslink ist ungültig.</span></div> <div ng-message="remote_not_found"><span translate="ACTIVATION_ERROR_NOT_REGISTERED" translate-value-link="<a href='#/signup' translate='ACTIVATION_ERROR_NOT_REGISTERED_LINK'></a>"></span></div> <div ng-message="remote_unknown"><span translate="FORM_ERROR_UNEXPECTED"></span></div> </div> <div class="row"> <div class="small-12 columns form-controls-password"> <label form-group="password"> <span form-label-valid="password" translate="FORM_PASSWORD_LABEL">Passwort</span> <span form-label-invalid="password" ng-messages="activation.form.password.$error"> <div ng-message="required"><span translate="FORM_PASSWORD_ERROR_REQUIRED">Bitte gib Dein Passwort ein</span></div> <div ng-message="pattern"><span translate="FORM_PASSWORD_ERROR_PATTERN">Das Passwort muss aus mindestens 8 Zeichen und einem Sonderzeichen bestehen</span></div> </span> <input type="password" name="password" ng-model="activation.user.password" placeholder="Passwort" required pattern="^(?=.*\W)(?=\S+$).{8,}$" reset-remote-validation translate-attr="{ placeholder: 'FORM_PASSWORD_PLACEHOLDER'}"> </label> </div> </div> <div class="row"> <div class="small-12 columns form-controls-repeated-password"> <label form-group="repeatedPassword"> <span form-label-valid="repeatedPassword" translate="FORM_PASSWORD_REPEAT_LABEL">Passwort wiederholen</span> <span form-label-invalid="repeatedPassword" ng-messages="activation.form.repeatedPassword.$error"> <div ng-message="required"><span translate="FORM_PASSWORD_REPEAT_ERROR_REQUIRED">Bitte gib Dein Passwort erneut ein</span></div> <div ng-message="remote_equal"><span translate="FORM_PASSWORD_REPEAT_ERROR_NOT_EQUAL">Die beiden Passwörter stimmen nicht überein</span></div> </span> <input type="password" name="repeatedPassword" ng-model="activation.user.repeatedPassword" placeholder="Passwort wiederholen" required reset-remote-validation translate-attr="{ placeholder: 'FORM_PASSWORD_REPEAT_PLACEHOLDER'}"> </label> </div> </div> <div class="row"> <div class="small-12 columns text-center"> <div> <button ng-if="activation.loading" type="submit" class="button-primary" ng-click="activation.activate()" ng-disabled="activation.loading" translate="BUTTON_LABEL_SAVING">Speichern...</button> <button ng-if="!activation.loading" type="submit" class="button-primary" ng-click="activation.activate()" ng-disabled="activation.loading" translate="BUTTON_LABEL_SAVE">Speichern</button> </div> </div> </div> </form> </content-row>
as-ideas/crowdsource
crowdsource-frontend/src/main/resources/public/app/user/activation/user-activation.html
HTML
gpl-2.0
4,731
/* * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Codename One through http://www.codenameone.com/ if you * need additional information or have any questions. */ package com.codename1.impl.ios; import com.codename1.contacts.Contact; import com.codename1.payment.Product; import com.codename1.social.GoogleImpl; import com.codename1.social.LoginCallback; import com.codename1.ui.geom.Rectangle; import java.io.Writer; import java.util.ArrayList; import java.util.Vector; /** * Abstraction of the underlying native API's * * @author Shai Almog */ public final class IOSNative { //native void startMainThread(Runnable r); native void initVM(); static native void deinitializeVM(); native boolean isPainted(); native int getDisplayWidth(); native int getDisplayHeight(); native void editStringAt(int x, int y, int w, int h, long peer, boolean singleLine, int rows, int maxSize, int constraint, String text, boolean forceSlideUp, int color, long imagePeer, int padTop, int padBottom, int padLeft, int padRight, String hint, boolean showToolbar); native void flushBuffer(long peer, int x, int y, int width, int height); native void imageRgbToIntArray(long imagePeer, int[] arr, int x, int y, int width, int height, int imgWidth, int imgHeight); native long createImageFromARGB(int[] argb, int width, int height); native long createImage(byte[] data, int[] widthHeight); native long createImageNSData(long nsData, int[] widthHeight); native long scale(long peer, int width, int height); native void setNativeClippingMutable(int x, int y, int width, int height, boolean firstClip); native void setNativeClippingGlobal(int x, int y, int width, int height, boolean firstClip); native void nativeDrawLineMutable(int color, int alpha, int x1, int y1, int x2, int y2); native void nativeDrawLineGlobal(int color, int alpha, int x1, int y1, int x2, int y2); native void nativeFillRectMutable(int color, int alpha, int x, int y, int width, int height); native void nativeFillRectGlobal(int color, int alpha, int x, int y, int width, int height); native void nativeDrawRectMutable(int color, int alpha, int x, int y, int width, int height); native void nativeDrawRectGlobal(int color, int alpha, int x, int y, int width, int height); native void nativeDrawRoundRectMutable(int color, int alpha, int x, int y, int width, int height, int arcWidth, int arcHeight); native void nativeDrawRoundRectGlobal(int color, int alpha, int x, int y, int width, int height, int arcWidth, int arcHeight); native void nativeFillRoundRectMutable(int color, int alpha, int x, int y, int width, int height, int arcWidth, int arcHeight); native void nativeFillRoundRectGlobal(int color, int alpha, int x, int y, int width, int height, int arcWidth, int arcHeight); native void nativeFillArcMutable(int color, int alpha, int x, int y, int width, int height, int startAngle, int arcAngle); native void nativeDrawArcMutable(int color, int alpha, int x, int y, int width, int height, int startAngle, int arcAngle); native void nativeFillArcGlobal(int color, int alpha, int x, int y, int width, int height, int startAngle, int arcAngle); native void nativeDrawArcGlobal(int color, int alpha, int x, int y, int width, int height, int startAngle, int arcAngle); native void nativeDrawStringMutable(int color, int alpha, long fontPeer, String str, int x, int y); native void nativeDrawStringGlobal(int color, int alpha, long fontPeer, String str, int x, int y); native void nativeDrawImageMutable(long peer, int alpha, int x, int y, int width, int height); native void nativeDrawImageGlobal(long peer, int alpha, int x, int y, int width, int height); native void nativeTileImageGlobal(long peer, int alpha, int x, int y, int width, int height); native int stringWidthNative(long peer, String str); native int charWidthNative(long peer, char ch); native int getFontHeightNative(long peer); native int fontAscentNative(long peer); native int fontDescentNative(long peer); native long createSystemFont(int face, int style, int size); byte[] loadResource(String name, String type) { int val = getResourceSize(name, type); if(val < 0) { return null; } byte[] data = new byte[val]; loadResource(name, type, data); return data; } native int getResourceSize(String name, String type); native void loadResource(String name, String type, byte[] data); native long createNativeMutableImage(int w, int h, int color); native void startDrawingOnImage(int w, int h, long peer); native long finishDrawingOnImage(); native void deleteNativePeer(long peer); native void deleteNativeFontPeer(long peer); native void resetAffineGlobal(); native void scaleGlobal(float x, float y); native void rotateGlobal(float angle); native void rotateGlobal(float angle, int x, int y); /* native void translateGlobal(int x, int y); native int getTranslateXGlobal(); native int getTranslateYGlobal(); */ native void shearGlobal(float x, float y); native void fillRectRadialGradientGlobal(int startColor, int endColor, int x, int y, int width, int height, float relativeX, float relativeY, float relativeSize); native void fillLinearGradientGlobal(int startColor, int endColor, int x, int y, int width, int height, boolean horizontal); native void fillRectRadialGradientMutable(int startColor, int endColor, int x, int y, int width, int height, float relativeX, float relativeY, float relativeSize); native void fillLinearGradientMutable(int startColor, int endColor, int x, int y, int width, int height, boolean horizontal); native boolean isTablet(); native boolean isIOS7(); native void setImageName(long nativeImage, String name); native boolean canExecute(String url); native void execute(String url); native void flashBacklight(int duration); native boolean isMinimized(); native boolean minimizeApplication(); native void restoreMinimizedApplication(); native void lockOrientation(boolean portrait); native void unlockOrientation(); native void lockScreen(); native void unlockScreen(); native void vibrate(int duration); native int getAudioDuration(long peer); native void playAudio(long peer); native int getAudioTime(long peer); native void pauseAudio(long peer); native void setAudioTime(long peer, int time); native boolean isAudioPlaying(long peer); native void cleanupAudio(long peer); native long createAudio(String uri, Runnable onCompletion); native long createAudio(byte[] data, Runnable onCompletion); native float getVolume(); native void setVolume(float vol); // Peer Component methods native void calcPreferredSize(long peer, int w, int h, int[] response); native void updatePeerPositionSize(long peer, int x, int y, int w, int h); native void peerInitialized(long peer, int x, int y, int w, int h); native void peerDeinitialized(long peer); native void peerSetVisible(long peer, boolean v); native long createPeerImage(long peer, int[] wh); native void releasePeer(long peer); native void retainPeer(long peer); native void setPinchToZoomEnabled(long peer, boolean e); native void setNativeBrowserScrollingEnabled(long peer, boolean e); native long createBrowserComponent(Object bc); native void setBrowserPage(long browserPeer, String html, String baseUrl); native void setBrowserURL(long browserPeer, String url); native void setBrowserUserAgent(long browserPeer, String ua); native void browserBack(long browserPeer); native void browserStop(long browserPeer); native void browserClearHistory(long browserPeer); native void browserExecute(long browserPeer, String javaScript); native String browserExecuteAndReturnString(long browserPeer, String javaScript); native void browserForward(long browserPeer); native boolean browserHasBack(long browserPeer); native boolean browserHasForward(long browserPeer); native void browserReload(long browserPeer); native String getBrowserTitle(long browserPeer); native String getBrowserURL(long browserPeer); native long createVideoComponent(String url); native long createVideoComponent(byte[] video); native long createVideoComponentNSData(long video); native long createNativeVideoComponent(String url); native long createNativeVideoComponent(byte[] video); native long createNativeVideoComponentNSData(long video); native void startVideoComponent(long peer); native void stopVideoComponent(long peer); native void pauseVideoComponent(long peer); native int getMediaTimeMS(long peer); native int setMediaTimeMS(long peer, int now); native int getMediaDuration(long peer); native void setMediaBgArtist(String artist); native void setMediaBgTitle(String title); native void setMediaBgDuration(long duration); native void setMediaBgPosition(long position); native void setMediaBgAlbumCover(long cover); native boolean isVideoPlaying(long peer); native void setVideoFullScreen(long peer, boolean fullscreen); native boolean isVideoFullScreen(long peer); native long getVideoViewPeer(long peer); native void showNativePlayerController(long peer); // IO methods native int writeToFile(byte[] data, String path); native int appendToFile(byte[] data, String path); native int getFileSize(String path); native long getFileLastModified(String path); native void readFile(String path, byte[] bytes); native String getDocumentsDir(); native String getCachesDir(); native String getResourcesDir(); native void deleteFile(String file); native boolean fileExists(String file); native boolean isDirectory(String file); native int fileCountInDir(String dir); native void listFilesInDir(String dir, String[] files); native void createDirectory(String dir); native void moveFile(String src, String dest); native long openConnection(String url, int timeout); native void connect(long peer); native void setMethod(long peer, String mtd); native int getResponseCode(long peer); native String getResponseMessage(long peer); native int getContentLength(long peer); native String getResponseHeader(long peer, String name); native int getResponseHeaderCount(long peer); native String getResponseHeaderName(long peer, int offset); native void addHeader(long peer, String key, String value); native void setBody(long peer, byte[] arr); native void setBody(long peer, String file); native void closeConnection(long peer); native String getUDID(); native String getOSVersion(); // location manager native long createCLLocation(); native boolean isGoodLocation(long clLocation); native long getCurrentLocationObject(long clLocation); native double getLocationLatitude(long location); native double getLocationAltitude(long location); native double getLocationLongtitude(long location); native double getLocationAccuracy(long location); native double getLocationDirection(long location); native double getLocationVelocity(long location); native long getLocationTimeStamp(long location); native void startUpdatingLocation(long clLocation); native void stopUpdatingLocation(long clLocation); // capture native void captureCamera(boolean movie); native void openGallery(int type); native long createAudioRecorder(String destinationFile); native void startAudioRecord(long peer); native void pauseAudioRecord(long peer); native void cleanupAudioRecord(long peer); native void sendEmailMessage(String[] recipients, String subject, String content, String[] attachment, String[] attachmentMimeType, boolean htmlMail); native boolean isContactsPermissionGranted(); native int getContactCount(boolean withNumbers); native void getContactRefIds(int[] refs, boolean withNumbers); native void updatePersonWithRecordID(int id, Contact cnt, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress); native long getPersonWithRecordID(int id); native String getPersonFirstName(long id); native String getPersonSurnameName(long id); native int getPersonPhoneCount(long id); native String getPersonPhone(long id, int offset); native String getPersonPhoneType(long id, int offset); native String getPersonPrimaryPhone(long id); native String getPersonEmail(long id); native String getPersonAddress(long id); native long createPersonPhotoImage(long id); native String createContact(String firstName, String surname, String officePhone, String homePhone, String cellPhone, String email); native boolean deleteContact(int id); native void dial(String phone); native void sendSMS(String phone, String text); native void registerPush(); native void deregisterPush(); native void setBadgeNumber(int number); native long createImageFile(long imagePeer, boolean jpeg, int width, int height, float quality); native int getNSDataSize(long nsData); native void nsDataToByteArray(long nsData, byte[] data); native long createNSData(String file); native long createNSDataResource(String name, String type); native int read(long nsData, int pointer); native void read(long nsData, byte[] destination, int offset, int length, int pointer); native boolean sqlDbExists(String name); native long sqlDbCreateAndOpen(String name); native void sqlDbDelete(String name); native void sqlDbClose(long db); native void sqlDbExec(long dbPeer, String sql, String[] args); native long sqlDbExecQuery(long dbPeer, String sql, String[] args); native boolean sqlCursorFirst(long statementPeer); native boolean sqlCursorNext(long statementPeer); native String sqlGetColName(long statementPeer, int index); native void sqlCursorCloseStatement(long statement); native byte[] sqlCursorValueAtColumnBlob(long statement, int col); native double sqlCursorValueAtColumnDouble(long statement, int col); native float sqlCursorValueAtColumnFloat(long statement, int col); native int sqlCursorValueAtColumnInteger(long statement, int col); native long sqlCursorValueAtColumnLong(long statement, int col); native short sqlCursorValueAtColumnShort(long statement, int col); native String sqlCursorValueAtColumnString(long statement, int col); native int sqlCursorGetColumnCount(long statementPeer); native void fetchProducts(String[] skus, Product[] products); native void purchase(String sku); native boolean canMakePayments(); native void restorePurchases(); native void zoozPurchase(double amount, String currency, String appKey, boolean sandbox, String invoiceNumber); native String formatInt(int i); native String formatDouble(double d); native String formatCurrency(double d); native String formatDate(long date); native String formatDateShort(long date); native String formatDateTime(long date); native double parseDouble(String localeFormattedDecimal); native String formatDateTimeMedium(long date); native String formatDateTimeShort(long date); native String getCurrencySymbol(); native void scanQRCode(); native void scanBarCode(); native long createTruetypeFont(String name); native long deriveTruetypeFont(long uiFont, boolean bold, boolean italic, float size); native void log(String text); native void addCookie(String key, String value, String domain, String path, boolean secure, boolean httpOnly, long expires); native void getCookiesForURL(String url, Vector out); native String getUserAgentString(); native void openDatePicker(int type, long time, int x, int y, int w, int h); native void openStringPicker(String[] stringArray, int selection, int x, int y, int w, int h); native void socialShare(String text, long imagePeer, Rectangle sourceRect); // facebook connect public native void facebookLogin(Object callback); public native boolean isFacebookLoggedIn(); public native String getFacebookToken(); public native void facebookLogout(); public native boolean askPublishPermissions(LoginCallback lc); public native boolean hasPublishPermissions(); public native boolean isAsyncEditMode(); public native void setAsyncEditMode(boolean b); public native void foldVKB(); public native void hideTextEditing(); public native int getVKBHeight(); public native int getVKBWidth(); public native long connectSocket(String host, int port); public native String getHostOrIP(); public native void disconnectSocket(long socket); public native boolean isSocketConnected(long socket); public native String getSocketErrorMessage(long socket); public native int getSocketErrorCode(long socket); public native int getSocketAvailableInput(long socket); public native byte[] readFromSocketStream(long socket); public native void writeToSocketStream(long socket, byte[] data); // Paths native long nativePathStrokerCreate(long consumerOutPtr, float lineWidth, int capStyle, int joinStyle, float miterLimit); native void nativePathStrokerCleanup(long ptr); native void nativePathStrokerReset(long ptr, float lineWidth, int capStyle, int joinStyle, float miterLimit); native long nativePathStrokerGetConsumer(long ptr); native long nativePathRendererCreate(int pix_boundsX, int pix_boundsY, int pix_boundsWidth, int pix_boundsHeight, int windingRule); native void nativePathRendererSetup(int subpixelLgPositionsX, int subpixelLgPositionsY); native void nativePathRendererCleanup(long ptr); native void nativePathRendererReset(long ptr, int pix_boundsX, int pix_boundsY, int pix_boundsWidth, int pix_boundsHeight, int windingRule); native void nativePathRendererGetOutputBounds(long ptr, int[] bounds); native long nativePathRendererGetConsumer(long ptr); native long nativePathRendererCreateTexture(long ptr); native int[] nativePathRendererToARGB(long ptr, int color); native void nativeDeleteTexture(long textureID); native void nativePathConsumerMoveTo(long ptr, float x, float y); native void nativePathConsumerLineTo(long ptr, float x, float y); native void nativePathConsumerQuadTo(long ptr, float xc, float yc, float x1, float y1); native void nativePathConsumerCurveTo(long ptr, float xc1, float yc1, float xc2, float yc2, float x1, float y1); native void nativePathConsumerClose(long ptr); native void nativePathConsumerDone(long ptr); native void nativeDrawPath(int color, int alpha, long ptr); native void nativeSetTransform( float a0, float a1, float a2, float a3, float b0, float b1, float b2, float b3, float c0, float c1, float c2, float c3, float d0, float d1, float d2, float d3, int originX, int originY ); native boolean nativeIsTransformSupportedGlobal(); native boolean nativeIsShapeSupportedGlobal(); native boolean nativeIsPerspectiveTransformSupportedGlobal(); native boolean nativeIsAlphaMaskSupportedGlobal(); native void drawTextureAlphaMask(long textureId, int color, int alpha, int x, int y, int w, int h); // End paths native void setNativeClippingMaskGlobal(long textureName, int x, int y, int width, int height); public native void printStackTraceToStream(Throwable t, Writer o); //public native String stackTraceToString(Throwable t); native void fillConvexPolygonGlobal(float[] points, int color, int alpha); native void drawConvexPolygonGlobal(float[] points, int color, int alpha, float lineWidth, int joinStyle, int capStyle, float miterLimit); native void setNativeClippingPolygonGlobal(float[] points); native void clearNativeCookies(); native void splitString(String source, char separator, ArrayList<String> out) ; native void readFile(long nsFileHandle, byte[] b, int off, int len); native int getNSFileOffset(long nsFileHandle); native int getNSFileAvailable(long nsFileHandle); native int getNSFileSize(long nsFileHandle); native long createNSFileHandle(String name, String type); native long createNSFileHandle(String file); native void setNSFileOffset(long nsFileHandle, int off); /** * Reads a single byte from filehandle. * @param nsFileHandle * @return */ native int readNSFile(long nsFileHandle); public native boolean isGoogleLoggedIn(); public native void googleLogin(Object callback); public native String getGoogleToken(); public native void googleLogout(); public native void inviteFriends(String appLinkUrl, String previewImageUrl); }
sdwolf/CodenameOne
Ports/iOSPort/src/com/codename1/impl/ios/IOSNative.java
Java
gpl-2.0
22,532
<!-- // $Id$ // $Author$ // $Log$ // Revision 1.1 2004/03/09 20:02:17 rufustfirefly // Fixed help system to work with newskin and new location. // // Revision 1.2 2001/12/06 16:25:51 rufustfirefly // more documentation changes/additions // // Revision 1.1 2001/11/21 21:03:27 rufustfirefly // all helpfiles had .php removed // // Revision 1.4 2001/11/20 22:00:29 rufustfirefly // cleanup and helpfile updates // // Revision 1.3 2001/11/19 22:54:41 rufustfirefly // new system for interlinked documentation (substitution via percents) // // Revision 1.2 2001/11/19 20:47:33 rufustfirefly // updated with CVS tags in HTML comment // --> Welcome to FreeMED, the world's premiere web-based open-source practice management and electronic medical record software! <P> If you need explaination of any of FreeMED's concepts, go to the %%Concept list,concept%%. <P> The main menu is the center of FreeMED's navigation. From here, you can use access any part of the FreeMED software. <P> <UL> <LI>%%Administration Menu,admin%% - If you have administrator access to FreeMED, you'll see this menu. It allows you to add and remove users, modify FreeMED's global configuration, and perform actions involving the database. If this is your first time running FreeMED as an administrator, you have to go to this menu and initialize the database, or else FreeMED will be unable to function properly. <LI><I>Billing Functions</I> - The entire billing interface of FreeMED is available via this menu. Some functions reqiure a patient to already be selected before using these functions. <LI><I>Call In</I> - Call-ins are available for potential patients who call for an appointment, but have a possibility of not showing up. This is useful if you don't want to fill up your patient database with people who you might not see in the office. <LI><I>Database Functions</I> - If you can see this menu, you have access to some of FreeMED's lower-level functions. With this menu, you can modify the internal workings, catalogs, and listings that make FreeMED work. <LI>%%Patient Functions,patient%% - This is the EMR, and all patient EMR functions are available via this menu. Some skins have a patient history on the left hand bar which allow you to simply select a recently viewed patient to view without having to reselect them. <LI><I>Reports</I> - This controls the report modules. More reports can be added by contacting your system administrator, or you can use Query Maker or the Custom Records portion of FreeMED. <LI><I>Calendar</I> - These are the calendar bits. <LI><I>Logout of FreeMED</I> - This will log you out of FreeMED. Please remember to log out if you will be away from your computer for an extended period of time. </UL>
freemed/freemed
locale/en_US/doc/main.en_US.html
HTML
gpl-2.0
2,802
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Rosegarden A MIDI and audio sequencer and musical notation editor. Copyright 2000-2014 the Rosegarden development team. Other copyrights also apply to some parts of this work. Please see the AUTHORS file and individual file headers for details. 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. See the file COPYING included with this distribution for more information. */ #ifndef RG_VELOCITYCOLOUR_H #define RG_VELOCITYCOLOUR_H #include <QColor> namespace Rosegarden { /** * Returns a QColour according to a formula. We provide three colours * to mix, a maximum value and three knees at which points the * intermediate colours max out. Play around to your satisfaction. */ class VelocityColour { public: VelocityColour(const QColor &loud, const QColor &medium, const QColor &quiet, int maximum, int loudKnee, int mediumKnee, int quietKnee); ~VelocityColour(); const QColor& getColour(int value); int getLoudKnee() const { return m_loudKnee; } int getMediumKnee() const { return m_mediumKnee; } int getQuietKnee() const { return m_quietKnee; } QColor getLoudColour() const { return m_loudColour; } QColor getMediumColour() const { return m_mediumColour; } QColor getQuietColour() const { return m_quietColour; } int getMaxValue() const { return m_maximum; } private: QColor m_loudColour; QColor m_mediumColour; QColor m_quietColour; int m_loudKnee; int m_mediumKnee; int m_quietKnee; int m_maximum; // the mixed colour that we can return QColor m_mixedColour; int m_loStartRed; int m_loStartGreen; int m_loStartBlue; int m_loStepRed; int m_loStepGreen; int m_loStepBlue; int m_hiStartRed; int m_hiStartGreen; int m_hiStartBlue; int m_hiStepRed; int m_hiStepGreen; int m_hiStepBlue; int m_multiplyFactor; }; } #endif
nengxu/rosegarden
src/gui/rulers/VelocityColour.h
C
gpl-2.0
2,320
/* ######################################################################## LXRAD - GUI for X programing ######################################################################## Copyright (c) : 2001-2021 Luis Claudio Gamboa Lopes 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, 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. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ #include"../include/cdraw.h" #include"../include/cmessage.h" #include"../include/lxutils.h" // CDraw_____________________________________________________________ CDraw::CDraw(void) { FileName = wxT (""); Data = NULL; LWidth = 0; SetX (10); SetY (10); SetWidth (100); SetHeight (100); SetClass (wxT ("CDraw")); SetTransparent (false); Sx = 1; Sy = 1; } CDraw::~CDraw(void) { } int CDraw::Create(CControl * control) { Win = control->GetWin (); Widget = new wxPanel (control->GetWidget (), GetWid (), wxPoint (GetX (), GetY ()), wxSize (GetWidth (), GetHeight ()), wxTAB_TRAVERSAL, GetName ()); Widget->SetBackgroundColour (wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOW)); Canvas.Create (Widget, 0); Canvas.Init (); Canvas.SetBgColor (255, 255, 255); Canvas.SetFgColor (0, 0, 0); Canvas.SetLineWidth (LWidth); Canvas.Rectangle (true, 0, 0, Width, Height); Canvas.End (); //Update (); if (Data != NULL) SetImgData (Data); if (FileName != wxT ("")) SetImgFileName (FileName); return CControl::Create (control); } void CDraw::Draw(void) { /*FIX*/ // gdk_draw_pixmap(Widget->window,Widget->style->fg_gc[GTK_WIDGET_STATE (Widget)],Pixmap,0,0,0,0,Width,Height); /* GdkRectangle update_rect; update_rect.x = 0; update_rect.y = 0; update_rect.width = Width; update_rect.height = Height; */ //gtk_widget_draw (Widget, &update_rect); } bool CDraw::GetTransparent(void) { return Transparent; } void CDraw::SetTransparent(bool transparent) { Transparent = transparent; } lxStringList CDraw::GetContext(void) { CControl::GetContext (); Context.AddLine (xml_out (wxT ("Transparent"), wxT ("bool"), itoa (GetTransparent ()))); Context.AddLine (xml_out (wxT ("ImgFileName"), wxT ("File"), GetImgFileName ())); return Context; } void CDraw::SetContext(lxStringList context) { lxString name, type, value; CControl::SetContext (context); for (uint i = 0; i < context.GetLinesCount (); i++) { xml_in (Context.GetLine (i), name, type, value); if (name.compare (wxT ("Transparent")) == 0) SetTransparent (atoi (value)); if (name.compare (wxT ("ImgFileName")) == 0) { if (value.size () > 0) SetImgFileName (value); else SetImgFileName (wxT ("")); } } } lxString CDraw::GetImgFileName(void) { return FileName; } bool CDraw::SetImgFileName(lxString filename, double sx, double sy) { FileName = filename; Sx = sx; Sy = sy; if ((Widget != NULL)&&(FileName != wxT (""))) { lxImage image(Win); if (image.LoadFile (FileName, 0, sx, sy)) { wxBitmap bitmap (image); Canvas.SetBitmap (&bitmap, 1.0, 1.0); Update (); } return true; } else return false; } bool CDraw::SetImgFileName(lxString filename) { FileName = filename; Sx = 1; Sy = 1; if ((Widget != NULL)&&(FileName != wxT (""))) { wxImage image; if (image.LoadFile (FileName)) { wxBitmap bitmap (image); Canvas.SetBitmap (&bitmap, 1, 1); Update (); } return true; } else return false; } bool CDraw::SetImgData(const char **data) { wxBitmap bitmap (data); Data = data; if (Widget != NULL) { Canvas.SetBitmap (&bitmap, Sx, Sy); Update (); } return false; } void CDraw::WriteImgToFile(lxString filename) { if (Widget != NULL) { Canvas.GetBitmapBuffer ()->SaveFile (filename, wxBITMAP_TYPE_PNG, NULL); } } //events void CDraw::on_draw(wxPaintEvent * event) { // gdk_draw_drawable (Widget->window, Canvas.GetGC(), Pixmap, event->area.x, event->area.y, event->area.x, event->area.y, event->area.width, event->area.height); Canvas.Init (); Canvas.End (); CControl::on_draw (event); }
lcgamboa/lxrad
lib/cdraw.cc
C++
gpl-2.0
4,702
liferay-mail-client =================== Liferay Mail Client to send mails to Users,Sites,Organisations and User Groups Tested with Liferay 6.1 CE
jento-tm/liferay-mail-client
README.md
Markdown
gpl-2.0
148
APP = dca TYPE = generated XGCC = msp430-gcc \ -mmcu=msp430x1611 \ -DUIP_CONF_IPV6_RPL \ -DCONTIKI=1 \ -DCONTIKI_TARGET_SKY=1 \ -DPROJECT_CONF_H=\"project-conf.h\" \ -DUIP_CONF_IPV6=1 \ -DUIP_CONF_IPV6_RPL=1 \ -DWITH_UIP6=1 \ -I. \ -I$(ROOT)/applications/contiki \ -I/home/alex/scm/contiki/platform/sky \ -I/home/alex/scm/contiki/platform/sky/dev \ -I/home/alex/scm/contiki/platform/sky/apps \ -I/home/alex/scm/contiki/platform/sky/net \ -I/home/alex/scm/contiki/cpu/msp430/f1xxx \ -I/home/alex/scm/contiki/cpu/msp430 \ -I/home/alex/scm/contiki/cpu/msp430/dev \ -I/home/alex/scm/contiki/core/dev \ -I/home/alex/scm/contiki/core/lib \ -I/home/alex/scm/contiki/core/net \ -I/home/alex/scm/contiki/core/net/mac \ -I/home/alex/scm/contiki/core/net/rime \ -I/home/alex/scm/contiki/core/net/rpl \ -I/home/alex/scm/contiki/core/sys \ -I/home/alex/scm/contiki/core/cfs \ -I/home/alex/scm/contiki/core/ctk \ -I/home/alex/scm/contiki/core/lib/ctk \ -I/home/alex/scm/contiki/core/loader \ -I/home/alex/scm/contiki/core \ include $(ROOT)/applications/contiki/common.mak
copton/ocram
applications/contiki/dca/generated/Makefile
Makefile
gpl-2.0
1,091
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: XACollectionTest.java,v 1.5.2.4 2008/01/07 15:14:24 cwl Exp $ */ package com.sleepycat.collections.test; import java.io.File; import javax.transaction.xa.XAResource; import junit.framework.Test; import junit.framework.TestSuite; import com.sleepycat.collections.TransactionRunner; import com.sleepycat.collections.TransactionWorker; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.DeadlockException; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import com.sleepycat.je.XAEnvironment; import com.sleepycat.je.log.LogUtils.XidImpl; import com.sleepycat.util.ExceptionUnwrapper; /** * Runs CollectionTest with special TestEnv and TransactionRunner objects to * simulate XA transactions. * * <p>This test is currently JE-only and will not compile on DB core.</p> */ public class XACollectionTest extends CollectionTest { public static Test suite() throws Exception { TestSuite suite = new TestSuite(); EnvironmentConfig config = new EnvironmentConfig(); config.setTransactional(true); TestEnv xaTestEnv = new XATestEnv(config); for (int j = 0; j < TestStore.ALL.length; j += 1) { for (int k = 0; k < 2; k += 1) { boolean entityBinding = (k != 0); suite.addTest(new XACollectionTest (xaTestEnv, TestStore.ALL[j], entityBinding)); } } return suite; } public XACollectionTest(TestEnv testEnv, TestStore testStore, boolean isEntityBinding) { super(testEnv, testStore, isEntityBinding, false /*isAutoCommit*/); } protected TransactionRunner newTransactionRunner(Environment env) throws DatabaseException { return new XARunner((XAEnvironment) env); } private static class XATestEnv extends TestEnv { private XATestEnv(EnvironmentConfig config) { super("XA", config); } protected Environment newEnvironment(File dir, EnvironmentConfig config) throws DatabaseException { return new XAEnvironment(dir, config); } } private static class XARunner extends TransactionRunner { private XAEnvironment xaEnv; private static int sequence; private XARunner(XAEnvironment env) { super(env); xaEnv = env; } public void run(TransactionWorker worker) throws Exception { if (xaEnv.getThreadTransaction() == null) { for (int i = 0;; i += 1) { sequence += 1; XidImpl xid = new XidImpl (1, String.valueOf(sequence).getBytes(), null); try { xaEnv.start(xid, 0); worker.doWork(); int ret = xaEnv.prepare(xid); xaEnv.end(xid, 0); if (ret != XAResource.XA_RDONLY) { xaEnv.commit(xid, false); } return; } catch (Exception e) { e = ExceptionUnwrapper.unwrap(e); try { xaEnv.end(xid, 0); xaEnv.rollback(xid); } catch (Exception e2) { e2.printStackTrace(); throw e; } if (i >= getMaxRetries() || !(e instanceof DeadlockException)) { throw e; } } } } else { /* Nested */ try { worker.doWork(); } catch (Exception e) { throw ExceptionUnwrapper.unwrap(e); } } } } }
nologic/nabs
client/trunk/shared/libraries/je-3.2.74/test/com/sleepycat/collections/test/XACollectionTest.java
Java
gpl-2.0
4,102
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. // Sanitize certain kinds of strings before they are output to the log file. #ifndef OPENVPN_OPTIONS_SANITIZE_H #define OPENVPN_OPTIONS_SANITIZE_H #include <string> #include <cstring> #include <openvpn/common/exception.hpp> #include <openvpn/common/options.hpp> namespace openvpn { inline std::string render_options_sanitized(const OptionList& opt, const unsigned int render_flags) { std::ostringstream out; for (size_t i = 0; i < opt.size(); i++) { const Option& o = opt[i]; #ifndef OPENVPN_SHOW_SESSION_TOKEN if (o.get_optional(0, 0) == "auth-token") out << i << " [auth-token] ..." << std::endl; else #endif out << i << ' ' << o.render(render_flags) << std::endl; } return out.str(); } // Remove security-sensitive strings from control message // so that they will not be output to log file. inline std::string sanitize_control_message(const std::string& src_str) { #ifdef OPENVPN_SHOW_SESSION_TOKEN return src_str; #else const char *src = src_str.c_str(); char *ret = new char[src_str.length()+1]; char *dest = ret; bool redact = false; int skip = 0; for (;;) { const char c = *src; if (c == '\0') break; if (c == 'S' && !::strncmp(src, "SESS_ID_", 8)) { skip = 7; redact = true; } else if (c == 'e' && !::strncmp(src, "echo ", 5)) { skip = 4; redact = true; } if (c == ',') /* end of redacted item? */ { skip = 0; redact = false; } if (redact) { if (skip > 0) { --skip; *dest++ = c; } } else *dest++ = c; ++src; } *dest = '\0'; const std::string ret_str(ret); delete [] ret; return ret_str; #endif } } #endif
proxysh/Safejumper-for-Android
app/src/main/cpp/openvpn3/openvpn/options/sanitize.hpp
C++
gpl-2.0
2,716
package com.jp.koncept.innerclass; public class OuterClass { private String str = "Outer-String"; private void printStr() { System.out.println(str); } class InnerClass { public void innerMethod() { String str = "Inner-String"; System.out.println(str); System.out.println(OuterClass.this.str); } } public static void main(String[] args) { OuterClass outerClass = new OuterClass(); outerClass.printStr(); InnerClass innerClass = outerClass.new InnerClass(); innerClass.innerMethod(); } } interface A { public void InterA(); } class Outer { A a = new A() { public void InterA() { System.out.println("OKKKK"); } }; }
javapathshala/WisdomCode
JP_KONCEPT/src/main/java/com/jp/koncept/innerclass/OuterClass.java
Java
gpl-2.0
697
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Fuzzy Hashing API: fuzzy.h Source File</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="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Fuzzy Hashing API </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">fuzzy.h</div> </div> </div><!--header--> <div class="contents"> <a href="fuzzy_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="preprocessor">#ifndef __FUZZY_H</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="preprocessor"></span><span class="preprocessor"># define __FUZZY_H</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="comment">// Fuzzy Hashing by Jesse Kornblum</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="comment">// Copyright (C) Kyrus 2012</span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="comment">//</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="comment">// $Id: fuzzy.h 147 2012-05-25 12:14:50Z jessekornblum $ </span></div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;</div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;</div> <div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160;</div> <div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160;<span class="preprocessor">#ifdef __cplusplus</span></div> <div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160;<span class="preprocessor"></span><span class="keyword">extern</span> <span class="stringliteral">&quot;C&quot;</span> {</div> <div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160;<span class="preprocessor">#ifndef _INTTYPES_H_</span></div> <div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160;<span class="preprocessor"></span><span class="preprocessor"># include &lt;inttypes.h&gt;</span></div> <div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160;</div> <div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160;</div> <div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160;<span class="keyword">extern</span> <span class="keywordtype">int</span> fuzzy_hash_buf(<span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *buf,</div> <div class="line"><a name="l00059"></a><span class="lineno"> 59</span>&#160; uint32_t buf_len,</div> <div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160; <span class="keywordtype">char</span> *result);</div> <div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160;</div> <div class="line"><a name="l00062"></a><span class="lineno"> 62</span>&#160;</div> <div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160;<span class="keyword">extern</span> <span class="keywordtype">int</span> fuzzy_hash_file(FILE *handle,</div> <div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160; <span class="keywordtype">char</span> *result);</div> <div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160;</div> <div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160;</div> <div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160;<span class="keyword">extern</span> <span class="keywordtype">int</span> fuzzy_hash_filename(<span class="keyword">const</span> <span class="keywordtype">char</span> * filename,</div> <div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160; <span class="keywordtype">char</span> * result);</div> <div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160;</div> <div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160;</div> <div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160;</div> <div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160;<span class="keyword">extern</span> <span class="keywordtype">int</span> fuzzy_compare(<span class="keyword">const</span> <span class="keywordtype">char</span> *sig1, <span class="keyword">const</span> <span class="keywordtype">char</span> *sig2);</div> <div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160;</div> <div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160;</div> <div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160;</div> <div class="line"><a name="l00105"></a><span class="lineno"><a class="code" href="fuzzy_8h.html#a2309f23e98c4c0370f32e3e3cb09afa5"> 105</a></span>&#160;<span class="preprocessor">#define FUZZY_MAX_RESULT (SPAMSUM_LENGTH + (SPAMSUM_LENGTH/2 + 20))</span></div> <div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00108"></a><span class="lineno"><a class="code" href="fuzzy_8h.html#a137a76507c72a195455009b62e28c671"> 108</a></span>&#160;<span class="preprocessor">#define SPAMSUM_LENGTH 64</span></div> <div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160;</div> <div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160;<span class="comment">// To end our &#39;extern &quot;C&quot; {&#39;</span></div> <div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160;<span class="preprocessor">#ifdef __cplusplus</span></div> <div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160;<span class="preprocessor"></span>} </div> <div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160;</div> <div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160;<span class="preprocessor">#endif // ifndef __FUZZY_H</span></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jul 23 2012 12:23:44 for Fuzzy Hashing API by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.1 </small></address> </body> </html>
chrisoei/ssdeep
doc/api/html/fuzzy_8h_source.html
HTML
gpl-2.0
8,874
//------------------------------------------------------------------------------ // <copyright file="MainWindow.xaml.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Samples.Kinect.ControlsBasics { using System; using System.Globalization; using System.Windows; using System.Windows.Data; using Microsoft.Kinect; using Microsoft.Kinect.Toolkit; using Microsoft.Kinect.Toolkit.Controls; /// <summary> /// Interaction logic for MainWindow /// </summary> public partial class MainWindow { public static readonly DependencyProperty PageLeftEnabledProperty = DependencyProperty.Register( "PageLeftEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); public static readonly DependencyProperty PageRightEnabledProperty = DependencyProperty.Register( "PageRightEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false)); private const double ScrollErrorMargin = 0.001; private const int PixelScrollByAmount = 20; private readonly KinectSensorChooser sensorChooser; /// <summary> /// Initializes a new instance of the <see cref="MainWindow"/> class. /// </summary> public MainWindow() { this.InitializeComponent(); // initialize the sensor chooser and UI this.sensorChooser = new KinectSensorChooser(); this.sensorChooser.KinectChanged += SensorChooserOnKinectChanged; this.sensorChooserUi.KinectSensorChooser = this.sensorChooser; this.sensorChooser.Start(); // Bind the sensor chooser's current sensor to the KinectRegion var regionSensorBinding = new Binding("Kinect") { Source = this.sensorChooser }; BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding); // Clear out placeholder content this.wrapPanel.Children.Clear(); // Add in display content for (var index = 0; index < 300; ++index) { var button = new KinectTileButton { Label = (index + 1).ToString(CultureInfo.CurrentCulture) }; this.wrapPanel.Children.Add(button); } // Bind listner to scrollviwer scroll position change, and check scroll viewer position this.UpdatePagingButtonState(); scrollViewer.ScrollChanged += (o, e) => this.UpdatePagingButtonState(); } /// <summary> /// CLR Property Wrappers for PageLeftEnabledProperty /// </summary> public bool PageLeftEnabled { get { return (bool)GetValue(PageLeftEnabledProperty); } set { this.SetValue(PageLeftEnabledProperty, value); } } /// <summary> /// CLR Property Wrappers for PageRightEnabledProperty /// </summary> public bool PageRightEnabled { get { return (bool)GetValue(PageRightEnabledProperty); } set { this.SetValue(PageRightEnabledProperty, value); } } /// <summary> /// Called when the KinectSensorChooser gets a new sensor /// </summary> /// <param name="sender">sender of the event</param> /// <param name="args">event arguments</param> private static void SensorChooserOnKinectChanged(object sender, KinectChangedEventArgs args) { if (args.OldSensor != null) { try { args.OldSensor.DepthStream.Range = DepthRange.Default; args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false; args.OldSensor.DepthStream.Disable(); args.OldSensor.SkeletonStream.Disable(); } catch (InvalidOperationException) { // KinectSensor might enter an invalid state while enabling/disabling streams or stream features. // E.g.: sensor might be abruptly unplugged. } } if (args.NewSensor != null) { try { args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30); args.NewSensor.SkeletonStream.Enable(); try { args.NewSensor.DepthStream.Range = DepthRange.Near; args.NewSensor.SkeletonStream.EnableTrackingInNearRange = true; } catch (InvalidOperationException) { // Non Kinect for Windows devices do not support Near mode, so reset back to default mode. args.NewSensor.DepthStream.Range = DepthRange.Default; args.NewSensor.SkeletonStream.EnableTrackingInNearRange = false; } } catch (InvalidOperationException) { // KinectSensor might enter an invalid state while enabling/disabling streams or stream features. // E.g.: sensor might be abruptly unplugged. } } } /// <summary> /// Execute shutdown tasks /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { this.sensorChooser.Stop(); } /// <summary> /// Handle a button click from the wrap panel. /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void KinectTileButtonClick(object sender, RoutedEventArgs e) { var button = (KinectTileButton)e.OriginalSource; var selectionDisplay = new SelectionDisplay(button.Label as string); this.kinectRegionGrid.Children.Add(selectionDisplay); e.Handled = true; } /// <summary> /// Handle paging right (next button). /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void PageRightButtonClick(object sender, RoutedEventArgs e) { scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + PixelScrollByAmount); } /// <summary> /// Handle paging left (previous button). /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void PageLeftButtonClick(object sender, RoutedEventArgs e) { scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - PixelScrollByAmount); } /// <summary> /// Change button state depending on scroll viewer position /// </summary> private void UpdatePagingButtonState() { this.PageLeftEnabled = scrollViewer.HorizontalOffset > ScrollErrorMargin; this.PageRightEnabled = scrollViewer.HorizontalOffset < scrollViewer.ScrollableWidth - ScrollErrorMargin; } } }
prembharath/myKinect
Kinect Interactions/ControlsBasics-WPF/MainWindow.xaml.cs
C#
gpl-2.0
7,917
<footer> <div class = "container"> <div class = "row text-center"> <div class = "col-xs-2 col-s-2 col-md-4 col-lg-4"></div> <div class = "col-xs-8 col-s-8 col-md-4 col-lg-4"> <img src="http://placehold.it/150x75"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vitae commodo arcu. Morbi bibendum a tellus nec gravida. Pellentesque et libero non nisi vehicula egestas. </p> <a href="#"><i class="fa fa-twitter fa-2x "></i></a> <a href="#"><i class="fa fa-facebook fa-2x "></i></a> <a href="#"><i class="fa fa-google fa-2x "></i></a> </div> <div class = "col-xs-2 col-s-2 col-md-4 col-lg-4"></div> </div> <div class = "row text-center"> <div class = "col-xs-0 col-s-0 col-md-2 col-lg-2"></div> <div class = "col-xs-6 col-s-6 col-md-4 col-lg-4"> <h3>Get in Touch</h3> <p><i class="fa fa-phone"></i> ###-###-####</p> <p><i class="fa fa-envelope-o"></i> person@email.site</p> <p><i class="fa fa-map-marker"></i> 1000 Not A Real Place, Texas, ######, USA</p> </div> <div class = "col-xs-6 col-s-6 col-md-4 col-lg-4"> <h3>Business Hours</h3> <p>Monday to Friday: 9AM to 9PM</p> <p>Saturday: 9AM to 6PM</p> <p>Sunday: Closed</p> </div> <div class = "col-xs-0 col-s-0 col-md-2 col-lg-2"></div> </div> </div> </footer> <script> (function(f,i,r,e,s,h,l){i['GoogleAnalyticsObject']=s;f[s]=f[s]||function(){ (f[s].q=f[s].q||[]).push(arguments)},f[s].l=1*new Date();h=i.createElement(r), l=i.getElementsByTagName(r)[0];h.async=1;h.src=e;l.parentNode.insertBefore(h,l) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-XX', 'yourdomain.com'); ga('send', 'pageview'); </script> </body> </html>
Ckhatri/construction
wp-content/themes/html5blank/footer.php
PHP
gpl-2.0
1,763
# # Copyright 2014 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. module Actions module Katello module Repository class CorrectChecksum < Actions::Base def plan(repo) plan_self(:repo_id => repo.id) end def finalize ::User.current = ::User.anonymous_admin repo = ::Katello::Repository.find(input[:repo_id]) found_checksum = repo.pulp_checksum_type if found_checksum && repo.checksum_type != found_checksum repo.checksum_type = found_checksum repo.save! end ensure ::User.current = nil end end end end end
ShimShtein/katello
app/lib/actions/katello/repository/correct_checksum.rb
Ruby
gpl-2.0
1,146
// Autogenerated AST node package pers.xia.jpython.ast; import pers.xia.jpython.object.PyObject; import java.io.DataOutputStream; import java.io.IOException; public class ClassDef extends stmtType { public String name; public java.util.List<exprType> bases; public java.util.List<keywordType> keywords; public java.util.List<stmtType> body; public java.util.List<exprType> decorator_list; public ClassDef(String name, java.util.List<exprType> bases, java.util.List<keywordType> keywords, java.util.List<stmtType> body, java.util.List<exprType> decorator_list,int lineno, int col_offset) { this.name = name; this.bases = bases; this.keywords = keywords; this.body = body; this.decorator_list = decorator_list; this.lineno = lineno; this.col_offset = col_offset; } public String toString() { return "ClassDef"; } public void pickle(DataOutputStream ostream) throws IOException { } public Object accept(VisitorIF visitor) throws Exception { return visitor.visitClassDef(this); } public void traverse(VisitorIF visitor) throws Exception { } }
xia-st/JPython
src/pers/xia/jpython/ast/ClassDef.java
Java
gpl-2.0
1,226
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.IO; namespace Gondwana.Logging { public class LogFile : IDisposable { #region events public delegate void RecordsWrittenToLogEventHandler(LogFile log, int numOfRecords); public event RecordsWrittenToLogEventHandler RecordsWrittenToLogFile; #endregion #region private fields private LoggingLevel loggingLevel = LoggingLevel.LogDebug; private List<LogRecord> logRecords = new List<LogRecord>(); private WriteFrequency writeFrequency = WriteFrequency.Automatic; private string fileName; private FileMode logFileMode; private LogFileOpenType logOpenType; private int lineLimitBeforeFlush = 1; private string logFileDelimiter = LogRecord.DEFAULT_DELIMITER; private FileStream stream = null; private StreamWriter writer = null; private StreamReader reader = null; #endregion #region constructor / finalizer public LogFile(string file, FileMode fileMode, LogFileOpenType openType) { fileName = file; logFileMode = fileMode; logOpenType = openType; OpenFileStreamWriterReader(file, fileMode, openType); } public LogFile(string file, FileMode fileMode, LogFileOpenType openType, string delimiter) { fileName = file; logFileMode = fileMode; logOpenType = openType; logFileDelimiter = delimiter; OpenFileStreamWriterReader(file, fileMode, openType); } ~LogFile() { Dispose(); } #endregion #region public properties public bool Dirty { get { if (logOpenType == LogFileOpenType.Read) return false; else { if (logRecords.Count == 0) return false; else return true; } } } public LoggingLevel LogLevel { get { return loggingLevel; } set { loggingLevel = value; if (logOpenType == LogFileOpenType.Write) { FlushBufferToStream(); writer.WriteLine(); writer.WriteLine(@"*** LogLevel set to [" + loggingLevel.ToString() + "] at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " ***"); writer.WriteLine(); writer.Flush(); } } } public List<LogRecord> WriteBuffer { get { switch (logOpenType) { case LogFileOpenType.Read: return null; case LogFileOpenType.Write: return logRecords; default: return null; } } } public ReadOnlyCollection<LogRecord> ReadBuffer { get { switch (logOpenType) { case LogFileOpenType.Read: return logRecords.AsReadOnly(); case LogFileOpenType.Write: return null; default: return null; } } } public WriteFrequency RecordWriteFrequency { get { return writeFrequency; } set { writeFrequency = value; // flush buffer to file if necessary CheckBufferForFlush(); } } public string FileName { get { return fileName; } } public FileMode LogFileMode { get { return logFileMode; } } public LogFileOpenType LogOpenType { get { return logOpenType; } } public int LineLimitBeforeFlush { get { return lineLimitBeforeFlush; } set { lineLimitBeforeFlush = value; // flush buffer to file if necessary CheckBufferForFlush(); } } public string LogFileDelimiter { get { return logFileDelimiter; } set { logFileDelimiter = value; } } public FileStream LogStream { get { return stream; } } #endregion #region public methods public void WriteLogRecord(LogRecord logRecord) { List<LogRecord> logRecords = new List<LogRecord>(); logRecords.Add(logRecord); WriteLogRecord(logRecords); } public void WriteLogRecord(DateTime logTime, LoggingLevel logLevel, string logUser, string logApp, string logMsg) { LogRecord logRecord; logRecord.LogTime = logTime; logRecord.LogLevel = logLevel; logRecord.LogUser = logUser; logRecord.LogApp = logApp; logRecord.LogMsg = logMsg; WriteLogRecord(logRecord); } public void WriteLogRecord(List<LogRecord> logRecords) { if (logOpenType == LogFileOpenType.Read) throw new LogFileException("File open as read-only; cannot write to file.", null); foreach (LogRecord logRecord in logRecords) { // only log if record is at least as high in priority as this.LogLevel if (logRecord.LogLevel >= loggingLevel) logRecords.Add(logRecord); } // flush buffer to file if necessary CheckBufferForFlush(); } public void FlushBufferToStream() { if (logOpenType == LogFileOpenType.Read) throw new LogFileException("File open as read-only; cannot write to file.", null); // if no records in buffer, no need to continue if (!this.Dirty) return; try { foreach (LogRecord logRecord in logRecords) writer.WriteLine(logRecord.ToString(logFileDelimiter)); if (RecordsWrittenToLogFile != null) RecordsWrittenToLogFile(this, logRecords.Count); logRecords.Clear(); writer.Flush(); } catch (Exception e) { throw new LogFileException( "Unable to write to log; check inner exception for more details.", e); } } public ReadOnlyCollection<LogRecord> ReadLogFile() { if (logOpenType == LogFileOpenType.Write) throw new LogFileException("File open for writing; cannot read file.", null); // clear the previously-read items and move to beginning of stream logRecords.Clear(); stream.Position = 0; try { string line; // read each line until end while ((line = reader.ReadLine()) != null) { if (!line.StartsWith("***") && line.Trim() != string.Empty) { LogRecord logRecord = new LogRecord(line, logFileDelimiter); // only read-in if record is at least as high in priority as this.LogLevel if (logRecord.LogLevel >= loggingLevel) logRecords.Add(logRecord); } } } catch (LogFileException) { throw; } catch (Exception e) { throw new LogFileException( "Error reading from file; check inner exception for more detials.", e); } return this.ReadBuffer; } #endregion #region private methods private void OpenFileStreamWriterReader(string file, FileMode fileMode, LogFileOpenType openType) { stream = new FileStream(file, fileMode); switch (openType) { case LogFileOpenType.Read: reader = new StreamReader(stream); break; case LogFileOpenType.Write: writer = new StreamWriter(stream); writer.WriteLine(@"*** Logging started with LogLevel of [" + loggingLevel.ToString() + "] at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " ***"); writer.WriteLine(); writer.Flush(); break; default: // nothing to be done here break; } } private void CheckBufferForFlush() { // just return if file open for read-only if (this.LogOpenType == LogFileOpenType.Read) return; // return if there are no records currently in buffer if (!this.Dirty) return; // flush buffer depending on this.LogWriteFrequency switch (writeFrequency) { // write all lines to file immediately case WriteFrequency.Automatic: FlushBufferToStream(); break; // write lines to file if line limit is reached case WriteFrequency.LineLimit: if (logRecords.Count >= lineLimitBeforeFlush) FlushBufferToStream(); break; // for Manual do nothing; call to FlushBufferToStream() will be called // outside of class, or on this.Dispose() case WriteFrequency.Manual: default: break; } } #endregion #region IDisposable Members public void Dispose() { GC.SuppressFinalize(this); if (writer != null) { FlushBufferToStream(); writer.WriteLine(); writer.WriteLine(@"*** Logging ended at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " ***"); writer.WriteLine(); writer.Flush(); writer.Dispose(); } if (reader != null) reader.Dispose(); if (stream != null) stream.Dispose(); } #endregion } }
Isthimius/Gondwana
Gondwana.Logging/LogFile.cs
C#
gpl-2.0
11,113
<?php if( ! defined( 'MC4WP_VERSION' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit; } ?> <div id="mc4wp-admin" class="wrap"> <h2><img src="<?php echo MC4WP_PLUGIN_URL . 'assets/img/menu-icon.png'; ?>" /> <?php _e( 'MailChimp for WordPress', 'mailchimp-for-wp' ); ?>: <?php _e( 'License & API Settings', 'mailchimp-for-wp' ); ?></h2> <?php settings_errors(); ?> <form method="post" action="options.php"> <?php settings_fields( 'mc4wp_settings' ); ?> <h3 class="mc4wp-title"> MailChimp <?php _e( 'API Settings', 'mailchimp-for-wp' ); ?> <?php if($connected) { ?> <span class="status positive"><?php _e( 'CONNECTED' ,'mailchimp-for-wp' ); ?></span> <?php } else { ?> <span class="status neutral"><?php _e( 'NOT CONNECTED', 'mailchimp-for-wp' ); ?></span> <?php } ?> </h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="mailchimp_api_key">MailChimp <?php _e( 'API Key', 'mailchimp-for-wp' ); ?></label></th> <td> <input type="text" class="widefat" placeholder="<?php _e( 'Your MailChimp API key', 'mailchimp-for-wp' ); ?>" id="mailchimp_api_key" name="mc4wp[api_key]" value="<?php echo esc_attr( $opts['api_key'] ); ?>" /> <p class="help"><a target="_blank" href="https://admin.mailchimp.com/account/api"><?php _e( 'Get your API key here.', 'mailchimp-for-wp' ); ?></a></p> </td> </tr> </table> <?php submit_button(); ?> </form> <div class="mc4wp-license-form"> <?php $this->license_manager->show_license_form( false ); ?> </div> <?php if( true === $connected ) { ?> <h3 class="mc4wp-title"><?php _e( 'MailChimp Data' ,'mailchimp-for-wp' ); ?></h3> <p><?php _e( 'The table below shows your MailChimp lists data. If you applied changes to your MailChimp lists, please use the following button to renew your cached data.', 'mailchimp-for-wp' ); ?></p> <form method="post" action=""> <input type="hidden" name="mc4wp-renew-cache" value="1" /> <p> <input type="submit" value="<?php _e( 'Renew MailChimp lists', 'mailchimp-for-wp' ); ?>" class="button" /> </p> </form> <table class="wp-list-table widefat"> <thead> <tr> <th class="mc4wp-hide-smallscreens" scope="col">List ID</th> <th scope="col">List Name</th> <th scope="col">Merge Fields <code>TAG</code></th> <th scope="col">Groupings</th> <th scope="col">Subscriber Count</th> </tr> </thead> <tbody> <?php if($lists) { foreach($lists as $list) { ?> <tr valign="top"> <td class="mc4wp-hide-smallscreens"><?php echo esc_html( $list->id ); ?></td> <td><?php echo esc_html( $list->name ); ?></td> <td> <?php if( ! empty( $list->merge_vars ) ) { ?> <ul class="ul-square" style="margin-top: 0;"> <?php foreach( $list->merge_vars as $merge_var ) { ?> <li><?php echo esc_html( $merge_var->name ); if( $merge_var->req ) { echo '<span style="color:red;">*</span>'; } ?> <code><?php echo esc_html( $merge_var->tag ); ?></code></li> <?php } ?> </ul> <?php } ?> </td> <td> <?php if( ! empty( $list->interest_groupings ) ) { foreach($list->interest_groupings as $grouping) { ?> <strong><?php echo esc_html( $grouping->name ); ?></strong> <?php if( ! empty( $grouping->groups ) ) { ?> <ul class="ul-square"> <?php foreach( $grouping->groups as $group ) { ?> <li><?php echo esc_html( $group->name ); ?></li> <?php } ?> </ul> <?php } ?> <?php } } else { ?>-<?php } ?> </td> <td><?php echo esc_html( $list->subscriber_count ); ?></td> </tr> <?php } } else { ?> <tr> <td colspan="5"> <p><?php _e( 'No lists were found in your MailChimp account.', 'mailchimp-for-wp' ); ?></p> </td> </tr> <?php } ?> </tbody> </table> <form method="post" action=""> <input type="hidden" name="mc4wp-renew-cache" value="1" /> <p> <input type="submit" value="<?php _e( 'Renew MailChimp lists', 'mailchimp-for-wp' ); ?>" class="button" /> </p> </form> <?php } ?> <?php require dirname( __FILE__ ) . '/../parts/admin-footer.php'; ?> </div>
jrald1291/atu
wp-content/plugins/mailchimp-for-wp-pro/includes/views/pages/admin-general-settings.php
PHP
gpl-2.0
4,391
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>Cohen Bible</title> <!-- Bootstrap --> <link href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> <link href="style.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Fixed navbar --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><div class="yii2demo-logo"></div></a> </div> <div id="navbar" class="navbar-collapse collapse pull-right"> <ul class="nav navbar-nav"> <li class="active"><a href="#"><span class="glyphicon glyphicon-home"></span></a></li> <li><a href="#"><div class="yii-logo"></div></a></li> <li><a href="#"><div class="wordpress-logo"></div></a></li> <li><a href="#"><div class="html5-logo"></div></a></li> <li><a href="#"><span class="glyphicon glyphicon-wrench"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-question-sign"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-search"></span></a></li> <li><a href="#"><span class="glyphicon glyphicon-user"></span></a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container" role="main"> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="row"> <div class="col-md-8"> <div class="row"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <div class="slide-content"> <div class="col-md-4 text"> <div class="title">先开始再说</div> <div class="author">作者:ABCD 发表时间:2015-10-11</div> <div class="detail">一直想做一款自己的主题,但迟迟没有动手。</div> </div> <div class="col-md-8"></div> </div> <div class="carousel-caption"> </div> </div> <div class="item"> <div class="slide-content"> <div class="col-md-4 text"> <div class="title">先开始再说</div> <div class="author">作者:ABCD 发表时间:2015-10-11</div> <div class="detail">一直想做一款自己的主题,但迟迟没有动手。</div> </div> <div class="col-md-8"></div> </div> <div class="carousel-caption"> </div> </div> <div class="item"> <div class="slide-content"> <div class="col-md-4 text"> <div class="title">先开始再说</div> <div class="author">作者:ABCD 发表时间:2015-10-11</div> <div class="detail">一直想做一款自己的主题,但迟迟没有动手。</div> </div> <div class="col-md-8"></div> </div> <div class="carousel-caption"> </div> </div> </div> </div> </div> <div class="row"> <div class="text-list"> <div class="text-header"> <i class="glyphicon glyphicon-bookmark pull-left"></i><span class="pull-left">&nbsp;&nbsp;&nbsp;最&nbsp;新&nbsp;文&nbsp;章</span><span class="article-number pull-right">300</span> </div> <div class="text-abstract"> <div class="row"> <div class="col-md-4"> <img src="css/text-image.png" class="img-responsive" alt="Responsive image"> </div> <div class="col-md-8"> <ul class="text-info"> <li class="title">先开始再说</li> <li class="author">作者:ABCD 发表时间:2015-10-11</li> <li class="detail">一直想做一款自己的主题,但迟迟没有动手。</li> </ul> </div> </div> <div class="row"> <div class="col-md-4"> <img src="css/text-image.png" class="img-responsive" alt="Responsive image"> </div> <div class="col-md-8"> <ul class="text-info"> <li class="title">先开始再说</li> <li class="author">作者:ABCD 发表时间:2015-10-11</li> <li class="detail">一直想做一款自己的主题,但迟迟没有动手。</li> </ul> </div> </div> </div> </div> </div> </div> <div class="col-md-4"> <div class="text-list"> <div class="text-header"> <i class="glyphicon glyphicon-heart pull-left"></i><span class="pull-left">&nbsp;&nbsp;&nbsp;热&nbsp;门&nbsp;文&nbsp;章</span> </div> <div class="text-hot clearfix"> <div class="image-story clearfix"> <div class="feature-img"> <span class="title center-block strong"> 先开始再说 </span> <img src="img/example-280-150.png" class="img-responsive" alt="Responsive image"> </div> <div class="feature-buttons"> <div class="col-md-4 view"><a class="view" href="#"><span class="glyphicon glyphicon-eye-open"></span></a></div> <div class="col-md-4 like"><a class="like" href="#"><span class="glyphicon glyphicon-heart"></span></a></div> <div class="col-md-4 share"><a class="share" href="#"><span class="glyphicon glyphicon-share"></span></a></div> </div> </div> <div class="image-story"> <div class="feature-img"> <span class="title center-block strong"> 先开始再说 </span> <img src="img/example-280-150.png" class="img-responsive" alt="Responsive image"> </div> <div class="feature-buttons"> <div class="col-md-4 view"><a class="view" href="#"><span class="glyphicon glyphicon-eye-open"></span></a></div> <div class="col-md-4 like"><a class="like" href="#"><span class="glyphicon glyphicon-heart"></span></a></div> <div class="col-md-4 share"><a class="share" href="#"><span class="glyphicon glyphicon-share"></span></a></div> </div> </div> </div> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <footer class="footer"> <div class="links"> <div class="container"> <div class="col-md-8"> <div class="col-md-4"> <ul> <li class="title strong">网站导航</li> <li><a href="">主页</a></li> <li><a href="">Yii</a></li> <li><a href="">WordPress</a></li> <li><a href="">Html5</a></li> <li><a href="">其他文章</a></li> </ul> </div> <div class="col-md-4"> <ul> <li class="title strong">关于本站</li> <li><a href="">关于我们</a></li> <li><a href="">联系我们</a></li> <li><a href="">版权声明</a></li> </ul> </div> <div class="col-md-4"> <ul> <li class="title strong">联系方式</li> <li><a href="">QQ:398036707</a></li> <li><a href="">邮箱:work_id_tjr@163.com</a></li> <li><a href="">微信:tianjingrong1991</a></li> </ul> </div> </div> <div class="col-md-4"> </div> </div> </div> <div class="copyright"> Copyright &copy;2000——2015 <a href="" class="strong">Yii2demo.com</a>. All rights reserved. Powered by <a href="" class="strong">Wordpress</a> </div> </footer> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="http://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- Page script --> <script type="text/javascript"> $(function () { }); </script> </body> </html>
TianJinRong/orange-fresh
home.html
HTML
gpl-2.0
10,848
// // Orientation.h // viewer // // Created by Sam Anklesaria on 11/21/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> #import "EAGLView.h" @interface Orientation : UIViewController { EAGLView *glView; } @property (nonatomic, retain) IBOutlet EAGLView *glView; @end
YUAA/toaster
viewer/Orientation.h
C
gpl-2.0
321
/* NOTES to contributors: * use 4 spaces indents, and keep code ALIGNED and ORDERED */ /* default */ * { -GtkArrow-arrow-scaling: 0.5; -GtkButton-child-displacement-x: 0; -GtkButton-child-displacement-y: 0; -GtkButton-default-border: 0; -GtkButton-image-spacing: 0; -GtkButton-inner-border: 1; -GtkButton-interior-focus: true; -GtkButtonBox-child-min-height: 24; -GtkButtonBox-child-internal-pad-y: 1; -GtkCheckButton-indicator-size: 16; -GtkCheckMenuItem-indicator-size: 14; -GtkExpander-expander-size: 8; -GtkHTML-link-color: @link_color; -GtkIMHtml-hyperlink-color: @link_color; -GtkMenu-horizontal-padding: 0; -GtkMenu-vertical-padding: 0; -GtkPaned-handle-size: 4; -GtkProgressBar-min-horizontal-bar-height: 12; -GtkProgressBar-min-vertical-bar-width: 12; -GtkRange-slider-width: 12; -GtkRange-stepper-spacing: 0; -GtkRange-trough-border: 0; -GtkRange-trough-under-steppers: 1; -GtkScrollbar-has-backward-stepper: true; -GtkScrollbar-has-forward-stepper: true; -GtkScrollbar-min-slider-length: 80; -GtkScrolledWindow-scrollbar-spacing: 0; -GtkScrolledWindow-scrollbars-within-bevel: 1; -GtkStatusbar-shadow-type: none; -GtkTextView-error-underline-color: @error_color; -GtkToolButton-icon-spacing: 6; -GtkToolItemGroup-expander-size: 8; -GtkTreeView-expander-size: 8; -GtkWidget-focus-line-width: 1; -GtkWidget-focus-padding: 0; -GtkWidget-link-color: @link_color; -GtkWidget-visited-link-color: @link_color; -GtkWindow-resize-grip-height: 0; -GtkWindow-resize-grip-width: 0; -WnckTasklist-fade-overlay-rect: 0; background-clip: padding-box; outline-color: alpha(@theme_selected_bg_color, 0.5); outline-style: solid; outline-offset: 0; } /*************** * base states * ***************/ .background { background-color: @theme_bg_color; color: @theme_fg_color; } * { /* inherit colors from parent */ color: inherit; background-color: inherit; } *:selected, *:selected:focus { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } *:insensitive, *:insensitive:insensitive { color: mix(@theme_fg_color, @theme_bg_color, 0.5); } /* apply effects to insensitive and prelit images */ *:insensitive { -gtk-image-effect: dim; } *:hover { -gtk-image-effect: highlight; } .gtkstyle-fallback { background-color: @theme_bg_color; color: @theme_fg_color; } .gtkstyle-fallback:prelight { background-color: shade(@theme_bg_color, 1.1); color: @theme_fg_color; } .gtkstyle-fallback:active { background-color: shade(@theme_bg_color, 0.9); color: @theme_fg_color; } .gtkstyle-fallback:insensitive { background-color: shade(shade(@theme_bg_color, 0.95), 1.05); color: mix(@theme_fg_color, @theme_bg_color, 0.5); } .gtkstyle-fallback:selected { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } GtkImage, GtkImage:insensitive, GtkLabel, GtkLabel:insensitive, GtkBox, GtkBox:insensitive, GtkGrid, GtkGrid:insensitive { background-color: transparent; } /****************** * visual effects * ******************/ /* transitions */ .button { transition: border 100ms ease-in-out; } .entry { transition: border 100ms ease-out; } .entry:focus { transition: border 100ms ease-in; } .entry.image.left { padding-right: 4px; } .notebook tab GtkLabel, .notebook .prelight-page, .notebook .prelight-page GtkLabel, .notebook .active-page, .notebook .active-page GtkLabel { transition: all 200ms ease-in; } /* inset shadows */ .button:active, .primary-toolbar .button:active, .toolbar .button:active, .header-bar .button:active, .notebook.header { box-shadow: inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset -1px 0 alpha(@dark_shadow, 0.07), inset 0 -1px alpha(@dark_shadow, 0.05); } .entry { } /* disable inset shadow */ .button:active *:insensitive, .primary-toolbar .button:active *:insensitive, .toolbar .button:active *:insensitive, .header-bar .button:active *:insensitive, .entry:insensitive { box-shadow: none; } /************* * assistant * *************/ GtkAssistant .sidebar .highlight { font: bold; } GtkAssistant .sidebar { padding: 4px; border-width: 0 1px 0 0; border-style: solid; border-right-color: shade(@theme_bg_color, 0.8); border-radius: 0; background-color: @theme_bg_color; color: mix(@theme_fg_color, @theme_bg_color, 0.1); } /********** * button * **********/ .button { -GtkWidget-focus-padding: 1; -GtkWidget-focus-line-width: 0; padding: 3px 4px; border-width: 1px; border-radius: 0px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 1.08); background-image: none; color: @theme_fg_color; } .button:hover { border-color: shade(@theme_selected_bg_color, 1.3); background-color: shade(@theme_selected_bg_color, 1.02); background-image: none; } .button:active, .button:checked { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@theme_selected_bg_color, 0.95); background-image: none; } .button:active:hover { border-color: shade(@theme_selected_bg_color, 1.3); } .button:focus, .button:hover:focus, .button:active:focus, .button:active:hover:focus { border-color: shade(@theme_selected_bg_color, 1.3); } .button:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; } .button:active *:insensitive { border-color: shade(@theme_bg_color, 0.75); background-color: shade(@theme_bg_color, 0.80); background-image: none; } /* default button */ .button.default { box-shadow: inset 0 0 0 1px shade(@theme_selected_bg_color, 1.1); border-color: shade(@theme_selected_bg_color, 1.1); background-color: shade(@theme_bg_color, 0.85); color: @theme_fg_color; } .button.default:hover { border-color: shade(@theme_selected_bg_color, 1.3); background-color: shade(@theme_selected_bg_color, 0.95); } .button.default:active { border-color: shade(@theme_selected_bg_color, 0.95); background-color: shade(@theme_selected_bg_color, 0.6); } .button.default:active:hover { border-color: shade(@theme_selected_bg_color, 1.3); background-color: shade(@theme_selected_bg_color, 0.6); } /* Flat button */ .button.flat { background-color: transparent; border: 2px solid transparent; background-image: none; box-shadow: none; } .button.flat:hover { border-width: 2px; border-color: shade(@theme_bg_color, 0.9); } .button.flat:active, .button.flat:active:focus, .button.flat:checked, .button.flat:checked:focus { border-width: 2px; border-color: shade(@theme_bg_color, 0.8); } /**************** * cell and row * ****************/ .cell { border-width: 0; border-radius: 0; } .cell:selected, .cell:selected:focus { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } row:selected, row:selected:hover, row:selected:focus { -GtkWidget-focus-padding: 1; -GtkWidget-focus-line-width: 0; border-width: 1px 0; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); background-color: @theme_selected_bg_color; background-image: none; color: @theme_selected_fg_color; } /******************* * check and radio * *******************/ .check, .radio, .check:insensitive, .radio:insensitive { border-style: none; background-color: transparent; } GtkCheckButton:hover, GtkCheckButton:active:hover, GtkCheckButton:selected, GtkCheckButton:selected:focus { background-color: transparent; } /***************** * column-header * *****************/ column-header .button, column-header .button:active { border-width: 0 1px 1px 0; border-radius: 0; } column-header .button, column-header .button:active, column-header .button:focus, column-header .button:active:focus { border-color: shade(@theme_base_color, 0.9); border-bottom-color: shade(@theme_base_color, 0.8); background-color: shade(@theme_base_color, 0.97); background-image: none; } column-header .button:hover, column-header .button:active:hover, column-header .button:hover:focus, column-header .button:active:hover:focus { border-color: shade(@theme_base_color, 0.9); border-bottom-color: shade(@theme_base_color, 0.8); background-color: shade(@theme_base_color, 0.99); background-image: none; } column-header:last-child .button { border-width: 0 0 1px 0; } /**************** * content view * ****************/ .content-view.view { background-color: @theme_base_color; } .content-view.view:prelight { background-color: alpha(@theme_selected_bg_color, 0.6); } .content-view.view:selected, .content-view.view:active { background-color: @theme_selected_bg_color; } .content-view.view:insensitive { background-color: shade(@theme_base_color, 0.9); } GdMainIconView.content-view { -GdMainIconView-icon-size: 40; } GtkIconView.content-view.check { background-color: transparent; } GtkIconView.content-view.check:active { background-color: transparent; } .content-view.view.check, .content-view.view.check:active { background-color: transparent; } GtkIconView.content-view.check:prelight, GtkIconView.content-view.check:insensitive, GtkIconView.content-view.check:selected { background-color: transparent; } /**************** * drawing area * ****************/ GtkDrawingArea { background-color: @theme_base_color; } GtkDrawingArea:insensitive { background-color: shade(@theme_base_color, 0.9); } /*********** * gtkhtml * ***********/ GtkHTML { background-color: @theme_base_color; color: @theme_text_color; } /*********** * calendar * ************/ GtkCalendar { padding: 4px; } GtkCalendar:inconsistent { color: mix(@theme_fg_color, @theme_bg_color, 0.5); } GtkCalendar.view, GtkCalendar.header, GtkCalendar.button, GtkCalendar.button:hover, GtkCalendar.button:insensitive { border-width: 0; background-color: transparent; background-image: none; } .highlight, GtkCalendar.highlight { border-width: 0; background-color: transparent; color: @theme_selected_bg_color; } /****************** * combobox entry * ******************/ .primary-toolbar GtkComboBox.combobox-entry .entry, .primary-toolbar GtkComboBox.combobox-entry .entry:active, .primary-toolbar GtkComboBox.combobox-entry .entry:focus, .primary-toolbar GtkComboBox.combobox-entry .entry:insensitive, GtkComboBox.combobox-entry .entry, GtkComboBox.combobox-entry .entry:active, GtkComboBox.combobox-entry .entry:focus, GtkComboBox.combobox-entry .entry:insensitive { border-width: 1px 0 1px 1px; border-top-right-radius: 0; border-bottom-right-radius: 0; } .primary-toolbar GtkComboBox.combobox-entry .button, .primary-toolbar GtkComboBox.combobox-entry .button:hover, .primary-toolbar GtkComboBox.combobox-entry .button:active, .primary-toolbar GtkComboBox.combobox-entry .button:insensitive, GtkComboBox.combobox-entry .button, GtkComboBox.combobox-entry .button:hover, GtkComboBox.combobox-entry .button:active, GtkComboBox.combobox-entry .button:insensitive { border-width: 1px 1px 1px 1px; border-bottom-left-radius: 0; border-top-left-radius: 0; } /********* * entry * *********/ .entry { padding: 4px 3px; border-width: 1px; border-style: solid; border-color: shade(@bg_color, 0.6); border-radius: 0px; background-color: @theme_base_color; background-image: none; color: @theme_text_color; } .entry:active, .entry:focus { border-color: shade(@selected_bg_color, 0.6); } .entry:selected, .entry:selected:focus { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } .entry:insensitive { background-color: shade(@theme_bg_color, 0.95); background-image: none; color: mix(@theme_text_color, @theme_base_color, 0.5); } .entry.progressbar { border-width: 0; border-radius: 0px; background-color: @bg_color; background-image: none; color: @theme_fg_color; } /************ * expander * ************/ .expander { color: alpha(currentColor, 0.7); border: alpha(currentColor, 0.7); } .expander:hover { color: alpha(currentColor, 0.8); border-color: alpha(currentColor, 0.8); } .expander:active { color: alpha(currentColor, 0.9); border-color: alpha(currentColor, 0.9); } /************** * list boxes * **************/ .list { background-color: shade(@theme_bg_color, 0.97); color: @theme_fg_color; } .list-row:hover { background-color: shade(@theme_bg_color, 1.02); } .list-row:selected { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /********* * frame * *********/ .frame { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0; } /******************* * scrolled window * *******************/ GtkScrolledWindow.frame { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0; } /* avoid double borders when a viewport is * packed into a GtkScrolledWindow */ GtkScrolledWindow GtkViewport.frame { border-style: none; } /************ * iconview * ************/ GtkIconView.view.cell:selected, GtkIconView.view.cell:selected:focus { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); border-radius: 0px; background-color: @theme_selected_bg_color; background-image: none; color: @theme_selected_fg_color; } .content-view.view.rubberband, .view.rubberband, .rubberband { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); border-radius: 0; background-color: alpha(@theme_selected_bg_color, 0.3); } /*********** * infobar * ***********/ GtkInfoBar { border-width: 0; border-style: none; } .info { border-width: 1px; border-style: solid; border-color: shade(@info_bg_color, 0.8); background-color: @info_bg_color; background-image: none; color: @info_fg_color; } .info .button { border-top-color: shade(@info_bg_color, 0.8); border-right-color: shade(@info_bg_color, 0.72); border-left-color: shade(@info_bg_color, 0.72); border-bottom-color: shade(@info_bg_color, 0.7); background-color: shade(@info_bg_color, 1.08); color: @info_fg_color; } .info .button:hover { border-top-color: shade(@info_bg_color, 0.85); border-right-color: shade(@info_bg_color, 0.78); border-left-color: shade(@info_bg_color, 0.78); border-bottom-color: shade(@info_bg_color, 0.7); background-color: shade(@info_bg_color, 1.10); } .info .button:active { border-color: shade(@info_bg_color, 0.6); background-color: shade(@info_bg_color, 0.95); } .info .button:active:hover { border-top-color: shade(@info_bg_color, 0.85); border-right-color: shade(@info_bg_color, 0.78); border-left-color: shade(@info_bg_color, 0.78); border-bottom-color: shade(@info_bg_color, 0.7); } .info .button.close { color: @info_fg_color; } .info .button.close:hover { background-color: alpha(white, 0.2); } .info .button.close:active { color: @info_fg_color; background-color: alpha(black, 0.1); } .warning { border-width: 1px; border-style: solid; border-color: shade(@warning_bg_color, 0.8); background-color: @warning_bg_color; background-image: none; color: @warning_fg_color; } .warning .button { border-top-color: shade(@warning_bg_color, 0.8); border-right-color: shade(@warning_bg_color, 0.72); border-left-color: shade(@warning_bg_color, 0.72); border-bottom-color: shade(@warning_bg_color, 0.7); background-color: shade(@warning_bg_color, 1.08); color: @warning_fg_color; } .warning .button:hover { border-top-color: shade(@warning_bg_color, 0.85); border-right-color: shade(@warning_bg_color, 0.78); border-left-color: shade(@warning_bg_color, 0.78); border-bottom-color: shade(@warning_bg_color, 0.7); background-color: shade(@warning_bg_color, 1.10); } .warning .button:active { border-color: shade(@warning_bg_color, 0.6); background-color: shade(@warning_bg_color, 0.95); } .warning .button:active:hover { border-top-color: shade(@warning_bg_color, 0.85); border-right-color: shade(@warning_bg_color, 0.78); border-left-color: shade(@warning_bg_color, 0.78); border-bottom-color: shade(@warning_bg_color, 0.7); } .warning .button.close { color: @warning_fg_color; } .warning .button.close:hover { background-color: alpha(white, 0.2); } .warning .button.close:active { color: @warning_fg_color; background-color: alpha(black, 0.1); } .question { border-width: 1px; border-style: solid; border-color: shade(@question_bg_color, 0.8); background-color: @question_bg_color; background-image: none; color: @question_fg_color; } .question .button { border-top-color: shade(@question_bg_color, 0.8); border-right-color: shade(@question_bg_color, 0.72); border-left-color: shade(@question_bg_color, 0.72); border-bottom-color: shade(@question_bg_color, 0.7); background-color: shade(@question_bg_color, 1.08); color: @question_fg_color; } .question .button:hover { border-top-color: shade(@question_bg_color, 0.85); border-right-color: shade(@question_bg_color, 0.78); border-left-color: shade(@question_bg_color, 0.78); border-bottom-color: shade(@question_bg_color, 0.7); background-color: shade(@question_bg_color, 1.10); } .question .button:active { border-color: shade(@question_bg_color, 0.6); background-color: shade(@question_bg_color, 0.95); } .question .button:active:hover { border-top-color: shade(@question_bg_color, 0.85); border-right-color: shade(@question_bg_color, 0.78); border-left-color: shade(@question_bg_color, 0.78); border-bottom-color: shade(@question_bg_color, 0.7); } .question .button.close { color: @question_fg_color; } .question .button.close:hover { background-color: alpha(white, 0.2); } .question .button.close:active { color: @question_fg_color; background-color: alpha(black, 0.1); } .error { border-width: 1px; border-style: solid; border-color: shade(@error_bg_color, 0.8); background-color: @error_bg_color; background-image: none; color: @error_fg_color; } .error .button { border-top-color: shade(@error_bg_color, 0.8); border-right-color: shade(@error_bg_color, 0.72); border-left-color: shade(@error_bg_color, 0.72); border-bottom-color: shade(@error_bg_color, 0.7); background-color: shade(@error_bg_color, 1.08); color: @error_fg_color; } .error .button:hover { border-top-color: shade(@error_bg_color, 0.85); border-right-color: shade(@error_bg_color, 0.78); border-left-color: shade(@error_bg_color, 0.78); border-bottom-color: shade(@error_bg_color, 0.7); background-color: shade(@error_bg_color, 1.10); } .error .button:active { border-color: shade(@error_bg_color, 0.6); background-color: shade(@error_bg_color, 0.95); } .error .button:active:hover { border-top-color: shade(@error_bg_color, 0.85); border-right-color: shade(@error_bg_color, 0.78); border-left-color: shade(@error_bg_color, 0.78); border-bottom-color: shade(@error_bg_color, 0.7); } .error .button.close { color: @error_fg_color; } .error .button.close:hover { background-color: alpha(white, 0.2); } .error .button.close:active { color: @error_fg_color; background-color: alpha(black, 0.1); } /******************* * symbolic images * *******************/ .image { color: alpha(currentColor, 0.5); } .image:hover { color: alpha(currentColor, 0.9); } .image:selected, .image:selected:hover { color: @theme_selected_fg_color; } .view.image, .view.image:hover { color: alpha(currentColor, 0.9); } .view.image:selected, .view.image:selected:hover { color: @theme_selected_fg_color; } /***************** * miscellaneous * *****************/ .floating-bar { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0px; background-color: @theme_bg_color; background-image: none; color: @theme_fg_color; } .floating-bar.top { border-top-width: 0; border-top-right-radius: 0; border-top-left-radius: 0; } .floating-bar.right { border-right-width: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; } .floating-bar.bottom { border-bottom-width: 0; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .floating-bar.left { border-left-width: 0; border-bottom-left-radius: 0; border-top-left-radius: 0; } .floating-bar .button { -GtkButton-image-spacing: 0; -GtkButton-inner-border: 0; border-style: none; background-color: transparent; background-image: none; } .view.dim-label, .dim-label { color: alpha(currentColor, 0.5); } .dnd { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); } .grip { background-color: transparent; } .arrow { color: alpha(currentColor, 0.7); } /******** * menu * ********/ GtkTreeMenu.menu, GtkMenuToolButton.menu, GtkComboBox .menu { background-color: @menu_bg_color; } .primary-toolbar .menu, .primary-toolbar .button .menu, .toolbar .menu, .toolbar .primary-toolbar .menu, .header-bar .menu, .header-bar .primary-toolbar .menu, .menu { padding: 0; border-radius: 0; border-style: none; background-color: @menu_bg_color; color: @menu_fg_color; } /* Hover-effect on play-button in ubuntu soundmenu */ .menu:selected { background-color: @selected_bg_color; } .menu.button:hover, .menu.button:active, .menu.button:active *:insensitive, .menu.button:insensitive, .menu.button { border-width: 0; background-color: @menu_bg_color; background-image: none; } .context-menu { font: initial; } /* ubuntu software center menu */ #toolbar-popup { background-color: @menu_bg_color; color: @menu_fg_color; } /*********** * menubar * ***********/ .menubar { -GtkWidget-window-dragging: true; border-style: none; background-color: @menubar_bg_color; background-image: none; color: @menubar_fg_color; } /*************** * menubaritem * ***************/ .menubar.menuitem, .menubar .menuitem { padding: 3px 5px; border-width: 1px; border-style: solid; border-color: transparent; background-color: transparent; background-image: none; color: @menubar_fg_color; } .menubar.menuitem:hover, .menubar .menuitem:hover { border-color: @theme_selected_bg_color; background-color: @theme_selected_bg_color; background-image: none; color: shade(@menubar_fg_color, 1.08); } .menubar .menuitem *:hover { color: shade(@menubar_fg_color, 1.08); } /************ * menuitem * ************/ GtkTreeMenu .menuitem { padding: 0; border-width: 0; } .menuitem, .menu .menuitem { -GtkMenuItem-arrow-scaling: 0.5; padding: 3px; border-width: 1px; border-style: solid; border-color: transparent; border-radius: 0; background-color: transparent; background-image: none; color: @menu_fg_color; } .menu .menuitem:active, .menu .menuitem:hover { border-color: shade(@theme_selected_bg_color, 0.9); background-color: @theme_selected_bg_color; background-image: none; } .menu .menuitem:active, .menu .menuitem *:active, .menu .menuitem:hover, .menu .menuitem *:hover { color: @theme_selected_fg_color; } .menu .menuitem:insensitive, .menu .menuitem *:insensitive { color: mix(@menu_fg_color, @menu_bg_color, 0.5); } .menuitem.check, .menuitem.radio, .menuitem.check:hover, .menuitem.radio:hover, .menuitem.check:insensitive, .menuitem.radio:insensitive { border-style: none; background-color: transparent; background-image: none; } .menuitem.check:active, .menuitem.radio:active { border-style: none; background-color: transparent; } .menuitem GtkCalendar:inconsistent { color: mix(@menu_fg_color, @menu_bg_color, 0.5); } .menuitem GtkCalendar.button { border-style: none; background-color: transparent; background-image: none; } .menuitem .entry { border-color: shade(@bg_color, 0.6); background-color: @menu_bg_color; background-image: none; color: @menu_fg_color; } .menuitem .entry:active, .menuitem .entry:focus { border-color: shade(@selected_bg_color, 0.6); } .menuitem .accelerator { color: alpha(@menu_fg_color, 0.6); } .menuitem .accelerator:hover { color: alpha(@theme_selected_fg_color, 0.8); } .menuitem .accelerator:insensitive { color: alpha(mix(@menu_fg_color, @menu_bg_color, 0.5), 0.6); } GtkModelMenuItem GtkBox GtkImage { padding-right: 4px; } /************ * popovers * ************/ GtkPopover { margin: 10px; padding: 2px; border-radius: 0px; border-color: shade(@theme_bg_color, 0.8); border-width: 1px; border-style: solid; background-clip: border-box; background-color: @theme_bg_color; color: @theme_fg_color; box-shadow: 0 2px 3px alpha(black, 0.5); } GtkPopover .button.flat { color: @theme_fg_color; } GtkPopover .button.flat:hover, GtkPopover .button.flat:active { border-width: 0; border-radius: 0; border-color: transparent; background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; background-image: none; box-shadow: none; } GtkPopover.osd { box-shadow: 0 2px 7px 3px alpha(black, 0.5); } GtkPopover > .list, GtkPopover > .view, GtkPopover > .toolbar { background-color: transparent; } GtkPopover.osd > .toolbar .button { border-radius: 0; border-width: 0; background-image: none; background-color: transparent; } GtkPopover .separator { border: 0; background-color: transparent; color: alpha(currentColor, 0.5); font-size: 80%; font-weight: bold; } GtkModelButton.button, GtkModelButton.button:active, GtkModelButton.button:insensitive, GtkModelButton.button:active:insensitive { background-color: transparent; background-image: none; border-color: transparent; border-style: none; box-shadow: none; color: @theme_fg_color; } GtkModelButton.button:active:hover, GtkModelButton.button:hover, GtkModelButton.button:selected { border-width: 0; border-color: transparent; background-color: @theme_selected_bg_color; background-image: none; color: @theme_selected_fg_color; } /************ * notebook * ************/ .notebook { background-color: shade (@bg_color, 1.02); background-image: none; border-radius: 0; padding: 0; background-clip: border-box; border-color: shade (@bg_color, 0.82); border-width: 1px; border-style: solid; } .notebook.frame { border-width: 1px; } .notebook.header { border-width: 0; background-color: @theme_bg_color; } .notebook.header.frame { border-color: @theme_bg_color; box-shadow: none; } .notebook tab { background-image: none; background-color: shade(@theme_bg_color, 0.9); border-style: solid; border-color: shade(@bg_color, 0.8); border-width: 1px; border-radius: 0px; box-shadow: none; } .notebook tab:active { border-color: shade (@bg_color, 0.82); border-style: solid; border-width: 1px; background-color: @theme_base_color; background-image: none; color: @fg_color; } .notebook tab GtkLabel { /*padding: 1px;*/ padding: 4px 8px 4px 8px; } .notebook tab { color: shade (@bg_color, 0.48); } .notebook tab.top:active { padding: 3px 7px 1px 7px; } .notebook tab.top { padding: 2px 5px 0 5px; } .notebook tab.right:active { padding: 4px 6px 4px 1px; background-image: none; background-color: @theme_base_color; } .notebook tab.right { padding: 3px 4px 3px 0; border-image-width: 1px 0; } .notebook tab.bottom:active { padding: 1px 7px 4px 7px; background-image: none; background-color: @theme_base_color; } .notebook tab.bottom { padding: 0 5px 3px 5px; border-image-width: 0 1px; } .notebook tab.left:active { padding: 4px 1px 4px 6px; background-image: none; background-color: @theme_base_color; } .notebook tab.left { padding: 3px 0 3px 4px; border-image-width: 1px 0; } .notebook tab .button { padding: 0; } .notebook GtkDrawingArea { background-color: shade (@bg_color, 1.02); } .notebook.frame { border-width: 1px; } /* close button styling */ .notebook tab .button, .notebook tab .button:active, .notebook tab .button:hover { padding: 1px; border-width: 1px; border-radius: 2px; border-style: solid; border-color: transparent; background-image: none; background-color: transparent; color: mix(@theme_text_color, @theme_base_color, 0.5); } .notebook tab .button:hover { color: @theme_text_color; border-color: shade(@theme_base_color, 0.8); } .notebook tab .button:active, .notebook tab .button:active:hover { border-color: shade(@theme_base_color, 0.7); background-color: shade(@theme_base_color, 0.95); } /****************** * pane separator * ******************/ .pane-separator { background-color: @theme_bg_color; color: transparent; } /************************* * progressbar and scale * *************************/ GtkProgressBar { padding: 0; border-width: 1px; border-radius: 0px; } .progressbar, .progressbar row, .progressbar row:hover, .progressbar row:selected, .progressbar row:selected:focus { background-image: none; background-color: @progressbar_color; box-shadow:none; border: 1px solid transparent; border-image: linear-gradient(to top, @progressbar_color) 8 8 8 8 / 8px 8px 8px 8px stretch; } .trough, .trough row, .trough row:hover, .trough row:selected, .trough row:selected:focus { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.7); background-color: shade(@theme_bg_color, 0.85); background-image: linear-gradient(shade(@theme_bg_color, 0.85));} /* level bars as used for password quality or remaining power */ GtkLevelBar { -GtkLevelBar-min-block-width: 34; -GtkLevelBar-min-block-height: 2; } GtkLevelBar.vertical { -GtkLevelBar-min-block-width: 2; -GtkLevelBar-min-block-height: 34; } .level-bar.trough { padding: 1px; border-radius: 0px; } .level-bar.fill-block { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); background-color: @theme_selected_bg_color; } .level-bar.indicator-continuous.fill-block { padding: 1px; border-radius: 0px; } .level-bar.indicator-discrete.fill-block.horizontal { margin: 0 1px; } .level-bar.indicator-discrete.fill-block.vertical { margin: 1px 0; } .level-bar.fill-block.level-high { border-color: shade(@success_color, 0.85); background-image: linear-gradient(to bottom, shade(@success_color, 1.2), @success_color 75%, shade(@success_color, 0.95) ); } .level-bar.fill-block.level-low { border-color: shade(@warning_color, 0.80); background-image: linear-gradient(to bottom, shade(@warning_color, 1.3), @warning_color 75%, shade(@warning_color, 0.9) ); } .level-bar.fill-block.empty-fill-block { border-color: alpha(@theme_fg_color, 0.1); background-color: transparent; background-image: none; } .scale { -GtkRange-slider-width: 19; -GtkRange-trough-border: 0; -GtkScale-slider-length: 11; padding: 0; border-width: 1px; border-radius: 0px; } .scale.slider { border-radius: 0px; background-image: url('assets/slider-horiz.png'); } .scale.slider:hover { background-image: url('assets/slider-horiz-hover.png'); } .scale.slider:insensitive { background-image: url('assets/slider-horiz-insensitive.png'); } /* vertical sliders */ .scale.slider.vertical { border-radius: 0px; background-image: url('assets/slider-vert.png'); } .scale.slider.vertical:hover { background-image: url('assets/slider-vert-hover.png'); } .scale.slider.vertical:insensitive { background-image: url('assets/slider-vert-insensitive.png'); } .scale.slider.fine-tune:active, .scale.slider.fine-tune:active:hover, .scale.slider.fine-tune.horizontal:active, .scale.slider.fine-tune.horizontal:active:hover { background-size: 50%; background-repeat: no-repeat; background-position: center; } .scale.mark { border-color: shade(@theme_bg_color, 0.8); } .scale.trough { margin: 8px 0; border-color: shade(@theme_bg_color, 0.8); border-radius: 0px; background-color: shade(@theme_bg_color, 1.08); background-image: none; } .scale.trough.vertical { margin: 0 8px; } /* .menuitem .scale.highlight.left, .scale.highlight.left { border-color: @theme_selected_bg_color; background-color: @theme_selected_bg_color; background-image: none; } .menuitem .scale.highlight.left:hover { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@theme_selected_bg_color, 0.8); } .scale.highlight.bottom { border-color: @theme_selected_bg_color; background-color: @theme_selected_bg_color; background-image: none; } */ .scale.trough:insensitive, .scale.highlight.left:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; } /************* * scrollbar * *************/ .scrollbar { border-width: 1px; border-style: solid; padding: 0; } .scrollbars-junction, .scrollbar.trough { border-width: 0; border-radius: 0; background-color: @scrollthrough_bg_color; background-image: none; } .scrollbar.button, .scrollbar.button:hover, .scrollbar.button:active, .scrollbar.button:active:hover, .scrollbar.button:insensitive { -GtkRange-arrow-scaling: 0.0; /* dirty hack to use our buttons */ border: none; box-shadow: none; background-position: center center; background-repeat: no-repeat; color: transparent; background-color: transparent; } .scrollbar.slider { border-width: 0; border-color: transparent; border-radius: 0; background-color: @scrollnorm_bg_color; } .scrollbar.slider:hover, .scrollbar.slider.vertical:hover { border-color: transparent; background-color: @scrollhover_bg_color; } .scrollbar.slider:active, .scrollbar.slider.vertical:active { border-color: transparent; background-color: @scrollpress_bg_color; } .scrollbar.slider.fine-tune:prelight:active { border-width: 2px; border-color: transparent; } /* overlay scrollbar */ OsThumb { color: shade(@theme_bg_color, 0.7); } OsThumb:selected, OsScrollbar:selected { background-color: @theme_selected_bg_color; } OsThumb:active, OsScrollbar:active { background-color: @theme_selected_bg_color; } OsThumb:insensitive, OsScrollbar:insensitive { background-color: shade(@theme_bg_color, 0.9); } /************* * separator * *************/ .sidebar.view.separator, .view.separator, .separator { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.9); color: shade(@theme_bg_color, 0.9); } .button .separator, .button.separator { border-color: shade(@theme_bg_color, 0.95); } .button .separator:insensitive, .button.separator:insensitive { border-color: shade(@theme_bg_color, 0.85); } .primary-toolbar GtkSeparatorToolItem, .primary-toolbar .separator, .primary-toolbar .separator:insensitive, .toolbar GtkSeparatorToolItem, .toolbar .separator, .toolbar .separator:insensitive { -GtkWidget-window-dragging: true; border-color: shade(@toolbar_bg_color, 0.95); color: shade(@toolbar_bg_color, 0.95); } .header-bar GtkSeparatorToolItem, .header-bar .separator, .header-bar .separator:insensitive, .titlebar GtkSeparatorToolItem, .titlebar .separator, .titlebar .separator:insensitive { -GtkWidget-window-dragging: true; border-color: shade(@titlebar_bg_color, 0.95); color: shade(@titlebar_bg_color, 0.95); } .primary-toolbar .button .separator, .primary-toolbar .button.separator, .toolbar .button .separator, .toolbar .button.separator { border-color: shade(@toolbar_bg_color, 0.95); } .header-bar .button .separator, .header-bar .button.separator, .titlebar .button .separator, .titlebar .button.separator { border-color: shade(@titlebar_bg_color, 0.95); } .primary-toolbar .button .separator:insensitive, .primary-toolbar .button.separator:insensitive, .toolbar .button .separator:insensitive, .toolbar .button.separator:insensitive { border-color: shade(@toolbar_bg_color, 0.85); } .header-bar .button .separator:insensitive, .header-bar .button.separator:insensitive, .titlebar .button .separator:insensitive, .titlebar .button.separator:insensitive { border-color: shade(@titlebar_bg_color, 0.85); } .menuitem.separator { -GtkMenuItem-horizontal-padding: 0; -GtkWidget-separator-height: 1; border-style: none; color: shade(@menu_bg_color, 0.9); } GtkComboBox .separator { /* always disable separators */ -GtkWidget-wide-separators: true; -GtkWidget-horizontal-separator: 0; -GtkWidget-vertical-separator: 0; border-style: none; } /*********** * sidebar * ***********/ .sidebar, .sidebar.view, .sidebar .view, .sidebar GtkScrolledWindow { background-color: @theme_bg_color; color: mix(@theme_fg_color, @theme_bg_color, 0.1); } .sidebar row:selected, .sidebar row:selected:hover, .sidebar row:selected:focus, .sidebar .view row:selected, .sidebar .view row:selected:hover, .sidebar .view row:selected:focus { border-color: shade(@theme_selected_bg_color, 0.9); background-color: @theme_selected_bg_color; background-image: none; color: @theme_selected_fg_color; } .sidebar row:prelight, .sidebar .view row:prelight { border-color: shade(@theme_selected_bg_color, 1.5); background-color: shade(@theme_selected_bg_color, 0.85); background-image: none; color: @theme_fg_color; } .sidebar row:selected:prelight, .sidebar .view row:selected:prelight { border-color: shade(@theme_selected_bg_color, 1.05); background-color: shade(@theme_selected_bg_color, 1.05); background-image: none; color: @theme_selected_fg_color; } .sidebar .frame { border-width: 0; } /* nemo sidebar padding */ NemoWindow .sidebar .cell { padding: 2px 2px; } /* nautilus sidebar hover in 3.18 */ .sidebar .list-row:hover { background-color: shade(@theme_selected_bg_color, 1.05); } /*addition start*/ .sidebar-item { padding: 10px 4px; } .sidebar-item > Gtklabel { padding-left: 6px; padding-right: 6px; } .sidebar-item.needs-attention > Gtklabel { background-size: 6px 6px, 0 0; } /* ------------- NEW ON GTK 3.18 ---------------*/ GtkSidebarRow.list-row { padding: 0px; } GtkSidebarRow .sidebar-revealer { padding: 1px 14px 1px 12px; } GtkSidebarRow .sidebar-icon:dir(ltr) { padding-right: 8px; } GtkSidebarRow .sidebar-icon:dir(rtl) { padding-left: 8px; } GtkSidebarRow .sidebar-label:dir(ltr) { padding-right: 2px; } GtkSidebarRow .sidebar-label:dir(rtl) { padding-left: 2px; } .sidebar-button.button.image-button { padding: 3px; border-radius: 0; box-shadow: 0px 0px 0px alpha(@dark_shadow,0)} .sidebar-button.button:not(:hover):not(:active) > GtkImage { opacity: 0.5; } .sidebar-item { padding: 10px 4px; } .sidebar-item > GtkLabel { padding-left: 6px; padding-right: 6px; } .sidebar-item.needs-attention > GtkLabel { background-size: 6px 6px, 0 0; } /*addition end*/ /************** * spinbutton * **************/ .spinbutton .button { color: mix(@theme_text_color, @theme_base_color, 0.4); padding: 2px 4px; border-width: 0; border-radius: 0; border-style: none; background-color: transparent; background-image: none; box-shadow: inset 1px 0 shade(@theme_base_color, 0.9); } .spinbutton .button:insensitive { color: mix(@theme_text_color, @theme_base_color, 0.7); box-shadow: inset 1px 0 shade(@theme_bg_color, 0.95); } .spinbutton .button:active, .spinbutton .button:hover { color: @theme_fg_color; } .spinbutton .button:first-child { border-radius: 0; box-shadow: none; } .spinbutton .button:last-child { border-radius: 0; } .spinbutton .button:dir(rtl) { box-shadow: inset -1px 0 shade(@theme_base_color, 0.9); } .spinbutton.vertical .button { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0px; background-color: shade(@theme_bg_color, 1.08); background-image: none; color: @theme_fg_color; box-shadow: none; } .spinbutton.vertical .button:hover { border-color: shade(@theme_bg_color, 0.7); background-color: shade(@theme_bg_color, 1.10); background-image: none; } .spinbutton.vertical .button:active { border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.95); background-image: none; } .spinbutton.vertical .button:active:hover { border-color: shade(@theme_bg_color, 0.7); } .spinbutton.vertical .button:focus, .spinbutton.vertical .button:hover:focus, .spinbutton.vertical .button:active:focus, .spinbutton.vertical .button:active:hover:focus { border-color: shade(@theme_bg_color, 0.7); } .spinbutton.vertical .button:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; } .spinbutton.vertical .button:first-child { border-width: 1px; border-bottom-width: 0; border-radius: 0px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .spinbutton.vertical .button:last-child { border-width: 1px; border-top-width: 0; border-radius: 0px; border-top-left-radius: 0; border-top-right-radius: 0; } .spinbutton.vertical.entry { border-width: 1px; border-style: solid; border-radius: 0; } /*********** * spinner * ***********/ @keyframes spinner { 00.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.70)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)); } 10.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.80)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.90)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.60)), to(transparent)); } 20.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.60)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.90)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.80)), to(transparent)); } 30.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.70)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)); } 40.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.20)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.50)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.80)), to(transparent)); } 50.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(transparent), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.30)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.60)), to(transparent)); } 60.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.20)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.10)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)); } 70.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.10)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.20)), to(transparent)); } 80.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.60)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.30)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(transparent), to(transparent)); } 90.0% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.80)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.50)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.20)), to(transparent)); } 100% { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.70)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)); } } .spinner { background-color: transparent; background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)); background-position: 0% 70%, 33% 70%, 70% 70%; background-size: 30% 30%; background-repeat: no-repeat; } .spinner:active { background-image: -gtk-gradient(radial, center center, 0, center center, 0.5, to(currentColor), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.70)), to(transparent)), -gtk-gradient(radial, center center, 0, center center, 0.5, to(alpha(currentColor, 0.40)), to(transparent)); animation: spinner 1s infinite linear; } .menu.spinner, .menu .spinner, .menu .spinner:hover, .primary-toolbar .spinner { color: @theme_selected_bg_color; border: none; box-shadow: none; } /************* * statusbar * *************/ GtkStatusbar { padding: 4px; color: @theme_fg_color; } GtkStatusbar .frame { border-width: 0; } /********** * switch * ********** GtkSwitch { padding: 0; border-radius: 0px; font: bold condensed; } GtkSwitch.slider { border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 1.08); background-image: none; } GtkSwitch.slider:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; } GtkSwitch.trough { border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.95); background-image: none; color: @theme_fg_color; } GtkSwitch.trough:active { border-color: shade(@theme_selected_bg_color, 0.9); background-color: @theme_selected_bg_color; background-image: none; color: @theme_selected_fg_color; } GtkSwitch.trough:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; color: mix(@theme_fg_color, @theme_bg_color, 0.5); }*/ GtkSwitch { -GtkWidget-focus-line-width: 0; border-radius: 8px; padding: 0; } .menu GtkSwitch.trough, .toolbar.menubar GtkSwitch.trough, .primary-toolbar .toolbar GtkSwitch.trough, .primary-toolbar.toolbar GtkSwitch.trough, GtkSwitch.trough, GtkSwitch.trough:insensitive, GtkSwitch.trough:backdrop { border: none; border-image: none; background: none; color: transparent; box-shadow: none; background-image: url("assets/switch-off.svg"); background-size: 44px 20px; background-position: center center; background-repeat: no-repeat; text-shadow: none; } GtkSwitch.trough { background-image: url("assets/switch-off.svg"); } GtkSwitch.trough:active { background-image: url("assets/switch-on.svg"); } GtkSwitch.trough:insensitive { background-image: url("assets/switch-off-disabled.svg"); } GtkSwitch.trough:active:insensitive { background-image: url("assets/switch-on-disabled.svg"); } .toolbar.menubar GtkSwitch.trough, .primary-toolbar .toolbar GtkSwitch.trough, .primary-toolbar.toolbar GtkSwitch.trough { background-image: url("assets/switch-dark-off.svg"); } .toolbar.menubar GtkSwitch.trough:active, .primary-toolbar .toolbar GtkSwitch.trough:active, .primary-toolbar.toolbar GtkSwitch.trough:active { background-image: url("assets/switch-dark-on.svg"); } .toolbar.menubar GtkSwitch.trough:insensitive, .primary-toolbar .toolbar GtkSwitch.trough:insensitive, .primary-toolbar.toolbar GtkSwitch.trough:insensitive { background-image: url("assets/switch-dark-off-disabled.svg"); } .toolbar.menubar GtkSwitch.trough:active:insensitive, .primary-toolbar .toolbar GtkSwitch.trough:active:insensitive, .primary-toolbar.toolbar GtkSwitch.trough:active:insensitive { background-image: url("assets/switch-dark-on-disabled.svg"); } GtkSwitch.slider { border: none; border-image: none; background: none; color: transparent; box-shadow: none; } /************ * textview * ************/ GtkTextView { background-color: @theme_base_color; color: @theme_text_color; } /***************** * color chooser * *****************/ GtkColorSwatch, GtkColorSwatch:selected { border-width: 1px; border-style: solid; border-color: alpha(black, 0.1); border-radius: 0px; background-color: transparent; background-clip: border-box; } GtkColorSwatch:hover, GtkColorSwatch:selected:hover { border-color: alpha(black, 0.3); } GtkColorSwatch.color-dark:hover { } GtkColorSwatch.color-light:hover { } GtkColorSwatch.color-light:selected:hover, GtkColorSwatch.color-dark:selected:hover { background-image: none; } GtkColorSwatch.left, GtkColorSwatch:first-child { border-top-left-radius: 0px; border-bottom-left-radius: 0px; } GtkColorSwatch.right, GtkColorSwatch:last-child { border-top-right-radius: 0px; border-bottom-right-radius: 0px; } GtkColorSwatch:only-child { border-radius: 0px; } GtkColorSwatch.top { border-top-left-radius: 0px; border-top-right-radius: 0px; } GtkColorSwatch.bottom { border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; } GtkColorChooserWidget #add-color-button { background-clip: padding-box; border-color: alpha(black, 0.1); background-color: shade(@theme_bg_color, 0.95); color: @theme_fg_color; } GtkColorChooserWidget #add-color-button:hover { border-color: alpha(black, 0.3); background-color: shade(@theme_bg_color, 0.90); color: @theme_fg_color; } .color-active-badge, .color-active-badge:selected { border-width: 1px; border-style: solid; border-width: 2px; background-color: transparent; } .color-active-badge.color-light, .color-active-badge.color-light:hover { border-color: alpha(black, 0.3); color: alpha(black, 0.3); } .color-active-badge.color-dark, .color-active-badge.color-dark:hover { border-color: alpha(white, 0.3); color: alpha(white, 0.3); } GtkColorEditor GtkColorSwatch { border-radius: 0px; } GtkColorEditor GtkColorSwatch.color-dark:hover, GtkColorEditor GtkColorSwatch.color-light:hover { background-image: none; border-color: alpha(black, 0.3); } GtkColorButton.button { padding: 2px; } /************** * header-bar * **************/ .header-bar { padding: 4px; border-width: 0 0 1px 0; border-style: solid; border-color: shade(@titlebar_bg_color, 0.8); background-color: @titlebar_bg_color; background-image: none; color: @titlebar_fg_color; } .header-bar .button.text-button { padding: 4px; } .header-bar .button.image-button { padding: 6px; } .header-bar .title { font: bold; padding: 0 12px; } .header-bar .subtitle { font: smaller; padding: 0 12px; } .header-bar GtkComboBox, .header-bar .button { border-color: shade(@titlebar_bg_color, 0.8); background-color: shade(@titlebar_bg_color, 1.08); background-image: none; color: @titlebar_fg_color; } .header-bar .button:hover { border-color: shade(@theme_selected_bg_color, 1.3); background-color: shade(@theme_selected_bg_color, 1.02); background-image: none; } .header-bar .button:active, .header-bar .button:checked { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@theme_selected_bg_color, 0.95); background-image: none; } .header-bar .button:active:hover { border-color: shade(@theme_selected_bg_color, 1.19); } .header-bar .button:focus, .header-bar .button:hover:focus, .header-bar .button:active:focus, .header-bar .button:active:hover:focus { border-color: shade(@theme_selected_bg_color, 1.15); } .header-bar .button:insensitive { border-color: shade(@titlebar_bg_color, 0.85); background-color: shade(@titlebar_bg_color, 0.9); background-image: none; } .header-bar .button:active *:insensitive { border-color: shade(@titlebar_bg_color, 0.75); background-color: shade(@titlebar_bg_color, 0.80); background-image: none; } .header-bar .entry { border-width: 1px; border-color: shade(@bg_color, 0.6); } .header-bar .entry:active, .header-bar .entry:focus { border-width: 1px; border-color: shade(@selected_bg_color, 0.6); } /*********** * toolbar * ***********/ .toolbar { padding: 4px; border-style: none; background-color: @toolbar_bg_color; background-image: none; color: @toolbar_fg_color; } .toolbar .button { padding: 2px; } .toolbar .button.text-button { padding: 2px 4px; } .toolbar .button.image-button { padding: 4px 3px 3px 4px; } .toolbar:insensitive { background-color: shade(@toolbar_bg_color, 0.9); color: mix(@toolbar_fg_color, @toolbar_bg_color, 0.5); } /* menubar toolbars */ .toolbar.menubar { -GtkToolbar-button-relief: normal; } /******************* * primary-toolbar * *******************/ .primary-toolbar, .primary-toolbar .toolbar, .primary-toolbar.toolbar { -GtkWidget-window-dragging: true; padding: 4px; border-width: 0; border-style: solid; border-color: shade(@toolbar_bg_color, 0.8); background-color: @toolbar_bg_color; background-image: none; color: @toolbar_fg_color; } .primary-toolbar GtkComboBox, .primary-toolbar .button { padding: 2px; border-width: 0; border-color: transparent; border-radius: 0px; background-color: transparent; background-image: none; color: @toolbar_fg_color; } .primary-toolbar .raised .button, .primary-toolbar .raised.button, .toolbar GtkComboBox, .toolbar .button { padding: 10px; border-color: transparent; background-color: shade(@toolbar_bg_color, 1.08); background-image: none; color: @toolbar_fg_color; } .primary-toolbar .button:hover, .toolbar .button:hover { border-color: transparent; background-color: shade(@toolbar_bg_color, 1.10); background-image: none; } .primary-toolbar .button:checked, .primary-toolbar .button:active, .toolbar .button:active { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@selected_bg_color, 0.9); background-image: none; } .primary-toolbar .button:active:hover, .toolbar .button:active:hover { border-color: transparent; } .primary-toolbar .button:focus, .primary-toolbar .button:hover:focus, .primary-toolbar .button:active:focus, .primary-toolbar .button:active:hover:focus, .toolbar .button:focus, .toolbar .button:hover:focus, .toolbar .button:active:focus, .toolbar .button:active:hover:focus { border-color: transparent; } .primary-toolbar .button:insensitive, .toolbar .button:insensitive { border-color: transparent; background-color: @toolbar_bg_color; background-image: none; } .primary-toolbar .button:active *:insensitive, .toolbar .button:active *:insensitive { border-color: transparent; background-color: shade(@toolbar_bg_color, 0.80); background-image: none; } .primary-toolbar .entry, .toolbar .entry { border-width: 1px; border-color: shade(@bg_color, 0.6); } .primary-toolbar .entry:active, .primary-toolbar .entry:focus, .toolbar .entry:active, .toolbar .entry:focus { border-width: 1px; border-color: shade(@selected_bg_color, 0.6); } /* inline-toolbar */ .inline-toolbar.toolbar { -GtkToolbar-button-relief: normal; padding: 1px; border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0; background-color: @theme_bg_color; background-image: none; } .inline-toolbar.toolbar:last-child { border-width: 1px; border-color: shade(@theme_bg_color, 0.8); border-radius: 0; } .inline-toolbar.toolbar .button { padding: 1px; border-width: 1px; border-style: solid; border-color: shade(@theme_bg_color, 0.8); border-radius: 0; background-color: shade(@theme_bg_color, 1.08); background-image: none; color: @theme_fg_color; } .inline-toolbar.toolbar .button:hover { border-color: shade(@theme_bg_color, 0.7); background-color: shade(@theme_bg_color, 1.10); background-image: none; } .inline-toolbar.toolbar .button:active { border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.95); background-image: none; } .inline-toolbar.toolbar .button:active:hover { border-color: shade(@theme_bg_color, 0.7); } .inline-toolbar.toolbar .button:focus, .inline-toolbar.toolbar .button:hover:focus, .inline-toolbar.toolbar .button:active:focus, .inline-toolbar.toolbar .button:active:hover:focus { border-color: shade(@theme_bg_color, 0.7); } .inline-toolbar.toolbar .button:insensitive, .inline-toolbar.toolbar GtkToolButton .button:insensitive { border-color: shade(@theme_bg_color, 0.85); background-color: shade(@theme_bg_color, 0.9); background-image: none; } .inline-toolbar.toolbar .button:active *:insensitive .inline-toolbar.toolbar GtkToolButton .button:active *:insensitive { border-color: shade(@theme_bg_color, 0.75); background-color: shade(@theme_bg_color, 0.80); background-image: none; } /****************** * linked buttons * *****************/ /* set up shadows for visual separation */ .linked .button, .inline-toolbar.toolbar .button, .inline-toolbar.toolbar GtkToolButton .button, .inline-toolbar.toolbar GtkToolButton > .button { box-shadow: inset -1px 0 shade(@theme_bg_color, 0.9); } .linked .button:active, .inline-toolbar.toolbar .button:active, .inline-toolbar.toolbar GtkToolButton .button:active, .inline-toolbar.toolbar GtkToolButton > .button:active { box-shadow: inset -1px 0 shade(@theme_bg_color, 0.9), inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset 0 -1px alpha(@dark_shadow, 0.05); } .linked .button:insensitive, .inline-toolbar.toolbar .button:insensitive, .inline-toolbar.toolbar GtkToolButton .button:insensitive, .inline-toolbar.toolbar GtkToolButton > .button:insensitive { box-shadow: inset -1px 0 shade(@theme_bg_color, 0.85); } /* remove box shadow from last-child and only-child */ .linked .button:last-child, .linked .button:only-child, .linked .button:insensitive:last-child, .linked .button:insensitive:only-child, .linked .button:active *:insensitive:last-child, .linked .button:active *:insensitive:only-child, .inline-toolbar.toolbar .button:last-child, .inline-toolbar.toolbar .button:only-child, .inline-toolbar.toolbar .button:insensitive:last-child, .inline-toolbar.toolbar .button:insensitive:only-child, .inline-toolbar.toolbar .button:active *:insensitive:last-child, .inline-toolbar.toolbar .button:active *:insensitive:only-child, .inline-toolbar.toolbar GtkToolButton:last-child > .button, .inline-toolbar.toolbar GtkToolButton:only-child > .button, .inline-toolbar.toolbar GtkToolButton:last-child > .button:insensitive, .inline-toolbar.toolbar GtkToolButton:only-child > .button:insensitive, .inline-toolbar.toolbar GtkToolButton:last-child > .button:active *:insensitive, .inline-toolbar.toolbar GtkToolButton:only-child > .button:active *:insensitive { box-shadow: none; } /* add back the inset shadow effect */ .linked .button:active:last-child, .linked .button:active:only-child, .inline-toolbar.toolbar .button:active:last-child, .inline-toolbar.toolbar .button:active:only-child, .inline-toolbar.toolbar GtkToolButton:last-child > .button:active, .inline-toolbar.toolbar GtkToolButton:only-child > .button:active { box-shadow: inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset -1px 0 alpha(@dark_shadow, 0.07); } /* middle button */ .linked .entry, .linked .button, .linked .button:active, .linked .button:active:hover, .linked .button:insensitive, .inline-toolbar.toolbar .button, .inline-toolbar.toolbar .button:active, .inline-toolbar.toolbar .button:insensitive, .inline-toolbar.toolbar GtkToolButton .button, .inline-toolbar.toolbar GtkToolButton .button:active, .inline-toolbar.toolbar GtkToolButton .button:insensitive { border-width: 1px; border-radius: 0; border-right-width: 0; border-left-width: 0; } /*leftmost button */ .linked .entry:first-child, .linked .button:first-child, .linked .button:active:first-child, .linked .button:active:hover:first-child, .linked .button:insensitive:first-child, .inline-toolbar.toolbar .button:first-child, .inline-toolbar.toolbar .button:active:first-child, .inline-toolbar.toolbar .button:insensitive:first-child, .inline-toolbar.toolbar GtkToolButton:first-child .button, .inline-toolbar.toolbar GtkToolButton:first-child .button:active, .inline-toolbar.toolbar GtkToolButton:first-child .button:insensitive { border-width: 1px; border-radius: 0px; border-right-width: 0; border-bottom-right-radius: 0; border-top-right-radius: 0; } /* rightmost button */ .linked .entry:last-child, .linked .button:last-child, .linked .button:active:last-child, .linked .button:active:hover:last-child, .linked .button:insensitive:last-child, .inline-toolbar.toolbar .button:last-child, .inline-toolbar.toolbar .button:active:last-child, .inline-toolbar.toolbar .button:insensitive:last-child, .inline-toolbar.toolbar GtkToolButton:last-child .button, .inline-toolbar.toolbar GtkToolButton:last-child .button:active, .inline-toolbar.toolbar GtkToolButton:last-child .button:insensitive { border-width: 1px; border-radius: 0px; border-left-width: 0; border-bottom-left-radius: 0; border-top-left-radius: 0; } /* linked single button */ .linked .entry:only-child, .linked .button:only-child, .linked .button:active:only-child, .linked .button:active:hover:only-child, .linked .button:insensitive:only-child, .inline-toolbar.toolbar .button:only-child, .inline-toolbar.toolbar .button:active:only-child, .inline-toolbar.toolbar .button:insensitive:only-child, .inline-toolbar.toolbar GtkToolButton:only-child .button, .inline-toolbar.toolbar GtkToolButton:only-child .button:active, .inline-toolbar.toolbar GtkToolButton:only-child .button:insensitive { border-width: 1px; border-radius: 0px; } /* linked button shadows (vertical) */ .linked.vertical .button, .inline-toolbar.toolbar.vertical .button, .inline-toolbar.toolbar.vertical GtkToolButton > .button { box-shadow: inset 0 -1px shade(@theme_bg_color, 0.9); } .linked.vertical .button:active, .inline-toolbar.toolbar.vertical .button:active, .inline-toolbar.toolbar.vertical GtkToolButton > .button:active { box-shadow: inset 0 -1px shade(@theme_bg_color, 0.9), inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset -1px 0 alpha(@dark_shadow, 0.07); } .linked.vertical .button:insensitive, .inline-toolbar.toolbar.vertical .button:insensitive, .inline-toolbar.toolbar.vertical GtkToolButton > .button:insensitive { box-shadow: inset 0 -1px shade(@theme_bg_color, 0.85); } /* remove box shadow from last-child and only-child */ .linked.vertical .button:last-child, .linked.vertical .button:only-child, .linked.vertical .button:insensitive:last-child, .linked.vertical .button:insensitive:only-child, .linked.vertical .button:active *:insensitive:last-child, .linked.vertical .button:active *:insensitive:only-child, .inline-toolbar.toolbar.vertical .button:last-child, .inline-toolbar.toolbar.vertical .button:only-child, .inline-toolbar.toolbar.vertical .button:insensitive:last-child, .inline-toolbar.toolbar.vertical .button:insensitive:only-child, .inline-toolbar.toolbar.vertical .button:active *:insensitive:last-child, .inline-toolbar.toolbar.vertical .button:active *:insensitive:only-child, .inline-toolbar.toolbar.vertical GtkToolButton:last-child > .button, .inline-toolbar.toolbar.vertical GtkToolButton:only-child > .button, .inline-toolbar.toolbar.vertical GtkToolButton:last-child > .button:insensitive, .inline-toolbar.toolbar.vertical GtkToolButton:only-child > .button:insensitive, .inline-toolbar.toolbar.vertical GtkToolButton:last-child > .button:active *:insensitive, .inline-toolbar.toolbar.vertical GtkToolButton:only-child > .button:active *:insensitive { box-shadow: none; } /* add back the inset shadow effect */ .linked.vertical .button:active:last-child, .linked.vertical .button:active:only-child, .inline-toolbar.toolbar.vertical .button:active:last-child, .inline-toolbar.toolbar.vertical .button:active:only-child, .inline-toolbar.toolbar.vertical GtkToolButton:last-child > .button:active, .inline-toolbar.toolbar.vertical GtkToolButton:only-child > .button:active { box-shadow: inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset -1px 0 alpha(@dark_shadow, 0.07); } /* middle button (vertical) */ .linked.vertical .entry, .linked.vertical .button, .linked.vertical .button:active, .linked.vertical .button:active:hover, .linked.vertical .button:insensitive { border-width: 1px; border-radius: 0; border-top-width: 0; border-bottom-width: 0; } /* top button (vertical) */ .linked.vertical .entry:first-child, .linked.vertical .button:first-child, .linked.vertical .button:active:first-child, .linked.vertical .button:active:hover:first-child, .linked.vertical .button:insensitive:first-child { border-width: 1px; border-radius: 0px; border-bottom-width: 0; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } /* bottom button (vertical) */ .linked.vertical .entry:last-child, .linked.vertical .button:last-child, .linked.vertical .button:active:last-child, .linked.vertical .button:active:hover:last-child, .linked.vertical .button:insensitive:last-child { border-width: 1px; border-radius: 0px; border-top-width: 0; border-top-left-radius: 0; border-top-right-radius: 0; } /* linked single button (vertical) */ .linked.vertical .entry:only-child, .linked.vertical .button:only-child, .linked.vertical .button:active:only-child, .linked.vertical .button:active:hover:only-child, .linked.vertical .button:insensitive:only-child { border-width: 1px; border-radius: 0px; } /* linked toolbar buttons */ .primary-toolbar .button.raised.linked, .primary-toolbar .raised.linked .button, .toolbar .button.raised.linked, .toolbar .raised.linked .button, .toolbar .linked .button { box-shadow: none; } .primary-toolbar .button.raised.linked:active, .primary-toolbar .raised.linked .button:active, .toolbar .button.raised.linked:active, .toolbar .raised.linked .button:active, .toolbar .linked .button:active { box-shadow: none; } .primary-toolbar .button.raised.linked:insensitive, .primary-toolbar .raised.linked .button:insensitive, .toolbar .button.raised.linked:insensitive, .toolbar .raised.linked .button:insensitive, .toolbar .linked .button:insensitive { box-shadow: none; } /* remove box shadow from last-child and only-child */ .primary-toolbar .button.raised.linked:last-child, .primary-toolbar .button.raised.linked:only-child, .primary-toolbar .button:insensitive.raised.linked:last-child, .primary-toolbar .button:insensitive.raised.linked:only-child, .primary-toolbar .button:active *:insensitive.raised.linked:last-child, .primary-toolbar .button:active *:insensitive.raised.linked:only-child, .primary-toolbar .raised.linked .button:last-child, .primary-toolbar .raised.linked .button:only-child, .primary-toolbar .raised.linked .button:insensitive:last-child, .primary-toolbar .raised.linked .button:insensitive:only-child, .primary-toolbar .raised.linked .button:active *:insensitive:last-child, .primary-toolbar .raised.linked .button:active *:insensitive:only-child, .toolbar .button.raised.linked:last-child, .toolbar .button.raised.linked:only-child, .toolbar .button:insensitive.raised.linked:last-child, .toolbar .button:insensitive.raised.linked:only-child, .toolbar .button:active *:insensitive.raised.linked:last-child, .toolbar .button:active *:insensitive.raised.linked:only-child, .toolbar .raised.linked .button:last-child, .toolbar .raised.linked .button:only-child, .toolbar .raised.linked .button:insensitive:last-child, .toolbar .raised.linked .button:insensitive:only-child, .toolbar .raised.linked .button:active *:insensitive:last-child, .toolbar .raised.linked .button:active *:insensitive:only-child, .toolbar .linked .button:last-child, .toolbar .linked .button:only-child, .toolbar .linked .button:insensitive:last-child, .toolbar .linked .button:insensitive:only-child, .toolbar .linked .button:active *:insensitive:last-child, .toolbar .linked .button:active *:insensitive:only-child { box-shadow: none; } /* middle button */ .primary-toolbar .button.raised.linked, .primary-toolbar .button.raised.linked:active, .primary-toolbar .button.raised.linked:insensitive, .primary-toolbar .raised.linked .button, .primary-toolbar .raised.linked .button:active, .primary-toolbar .raised.linked .button:insensitive, .toolbar .button.raised.linked, .toolbar .button.raised.linked:active, .toolbar .button.raised.linked:insensitive, .toolbar .raised.linked .button, .toolbar .raised.linked .button:active, .toolbar .raised.linked .button:insensitive, .toolbar .linked .button, .toolbar .linked .button:active, .toolbar .linked .button:insensitive { border-width: 1px; border-radius: 0; border-right-width: 0; border-left-width: 0; } /* leftmost button */ .primary-toolbar .button.raised.linked:first-child, .primary-toolbar .button.raised.linked:active:first-child, .primary-toolbar .button.raised.linked:insensitive:first-child, .primary-toolbar .raised.linked .button:first-child, .primary-toolbar .raised.linked .button:active:first-child, .primary-toolbar .raised.linked .button:insensitive:first-child, .toolbar .button.raised.linked:first-child, .toolbar .button.raised.linked:active:first-child, .toolbar .button.raised.linked:insensitive:first-child, .toolbar .raised.linked .button:first-child, .toolbar .raised.linked .button:active:first-child, .toolbar .raised.linked .button:insensitive:first-child, .toolbar .linked .button:first-child, .toolbar .linked .button:active:first-child { border-width: 1px; border-radius: 0px; border-right-width: 0; border-bottom-right-radius: 0; border-top-right-radius: 0; } /* rightmost button */ .primary-toolbar .button.raised.linked:last-child, .primary-toolbar .button.raised.linked:active:last-child, .primary-toolbar .button.raised.linked:insensitive:last-child, .primary-toolbar .raised.linked .button:last-child, .primary-toolbar .raised.linked .button:active:last-child, .primary-toolbar .raised.linked .button:insensitive:last-child, .toolbar .button.raised.linked:last-child, .toolbar .button.raised.linked:active:last-child, .toolbar .button.raised.linked:insensitive:last-child, .toolbar .raised.linked .button:last-child, .toolbar .raised.linked .button:active:last-child, .toolbar .raised.linked .button:insensitive:last-child, .toolbar .linked .button:last-child, .toolbar .linked .button:active:last-child, .toolbar .linked .button:insensitive:last-child { border-width: 1px; border-radius: 0px; border-left-width: 0; border-bottom-left-radius: 0; border-top-left-radius: 0; } /* linked single button */ .primary-toolbar .button.raised.linked:only-child, .primary-toolbar .button.raised.linked:active:only-child, .primary-toolbar .button.raised.linked:insensitive:only-child, .primary-toolbar .raised.linked .button:only-child, .primary-toolbar .raised.linked .button:active:only-child, .primary-toolbar .raised.linked .button:insensitive:only-child, .toolbar .button.raised.linked:only-child, .toolbar .button.raised.linked:active:only-child, .toolbar .button.raised.linked:insensitive:only-child, .toolbar .raised.linked .button:only-child, .toolbar .raised.linked .button:active:only-child, .toolbar .raised.linked .button:insensitive:only-child, .toolbar .linked .button:only-child, .toolbar .linked .button:active:only-child, .toolbar .linked .button:insensitive:only-child { border-width: 1px; border-radius: 0px; } /* linked titlebar buttons */ .header-bar .button.raised.linked, .header-bar .raised.linked .button, .header-bar .linked .button { box-shadow: inset -1px 0 shade(@titlebar_bg_color, 0.9); } .header-bar .button.raised.linked:active, .header-bar .raised.linked .button:active, .header-bar .linked .button:active { box-shadow: inset -1px 0 shade(@titlebar_bg_color, 0.9), inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset 0 -1px alpha(@dark_shadow, 0.05); } .header-bar .button.raised.linked:insensitive, .header-bar .raised.linked .button:insensitive, .header-bar .linked .button:insensitive { box-shadow: inset -1px 0 shade(@titlebar_bg_color, 0.85); } /* remove box shadow from last-child and only-child */ .header-bar .button.raised.linked:last-child, .header-bar .button.raised.linked:only-child, .header-bar .button:insensitive.raised.linked:last-child, .header-bar .button:insensitive.raised.linked:only-child, .header-bar .button:active *:insensitive.raised.linked:last-child, .header-bar .button:active *:insensitive.raised.linked:only-child, .header-bar .raised.linked .button:last-child, .header-bar .raised.linked .button:only-child, .header-bar .raised.linked .button:insensitive:last-child, .header-bar .raised.linked .button:insensitive:only-child, .header-bar .raised.linked .button:active *:insensitive:last-child, .header-bar .raised.linked .button:active *:insensitive:only-child, .header-bar .linked .button:last-child, .header-bar .linked .button:only-child, .header-bar .linked .button:insensitive:last-child, .header-bar .linked .button:insensitive:only-child, .header-bar .linked .button:active *:insensitive:last-child, .header-bar .linked .button:active *:insensitive:only-child { box-shadow: none; } /* add back the inset shadow effect */ .header-bar .button:active.raised.linked:last-child, .header-bar .button:active.raised.linked:only-child, .header-bar .raised.linked .button:active:last-child, .header-bar .raised.linked .button:active:only-child, .header-bar .linked .button:active:last-child, .header-bar .linked .button:active:only-child { box-shadow: inset 1px 0 alpha(@dark_shadow, 0.07), inset 0 1px alpha(@dark_shadow, 0.08), inset -1px 0 alpha(@dark_shadow, 0.07); } /* middle button */ .header-bar .button.raised.linked, .header-bar .button.raised.linked:active, .header-bar .button.raised.linked:insensitive, .header-bar .raised.linked .button, .header-bar .raised.linked .button:active, .header-bar .raised.linked .button:insensitive, .header-bar .linked .button, .header-bar .linked .button:active, .header-bar .linked .button:insensitive { border-width: 1px; border-radius: 0; border-right-width: 0; border-left-width: 0; } /* leftmost button */ .header-bar .button.raised.linked:first-child, .header-bar .button.raised.linked:active:first-child, .header-bar .button.raised.linked:insensitive:first-child, .header-bar .raised.linked .button:first-child, .header-bar .raised.linked .button:active:first-child, .header-bar .raised.linked .button:insensitive:first-child, .header-bar .linked .button:first-child, .header-bar .linked .button:active:first-child, .header-bar .linked .button:insensitive:first-child { border-width: 1px; border-radius: 0px; border-right-width: 0; border-bottom-right-radius: 0; border-top-right-radius: 0; } /* rightmost button */ .header-bar .button.raised.linked:last-child, .header-bar .button.raised.linked:active:last-child, .header-bar .button.raised.linked:insensitive:last-child, .header-bar .raised.linked .button:last-child, .header-bar .raised.linked .button:active:last-child, .header-bar .raised.linked .button:insensitive:last-child, .header-bar .linked .button:last-child, .header-bar .linked .button:active:last-child, .header-bar .linked .button:insensitive:last-child { border-width: 1px; border-radius: 0px; border-left-width: 0; border-bottom-left-radius: 0; border-top-left-radius: 0; } /* linked single button */ .header-bar .button.raised.linked:only-child, .header-bar .button.raised.linked:active:only-child, .header-bar .button.raised.linked:insensitive:only-child, .header-bar .raised.linked .button:only-child, .header-bar .raised.linked .button:active:only-child, .header-bar .raised.linked .button:insensitive:only-child, .header-bar .linked .button:only-child, .header-bar .linked .button:active:only-child, .header-bar .linked .button:insensitive:only-child { border-width: 1px; border-radius: 0px; } /*********** * tooltip * ***********/ .tooltip { border-width: 1px; border-style: solid; border-color: shade(@theme_tooltip_bg_color, 0.8); border-radius: 0px; background-color: @theme_tooltip_bg_color; background-image: none; color: @theme_tooltip_fg_color; } .tooltip * { background-color: transparent; } /************ * treeview * ************/ GtkTreeView { -GtkTreeView-vertical-separator: 0; -GtkWidget-focus-line-width: 1; -GtkWidget-focus-padding: 1; } GtkTreeView.dnd { border-width: 1px; border-style: solid; border-color: @theme_selected_bg_color; border-radius: 0; } GtkTreeView .entry { padding: 0 6px; border-radius: 0; background-color: @theme_base_color; background-image: none; } /************ * viewport * ************/ GtkViewport.frame { border-width: 0; } .view { background-color: @theme_base_color; color: @theme_text_color; } .view:insensitive, .view:insensitive:insensitive { background-color: shade(@theme_base_color, 0.9); color: mix(@theme_fg_color, @theme_bg_color, 0.5); } .view:selected, .view:selected:focus { background-color: @theme_selected_bg_color; color: @theme_selected_fg_color; } /************** * action-bar * **************/ .action-bar { padding: 4px; border-width: 1px 0 0 0; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: @theme_bg_color; background-image: none; color: @theme_fg_color; } .action-bar .button.text-button { padding: 4px; } .action-bar .button.image-button { padding: 6px; } .action-bar .title { font: bold; padding: 0 12px; } .action-bar .subtitle { font: smaller; padding: 0 12px; } /*************** * search bars * ***************/ .search-bar { border-width: 0; border-style: solid; border-color: shade(@theme_bg_color, 0.8); background-color: shade(@theme_bg_color, 0.98); } .search-bar .button.close-button { padding: 4px; } /******************** * various choosers * ********************/ GtkFontButton .separator, GtkFileChooserButton .separator { /* always disable separators */ -GtkWidget-wide-separators: true; -GtkWidget-horizontal-separator: 0; -GtkWidget-vertical-separator: 0; } GtkFontButton GtkLabel:last-child { color: alpha(currentColor, 0.7); } GtkFileChooserButton GtkImage:last-child { color: alpha(currentColor, 0.7); } /********************* * app notifications * *********************/ .app-notification { border-style: solid; border-color: shade(@theme_base_color, 0.8); border-width: 0 1px 1px 1px; border-radius: 0; padding: 8px; background-color: @theme_base_color; background-image: none; color: @theme_text_color; } /******* * osd * *******/ .background.osd { color: @osd_fg; background-color: @osd_bg; } GtkOverlay.osd { background-color: transparent; } .osd.frame { background-clip: border-box; background-origin: border-box; } .osd.button, .osd .button { padding: 4px; border-width: 1px; border-style: solid; border-color: shade(@osd_bg, 0.8); border-radius: 0px; background-color: shade(@osd_bg, 1.08); background-image: none; color: @osd_fg; } .osd.button:prelight, .osd.button:hover, .osd .button:hover { border-color: shade(@osd_bg, 0.7); background-color: shade(@osd_bg, 1.10); background-image: none; } .osd.button:active, .osd .button:active, .osd GtkMenuButton.button:active { border-color: shade(@osd_bg, 0.8); background-color: shade(@osd_bg, 0.95); background-image: none; } .osd.button:active:hover, .osd .button:active:hover, .osd GtkMenuButton.button:active:hover { border-color: shade(@osd_bg, 0.7); } .osd.button:insensitive, .osd .button:insensitive { border-color: shade(@osd_bg, 0.85); background-color: shade(@osd_bg, 0.9); background-image: none; } .osd.button:active *:insensitive, .osd .button:active *:insensitive { background-color: shade(@osd_bg, 0.80); background-image: none; } .osd.toolbar { -GtkToolbar-button-relief: normal; padding: 4px; border-width: 1px; border-style: solid; border-radius: 0px; border-color: shade(@osd_bg, 0.8); background-color: @osd_bg; background-image: none; color: @osd_fg; } .osd.toolbar .button { padding: 4px; border-width: 1px; border-style: solid; border-color: shade(@osd_bg, 0.8); border-radius: 0px; background-color: shade(@osd_bg, 1.08); background-image: none; color: @osd_fg; } .osd.toolbar .button:hover { border-color: shade(@osd_bg, 0.7); background-color: shade(@osd_bg, 1.10); background-image: none; } .osd.toolbar .button:active { border-color: shade(@osd_bg, 0.8); background-color: shade(@osd_bg, 0.95); background-image: none; } .osd.toolbar .button:active:hover { border-color: shade(@osd_bg, 0.7); } .osd.toolbar .button:focus, .osd.toolbar .button:hover:focus, .osd.toolbar .button:active:focus, .osd.toolbar .button:active:hover:focus { border-color: shade(@osd_bg, 0.7); } .osd.toolbar .button:insensitive { border-color: shade(@osd_bg, 0.85); background-color: shade(@osd_bg, 0.9); background-image: none; } .osd.toolbar .button:active *:insensitive { border-color: shade(@osd_bg, 0.75); background-color: shade(@osd_bg, 0.80); background-image: none; } .osd.toolbar .button:first-child { border-radius: 0px; border-width: 1px 0 1px 1px; box-shadow: inset -1px 0 shade(@osd_bg, 0.9); } .osd.toolbar .button:last-child { box-shadow: none; border-radius: 0; border-width: 1px 1px 1px 0; } .osd.toolbar .button:only-child, .osd.toolbar GtkToolButton .button, .osd.toolbar GtkToolButton:only-child .button, .osd.toolbar GtkToolButton:last-child .button, .osd.toolbar GtkToolButton:first-child .button { border-width: 1px; border-radius: 0px; border-style: solid; } .osd.toolbar .separator { color: shade(@osd_bg, 0.9); } /* used by gnome-settings-daemon's media-keys OSD */ .osd.trough { background-color: shade(@osd_bg, 0.8); } .osd.progressbar { background-color: @osd_fg; } .osd .scale.slider { background-color: shade(@osd_bg, 1.08); background-image: none; /* we will draw the border using box shadow for now */ box-shadow: inset 1px 0 shade(@osd_bg, 0.8), inset 0 1px shade(@osd_bg, 0.8), inset -1px 0 shade(@osd_bg, 0.8), inset 0 -1px shade(@osd_bg, 0.8); } .osd .scale.slider:hover { box-shadow: inset 1px 0 shade(@osd_bg, 0.7), inset 0 1px shade(@osd_bg, 0.7), inset -1px 0 shade(@osd_bg, 0.7), inset 0 -1px shade(@osd_bg, 0.7); } .osd .scale.slider:insensitive { background-color: shade(@osd_bg, 0.9); background-image: none; box-shadow: inset 1px 0 shade(@osd_bg, 0.85), inset 0 1px shade(@osd_bg, 0.85), inset -1px 0 shade(@osd_bg, 0.85), inset 0 -1px shade(@osd_bg, 0.85); } .osd .scale.trough { border-color: shade(@osd_bg, 0.8); background-color: shade(@osd_bg, 1.08); background-image: none; } .osd .scale.trough.highlight { border-color: @theme_selected_bg_color; background-color: @theme_selected_bg_color; background-image: none; } .osd .scale.trough:insensitive, .osd .scale.trough.highlight:insensitive { border-color: shade(@osd_bg, 0.85); background-color: shade(@osd_bg, 0.9); background-image: none; } .osd GtkProgressBar, GtkProgressBar.osd { -GtkProgressBar-xspacing: 0; -GtkProgressBar-yspacing: 2px; -GtkProgressBar-min-horizontal-bar-height: 2px; padding: 0; } .osd GtkProgressBar.trough, GtkProgressBar.osd.trough { padding: 0; border-style: none; border-radius: 0; background-image: none; background-color: transparent; } .osd GtkProgressBar.progressbar, GtkProgressBar.osd.progressbar { border-style: none; border-radius: 0; background-color: @progressbar_color; background-image: none; } .osd .view, .osd.view { background-color: @osd_base; } .osd .scrollbar.trough { background-color: @osd_bg; } .osd .scrollbar.slider { border-width: 1px; border-color: mix(shade(@osd_base, 0.87), @osd_fg, 0.21); border-radius: 0; background-color: mix(@osd_base, @osd_fg, 0.21); } .osd .scrollbar.slider:hover { border-color: mix(shade(@osd_base, 0.87), @osd_fg, 0.31); background-color: mix(@osd_base, @osd_fg, 0.31); } .osd .scrollbar.slider:active { border-color: shade(@theme_bg_color, 0.9); background-color: @theme_bg_color; } .osd GtkIconView.cell:selected, .osd GtkIconView.cell:selected:focus { background-color: transparent; border-style: solid; border-radius: 0px; border-width: 3px; border-color: @osd_fg; outline-color: transparent; } /* used by Documents */ .osd .page-thumbnail { border-style: solid; border-width: 1px; border-color: shade(@osd_bg, 0.9); /* when there's no pixbuf yet */ background-color: @osd_bg; } /****************************** * destructive action buttons * ******************************/ .destructive-action.button { border-width: 1px; border-style: solid; border-color: shade(@error_color, 0.8); border-radius: 0px; background-color: @error_color; background-image: none; color: mix(@theme_selected_fg_color, @error_color, 0.1); } .destructive-action.button:hover { border-color: shade(@error_color, 0.7); background-color: shade(@error_color, 1.12); background-image: none; } .destructive-action.button:active { border-color: shade(@error_color, 0.8); background-color: shade(@error_color, 0.87); background-image: none; } .destructive-action.button:hover:active { border-color: shade(@error_color, 0.7); } /****************************** * suggested action buttons * ******************************/ .suggested-action.button { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); border-radius: 0px; background-color: shade(@theme_selected_bg_color, 1.18); background-image: none; color: mix(@theme_selected_fg_color, @theme_selected_bg_color, 0.1); } .suggested-action.button:hover { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@theme_selected_bg_color, 1.20); background-image: none; } .suggested-action.button:active { border-color: shade(@theme_selected_bg_color, 0.9); background-color: shade(@theme_selected_bg_color, 1.05); background-image: none; } .suggested-action.button:hover:active { border-color: shade(@theme_selected_bg_color, 0.8); } /****************** * selection mode * ******************/ .selection-mode.header-bar, .selection-mode.toolbar { border-style: solid; border-color: @theme_selected_bg_color; background-color: shade(@theme_selected_bg_color, 1.6); background-image: none; color: @theme_selected_bg_color; } .selection-mode.header-bar { border-top-color: shade(@theme_selected_bg_color, 1.6); border-bottom-color: @theme_selected_bg_color; } .selection-mode.toolbar { padding: 4px; } /* regular button */ .selection-mode.header-bar .button, .selection-mode.toolbar .button, .selection-mode.toolbar GtkToolButton .button { border-width: 1px; border-style: solid; border-color: @theme_selected_bg_color; border-radius: 0px; background-color: shade(@theme_selected_bg_color, 1.68); background-image: none; color: shade(@theme_selected_bg_color, 0.8); } .selection-mode.header-bar .button:hover, .selection-mode.toolbar .button:hover, .selection-mode.toolbar GtkToolButton .button:hover { border-color: shade(@theme_selected_bg_color, 0.9); background-color: shade(@theme_selected_bg_color, 1.70); background-image: none; } .selection-mode.header-bar .button:active, .selection-mode.toolbar .button:active, .selection-mode.toolbar GtkToolButton .button:active { border-color: shade(@theme_selected_bg_color, 0.9); background-color: shade(@theme_selected_bg_color, 1.55); background-image: none; } .selection-mode.header-bar .button:hover:active, .selection-mode.toolbar .button:hover:active, .selection-mode.toolbar GtkToolButton .button:hover:active { border-color: shade(@theme_selected_bg_color, 0.8); } /* suggested button */ .selection-mode.header-bar .suggested-action.button, .selection-mode.toolbar .suggested-action.button, .selection-mode.toolbar GtkToolButton.suggested-action .button { border-width: 1px; border-style: solid; border-color: shade(@theme_selected_bg_color, 0.9); border-radius: 0px; background-color: shade(@theme_selected_bg_color, 1.18); background-image: none; color: mix(@theme_selected_fg_color, @theme_selected_bg_color, 0.1); } .selection-mode.header-bar .suggested-action.button:hover, .selection-mode.toolbar .suggested-action.button:hover, .selection-mode.toolbar GtkToolButton.suggested-action .button:hover { border-color: shade(@theme_selected_bg_color, 0.8); background-color: shade(@theme_selected_bg_color, 1.20); background-image: none; } .selection-mode.header-bar .suggested-action.button:active, .selection-mode.toolbar .suggested-action.button:active, .selection-mode.toolbar GtkToolButton.suggested-action:active { border-color: shade(@theme_selected_bg_color, 0.9); background-color: shade(@theme_selected_bg_color, 1.05); background-image: none; } .selection-mode.header-bar .suggested-action.button:hover:active, .selection-mode.toolbar .suggested-action.button:hover:active, .selection-mode.toolbar GtkToolButton.suggested-action .button:hover:active { border-color: shade(@theme_selected_bg_color, 0.8); } /* menu button */ .selection-mode.header-bar .selection-menu.button, .selection-mode.toolbar .selection-menu.button { border-style: none; background-color: transparent; background-image: none; color: shade(@theme_selected_bg_color, 0.8); } .selection-mode.toolbar .dim-label, .selection-mode.toolbar .selection-menu.button .dim-label { color: shade(@theme_selected_bg_color, 0.7); } .selection-mode.header-bar .selection-menu.button:hover, .selection-mode.toolbar .dim-label:hover, .selection-mode.toolbar .selection-menu.button:hover, .selection-mode.toolbar .selection-menu.button .dim-label:hover { color: shade(@theme_selected_bg_color, 0.7); } .selection-mode.header-bar .selection-menu.button:active, .selection-mode.toolbar .selection-menu.button:active { color: shade(@theme_selected_bg_color, 0.8); box-shadow: none; } /************************* * touch text selections * *************************/ GtkBubbleWindow { border-radius: 0px; background-clip: border-box; } GtkBubbleWindow.osd.background { background-color: @osd_bg; } GtkBubbleWindow .toolbar { background-color: transparent; } /******* * CSD * *******/ .titlebar { border-radius: 0; background-color: @titlebar_bg_color; background-image: none; color: mix(@titlebar_fg_color, @titlebar_bg_color, 0.1); text-shadow: none; } .titlebar.default-decoration { border: none; box-shadow: none; } .tiled .titlebar { border-radius: 0; } .maximized .titlebar { border-radius: 0; } /* this is the default titlebar that is added by GTK * when client-side decorations are in use and the application * did not set a custom titlebar. */ .titlebar.default-decoration { border: none; box-shadow: none; } .titlebar .title { font: bold; } .titlebar:backdrop { background-image: none; background-color: @titlebar_bg_color; color: mix(@titlebar_fg_color, @titlebar_bg_color, 0.4); text-shadow: none; } .titlebar .titlebutton { padding: 6px 12px; border-style: none; background: none; color: @theme_selected_bg_color; icon-shadow: none; } .titlebar .titlebutton:hover, .titlebar .titlebutton:hover:focus { background: none; color: @theme_selected_bg_color; } .titlebar .titlebutton:active, .titlebar .titlebutton:active:hover { background: none; color: @theme_selected_bg_color; box-shadow: none; } .titlebar .titlebutton:backdrop { background-image: none; color: mix(@titlebar_fg_color, @titlebar_bg_color, 0.4); icon-shadow: none; } .window-frame { border-style: none; border-radius: 0; box-shadow: 0 3px 7px 1px alpha(black, 0.7), 0 0 0 1px mix(shade(@titlebar_bg_color, 0.7), @titlebar_fg_color, 0.21); /* this is used for the resize cursor area */ margin: 10px; } .window-frame.tiled { border-radius: 0; } .window-frame:backdrop { box-shadow: 0 6px 6px 1px alpha(black, 0.5), 0 0 0 1px mix(shade(@titlebar_bg_color, 0.7), @titlebar_fg_color, 0.12); } /* Server-side decoration (SSD) */ .window-frame.ssd { border-radius: 0; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.18); } .window-frame.ssd, .window-frame.ssd:backdrop { background-color: @titlebar_bg_color; } /* Client-side Decorations (CSD)*/ .window-frame.csd.tooltip { border-radius: 0; box-shadow: none; } .window-frame.csd.message-dialog { border-radius: 0; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.13); } .window-frame.solid-csd { border: solid 1px shade(@bg_color, 0.8); border-radius: 0; margin: 2px; background-color: @titlebar_bg_color; box-shadow: none; } /************** * over under * **************/ /* these elements MUST be hidden, otherwise scrolling pages will have * missing chunks */ .overshoot.top { background-image: -gtk-gradient(radial, center top, 0, center top, 0.6, from(rgba(64, 128, 251, 0.2)), to(rgba(64, 128, 251, 0))); background-size: 100% 60%; background-repeat: no-repeat; background-position: center top; background-color: transparent; border: none; box-shadow: none; } .overshoot.bottom { background-image: -gtk-gradient(radial, center bottom, 0, center bottom, 0.6, from(rgba(64, 128, 251, 0.2)), to(rgba(64, 128, 251, 0))); background-size: 100% 60%; background-repeat: no-repeat; background-position: center bottom; background-color: transparent; border: none; box-shadow: none; } .overshoot.left { background-image: -gtk-gradient(radial, left center, 0, left center, 0.6, from(rgba(64, 128, 251, 0.2)), to(rgba(64, 128, 251, 0))); background-size: 60% 100%; background-repeat: no-repeat; background-position: left center; background-color: transparent; border: none; box-shadow: none; } .overshoot.right { background-image: -gtk-gradient(radial, right center, 0, right center, 0.6, from(rgba(64, 128, 251, 0.2)), to(rgba(64, 128, 251, 0))); background-size: 60% 100%; background-repeat: no-repeat; background-position: right center; background-color: transparent; border: none; box-shadow: none; } .undershoot.top { background-color: transparent; background-image: linear-gradient(to left, rgba(255, 255, 255, 0.2) 50%, rgba(0, 0, 0, 0.2) 50%); padding-top: 1px; background-size: 10px 1px; background-repeat: repeat-x; background-origin: content-box; background-position: center top; } .undershoot.bottom { background-color: transparent; background-image: linear-gradient(to left, rgba(255, 255, 255, 0.2) 50%, rgba(0, 0, 0, 0.2) 50%); padding-bottom: 1px; background-size: 10px 1px; background-repeat: repeat-x; background-origin: content-box; background-position: center bottom; } .undershoot.left { background-color: transparent; background-image: linear-gradient(to top, rgba(255, 255, 255, 0.2) 50%, rgba(0, 0, 0, 0.2) 50%); padding-left: 1px; background-size: 1px 10px; background-repeat: repeat-y; background-origin: content-box; background-position: left center; } .undershoot.right { background-color: transparent; background-image: linear-gradient(to top, rgba(255, 255, 255, 0.2) 50%, rgba(0, 0, 0, 0.2) 50%); padding-right: 1px; background-size: 1px 10px; background-repeat: repeat-y; background-origin: content-box; background-position: right center; } .overlay-bar { background-color: rgba(0, 0, 0, 0.8); border-radius: 4px; padding: 3px 6px; margin: 3px; } .overlay-bar GtkLabel { color: @tooltip_fg_color; }
inukaze/maestro
Temas/usr/share/themes/Windows-10-Dark-master/gtk-3.0/gtk-widgets.css
CSS
gpl-2.0
100,965
/* * Copyright (C) 2017 h0MER247 * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package Hardware.CPU.Intel80386.Condition.Conditions; import Hardware.CPU.Intel80386.Condition.Condition; import Hardware.CPU.Intel80386.Intel80386; public final class ConditionNotLessOrEqual implements Condition { private final Intel80386 m_cpu; public ConditionNotLessOrEqual(Intel80386 cpu) { m_cpu = cpu; } @Override public boolean isTrue() { return (m_cpu.FLAGS.SF == m_cpu.FLAGS.OF) && !m_cpu.FLAGS.ZF; } @Override public String toString() { return "nle"; } }
h0MER247/jPC
src/Hardware/CPU/Intel80386/Condition/Conditions/ConditionNotLessOrEqual.java
Java
gpl-2.0
1,328
<link href="https://gist.githubusercontent.com/tuzz/3331384/raw/94f2380c2b798fab2139fd0a8f478c4f2d642e3b/github.css" rel="stylesheet"></link> ## Overview This is a project that tries to solve Jermann Quadrini (2012 AER) with minimal modification. ## Folder and Files + /cppcode.cpp: only source code only GCC4.8+ understands. + /cuda\_helpers.h: all the rest of helper codes go in here. + /Model/: contains LyX and PDF that describe the model. + /MATLAB/: contains some codes written in MATLAB + /Dynare/: contains some codes written in Dynare to check accuracy of linearization ## Goal + Solve it somehow.
linxichen/jq_201406211740_fullmodel_linear_bond_adjustment
README.md
Markdown
gpl-2.0
611
/* * include/asm-s390/ptrace.h * * S390 version * Copyright (C) 1999,2000 IBM Deutschland Entwicklung GmbH, IBM Corporation * Author(s): Denis Joseph Barrow (djbarrow@de.ibm.com,barrow_dj@yahoo.com) */ #ifndef _S390_PTRACE_H #define _S390_PTRACE_H /* * Offsets in the user_regs_struct. They are used for the ptrace * system call and in entry.S */ #ifndef __s390x__ #define PT_PSWMASK 0x00 #define PT_PSWADDR 0x04 #define PT_GPR0 0x08 #define PT_GPR1 0x0C #define PT_GPR2 0x10 #define PT_GPR3 0x14 #define PT_GPR4 0x18 #define PT_GPR5 0x1C #define PT_GPR6 0x20 #define PT_GPR7 0x24 #define PT_GPR8 0x28 #define PT_GPR9 0x2C #define PT_GPR10 0x30 #define PT_GPR11 0x34 #define PT_GPR12 0x38 #define PT_GPR13 0x3C #define PT_GPR14 0x40 #define PT_GPR15 0x44 #define PT_ACR0 0x48 #define PT_ACR1 0x4C #define PT_ACR2 0x50 #define PT_ACR3 0x54 #define PT_ACR4 0x58 #define PT_ACR5 0x5C #define PT_ACR6 0x60 #define PT_ACR7 0x64 #define PT_ACR8 0x68 #define PT_ACR9 0x6C #define PT_ACR10 0x70 #define PT_ACR11 0x74 #define PT_ACR12 0x78 #define PT_ACR13 0x7C #define PT_ACR14 0x80 #define PT_ACR15 0x84 #define PT_ORIGGPR2 0x88 #define PT_FPC 0x90 /* * A nasty fact of life that the ptrace api * only supports passing of longs. */ #define PT_FPR0_HI 0x98 #define PT_FPR0_LO 0x9C #define PT_FPR1_HI 0xA0 #define PT_FPR1_LO 0xA4 #define PT_FPR2_HI 0xA8 #define PT_FPR2_LO 0xAC #define PT_FPR3_HI 0xB0 #define PT_FPR3_LO 0xB4 #define PT_FPR4_HI 0xB8 #define PT_FPR4_LO 0xBC #define PT_FPR5_HI 0xC0 #define PT_FPR5_LO 0xC4 #define PT_FPR6_HI 0xC8 #define PT_FPR6_LO 0xCC #define PT_FPR7_HI 0xD0 #define PT_FPR7_LO 0xD4 #define PT_FPR8_HI 0xD8 #define PT_FPR8_LO 0XDC #define PT_FPR9_HI 0xE0 #define PT_FPR9_LO 0xE4 #define PT_FPR10_HI 0xE8 #define PT_FPR10_LO 0xEC #define PT_FPR11_HI 0xF0 #define PT_FPR11_LO 0xF4 #define PT_FPR12_HI 0xF8 #define PT_FPR12_LO 0xFC #define PT_FPR13_HI 0x100 #define PT_FPR13_LO 0x104 #define PT_FPR14_HI 0x108 #define PT_FPR14_LO 0x10C #define PT_FPR15_HI 0x110 #define PT_FPR15_LO 0x114 #define PT_CR_9 0x118 #define PT_CR_10 0x11C #define PT_CR_11 0x120 #define PT_IEEE_IP 0x13C #define PT_LASTOFF PT_IEEE_IP #define PT_ENDREGS 0x140-1 #define GPR_SIZE 4 #define CR_SIZE 4 #define STACK_FRAME_OVERHEAD 96 /* size of minimum stack frame */ #else /* __s390x__ */ #define PT_PSWMASK 0x00 #define PT_PSWADDR 0x08 #define PT_GPR0 0x10 #define PT_GPR1 0x18 #define PT_GPR2 0x20 #define PT_GPR3 0x28 #define PT_GPR4 0x30 #define PT_GPR5 0x38 #define PT_GPR6 0x40 #define PT_GPR7 0x48 #define PT_GPR8 0x50 #define PT_GPR9 0x58 #define PT_GPR10 0x60 #define PT_GPR11 0x68 #define PT_GPR12 0x70 #define PT_GPR13 0x78 #define PT_GPR14 0x80 #define PT_GPR15 0x88 #define PT_ACR0 0x90 #define PT_ACR1 0x94 #define PT_ACR2 0x98 #define PT_ACR3 0x9C #define PT_ACR4 0xA0 #define PT_ACR5 0xA4 #define PT_ACR6 0xA8 #define PT_ACR7 0xAC #define PT_ACR8 0xB0 #define PT_ACR9 0xB4 #define PT_ACR10 0xB8 #define PT_ACR11 0xBC #define PT_ACR12 0xC0 #define PT_ACR13 0xC4 #define PT_ACR14 0xC8 #define PT_ACR15 0xCC #define PT_ORIGGPR2 0xD0 #define PT_FPC 0xD8 #define PT_FPR0 0xE0 #define PT_FPR1 0xE8 #define PT_FPR2 0xF0 #define PT_FPR3 0xF8 #define PT_FPR4 0x100 #define PT_FPR5 0x108 #define PT_FPR6 0x110 #define PT_FPR7 0x118 #define PT_FPR8 0x120 #define PT_FPR9 0x128 #define PT_FPR10 0x130 #define PT_FPR11 0x138 #define PT_FPR12 0x140 #define PT_FPR13 0x148 #define PT_FPR14 0x150 #define PT_FPR15 0x158 #define PT_CR_9 0x160 #define PT_CR_10 0x168 #define PT_CR_11 0x170 #define PT_IEEE_IP 0x1A8 #define PT_LASTOFF PT_IEEE_IP #define PT_ENDREGS 0x1B0-1 #define GPR_SIZE 8 #define CR_SIZE 8 #define STACK_FRAME_OVERHEAD 160 /* size of minimum stack frame */ #endif /* __s390x__ */ #define NUM_GPRS 16 #define NUM_FPRS 16 #define NUM_CRS 16 #define NUM_ACRS 16 #define NUM_CR_WORDS 3 #define FPR_SIZE 8 #define FPC_SIZE 4 #define FPC_PAD_SIZE 4 /* gcc insists on aligning the fpregs */ #define ACR_SIZE 4 #define PTRACE_OLDSETOPTIONS 21 #ifndef __ASSEMBLY__ #include <linux/stddef.h> #include <linux/types.h> typedef union { float f; double d; __u64 ui; struct { __u32 hi; __u32 lo; } fp; } freg_t; typedef struct { __u32 fpc; freg_t fprs[NUM_FPRS]; } s390_fp_regs; #define FPC_EXCEPTION_MASK 0xF8000000 #define FPC_FLAGS_MASK 0x00F80000 #define FPC_DXC_MASK 0x0000FF00 #define FPC_RM_MASK 0x00000003 #define FPC_VALID_MASK 0xF8F8FF03 /* this typedef defines how a Program Status Word looks like */ typedef struct { unsigned long mask; unsigned long addr; } __attribute__ ((aligned(8))) psw_t; typedef struct { __u32 mask; __u32 addr; } __attribute__ ((aligned(8))) psw_compat_t; #ifndef __s390x__ #define PSW_MASK_PER 0x40000000UL #define PSW_MASK_DAT 0x04000000UL #define PSW_MASK_IO 0x02000000UL #define PSW_MASK_EXT 0x01000000UL #define PSW_MASK_KEY 0x00F00000UL #define PSW_MASK_MCHECK 0x00040000UL #define PSW_MASK_WAIT 0x00020000UL #define PSW_MASK_PSTATE 0x00010000UL #define PSW_MASK_ASC 0x0000C000UL #define PSW_MASK_CC 0x00003000UL #define PSW_MASK_PM 0x00000F00UL #define PSW_ADDR_AMODE 0x80000000UL #define PSW_ADDR_INSN 0x7FFFFFFFUL #define PSW_BASE_BITS 0x00080000UL #define PSW_DEFAULT_KEY (((unsigned long) PAGE_DEFAULT_ACC) << 20) #define PSW_ASC_PRIMARY 0x00000000UL #define PSW_ASC_ACCREG 0x00004000UL #define PSW_ASC_SECONDARY 0x00008000UL #define PSW_ASC_HOME 0x0000C000UL #else /* __s390x__ */ #define PSW_MASK_PER 0x4000000000000000UL #define PSW_MASK_DAT 0x0400000000000000UL #define PSW_MASK_IO 0x0200000000000000UL #define PSW_MASK_EXT 0x0100000000000000UL #define PSW_MASK_KEY 0x00F0000000000000UL #define PSW_MASK_MCHECK 0x0004000000000000UL #define PSW_MASK_WAIT 0x0002000000000000UL #define PSW_MASK_PSTATE 0x0001000000000000UL #define PSW_MASK_ASC 0x0000C00000000000UL #define PSW_MASK_CC 0x0000300000000000UL #define PSW_MASK_PM 0x00000F0000000000UL #define PSW_ADDR_AMODE 0x0000000000000000UL #define PSW_ADDR_INSN 0xFFFFFFFFFFFFFFFFUL #define PSW_BASE_BITS 0x0000000180000000UL #define PSW_BASE32_BITS 0x0000000080000000UL #define PSW_DEFAULT_KEY (((unsigned long) PAGE_DEFAULT_ACC) << 52) #define PSW_ASC_PRIMARY 0x0000000000000000UL #define PSW_ASC_ACCREG 0x0000400000000000UL #define PSW_ASC_SECONDARY 0x0000800000000000UL #define PSW_ASC_HOME 0x0000C00000000000UL #endif /* __s390x__ */ #ifdef __KERNEL__ extern long psw_kernel_bits; extern long psw_user_bits; #ifdef CONFIG_64BIT extern long psw_user32_bits; #endif #endif /* This macro merges a NEW PSW mask specified by the user into the currently active PSW mask CURRENT, modifying only those bits in CURRENT that the user may be allowed to change: this is the condition code and the program mask bits. */ #define PSW_MASK_MERGE(CURRENT,NEW) \ (((CURRENT) & ~(PSW_MASK_CC|PSW_MASK_PM)) | \ ((NEW) & (PSW_MASK_CC|PSW_MASK_PM))) /* * The s390_regs structure is used to define the elf_gregset_t. */ typedef struct { psw_t psw; unsigned long gprs[NUM_GPRS]; unsigned int acrs[NUM_ACRS]; unsigned long orig_gpr2; } s390_regs; typedef struct { psw_compat_t psw; __u32 gprs[NUM_GPRS]; __u32 acrs[NUM_ACRS]; __u32 orig_gpr2; } s390_compat_regs; typedef struct { __u32 gprs_high[NUM_GPRS]; } s390_compat_regs_high; #ifdef __KERNEL__ /* * The pt_regs struct defines the way the registers are stored on * the stack during a system call. */ struct pt_regs { unsigned long args[1]; psw_t psw; unsigned long gprs[NUM_GPRS]; unsigned long orig_gpr2; unsigned short ilc; unsigned short svcnr; }; #endif /* * Now for the program event recording (trace) definitions. */ typedef struct { unsigned long cr[NUM_CR_WORDS]; } per_cr_words; #define PER_EM_MASK 0xE8000000UL typedef struct { #ifdef __s390x__ unsigned : 32; #endif /* __s390x__ */ unsigned em_branching : 1; unsigned em_instruction_fetch : 1; /* * Switching on storage alteration automatically fixes * the storage alteration event bit in the users std. */ unsigned em_storage_alteration : 1; unsigned em_gpr_alt_unused : 1; unsigned em_store_real_address : 1; unsigned : 3; unsigned branch_addr_ctl : 1; unsigned : 1; unsigned storage_alt_space_ctl : 1; unsigned : 21; unsigned long starting_addr; unsigned long ending_addr; } per_cr_bits; typedef struct { unsigned short perc_atmid; unsigned long address; unsigned char access_id; } per_lowcore_words; typedef struct { unsigned perc_branching : 1; unsigned perc_instruction_fetch : 1; unsigned perc_storage_alteration : 1; unsigned perc_gpr_alt_unused : 1; unsigned perc_store_real_address : 1; unsigned : 3; unsigned atmid_psw_bit_31 : 1; unsigned atmid_validity_bit : 1; unsigned atmid_psw_bit_32 : 1; unsigned atmid_psw_bit_5 : 1; unsigned atmid_psw_bit_16 : 1; unsigned atmid_psw_bit_17 : 1; unsigned si : 2; unsigned long address; unsigned : 4; unsigned access_id : 4; } per_lowcore_bits; typedef struct { union { per_cr_words words; per_cr_bits bits; } control_regs; /* * Use these flags instead of setting em_instruction_fetch * directly they are used so that single stepping can be * switched on & off while not affecting other tracing */ unsigned single_step : 1; unsigned instruction_fetch : 1; unsigned : 30; /* * These addresses are copied into cr10 & cr11 if single * stepping is switched off */ unsigned long starting_addr; unsigned long ending_addr; union { per_lowcore_words words; per_lowcore_bits bits; } lowcore; } per_struct; typedef struct { unsigned int len; unsigned long kernel_addr; unsigned long process_addr; } ptrace_area; /* * S/390 specific non posix ptrace requests. I chose unusual values so * they are unlikely to clash with future ptrace definitions. */ #define PTRACE_PEEKUSR_AREA 0x5000 #define PTRACE_POKEUSR_AREA 0x5001 #define PTRACE_PEEKTEXT_AREA 0x5002 #define PTRACE_PEEKDATA_AREA 0x5003 #define PTRACE_POKETEXT_AREA 0x5004 #define PTRACE_POKEDATA_AREA 0x5005 #define PTRACE_GET_LAST_BREAK 0x5006 /* * PT_PROT definition is loosely based on hppa bsd definition in * gdb/hppab-nat.c */ #define PTRACE_PROT 21 typedef enum { ptprot_set_access_watchpoint, ptprot_set_write_watchpoint, ptprot_disable_watchpoint } ptprot_flags; typedef struct { unsigned long lowaddr; unsigned long hiaddr; ptprot_flags prot; } ptprot_area; /* Sequence of bytes for breakpoint illegal instruction. */ #define S390_BREAKPOINT {0x0,0x1} #define S390_BREAKPOINT_U16 ((__u16)0x0001) #define S390_SYSCALL_OPCODE ((__u16)0x0a00) #define S390_SYSCALL_SIZE 2 /* * The user_regs_struct defines the way the user registers are * store on the stack for signal handling. */ struct user_regs_struct { psw_t psw; unsigned long gprs[NUM_GPRS]; unsigned int acrs[NUM_ACRS]; unsigned long orig_gpr2; s390_fp_regs fp_regs; /* * These per registers are in here so that gdb can modify them * itself as there is no "official" ptrace interface for hardware * watchpoints. This is the way intel does it. */ per_struct per_info; unsigned long ieee_instruction_pointer; /* Used to give failing instruction back to user for ieee exceptions */ }; #ifdef __KERNEL__ /* * These are defined as per linux/ptrace.h, which see. */ #define arch_has_single_step() (1) extern void show_regs(struct pt_regs * regs); #define user_mode(regs) (((regs)->psw.mask & PSW_MASK_PSTATE) != 0) #define instruction_pointer(regs) ((regs)->psw.addr & PSW_ADDR_INSN) #define user_stack_pointer(regs)((regs)->gprs[15]) #define regs_return_value(regs)((regs)->gprs[2]) #define profile_pc(regs) instruction_pointer(regs) int regs_query_register_offset(const char *name); const char *regs_query_register_name(unsigned int offset); unsigned long regs_get_register(struct pt_regs *regs, unsigned int offset); unsigned long regs_get_kernel_stack_nth(struct pt_regs *regs, unsigned int n); static inline unsigned long kernel_stack_pointer(struct pt_regs *regs) { return regs->gprs[15] & PSW_ADDR_INSN; } #endif /* __KERNEL__ */ #endif /* __ASSEMBLY__ */ #endif /* _S390_PTRACE_H */
skywalker01/Samsung-Galaxy-S-Plus
arch/s390/include/asm/ptrace.h
C
gpl-2.0
12,825
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>CoffeeScript API Documentation</title> <script src='../../javascript/application.js'></script> <script src='../../javascript/search.js'></script> <link rel='stylesheet' href='../../stylesheets/application.css' type='text/css'> </head> <body> <div id='base' data-path='../../'></div> <div id='header'> <div id='menu'> <a href='../../extra/README.md.html' title='Nodes'> Nodes </a> &raquo; <a href='../../alphabetical_index.html' title='Index'> Index </a> &raquo; <span class='title'>src\illisian\sublayouts\contact.coffee</span> </div> </div> <div id='content'> <h1> File: contact.coffee </h1> <table class='box'> <tr> <td>Defined in:</td> <td>src\illisian\sublayouts</td> </tr> <tr> <td> Classes: </td> <td> <a href='../../class/Contact.html'> Contact </a> </td> </tr> </table> <h2>Variables Summary</h2> <dl class='constants'> <dt id='module.exports-variable'> module.exports = </dt> <dd> <pre><code class='coffeescript'>Contact</code></pre> </dd> </dl> </div> <div id='footer'> November 22, 13 14:43:08 by <a href='https://github.com/coffeescript/codo' title='CoffeeScript API documentation generator'> Codo </a> 2.0.0-rc.4 &#10034; Press H to see the keyboard shortcuts &#10034; <a href='http://twitter.com/netzpirat' target='_parent'>@netzpirat</a> &#10034; <a href='http://twitter.com/_inossidabile' target='_parent'>@_inossidabile</a> &#10034; <a href='https://mksoft.ch' target='_parent'>mksoft.ch</a> </div> <iframe id='search_frame'></iframe> <div id='fuzzySearch'> <input type='text'> <ol></ol> </div> <div id='help'> <p> Quickly fuzzy find classes, mixins, methods, file: </p> <ul> <li> <span>T</span> Open fuzzy finder dialog </li> </ul> <p> Control the navigation frame: </p> <ul> <li> <span>L</span> Toggle list view </li> <li> <span>C</span> Show class list </li> <li> <span>I</span> Show mixin list </li> <li> <span>F</span> Show file list </li> <li> <span>M</span> Show method list </li> <li> <span>E</span> Show extras list </li> </ul> <p> You can focus and blur the search input: </p> <ul> <li> <span>S</span> Focus search input </li> <li> <span>Esc</span> Blur search input </li> </ul> </div> </body> </html>
Illisian/Nodes
doc/file/src/illisian/sublayouts/contact.coffee.html
HTML
gpl-2.0
2,731
<?php // autogenerated file 10.09.2012 12:58 // $Id: $ // $Log: $ // require_once 'EbatNs_FacetType.php'; /** * Contains values for shipped status. * * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/SellingManagerShippedStatusCodeType.html * * @property string Shipped * @property string Unshipped * @property string CustomCode */ class SellingManagerShippedStatusCodeType extends EbatNs_FacetType { const CodeType_Shipped = 'Shipped'; const CodeType_Unshipped = 'Unshipped'; const CodeType_CustomCode = 'CustomCode'; /** * @return */ function __construct() { parent::__construct('SellingManagerShippedStatusCodeType', 'urn:ebay:apis:eBLBaseComponents'); } } $Facet_SellingManagerShippedStatusCodeType = new SellingManagerShippedStatusCodeType(); ?>
Serdy/treasureantique.com
wp-content/plugins/wp-lister-for-ebay/includes/EbatNs/SellingManagerShippedStatusCodeType.php
PHP
gpl-2.0
836
#include "shn.h" #include "../pcmconv.h" /******************************************************** Audio Tools, a module and set of tools for manipulating audio data Copyright (C) 2007-2012 Brian Langenberger 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 *******************************************************/ PyObject* SHNDecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { decoders_SHNDecoder *self; self = (decoders_SHNDecoder *)type->tp_alloc(type, 0); return (PyObject *)self; } int SHNDecoder_init(decoders_SHNDecoder *self, PyObject *args, PyObject *kwds) { char* filename; FILE* fp; self->filename = NULL; self->bitstream = NULL; self->stream_finished = 0; self->means = array_ia_new(); self->previous_samples = array_ia_new(); /*setup temporary buffers*/ self->samples = array_ia_new(); self->unshifted = array_ia_new(); self->pcm_header = array_i_new(); self->pcm_footer = array_i_new(); if ((self->audiotools_pcm = open_audiotools_pcm()) == NULL) return -1; if (!PyArg_ParseTuple(args, "s", &filename)) return -1; self->filename = strdup(filename); /*open the shn file*/ if ((fp = fopen(filename, "rb")) == NULL) { self->bitstream = NULL; PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename); return -1; } else { self->bitstream = br_open(fp, BS_BIG_ENDIAN); } /*read Shorten header for basic info*/ if (!setjmp(*br_try(self->bitstream))) { uint8_t magic_number[4]; unsigned version; unsigned i; self->bitstream->parse(self->bitstream, "4b 8u", magic_number, &version); if (memcmp(magic_number, "ajkg", 4)) { PyErr_SetString(PyExc_ValueError, "invalid magic number"); br_etry(self->bitstream); return -1; } if (version != 2) { PyErr_SetString(PyExc_ValueError, "invalid Shorten version"); br_etry(self->bitstream); return -1; } self->header.file_type = read_long(self->bitstream); self->header.channels = read_long(self->bitstream); self->block_length = read_long(self->bitstream); self->header.max_LPC = read_long(self->bitstream); self->header.mean_count = read_long(self->bitstream); self->bitstream->skip_bytes(self->bitstream, read_long(self->bitstream)); if ((1 <= self->header.file_type) && (self->header.file_type <= 2)) { self->bits_per_sample = 8; self->signed_samples = (self->header.file_type == 1); } else if ((3 <= self->header.file_type) && (self->header.file_type <= 6)) { self->bits_per_sample = 16; self->signed_samples = ((self->header.file_type == 3) || (self->header.file_type == 5)); } else { PyErr_SetString(PyExc_ValueError, "unsupported Shorten file type"); br_etry(self->bitstream); return -1; } for (i = 0; i < self->header.channels; i++) { array_i* means = self->means->append(self->means); means->mset(means, self->header.mean_count, 0); self->previous_samples->append(self->previous_samples); } /*process first instruction for wave/aiff header, if present*/ if (process_header(self->bitstream, &(self->sample_rate), &(self->channel_mask))) { br_etry(self->bitstream); return -1; } br_etry(self->bitstream); return 0; } else { /*read error in Shorten header*/ br_etry(self->bitstream); PyErr_SetString(PyExc_IOError, "I/O error reading Shorten header"); return -1; } } void SHNDecoder_dealloc(decoders_SHNDecoder *self) { self->means->del(self->means); self->previous_samples->del(self->previous_samples); self->samples->del(self->samples); self->unshifted->del(self->unshifted); self->pcm_header->del(self->pcm_header); self->pcm_footer->del(self->pcm_footer); Py_XDECREF(self->audiotools_pcm); if (self->bitstream != NULL) { self->bitstream->close(self->bitstream); } if (self->filename != NULL) free(self->filename); self->ob_type->tp_free((PyObject*)self); } PyObject* SHNDecoder_close(decoders_SHNDecoder* self, PyObject *args) { Py_INCREF(Py_None); return Py_None; } static PyObject* SHNDecoder_sample_rate(decoders_SHNDecoder *self, void *closure) { return Py_BuildValue("I", self->sample_rate); } static PyObject* SHNDecoder_bits_per_sample(decoders_SHNDecoder *self, void *closure) { return Py_BuildValue("I", self->bits_per_sample); } static PyObject* SHNDecoder_channels(decoders_SHNDecoder *self, void *closure) { return Py_BuildValue("I", self->header.channels); } static PyObject* SHNDecoder_channel_mask(decoders_SHNDecoder *self, void *closure) { return Py_BuildValue("I", self->channel_mask); } PyObject* SHNDecoder_read(decoders_SHNDecoder* self, PyObject *args) { unsigned c = 0; PyThreadState *thread_state = NULL; self->samples->reset(self->samples); self->unshifted->reset(self->unshifted); if (self->stream_finished) { return empty_FrameList(self->audiotools_pcm, self->header.channels, self->bits_per_sample); } thread_state = PyEval_SaveThread(); if (!setjmp(*br_try(self->bitstream))) { while (1) { const unsigned command = read_unsigned(self->bitstream, COMMAND_SIZE); if (((FN_DIFF0 <= command) && (command <= FN_DIFF3)) || ((FN_QLPC <= command) && (command <= FN_ZERO))) { /*audio data commands*/ array_i* means = self->means->_[c]; array_i* previous_samples = self->previous_samples->_[c]; array_i* samples = self->samples->append(self->samples); array_i* unshifted = self->unshifted->append(self->unshifted); switch (command) { case FN_DIFF0: read_diff0(self->bitstream, self->block_length, means, samples); break; case FN_DIFF1: read_diff1(self->bitstream, self->block_length, previous_samples, samples); break; case FN_DIFF2: read_diff2(self->bitstream, self->block_length, previous_samples, samples); break; case FN_DIFF3: read_diff3(self->bitstream, self->block_length, previous_samples, samples); break; case FN_QLPC: read_qlpc(self->bitstream, self->block_length, previous_samples, means, samples); break; case FN_ZERO: samples->mset(samples, self->block_length, 0); break; default: break; /*can't get here*/ } /*calculate next mean for given channel*/ means->append(means, shnmean(samples)); means->tail(means, self->header.mean_count, means); /*wrap samples for next set of channels*/ samples->tail(samples, MAX(3, self->header.max_LPC), previous_samples); /*apply any left shift to channel*/ if (self->left_shift) { unsigned i; for (i = 0; i < samples->len; i++) unshifted->append(unshifted, samples->_[i] << self->left_shift); } else { samples->copy(samples, unshifted); } /*if stream is unsigned, convert unshifted samples to signed*/ if (!self->signed_samples) { const int adjustment = 1 << (self->bits_per_sample - 1); unsigned i; for (i = 0; i < unshifted->len; i++) unshifted->_[i] -= adjustment; } /*move on to next channel*/ c++; /*once all channels are constructed, return a complete set of PCM frames*/ if (c == self->header.channels) { br_etry(self->bitstream); PyEval_RestoreThread(thread_state); return array_ia_to_FrameList(self->audiotools_pcm, self->unshifted, self->bits_per_sample); } } else if (((FN_QUIT <= command) && (command <= FN_BITSHIFT)) || (command == FN_VERBATIM)) { unsigned verbatim_size; unsigned i; /*non audio commands*/ switch (command) { case FN_QUIT: self->stream_finished = 1; br_etry(self->bitstream); PyEval_RestoreThread(thread_state); return empty_FrameList(self->audiotools_pcm, self->header.channels, self->bits_per_sample); break; case FN_BLOCKSIZE: self->block_length = read_long(self->bitstream); break; case FN_BITSHIFT: self->left_shift = read_unsigned(self->bitstream, SHIFT_SIZE); break; case FN_VERBATIM: verbatim_size = read_unsigned(self->bitstream, VERBATIM_CHUNK_SIZE); for (i = 0; i < verbatim_size; i++) skip_unsigned(self->bitstream, VERBATIM_BYTE_SIZE); break; default: break; /*can't get here*/ } } else { /*unknown command*/ br_etry(self->bitstream); PyEval_RestoreThread(thread_state); PyErr_SetString(PyExc_ValueError, "unknown command in Shorten stream"); return NULL; } } } else { br_etry(self->bitstream); PyEval_RestoreThread(thread_state); PyErr_SetString(PyExc_IOError, "I/O error reading Shorten file"); return NULL; } } static void read_diff0(BitstreamReader* bs, unsigned block_length, const array_i* means, array_i* samples) { const int offset = shnmean(means); const unsigned energy = read_unsigned(bs, ENERGY_SIZE); unsigned i; samples->reset(samples); for (i = 0; i < block_length; i++) { const int residual = read_signed(bs, energy); samples->append(samples, residual + offset); } } static void read_diff1(BitstreamReader* bs, unsigned block_length, array_i* previous_samples, array_i* samples) { unsigned i; unsigned energy; /*ensure "previous_samples" contains at least 1 value*/ if (previous_samples->len < 1) { samples->mset(samples, 1 - previous_samples->len, 0); samples->extend(samples, previous_samples); } else { previous_samples->tail(previous_samples, 1, samples); } energy = read_unsigned(bs, ENERGY_SIZE); /*process the residuals to samples*/ for (i = 1; i < (block_length + 1); i++) { const int residual = read_signed(bs, energy); samples->append(samples, samples->_[i - 1] + residual); } /*truncate samples to block length*/ samples->tail(samples, block_length, samples); } static void read_diff2(BitstreamReader* bs, unsigned block_length, array_i* previous_samples, array_i* samples) { unsigned i; unsigned energy; /*ensure "previous_samples" contains at least 2 values*/ if (previous_samples->len < 2) { samples->mset(samples, 2 - previous_samples->len, 0); samples->extend(samples, previous_samples); } else { previous_samples->tail(previous_samples, 2, samples); } energy = read_unsigned(bs, ENERGY_SIZE); /*process the residuals to samples*/ for (i = 2; i < (block_length + 2); i++) { const int residual = read_signed(bs, energy); samples->append(samples, (2 * samples->_[i - 1]) - samples->_[i - 2] + residual); } /*truncate samples to block length*/ samples->tail(samples, block_length, samples); } static void read_diff3(BitstreamReader* bs, unsigned block_length, array_i* previous_samples, array_i* samples) { unsigned i; unsigned energy; /*ensure "previous_samples" contains at least 3 values*/ if (previous_samples->len < 3) { samples->mset(samples, 3 - previous_samples->len, 0); samples->extend(samples, previous_samples); } else { previous_samples->tail(previous_samples, 3, samples); } energy = read_unsigned(bs, ENERGY_SIZE); /*process the residuals to samples*/ for (i = 3; i < (block_length + 3); i++) { const int residual = read_signed(bs, energy); samples->append(samples, (3 * (samples->_[i - 1] - samples->_[i - 2])) + samples->_[i - 3] + residual); } /*truncate samples to block length*/ samples->tail(samples, block_length, samples); } static void read_qlpc(BitstreamReader* bs, unsigned block_length, array_i* previous_samples, array_i* means, array_i* samples) { /*read some QLPC setup values*/ const int offset = shnmean(means); const unsigned energy = read_unsigned(bs, ENERGY_SIZE); const unsigned LPC_count = read_unsigned(bs, LPC_COUNT_SIZE); array_i* LPC_coeff = array_i_new(); array_i* offset_samples = array_i_new(); array_i* unoffset_samples = array_i_new(); if (!setjmp(*br_try(bs))) { int i; for (i = 0; i < LPC_count; i++) LPC_coeff->append(LPC_coeff, read_signed(bs, LPC_COEFF_SIZE)); /*ensure "previous_samples" contains at least "LPC count" values*/ if (previous_samples->len < LPC_count) { offset_samples->mset(offset_samples, LPC_count - previous_samples->len, 0); offset_samples->extend(offset_samples, previous_samples); } else { previous_samples->tail(previous_samples, LPC_count, offset_samples); } /*process the residuals to unoffset samples*/ for (i = 0; i < block_length; i++) { const int residual = read_signed(bs, energy); int sum = 1 << 5; int j; for (j = 0; j < LPC_count; j++) { if ((i - j - 1) < 0) { sum += LPC_coeff->_[j] * (offset_samples->_[LPC_count + (i - j - 1)] - offset); } else { sum += LPC_coeff->_[j] * unoffset_samples->_[i - j - 1]; } } unoffset_samples->append(unoffset_samples, (sum >> 5) + residual); } /*reapply offset to unoffset samples*/ samples->reset(samples); for (i = 0; i < unoffset_samples->len; i++) { samples->append(samples, unoffset_samples->_[i] + offset); } /*deallocate temporary arrays before returning successfully*/ LPC_coeff->del(LPC_coeff); offset_samples->del(offset_samples); unoffset_samples->del(unoffset_samples); br_etry(bs); } else { /*error reading QLPC, so deallocate temporary arrays*/ LPC_coeff->del(LPC_coeff); offset_samples->del(offset_samples); unoffset_samples->del(unoffset_samples); br_etry(bs); /*before aborting to the next spot on the abort stack*/ br_abort(bs); } } static int shnmean(const array_i* values) { return ((int)(values->len / 2) + values->sum(values)) / (int)(values->len); } static PyObject* SHNDecoder_pcm_split(decoders_SHNDecoder* self, PyObject *args) { if (!setjmp(*br_try(self->bitstream))) { array_i* header = self->pcm_header; array_i* footer = self->pcm_footer; array_i* current = header; uint8_t* header_s; uint8_t* footer_s; PyObject* tuple; unsigned command; unsigned i; header->reset(header); footer->reset(footer); /*walk through file, processing all commands*/ do { unsigned energy; unsigned LPC_count; unsigned verbatim_size; command = read_unsigned(self->bitstream, COMMAND_SIZE); switch (command) { case FN_DIFF0: case FN_DIFF1: case FN_DIFF2: case FN_DIFF3: /*all the DIFF commands have the same structure*/ energy = read_unsigned(self->bitstream, ENERGY_SIZE); for (i = 0; i < self->block_length; i++) { skip_signed(self->bitstream, energy); } current = footer; break; case FN_QUIT: self->stream_finished = 1; break; case FN_BLOCKSIZE: self->block_length = read_long(self->bitstream); break; case FN_BITSHIFT: skip_unsigned(self->bitstream, SHIFT_SIZE); break; case FN_QLPC: energy = read_unsigned(self->bitstream, ENERGY_SIZE); LPC_count = read_unsigned(self->bitstream, LPC_COUNT_SIZE); for (i = 0; i < LPC_count; i++) { skip_signed(self->bitstream, LPC_COEFF_SIZE); } for (i = 0; i < self->block_length; i++) { skip_signed(self->bitstream, energy); } current = footer; break; case FN_ZERO: current = footer; break; case FN_VERBATIM: /*any VERBATIM commands have their data appended to header or footer*/ verbatim_size = read_unsigned(self->bitstream, VERBATIM_CHUNK_SIZE); for (i = 0; i < verbatim_size; i++) { current->append(current, read_unsigned(self->bitstream, VERBATIM_BYTE_SIZE)); } break; } } while (command != FN_QUIT); br_etry(self->bitstream); /*once all commands have been processed, transform the bytes in header and footer to strings*/ header_s = malloc(sizeof(uint8_t) * header->len); for (i = 0; i < header->len; i++) header_s[i] = (uint8_t)(header->_[i] & 0xFF); footer_s = malloc(sizeof(uint8_t) * footer->len); for (i = 0; i < footer->len; i++) footer_s[i] = (uint8_t)(footer->_[i] & 0xFF); /*generate a tuple from the strings*/ tuple = Py_BuildValue("(s#s#)", header_s, header->len, footer_s, footer->len); /*deallocate temporary space before returning tuple*/ free(header_s); free(footer_s); return tuple; } else { br_etry(self->bitstream); PyErr_SetString(PyExc_IOError, "I/O error reading Shorten file"); return NULL; } } static unsigned read_unsigned(BitstreamReader* bs, unsigned count) { const unsigned MSB = bs->read_unary(bs, 1); const unsigned LSB = bs->read(bs, count); return (MSB << count) | LSB; } static int read_signed(BitstreamReader* bs, unsigned count) { /*1 additional sign bit*/ const unsigned u = read_unsigned(bs, count + 1); if (u % 2) return -(u >> 1) - 1; else return u >> 1; } unsigned int read_long(BitstreamReader* bs) { return read_unsigned(bs, read_unsigned(bs, 2)); } void skip_unsigned(BitstreamReader* bs, unsigned int count) { bs->skip_unary(bs, 1); bs->skip(bs, count); } void skip_signed(BitstreamReader* bs, unsigned int count) { bs->skip_unary(bs, 1); bs->skip(bs, count + 1); } static int process_header(BitstreamReader* bs, unsigned* sample_rate, unsigned* channel_mask) { unsigned command; bs->mark(bs); if (!setjmp(*br_try(bs))) { command = read_unsigned(bs, COMMAND_SIZE); if (command == FN_VERBATIM) { BitstreamReader* verbatim; unsigned verbatim_size; verbatim = read_verbatim(bs, &verbatim_size); verbatim->mark(verbatim); if (!read_wave_header(verbatim, verbatim_size, sample_rate, channel_mask)) { verbatim->unmark(verbatim); verbatim->close(verbatim); bs->rewind(bs); bs->unmark(bs); br_etry(bs); return 0; } else { verbatim->rewind(verbatim); } if (!read_aiff_header(verbatim, verbatim_size, sample_rate, channel_mask)) { verbatim->unmark(verbatim); verbatim->close(verbatim); bs->rewind(bs); bs->unmark(bs); br_etry(bs); return 0; } else { verbatim->rewind(verbatim); } /*neither wave header or aiff header found, so use dummy values again*/ verbatim->unmark(verbatim); verbatim->close(verbatim); bs->rewind(bs); bs->unmark(bs); *sample_rate = 44100; *channel_mask = 0; br_etry(bs); return 0; } else { /*VERBATIM isn't the first command so rewind and set some dummy values*/ bs->rewind(bs); bs->unmark(bs); *sample_rate = 44100; *channel_mask = 0; br_etry(bs); return 0; } } else { bs->unmark(bs); br_etry(bs); br_abort(bs); return 0; /*won't get here*/ } } static BitstreamReader* read_verbatim(BitstreamReader* bs, unsigned* verbatim_size) { BitstreamReader* verbatim = br_substream_new(BS_BIG_ENDIAN); if (!setjmp(*br_try(bs))) { *verbatim_size = read_unsigned(bs, VERBATIM_CHUNK_SIZE); unsigned i; for (i = 0; i < *verbatim_size; i++) { const unsigned byte = read_unsigned(bs, VERBATIM_BYTE_SIZE) & 0xFF; buf_putc((int)byte, verbatim->input.substream); } br_etry(bs); return verbatim; } else { /*I/O error reading from main bitstream*/ verbatim->close(verbatim); br_etry(bs); br_abort(bs); return NULL; /*shouldn't get here*/ } } int read_wave_header(BitstreamReader* bs, unsigned verbatim_size, unsigned* sample_rate, unsigned* channel_mask) { if (!setjmp(*br_try(bs))) { uint8_t RIFF[4]; unsigned SIZE; uint8_t WAVE[4]; bs->set_endianness(bs, BS_LITTLE_ENDIAN); bs->parse(bs, "4b 32u 4b", RIFF, &SIZE, WAVE); if (memcmp(RIFF, "RIFF", 4) || memcmp(WAVE, "WAVE", 4)) { br_etry(bs); return 1; } else { verbatim_size -= bs_format_byte_size("4b 32u 4b"); } while (verbatim_size > 0) { uint8_t chunk_id[4]; unsigned chunk_size; bs->parse(bs, "4b 32u", chunk_id, &chunk_size); verbatim_size -= bs_format_byte_size("4b 32u"); if (!memcmp(chunk_id, "fmt ", 4)) { /*parse fmt chunk*/ unsigned compression; unsigned channels; unsigned bytes_per_second; unsigned block_align; unsigned bits_per_sample; bs->parse(bs, "16u 16u 32u 32u 16u 16u", &compression, &channels, sample_rate, &bytes_per_second, &block_align, &bits_per_sample); if (compression == 1) { /*if we have a multi-channel WAVE file that's not WAVEFORMATEXTENSIBLE, assume the channels follow SMPTE/ITU-R recommendations and hope for the best*/ switch (channels) { case 1: *channel_mask = 0x4; break; case 2: *channel_mask = 0x3; break; case 3: *channel_mask = 0x7; break; case 4: *channel_mask = 0x33; break; case 5: *channel_mask = 0x37; break; case 6: *channel_mask = 0x3F; break; default: *channel_mask = 0; break; } br_etry(bs); return 0; } else if (compression == 0xFFFE) { unsigned cb_size; unsigned valid_bits_per_sample; uint8_t sub_format[16]; bs->parse(bs, "16u 16u 32u 16b", &cb_size, &valid_bits_per_sample, channel_mask, sub_format); if (!memcmp(sub_format, "\x01\x00\x00\x00\x00\x00\x10\x00" "\x80\x00\x00\xaa\x00\x38\x9b\x71", 16)) { br_etry(bs); return 0; } else { /*invalid sub format*/ br_etry(bs); return 1; } } else { /*unsupported wave compression*/ br_etry(bs); return 1; } } else { if (chunk_size % 2) { /*handle odd-sized chunks*/ bs->skip_bytes(bs, chunk_size + 1); verbatim_size -= (chunk_size + 1); } else { bs->skip_bytes(bs, chunk_size); verbatim_size -= chunk_size; } } } /*no fmt chunk found in wave header*/ br_etry(bs); return 1; } else { /*I/O error bouncing through wave chunks*/ br_etry(bs); return 1; } } int read_aiff_header(BitstreamReader* bs, unsigned verbatim_size, unsigned* sample_rate, unsigned* channel_mask) { if (!setjmp(*br_try(bs))) { uint8_t FORM[4]; unsigned SIZE; uint8_t AIFF[4]; bs->set_endianness(bs, BS_BIG_ENDIAN); bs->parse(bs, "4b 32u 4b", FORM, &SIZE, AIFF); if (memcmp(FORM, "FORM", 4) || memcmp(AIFF, "AIFF", 4)) { br_etry(bs); return 1; } else { verbatim_size -= bs_format_byte_size("4b 32u 4b"); } while (verbatim_size > 0) { uint8_t chunk_id[4]; unsigned chunk_size; bs->parse(bs, "4b 32u", chunk_id, &chunk_size); verbatim_size -= bs_format_byte_size("4b 32u"); if (!memcmp(chunk_id, "COMM", 4)) { /*parse COMM chunk*/ unsigned channels; unsigned total_sample_frames; unsigned bits_per_sample; bs->parse(bs, "16u 32u 16u", &channels, &total_sample_frames, &bits_per_sample); *sample_rate = read_ieee_extended(bs); switch (channels) { case 1: *channel_mask = 0x4; break; case 2: *channel_mask = 0x3; break; default: *channel_mask = 0; break; } br_etry(bs); return 0; } else { if (chunk_size % 2) { /*handle odd-sized chunks*/ bs->skip_bytes(bs, chunk_size + 1); verbatim_size -= (chunk_size + 1); } else { bs->skip_bytes(bs, chunk_size); verbatim_size -= chunk_size; } } } /*no COMM chunk found in aiff header*/ br_etry(bs); return 1; } else { /*I/O error bouncing through aiff chunks*/ br_etry(bs); return 1; } } int read_ieee_extended(BitstreamReader* bs) { unsigned sign; unsigned exponent; uint64_t mantissa; bs->parse(bs, "1u 15u 64U", &sign, &exponent, &mantissa); if ((exponent == 0) && (mantissa == 0)) { return 0; } else if (exponent == 0x7FFF) { return INT_MAX; } else { const int f = (int)((double)mantissa * pow(2.0, (double)exponent - 16383 - 63)); if (sign) return -f; else return f; } }
R-a-dio/python-audio-tools
src/decoders/shn.c
C
gpl-2.0
31,275
# Code Review [Back to top](../README.md) A guide for reviewing code and having your code reviewed. ## Everyone * Accept that many programming decisions are opinions. Discuss tradeoffs, which you prefer, and reach a resolution quickly. * Ask good questions; don't make demands. ("What do you think about naming this `:user_id`?") * Good questions avoid judgment and avoid assumptions about the author's perspective. * Ask for clarification. ("I didn't understand. Can you clarify?") * Avoid selective ownership of code. ("mine", "not mine", "yours") * Avoid using terms that could be seen as referring to personal traits. ("dumb", "stupid"). Assume everyone is intelligent and well-meaning. * Be explicit. Remember people don't always understand your intentions online. * Be humble. ("I'm not sure - let's look it up.") * Don't use hyperbole. ("always", "never", "endlessly", "nothing") * Don't use sarcasm. * Keep it real. If emoji, animated gifs, or humor aren't you, don't force them. If they are, use them with aplomb. * Talk synchronously (e.g. chat, screensharing, in person) if there are too many "I didn't understand" or "Alternative solution:" comments. Post a follow-up comment summarizing the discussion. ## Having Your Code Reviewed * Be grateful for the reviewer's suggestions. ("Good call. I'll make that change.") * A common axiom is "Don't take it personally. The review is of the code, not you." We used to include this, but now prefer to say what we mean: Be aware of [how hard it is to convey emotion online] and how easy it is to misinterpret feedback. If a review seems aggressive or angry or otherwise personal, consider if it is intended to be read that way and ask the person for clarification of intent, in person if possible. * Keeping the previous point in mind: assume the best intention from the reviewer's comments. * Explain why the code exists. ("It's like that because of these reasons. Would it be more clear if I rename this class/file/method/variable?") * Extract some changes and refactorings into future tickets/stories. * Link to the code review from the ticket/story. ("Ready for review: https://github.com/organization/project/pull/1") * Push commits based on earlier rounds of feedback as isolated commits to the branch. Do not squash until the branch is ready to merge. Reviewers should be able to read individual updates based on their earlier feedback. * Seek to understand the reviewer's perspective. * Try to respond to every comment. * Wait to merge the branch until Continuous Integration (TDDium, TravisCI, etc.) tells you the test suite is green in the branch. * Merge once you feel confident in the code and its impact on the project. [how hard it is to convey emotion online]: https://www.fastcodesign.com/3036748/why-its-so-hard-to-detect-emotion-in-emails-and-texts ## Reviewing Code Understand why the change is necessary (fixes a bug, improves the user experience, refactors the existing code). Then: * Communicate which ideas you feel strongly about and those you don't. * Identify ways to simplify the code while still solving the problem. * If discussions turn too philosophical or academic, move the discussion offline to a regular Friday afternoon technique discussion. In the meantime, let the author make the final decision on alternative implementations. * Offer alternative implementations, but assume the author already considered them. ("What do you think about using a custom validator here?") * Seek to understand the author's perspective. * Sign off on the pull request with a :thumbsup: or "Ready to merge" comment. ## Style Comments Reviewers should comment on missed [style](../style) guidelines. Example comment: [Style](../style): > Order resourceful routes alphabetically by name. An example response to style comments: Whoops. Good catch, thanks. Fixed in a4994ec. If you disagree with a guideline, open an issue on the guides repository rather than debating it within the code review. In the meantime, apply the guideline. ### Resources These guidelines have been taken from Thoughtbot's guidelines found at <https://github.com/thoughtbot/guides> under the [Creative Commons Attribution Licence (CC BY 3.0)](https://creativecommons.org/licenses/by/3.0/). Useful best practices for code reviews can be read more in-depth at [Best practices for peer code review](https://smartbear.com/learn/code-review/best-practices-for-peer-code-review/)
felixnorden/moppepojkar
documentation/code-review.md
Markdown
gpl-2.0
4,544
class TenderCorruptionFlag < ActiveRecord::Base belongs_to :tender belongs_to :corruption_indicator attr_accessible :id, :tender_id, :corruption_indicator_id, :value end
tigeorgia/e-procurement-site
app/models/tender_corruption_flag.rb
Ruby
gpl-2.0
183
/*- * APT - Analysis of Petri Nets and labeled Transition systems * Copyright (C) 2012-2013 Members of the project group APT * * 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. */ package uniol.apt.analysis.connectivity; import java.util.Set; import uniol.apt.adt.IGraph; import uniol.apt.adt.INode; import uniol.apt.module.AbstractModule; import uniol.apt.module.AptModule; import uniol.apt.module.Category; import uniol.apt.module.InterruptibleModule; import uniol.apt.module.ModuleInput; import uniol.apt.module.ModuleInputSpec; import uniol.apt.module.ModuleOutput; import uniol.apt.module.ModuleOutputSpec; import uniol.apt.module.exception.ModuleException; /** * Provide the weak components test as a module. * @author Uli Schlachter, vsp */ @AptModule public class WeakComponentsModule extends AbstractModule implements InterruptibleModule { @Override public String getShortDescription() { return "Find the weakly connected components of a Petri net or LTS"; } @Override public String getName() { return "weak_components"; } @Override public void require(ModuleInputSpec inputSpec) { inputSpec.addParameter("graph", IGraph.class, "The graph that should be examined"); } @Override public void provide(ModuleOutputSpec outputSpec) { outputSpec.addReturnValue("weak_components", Components.class); } @Override public void run(ModuleInput input, ModuleOutput output) throws ModuleException { IGraph<?, ?, ?> graph = input.getParameter("graph", IGraph.class); Set<? extends Set<? extends INode<?, ?, ?>>> components = run(graph); output.setReturnValue("weak_components", Components.class, new Components(components)); } @SuppressWarnings("unchecked") private static <G extends IGraph<G, ?, N>, N extends INode<G, ?, N>> Set<? extends Set<? extends INode<?, ?, ?>>> run(IGraph<?, ?, ?> graph) { return Connectivity.getWeaklyConnectedComponents((G) graph); } @Override public Category[] getCategories() { return new Category[]{Category.PN, Category.LTS}; } } // vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
CvO-Theory/apt
src/module/uniol/apt/analysis/connectivity/WeakComponentsModule.java
Java
gpl-2.0
2,732
#!/usr/bin/python # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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. # # Fail2Ban 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 Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. __author__ = "Cyril Jaquier, Steven Hiscocks, Yaroslav Halchenko" __copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2008-2013 Fail2Ban Contributors" __license__ = "GPL" try: import setuptools from setuptools import setup except ImportError: setuptools = None from distutils.core import setup try: # python 3.x from distutils.command.build_py import build_py_2to3 as build_py from distutils.command.build_scripts \ import build_scripts_2to3 as build_scripts except ImportError: # python 2.x from distutils.command.build_py import build_py from distutils.command.build_scripts import build_scripts import os from os.path import isfile, join, isdir import sys import warnings from glob import glob if setuptools and "test" in sys.argv: import logging logSys = logging.getLogger("fail2ban") hdlr = logging.StreamHandler(sys.stdout) fmt = logging.Formatter("%(asctime)-15s %(message)s") hdlr.setFormatter(fmt) logSys.addHandler(hdlr) if set(["-q", "--quiet"]) & set(sys.argv): logSys.setLevel(logging.CRITICAL) warnings.simplefilter("ignore") sys.warnoptions.append("ignore") elif set(["-v", "--verbose"]) & set(sys.argv): logSys.setLevel(logging.DEBUG) else: logSys.setLevel(logging.INFO) elif "test" in sys.argv: print("python distribute required to execute fail2ban tests") print("") longdesc = ''' Fail2Ban scans log files like /var/log/pwdfail or /var/log/apache/error_log and bans IP that makes too many password failures. It updates firewall rules to reject the IP address or executes user defined commands.''' if setuptools: setup_extra = { 'test_suite': "fail2ban.tests.utils.gatherTests", 'use_2to3': True, } else: setup_extra = {} data_files_extra = [] if os.path.exists('/var/run'): # if we are on the system with /var/run -- we are to use it for having fail2ban/ # directory there for socket file etc data_files_extra += [('/var/run/fail2ban', '')] # Get version number, avoiding importing fail2ban. # This is due to tests not functioning for python3 as 2to3 takes place later exec(open(join("fail2ban", "version.py")).read()) setup( name="fail2ban", version=version, description="Ban IPs that make too many password failures", long_description=longdesc, author="Cyril Jaquier & Fail2Ban Contributors", author_email="cyril.jaquier@fail2ban.org", url="http://www.fail2ban.org", license="GPL", platforms="Posix", cmdclass={'build_py': build_py, 'build_scripts': build_scripts}, scripts=[ 'bin/fail2ban-client', 'bin/fail2ban-server', 'bin/fail2ban-regex', 'bin/fail2ban-testcases', ], packages=[ 'fail2ban', 'fail2ban.client', 'fail2ban.server', 'fail2ban.tests', 'fail2ban.tests.action_d', ], package_data={ 'fail2ban.tests': [join(w[0], f).replace("fail2ban/tests/", "", 1) for w in os.walk('fail2ban/tests/files') for f in w[2]] + [join(w[0], f).replace("fail2ban/tests/", "", 1) for w in os.walk('fail2ban/tests/config') for f in w[2]] + [join(w[0], f).replace("fail2ban/tests/", "", 1) for w in os.walk('fail2ban/tests/action_d') for f in w[2]] }, data_files=[ ('/etc/fail2ban', glob("config/*.conf") ), ('/etc/fail2ban/filter.d', glob("config/filter.d/*.conf") ), ('/etc/fail2ban/filter.d/ignorecommands', glob("config/filter.d/ignorecommands/*") ), ('/etc/fail2ban/action.d', glob("config/action.d/*.conf") + glob("config/action.d/*.py") ), ('/etc/fail2ban/fail2ban.d', '' ), ('/etc/fail2ban/jail.d', '' ), ('/var/lib/fail2ban', '' ), ('/usr/share/doc/fail2ban', ['README.md', 'README.Solaris', 'DEVELOP', 'FILTERS', 'doc/run-rootless.txt'] ) ] + data_files_extra, **setup_extra ) # Do some checks after installation # Search for obsolete files. obsoleteFiles = [] elements = { "/etc/": [ "fail2ban.conf" ], "/usr/bin/": [ "fail2ban.py" ], "/usr/lib/fail2ban/": [ "version.py", "protocol.py" ] } for directory in elements: for f in elements[directory]: path = join(directory, f) if isfile(path): obsoleteFiles.append(path) if obsoleteFiles: print("") print("Obsolete files from previous Fail2Ban versions were found on " "your system.") print("Please delete them:") print("") for f in obsoleteFiles: print("\t" + f) print("") if isdir("/usr/lib/fail2ban"): print("") print("Fail2ban is not installed under /usr/lib anymore. The new " "location is under /usr/share. Please remove the directory " "/usr/lib/fail2ban and everything under this directory.") print("") # Update config file if sys.argv[1] == "install": print("") print("Please do not forget to update your configuration files.") print("They are in /etc/fail2ban/.") print("")
pheanex/fail2ban
setup.py
Python
gpl-2.0
5,567
/* * Configuration.hpp * * RTfact - Real-Time Ray Tracing Library * * Copyright (C) 2009 Saarland University * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Created on: 2008-11-07 18:41:48 +0100 * Author(s): Iliyan Georgiev */ #ifndef RTFACT__CONFIGURATION_HPP #define RTFACT__CONFIGURATION_HPP #include <RTfact/Config/Common.hpp> #include <fstream> #include <sstream> #include <map> #include <set> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <RTfact/Utils/Containers/Vector.hpp> #include <RTfact/Utils/Packets/Vec3f.hpp> #define RTFACT__GLOBAL_GROUP_NAME "_Global_" RTFACT_NAMESPACE_BEGIN namespace IO { class Configuration { struct QuoteTrimPredicate { bool operator()(const char aChar) { return (aChar == '\'') || (aChar == '"'); } }; static void trimQuotes( std::string& aString) { static QuoteTrimPredicate trimPredicate; boost::algorithm::trim_if(aString, trimPredicate); } public: class Entry : public std::string { public: template< class tType> Entry( const tType& aValue ) : std::string(boost::lexical_cast<std::string>(aValue)) {} template< class tType> tType as() const { return boost::lexical_cast<tType>(*this); } }; class EntryGroup { typedef std::map<std::string, Entry> t_EntryMap; t_EntryMap mEntries; std::string mName; public: EntryGroup() {} EntryGroup( const std::string& aName ) : mName(aName) {} RTFACT_DEFINE_PROPERTY(std::string&, Name); bool exists( const std::string& aKey) const { return mEntries.find(aKey) != mEntries.end(); } template< class tType> void add( const std::string& aKey, const tType& aValue) { RTFACT_USER_ERROR_IF_F(exists(aKey), "Entry already exists: %1%/%2%=%3%", mName % aKey % (*this)[aKey]); mEntries.insert(t_EntryMap::value_type(aKey, Entry(aValue))); } const Entry& operator[]( const std::string& aKey) const { RTFACT_USER_ERROR_IF_F(!exists(aKey), "Entry does not exist: %1%/%2%", mName % aKey); return mEntries.find(aKey)->second; } Entry& operator[]( const std::string& aKey) { RTFACT_USER_ERROR_IF_F(!exists(aKey), "Entry does not exist: %1%/%2%", mName % aKey); return mEntries.find(aKey)->second; } }; protected: typedef std::map<std::string, EntryGroup> t_GroupMap; t_GroupMap mGroups; public: Configuration() { mGroups.insert(t_GroupMap::value_type( RTFACT__GLOBAL_GROUP_NAME, EntryGroup(RTFACT__GLOBAL_GROUP_NAME))); } Configuration( const int argc, const char** argv) { //TODO: implement } Configuration( const std::string& aPath) { mGroups.insert(t_GroupMap::value_type( RTFACT__GLOBAL_GROUP_NAME, EntryGroup(RTFACT__GLOBAL_GROUP_NAME))); RTFACT_USER_ERROR_IF_F(!loadFromFile(aPath), "Could not load configuration file: %1%", aPath); } Configuration( std::istream& aStream) { mGroups.insert(t_GroupMap::value_type( RTFACT__GLOBAL_GROUP_NAME, EntryGroup(RTFACT__GLOBAL_GROUP_NAME))); loadFromStream(aStream); } bool loadFromFile( const std::string& aPath) { std::ifstream inStream(aPath.c_str()); if(!inStream.good()) { return false; } return loadFromStream(inStream); } bool loadFromStream( std::istream& aStream) { uint lineNum = 0; std::string curGroup(RTFACT__GLOBAL_GROUP_NAME); bool curGroupIsUsed = false; typedef std::set<std::string> t_UsedGroupSet; t_UsedGroupSet usedGroups; while(aStream.good() && !aStream.eof()) { ++lineNum; std::string curLine; std::getline(aStream, curLine); boost::algorithm::trim(curLine); bool singleQuoteOpened = false; bool doubleQuoteOpened = false; size_t firstSemiColonIndex = size_t(-1); // remove comments, except between quotes for(uint i = 0; i < curLine.length(); ++i) { if(curLine[i] == ';' && !singleQuoteOpened && !doubleQuoteOpened) { firstSemiColonIndex = i; break; } if(curLine[i] == '\'') { singleQuoteOpened = !singleQuoteOpened; } else if(curLine[i] == '"') { doubleQuoteOpened = !doubleQuoteOpened; } } if(firstSemiColonIndex != size_t(-1)) { curLine = curLine.substr(0, firstSemiColonIndex); boost::algorithm::trim(curLine); } std::istringstream issLine(curLine); std::string firstWord; issLine >> firstWord >> std::ws; if(firstWord.length() == 0) { continue; } if(firstWord[0] == '[') // group { curGroup = curLine.substr(1, curLine.length() - 2); mGroups.insert(t_GroupMap::value_type( curGroup, EntryGroup(curGroup))); curGroupIsUsed = (usedGroups.find(curGroup) != usedGroups.end()); } else if(firstWord[0] != '\r' && firstWord[0] != '\n' && firstWord[0] != '=') // entry { size_t delimIndex = curLine.find('='); std::string key = curLine.substr(0, delimIndex); std::string value = curLine.substr(delimIndex + 1, curLine.length() - delimIndex); trimQuotes(key); trimQuotes(value); RTFACT_USER_ERROR_IF_F(key.length() == 0, "Invalid key on line: %1%", lineNum); RTFACT_USER_ERROR_IF_F(value.length() == 0, "Empty value on line: %1%", lineNum); if(curGroup == RTFACT__GLOBAL_GROUP_NAME && key == "use") { usedGroups.insert(value); } else if(curGroupIsUsed) { add(key, value); } mGroups[curGroup].add(key, value); } } return true; } bool exists( const std::string& aKey) const { return mGroups.find(RTFACT__GLOBAL_GROUP_NAME)->second.exists(aKey); } bool existsGroup( const std::string& aName) const { return mGroups.find(aName) != mGroups.end(); } EntryGroup& operator()( const std::string& aName) { t_GroupMap::iterator it = mGroups.find(aName); RTFACT_USER_ERROR_IF_F(it == mGroups.end(), "Group does not exist: %1%", aName); return it->second; } const EntryGroup& operator()( const std::string& aName) const { t_GroupMap::const_iterator it = mGroups.find(aName); RTFACT_USER_ERROR_IF_F(it == mGroups.end(), "Group does not exist: %1%", aName); return it->second; } Entry& operator[]( const std::string& aKey) { RTFACT_USER_ERROR_IF_F(!exists(aKey), "Entry does not exist: %1%", aKey); return mGroups.find(RTFACT__GLOBAL_GROUP_NAME)->second[aKey]; } const Entry& operator[]( const std::string& aKey) const { RTFACT_USER_ERROR_IF_F(!exists(aKey), "Entry does not exist: %1%", aKey); return mGroups.find(RTFACT__GLOBAL_GROUP_NAME)->second[aKey]; } template< class tType> void add( const std::string& aKey, const tType& aValue) { RTFACT_USER_ERROR_IF_F(exists(aKey), "Entry already exists: %1%", aKey); mGroups[RTFACT__GLOBAL_GROUP_NAME].add(aKey, aValue); } void addGroup( const std::string& aName) { RTFACT_USER_ERROR_IF_F(existsGroup(aName), "Group already exists: %1%", aName); mGroups.insert( t_GroupMap::value_type(aName, EntryGroup(aName))).first->second; } }; template<> RTFACT_INLINE Vec3f1 Configuration::Entry::as<Vec3f1>() const { std::istringstream issLine(*this); char comma; Vec3f1 res; if(this->find(',') != std::string::npos) { issLine >> res.x >> comma >> res.y >> comma >> res.z; } else { issLine >> res.x >> res.y >> res.z; } return res; } template<> RTFACT_INLINE bool Configuration::Entry::as<bool>() const { return (*this == "1" || *this == "true"); } } // namespace IO RTFACT_NAMESPACE_END #undef RTFACT__GLOBAL_GROUP_NAME #endif // RTFACT__CONFIGURATION_HPP
BALL-Contrib/contrib_rtfact_4f1d028
include/RTfact/Utils/IO/Configuration.hpp
C++
gpl-2.0
10,079
#ifndef __CREATE_PARENT_H__ #define __CREATE_PARENT_H__ /* * KFontInst - KDE Font Installer * * Copyright 2003-2007 Craig Drummond <craig@kde.org> * * ---- * * 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; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QX11Info> #include <X11/Xlib.h> #include <fixx11h.h> // // *Very* hacky way to get some KDE dialogs to appear to be transient // for 'xid' // // Create's a QWidget with size 0/0 and no border, makes this transient // for xid, and all other widgets can use this as their parent... static QWidget * createParent(int xid) { if(!xid) return NULL; QWidget *parent=new QWidget(NULL, Qt::FramelessWindowHint); parent->resize(1, 1); parent->show(); XWindowAttributes attr; int rx, ry; Window junkwin; XSetTransientForHint(QX11Info::display(), parent->winId(), xid); if(XGetWindowAttributes(QX11Info::display(), xid, &attr)) { XTranslateCoordinates(QX11Info::display(), xid, attr.root, -attr.border_width, -16, &rx, &ry, &junkwin); rx=(rx+(attr.width/2)); if(rx<0) rx=0; ry=(ry+(attr.height/2)); if(ry<0) ry=0; parent->move(rx, ry); } parent->setWindowOpacity(0); return parent; } #endif
jschwartzenberg/kicker
kcontrol/kfontinst/apps/CreateParent.h
C
gpl-2.0
1,963
package OpenInteract2::ContentType; # $Id: ContentType.pm,v 1.2 2004/04/09 11:38:26 lachoy Exp $ use strict; @OpenInteract2::ContentType::ISA = qw( OpenInteract2::ContentTypePersist ); $OpenInteract2::ContentType::VERSION = sprintf("%d.%02d", q$Revision: 1.2 $ =~ /(\d+)\.(\d+)/); use constant DEFAULT_MIME_TYPE => 'text/plain'; my $BOUND_CHARACTER = ';'; ######################################## # RULES ######################################## # The rules here are to ensure that the extensions can be found # properly sub ruleset_factory { my ( $class, $rs ) = @_; push @{ $rs->{post_fetch_action} }, \&split_extensions; push @{ $rs->{pre_save_action} }, \&merge_extensions; return __PACKAGE__; } sub split_extensions { my ( $self ) = @_; $self->{extensions} = join( ' ', grep ! /^\s*$/, split ( /$BOUND_CHARACTER/, $self->{extensions} ) ); return 1; } sub merge_extensions { my ( $self ) = @_; $self->{extensions} = $BOUND_CHARACTER . join( $BOUND_CHARACTER, split /\s+/, $self->{extensions} ) . $BOUND_CHARACTER; return 1; } ######################################## # CLASS METHODS ######################################## # Class method so that you can lookup a MIME type by an extension. If # the extension isn't found, we return DEFAULT_MIME_TYPE. # $p is used here to pass extra information to the SELECT, like a # value for 'DEBUG' sub mime_type_by_extension { my ( $class, $extension, $p ) = @_; $extension = lc $extension; $p ||= {}; my $type_list = $class->db_select({ %{ $p }, from => $class->table_name, select => [ 'mime_type' ], where => 'extensions LIKE ?', value => [ "%$BOUND_CHARACTER$extension$BOUND_CHARACTER%" ], return => 'single-list', db => $class->global_datasource_handle }); return ( $type_list->[0] ) ? $type_list->[0] : DEFAULT_MIME_TYPE; } 1;
cwinters/OpenInteract2
pkg/base_page/OpenInteract2/ContentType.pm
Perl
gpl-2.0
2,168
/* * This file is part of the coreboot project. * * Copyright (C) 2009 coresystems GmbH * Copyright (C) 2009 Libra Li <libra.li@technexion.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "registers.h" /* setup interrupt handlers for mainboard */ extern void mainboard_interrupt_handlers(int intXX, void *intXX_func);
wt/coreboot
src/arch/i386/include/arch/interrupt.h
C
gpl-2.0
1,009
/* * This source code is part of * * G R O M A C S * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2009, The GROMACS Development Team * * Gromacs is a library for molecular simulation and trajectory analysis, * written by Erik Lindahl, David van der Spoel, Berk Hess, and others - for * a full list of developers and information, check out http://www.gromacs.org * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU Lesser General Public License. * * In plain-speak: do not worry about classes/macros/templates either - only * changes to the library have to be LGPL, not an application linking with it. * * To help fund GROMACS development, we humbly ask that you cite * the papers people have written on it - you can find them on the website! */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <math.h> #include "vec.h" #include "gmx_thread.h" #include "nb_kernel132.h" /* * Gromacs nonbonded kernel nb_kernel132 * Coulomb interaction: Normal Coulomb * VdW interaction: Tabulated * water optimization: pairs of SPC/TIP3P interactions * Calculate forces: yes */ void nb_kernel132( int * p_nri, int * iinr, int * jindex, int * jjnr, int * shift, real * shiftvec, real * fshift, int * gid, real * pos, real * faction, real * charge, real * p_facel, real * p_krf, real * p_crf, real * Vc, int * type, int * p_ntype, real * vdwparam, real * Vvdw, real * p_tabscale, real * VFtab,real * enerd1,real * enerd2,real * enerd3,real * enerd4,int * start,int * end,int * homenr,int * nbsum, real * invsqrta, real * dvda, real * p_gbtabscale, real * GBtab, int * p_nthreads, int * count, void * mtx, int * outeriter, int * inneriter, real * work) { int nri,ntype,nthreads; real facel,krf,crf,tabscale,gbtabscale; int n,ii,is3,ii3,k,nj0,nj1,jnr,j3,ggid; int nn0,nn1,nouter,ninner; real shX,shY,shZ; real fscal,tx,ty,tz; real rinvsq; real qq,vcoul,vctot; int tj; real Vvdw6,Vvdwtot; real Vvdw12; real r,rt,eps,eps2; int n0,nnn; real Y,F,Geps,Heps2,Fp,VV; real FF; real fijD,fijR; real ix1,iy1,iz1,fix1,fiy1,fiz1; real ix2,iy2,iz2,fix2,fiy2,fiz2; real ix3,iy3,iz3,fix3,fiy3,fiz3; real jx1,jy1,jz1,fjx1,fjy1,fjz1; real jx2,jy2,jz2,fjx2,fjy2,fjz2; real jx3,jy3,jz3,fjx3,fjy3,fjz3; real dx11,dy11,dz11,rsq11,rinv11; real dx12,dy12,dz12,rsq12,rinv12; real dx13,dy13,dz13,rsq13,rinv13; real dx21,dy21,dz21,rsq21,rinv21; real dx22,dy22,dz22,rsq22,rinv22; real dx23,dy23,dz23,rsq23,rinv23; real dx31,dy31,dz31,rsq31,rinv31; real dx32,dy32,dz32,rsq32,rinv32; real dx33,dy33,dz33,rsq33,rinv33; real qO,qH,qqOO,qqOH,qqHH; real c6,c12; nri = *p_nri; ntype = *p_ntype; nthreads = *p_nthreads; facel = *p_facel; krf = *p_krf; crf = *p_crf; tabscale = *p_tabscale; /* Initialize water data */ ii = iinr[0]; qO = charge[ii]; qH = charge[ii+1]; qqOO = facel*qO*qO; qqOH = facel*qO*qH; qqHH = facel*qH*qH; tj = 2*(ntype+1)*type[ii]; c6 = vdwparam[tj]; c12 = vdwparam[tj+1]; /* Reset outer and inner iteration counters */ nouter = 0; ninner = 0; /* Loop over thread workunits */ do { #ifdef GMX_THREADS gmx_thread_mutex_lock((gmx_thread_mutex_t *)mtx); nn0 = *count; /* Take successively smaller chunks (at least 10 lists) */ nn1 = nn0+(nri-nn0)/(2*nthreads)+10; *count = nn1; gmx_thread_mutex_unlock((gmx_thread_mutex_t *)mtx); if(nn1>nri) nn1=nri; #else nn0 = 0; nn1 = nri; #endif /* Start outer loop over neighborlists */ for(n=nn0; (n<nn1); n++) { /* Load shift vector for this list */ is3 = 3*shift[n]; shX = shiftvec[is3]; shY = shiftvec[is3+1]; shZ = shiftvec[is3+2]; /* Load limits for loop over neighbors */ nj0 = jindex[n]; nj1 = jindex[n+1]; /* Get outer coordinate index */ ii = iinr[n]; ii3 = 3*ii; /* Load i atom data, add shift vector */ ix1 = shX + pos[ii3+0]; iy1 = shY + pos[ii3+1]; iz1 = shZ + pos[ii3+2]; ix2 = shX + pos[ii3+3]; iy2 = shY + pos[ii3+4]; iz2 = shZ + pos[ii3+5]; ix3 = shX + pos[ii3+6]; iy3 = shY + pos[ii3+7]; iz3 = shZ + pos[ii3+8]; /* Zero the potential energy for this list */ vctot = 0; Vvdwtot = 0; /* Clear i atom forces */ fix1 = 0; fiy1 = 0; fiz1 = 0; fix2 = 0; fiy2 = 0; fiz2 = 0; fix3 = 0; fiy3 = 0; fiz3 = 0; for(k=nj0; (k<nj1); k++) { /* Get j neighbor index, and coordinate index */ jnr = jjnr[k]; j3 = 3*jnr; /* load j atom coordinates */ jx1 = pos[j3+0]; jy1 = pos[j3+1]; jz1 = pos[j3+2]; jx2 = pos[j3+3]; jy2 = pos[j3+4]; jz2 = pos[j3+5]; jx3 = pos[j3+6]; jy3 = pos[j3+7]; jz3 = pos[j3+8]; /* Calculate distance */ dx11 = ix1 - jx1; dy11 = iy1 - jy1; dz11 = iz1 - jz1; rsq11 = dx11*dx11+dy11*dy11+dz11*dz11; dx12 = ix1 - jx2; dy12 = iy1 - jy2; dz12 = iz1 - jz2; rsq12 = dx12*dx12+dy12*dy12+dz12*dz12; dx13 = ix1 - jx3; dy13 = iy1 - jy3; dz13 = iz1 - jz3; rsq13 = dx13*dx13+dy13*dy13+dz13*dz13; dx21 = ix2 - jx1; dy21 = iy2 - jy1; dz21 = iz2 - jz1; rsq21 = dx21*dx21+dy21*dy21+dz21*dz21; dx22 = ix2 - jx2; dy22 = iy2 - jy2; dz22 = iz2 - jz2; rsq22 = dx22*dx22+dy22*dy22+dz22*dz22; dx23 = ix2 - jx3; dy23 = iy2 - jy3; dz23 = iz2 - jz3; rsq23 = dx23*dx23+dy23*dy23+dz23*dz23; dx31 = ix3 - jx1; dy31 = iy3 - jy1; dz31 = iz3 - jz1; rsq31 = dx31*dx31+dy31*dy31+dz31*dz31; dx32 = ix3 - jx2; dy32 = iy3 - jy2; dz32 = iz3 - jz2; rsq32 = dx32*dx32+dy32*dy32+dz32*dz32; dx33 = ix3 - jx3; dy33 = iy3 - jy3; dz33 = iz3 - jz3; rsq33 = dx33*dx33+dy33*dy33+dz33*dz33; /* Calculate 1/r and 1/r2 */ rinv11 = invsqrt(rsq11); rinv12 = invsqrt(rsq12); rinv13 = invsqrt(rsq13); rinv21 = invsqrt(rsq21); rinv22 = invsqrt(rsq22); rinv23 = invsqrt(rsq23); rinv31 = invsqrt(rsq31); rinv32 = invsqrt(rsq32); rinv33 = invsqrt(rsq33); /* Load parameters for j atom */ qq = qqOO; rinvsq = rinv11*rinv11; /* Coulomb interaction */ vcoul = qq*rinv11; vctot = vctot+vcoul; /* Calculate table index */ r = rsq11*rinv11; /* Calculate table index */ rt = r*tabscale; n0 = rt; eps = rt-n0; eps2 = eps*eps; nnn = 8*n0; /* Tabulated VdW interaction - dispersion */ Y = VFtab[nnn]; F = VFtab[nnn+1]; Geps = eps*VFtab[nnn+2]; Heps2 = eps2*VFtab[nnn+3]; Fp = F+Geps+Heps2; VV = Y+eps*Fp; FF = Fp+Geps+2.0*Heps2; Vvdw6 = c6*VV; fijD = c6*FF; /* Tabulated VdW interaction - repulsion */ nnn = nnn+4; Y = VFtab[nnn]; F = VFtab[nnn+1]; Geps = eps*VFtab[nnn+2]; Heps2 = eps2*VFtab[nnn+3]; Fp = F+Geps+Heps2; VV = Y+eps*Fp; FF = Fp+Geps+2.0*Heps2; Vvdw12 = c12*VV; fijR = c12*FF; Vvdwtot = Vvdwtot+ Vvdw6 + Vvdw12; fscal = (vcoul)*rinvsq-((fijD+fijR)*tabscale)*rinv11; /* Calculate temporary vectorial force */ tx = fscal*dx11; ty = fscal*dy11; tz = fscal*dz11; /* Increment i atom force */ fix1 = fix1 + tx; fiy1 = fiy1 + ty; fiz1 = fiz1 + tz; /* Decrement j atom force */ fjx1 = faction[j3+0] - tx; fjy1 = faction[j3+1] - ty; fjz1 = faction[j3+2] - tz; /* Load parameters for j atom */ qq = qqOH; rinvsq = rinv12*rinv12; /* Coulomb interaction */ vcoul = qq*rinv12; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx12; ty = fscal*dy12; tz = fscal*dz12; /* Increment i atom force */ fix1 = fix1 + tx; fiy1 = fiy1 + ty; fiz1 = fiz1 + tz; /* Decrement j atom force */ fjx2 = faction[j3+3] - tx; fjy2 = faction[j3+4] - ty; fjz2 = faction[j3+5] - tz; /* Load parameters for j atom */ qq = qqOH; rinvsq = rinv13*rinv13; /* Coulomb interaction */ vcoul = qq*rinv13; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx13; ty = fscal*dy13; tz = fscal*dz13; /* Increment i atom force */ fix1 = fix1 + tx; fiy1 = fiy1 + ty; fiz1 = fiz1 + tz; /* Decrement j atom force */ fjx3 = faction[j3+6] - tx; fjy3 = faction[j3+7] - ty; fjz3 = faction[j3+8] - tz; /* Load parameters for j atom */ qq = qqOH; rinvsq = rinv21*rinv21; /* Coulomb interaction */ vcoul = qq*rinv21; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx21; ty = fscal*dy21; tz = fscal*dz21; /* Increment i atom force */ fix2 = fix2 + tx; fiy2 = fiy2 + ty; fiz2 = fiz2 + tz; /* Decrement j atom force */ fjx1 = fjx1 - tx; fjy1 = fjy1 - ty; fjz1 = fjz1 - tz; /* Load parameters for j atom */ qq = qqHH; rinvsq = rinv22*rinv22; /* Coulomb interaction */ vcoul = qq*rinv22; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx22; ty = fscal*dy22; tz = fscal*dz22; /* Increment i atom force */ fix2 = fix2 + tx; fiy2 = fiy2 + ty; fiz2 = fiz2 + tz; /* Decrement j atom force */ fjx2 = fjx2 - tx; fjy2 = fjy2 - ty; fjz2 = fjz2 - tz; /* Load parameters for j atom */ qq = qqHH; rinvsq = rinv23*rinv23; /* Coulomb interaction */ vcoul = qq*rinv23; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx23; ty = fscal*dy23; tz = fscal*dz23; /* Increment i atom force */ fix2 = fix2 + tx; fiy2 = fiy2 + ty; fiz2 = fiz2 + tz; /* Decrement j atom force */ fjx3 = fjx3 - tx; fjy3 = fjy3 - ty; fjz3 = fjz3 - tz; /* Load parameters for j atom */ qq = qqOH; rinvsq = rinv31*rinv31; /* Coulomb interaction */ vcoul = qq*rinv31; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx31; ty = fscal*dy31; tz = fscal*dz31; /* Increment i atom force */ fix3 = fix3 + tx; fiy3 = fiy3 + ty; fiz3 = fiz3 + tz; /* Decrement j atom force */ faction[j3+0] = fjx1 - tx; faction[j3+1] = fjy1 - ty; faction[j3+2] = fjz1 - tz; /* Load parameters for j atom */ qq = qqHH; rinvsq = rinv32*rinv32; /* Coulomb interaction */ vcoul = qq*rinv32; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx32; ty = fscal*dy32; tz = fscal*dz32; /* Increment i atom force */ fix3 = fix3 + tx; fiy3 = fiy3 + ty; fiz3 = fiz3 + tz; /* Decrement j atom force */ faction[j3+3] = fjx2 - tx; faction[j3+4] = fjy2 - ty; faction[j3+5] = fjz2 - tz; /* Load parameters for j atom */ qq = qqHH; rinvsq = rinv33*rinv33; /* Coulomb interaction */ vcoul = qq*rinv33; vctot = vctot+vcoul; fscal = (vcoul)*rinvsq; /* Calculate temporary vectorial force */ tx = fscal*dx33; ty = fscal*dy33; tz = fscal*dz33; /* Increment i atom force */ fix3 = fix3 + tx; fiy3 = fiy3 + ty; fiz3 = fiz3 + tz; /* Decrement j atom force */ faction[j3+6] = fjx3 - tx; faction[j3+7] = fjy3 - ty; faction[j3+8] = fjz3 - tz; /* Inner loop uses 266 flops/iteration */ } /* Add i forces to mem and shifted force list */ faction[ii3+0] = faction[ii3+0] + fix1; faction[ii3+1] = faction[ii3+1] + fiy1; faction[ii3+2] = faction[ii3+2] + fiz1; faction[ii3+3] = faction[ii3+3] + fix2; faction[ii3+4] = faction[ii3+4] + fiy2; faction[ii3+5] = faction[ii3+5] + fiz2; faction[ii3+6] = faction[ii3+6] + fix3; faction[ii3+7] = faction[ii3+7] + fiy3; faction[ii3+8] = faction[ii3+8] + fiz3; fshift[is3] = fshift[is3]+fix1+fix2+fix3; fshift[is3+1] = fshift[is3+1]+fiy1+fiy2+fiy3; fshift[is3+2] = fshift[is3+2]+fiz1+fiz2+fiz3; /* Add potential energies to the group for this list */ ggid = gid[n]; Vc[ggid] = Vc[ggid] + vctot; Vvdw[ggid] = Vvdw[ggid] + Vvdwtot; /* Increment number of inner iterations */ ninner = ninner + nj1 - nj0; /* Outer loop uses 29 flops/iteration */ } /* Increment number of outer iterations */ nouter = nouter + nn1 - nn0; } while (nn1<nri); /* Write outer/inner iteration count to pointers */ *outeriter = nouter; *inneriter = ninner; } /* * Gromacs nonbonded kernel nb_kernel132nf * Coulomb interaction: Normal Coulomb * VdW interaction: Tabulated * water optimization: pairs of SPC/TIP3P interactions * Calculate forces: no */ void nb_kernel132nf( int * p_nri, int * iinr, int * jindex, int * jjnr, int * shift, real * shiftvec, real * fshift, int * gid, real * pos, real * faction, real * charge, real * p_facel, real * p_krf, real * p_crf, real * Vc, int * type, int * p_ntype, real * vdwparam, real * Vvdw, real * p_tabscale, real * VFtab,real * enerd1,real * enerd2,real * enerd3,real * enerd4,int * start,int * end,int * homenr,int * nbsum, real * invsqrta, real * dvda, real * p_gbtabscale, real * GBtab, int * p_nthreads, int * count, void * mtx, int * outeriter, int * inneriter, real * work) { int nri,ntype,nthreads; real facel,krf,crf,tabscale,gbtabscale; int n,ii,is3,ii3,k,nj0,nj1,jnr,j3,ggid; int nn0,nn1,nouter,ninner; real shX,shY,shZ; real qq,vcoul,vctot; int tj; real Vvdw6,Vvdwtot; real Vvdw12; real r,rt,eps,eps2; int n0,nnn; real Y,F,Geps,Heps2,Fp,VV; real ix1,iy1,iz1; real ix2,iy2,iz2; real ix3,iy3,iz3; real jx1,jy1,jz1; real jx2,jy2,jz2; real jx3,jy3,jz3; real dx11,dy11,dz11,rsq11,rinv11; real dx12,dy12,dz12,rsq12,rinv12; real dx13,dy13,dz13,rsq13,rinv13; real dx21,dy21,dz21,rsq21,rinv21; real dx22,dy22,dz22,rsq22,rinv22; real dx23,dy23,dz23,rsq23,rinv23; real dx31,dy31,dz31,rsq31,rinv31; real dx32,dy32,dz32,rsq32,rinv32; real dx33,dy33,dz33,rsq33,rinv33; real qO,qH,qqOO,qqOH,qqHH; real c6,c12; nri = *p_nri; ntype = *p_ntype; nthreads = *p_nthreads; facel = *p_facel; krf = *p_krf; crf = *p_crf; tabscale = *p_tabscale; /* Initialize water data */ ii = iinr[0]; qO = charge[ii]; qH = charge[ii+1]; qqOO = facel*qO*qO; qqOH = facel*qO*qH; qqHH = facel*qH*qH; tj = 2*(ntype+1)*type[ii]; c6 = vdwparam[tj]; c12 = vdwparam[tj+1]; /* Reset outer and inner iteration counters */ nouter = 0; ninner = 0; /* Loop over thread workunits */ do { #ifdef GMX_THREADS gmx_thread_mutex_lock((gmx_thread_mutex_t *)mtx); nn0 = *count; /* Take successively smaller chunks (at least 10 lists) */ nn1 = nn0+(nri-nn0)/(2*nthreads)+10; *count = nn1; gmx_thread_mutex_unlock((gmx_thread_mutex_t *)mtx); if(nn1>nri) nn1=nri; #else nn0 = 0; nn1 = nri; #endif /* Start outer loop over neighborlists */ for(n=nn0; (n<nn1); n++) { /* Load shift vector for this list */ is3 = 3*shift[n]; shX = shiftvec[is3]; shY = shiftvec[is3+1]; shZ = shiftvec[is3+2]; /* Load limits for loop over neighbors */ nj0 = jindex[n]; nj1 = jindex[n+1]; /* Get outer coordinate index */ ii = iinr[n]; ii3 = 3*ii; /* Load i atom data, add shift vector */ ix1 = shX + pos[ii3+0]; iy1 = shY + pos[ii3+1]; iz1 = shZ + pos[ii3+2]; ix2 = shX + pos[ii3+3]; iy2 = shY + pos[ii3+4]; iz2 = shZ + pos[ii3+5]; ix3 = shX + pos[ii3+6]; iy3 = shY + pos[ii3+7]; iz3 = shZ + pos[ii3+8]; /* Zero the potential energy for this list */ vctot = 0; Vvdwtot = 0; /* Clear i atom forces */ for(k=nj0; (k<nj1); k++) { /* Get j neighbor index, and coordinate index */ jnr = jjnr[k]; j3 = 3*jnr; /* load j atom coordinates */ jx1 = pos[j3+0]; jy1 = pos[j3+1]; jz1 = pos[j3+2]; jx2 = pos[j3+3]; jy2 = pos[j3+4]; jz2 = pos[j3+5]; jx3 = pos[j3+6]; jy3 = pos[j3+7]; jz3 = pos[j3+8]; /* Calculate distance */ dx11 = ix1 - jx1; dy11 = iy1 - jy1; dz11 = iz1 - jz1; rsq11 = dx11*dx11+dy11*dy11+dz11*dz11; dx12 = ix1 - jx2; dy12 = iy1 - jy2; dz12 = iz1 - jz2; rsq12 = dx12*dx12+dy12*dy12+dz12*dz12; dx13 = ix1 - jx3; dy13 = iy1 - jy3; dz13 = iz1 - jz3; rsq13 = dx13*dx13+dy13*dy13+dz13*dz13; dx21 = ix2 - jx1; dy21 = iy2 - jy1; dz21 = iz2 - jz1; rsq21 = dx21*dx21+dy21*dy21+dz21*dz21; dx22 = ix2 - jx2; dy22 = iy2 - jy2; dz22 = iz2 - jz2; rsq22 = dx22*dx22+dy22*dy22+dz22*dz22; dx23 = ix2 - jx3; dy23 = iy2 - jy3; dz23 = iz2 - jz3; rsq23 = dx23*dx23+dy23*dy23+dz23*dz23; dx31 = ix3 - jx1; dy31 = iy3 - jy1; dz31 = iz3 - jz1; rsq31 = dx31*dx31+dy31*dy31+dz31*dz31; dx32 = ix3 - jx2; dy32 = iy3 - jy2; dz32 = iz3 - jz2; rsq32 = dx32*dx32+dy32*dy32+dz32*dz32; dx33 = ix3 - jx3; dy33 = iy3 - jy3; dz33 = iz3 - jz3; rsq33 = dx33*dx33+dy33*dy33+dz33*dz33; /* Calculate 1/r and 1/r2 */ rinv11 = invsqrt(rsq11); rinv12 = invsqrt(rsq12); rinv13 = invsqrt(rsq13); rinv21 = invsqrt(rsq21); rinv22 = invsqrt(rsq22); rinv23 = invsqrt(rsq23); rinv31 = invsqrt(rsq31); rinv32 = invsqrt(rsq32); rinv33 = invsqrt(rsq33); /* Load parameters for j atom */ qq = qqOO; /* Coulomb interaction */ vcoul = qq*rinv11; vctot = vctot+vcoul; /* Calculate table index */ r = rsq11*rinv11; /* Calculate table index */ rt = r*tabscale; n0 = rt; eps = rt-n0; eps2 = eps*eps; nnn = 8*n0; /* Tabulated VdW interaction - dispersion */ Y = VFtab[nnn]; F = VFtab[nnn+1]; Geps = eps*VFtab[nnn+2]; Heps2 = eps2*VFtab[nnn+3]; Fp = F+Geps+Heps2; VV = Y+eps*Fp; Vvdw6 = c6*VV; /* Tabulated VdW interaction - repulsion */ nnn = nnn+4; Y = VFtab[nnn]; F = VFtab[nnn+1]; Geps = eps*VFtab[nnn+2]; Heps2 = eps2*VFtab[nnn+3]; Fp = F+Geps+Heps2; VV = Y+eps*Fp; Vvdw12 = c12*VV; Vvdwtot = Vvdwtot+ Vvdw6 + Vvdw12; /* Load parameters for j atom */ qq = qqOH; /* Coulomb interaction */ vcoul = qq*rinv12; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqOH; /* Coulomb interaction */ vcoul = qq*rinv13; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqOH; /* Coulomb interaction */ vcoul = qq*rinv21; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqHH; /* Coulomb interaction */ vcoul = qq*rinv22; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqHH; /* Coulomb interaction */ vcoul = qq*rinv23; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqOH; /* Coulomb interaction */ vcoul = qq*rinv31; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqHH; /* Coulomb interaction */ vcoul = qq*rinv32; vctot = vctot+vcoul; /* Load parameters for j atom */ qq = qqHH; /* Coulomb interaction */ vcoul = qq*rinv33; vctot = vctot+vcoul; /* Inner loop uses 155 flops/iteration */ } /* Add i forces to mem and shifted force list */ /* Add potential energies to the group for this list */ ggid = gid[n]; Vc[ggid] = Vc[ggid] + vctot; Vvdw[ggid] = Vvdw[ggid] + Vvdwtot; /* Increment number of inner iterations */ ninner = ninner + nj1 - nj0; /* Outer loop uses 11 flops/iteration */ } /* Increment number of outer iterations */ nouter = nouter + nn1 - nn0; } while (nn1<nri); /* Write outer/inner iteration count to pointers */ *outeriter = nouter; *inneriter = ninner; }
aar2163/GROMACS
src/gmxlib/nonbonded/nb_kernel_c/nb_kernel132.c
C
gpl-2.0
35,960
/***************************************************************************** 1 Í·Îļþ°üº¬ *****************************************************************************/ #include "GmmInc.h" #include "GmmCasGlobal.h" #include "GmmCasTimer.h" #include "GmmCasSend.h" #include "GmmCasComm.h" #ifdef __cplusplus #if __cplusplus extern "C"{ #endif #endif /***************************************************************************** ЭÒéÕ»´òÓ¡´òµã·½Ê½ÏµÄ.CÎļþºê¶¨Òå *****************************************************************************/ /*lint -e767 ÐÞ¸ÄÈË:luojian 107747;¼ìÊÓÈË:sunshaohua65952;Ô­Òò:LOG·½°¸Éè¼ÆÐèÒª*/ #define THIS_FILE_ID PS_FILE_ID_GMM_CASTIMER_C /*lint +e767 ÐÞ¸ÄÈË:luojian 107747;¼ìÊÓÈË:sunshaohua*/ VOS_VOID GMM_TimReadyExpired(VOS_VOID) { VOS_UINT32 ulT3311Status; VOS_UINT32 ulT3302Status; if (GMM_DEREGISTERED_NORMAL_SERVICE == g_GmmGlobalCtrl.ucState) { gstGmmCasGlobalCtrl.GmmSrvState = GMM_IU_PMM_DETACHED; } else { gstGmmCasGlobalCtrl.GmmSrvState = GMM_AGB_GPRS_STANDBY; } /* WCDMAģʽ£¬ÓÉHSS 4100 V100R001´úÂë´¦Àí */ if (NAS_MML_NET_RAT_TYPE_WCDMA == NAS_MML_GetCurrNetRatType()) { /* ÔÚ×¢²á״̬,²¢ÇÒ·þÎñ״̬ÊÇ¿ÕÏÐ̬ʱ,Æô¶¯3312 */ if ((0x20 == (g_GmmGlobalCtrl.ucState & 0xF0)) && (GMM_FALSE == g_GmmGlobalCtrl.ucSigConFlg) && (GMM_TRUE != g_GmmRauCtrl.ucT3312ExpiredFlg )) { #if (FEATURE_LTE == FEATURE_ON) if (GMM_TIMER_T3312_FLG != (GMM_TIMER_T3312_FLG & g_GmmTimerMng.ulTimerRunMask)) { NAS_GMM_SndLmmTimerInfoNotify(GMM_TIMER_T3312, GMM_LMM_TIMER_START); } #endif Gmm_TimerStart(GMM_TIMER_T3312); } return; /* ²»Ðè´¦Àí·µ»Ø */ } if (GMM_DEREGISTERED_NORMAL_SERVICE == g_GmmGlobalCtrl.ucState) { gstGmmCasGlobalCtrl.GmmSrvState = GMM_IU_PMM_DETACHED; } else { ulT3311Status = NAS_GMM_QryTimerStatus(GMM_TIMER_T3311); ulT3302Status = NAS_GMM_QryTimerStatus(GMM_TIMER_T3302); if ((GMM_REGISTERED_ATTEMPTING_TO_UPDATE_MM == g_GmmGlobalCtrl.ucState) || (GMM_REGISTERED_ATTEMPTING_TO_UPDATE == g_GmmGlobalCtrl.ucState)) { if ((VOS_FALSE == ulT3311Status) && (VOS_FALSE == ulT3302Status)) { #if (FEATURE_LTE == FEATURE_ON) if (GMM_TIMER_T3312_FLG != (GMM_TIMER_T3312_FLG & g_GmmTimerMng.ulTimerRunMask)) { NAS_GMM_SndLmmTimerInfoNotify(GMM_TIMER_T3312, GMM_LMM_TIMER_START); } #endif Gmm_TimerStart(GMM_TIMER_T3312); } } else { if ((0x10 != (g_GmmGlobalCtrl.ucState & 0xF0)) && (GMM_REGISTERED_INITIATED != g_GmmGlobalCtrl.ucState)) { #if (FEATURE_LTE == FEATURE_ON) if (GMM_TIMER_T3312_FLG != (GMM_TIMER_T3312_FLG & g_GmmTimerMng.ulTimerRunMask)) { NAS_GMM_SndLmmTimerInfoNotify(GMM_TIMER_T3312, GMM_LMM_TIMER_START); } #endif Gmm_TimerStart(GMM_TIMER_T3312); } } gstGmmCasGlobalCtrl.GmmSrvState = GMM_AGB_GPRS_STANDBY; } NAS_GMM_SndGasInfoChangeReq(NAS_GSM_MASK_GSM_GMM_STATE); return; } VOS_VOID GMM_TimRauRspExpired(VOS_VOID) { gstGmmCasGlobalCtrl.ucRabmRauRspRcvdFlg = VOS_TRUE; /* ²»ÐèÒªµÈ´ýWRRµÄ»Ø¸´ÏûÏ¢£¬»òÕßÒѾ­ÊÕµ½WRRµÄ»Ø¸´ÏûÏ¢£¬½øÐÐRAUÁ÷³Ì½áÊøµÄÏàÓ¦´¦Àí */ if ( (VOS_FALSE == g_GmmInterRatInfoCtrl.ucRauCmpWaitInterRatCnfMsg) || (VOS_TRUE == g_GmmInterRatInfoCtrl.ucInterRatCnfMsgRcvdFlg)) { NAS_GMM_RauCompleteHandling(); } return; } #ifdef __cplusplus #if __cplusplus } #endif #endif
Honor8Dev/android_kernel_huawei_FRD-L04
drivers/vendor/hisi/modem/ps/nas/gu/src/Gmm/Src/GmmCasTimer.c
C
gpl-2.0
3,876
package com.example; import org.apache.coyote.http11.AbstractHttp11Protocol; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.vaadin.spring.EnableVaadin; import org.vaadin.spring.boot.EnableVaadinServlet; @Configuration @ComponentScan @EnableAutoConfiguration @EnableVaadin @EnableVaadinServlet public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean EmbeddedServletContainerCustomizer servletContainerCustomizer() { return servletContainer -> ((TomcatEmbeddedServletContainerFactory) servletContainer) .addConnectorCustomizers(connector -> { AbstractHttp11Protocol<?> httpProtocol = (AbstractHttp11Protocol<?>) connector.getProtocolHandler(); httpProtocol.setCompression("on"); httpProtocol.setCompressionMinSize(256); String mimeTypes = httpProtocol.getCompressableMimeTypes(); String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE + ",application/javascript"; httpProtocol.setCompressableMimeTypes(mimeTypesWithJson); }); } }
GJRTimmer/vaadin-security-template
src/main/java/com/example/Application.java
Java
gpl-2.0
1,698
 namespace UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.Proxy { using System; using System.Collections.Generic; using System.Text; using System.IO; using System.ServiceModel; using System.Runtime.Serialization; using UFSoft.UBF; using UFSoft.UBF.Exceptions; using UFSoft.UBF.Util.Context; using UFSoft.UBF.Service; using UFSoft.UBF.Service.Base ; [System.ServiceModel.ServiceContractAttribute(Namespace = "http://www.UFIDA.org", Name="UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.IReceivementImportBP")] public interface IReceivementImportBP { [ServiceKnownType(typeof(ApplicationContext))] [ServiceKnownType(typeof(PlatformContext))] [ServiceKnownType(typeof(ThreadContext))] [ServiceKnownType(typeof( UFSoft.UBF.Business.BusinessException))] [ServiceKnownType(typeof( UFSoft.UBF.Business.EntityNotExistException))] [ServiceKnownType(typeof( UFSoft.UBF.Business.AttributeInValidException))] [ServiceKnownType(typeof(UFSoft.UBF.Business.AttrsContainerException))] [ServiceKnownType(typeof(UFSoft.UBF.Exceptions.MessageBase))] [FaultContract(typeof(UFSoft.UBF.Service.ServiceLostException))] [FaultContract(typeof(UFSoft.UBF.Service.ServiceException))] [FaultContract(typeof(UFSoft.UBF.Service.ServiceExceptionDetail))] [FaultContract(typeof(ExceptionBase))] [FaultContract(typeof(Exception))] [OperationContract()] PublicDataTransObj.PublicReturnDTOData Do(IContext context, out IList<MessageBase> outMessages ,System.Int64 relationId); } [Serializable] public class ReceivementImportBPProxy : OperationProxyBase//, UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.Proxy.IReceivementImportBP { #region Fields private System.Int64 relationId ; #endregion #region Properties /// <summary> /// 相关表ID (该属性可为空,但有默认值) /// 标准收货单导入操作.Misc.相关表ID /// </summary> /// <value>System.Int64</value> public System.Int64 RelationId { get { return this.relationId; } set { this.relationId = value; } } #endregion #region Constructors public ReceivementImportBPProxy() { } #endregion #region Public Method public PublicDataTransObj.PublicReturnDTOData Do() { InitKeyList() ; PublicDataTransObj.PublicReturnDTOData result = (PublicDataTransObj.PublicReturnDTOData)InvokeAgent<UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.Proxy.IReceivementImportBP>(); return GetRealResult(result); } protected override object InvokeImplement<T>(T oChannel) { IContext context = ContextManager.Context; IReceivementImportBP channel = oChannel as IReceivementImportBP; if (channel != null) { return channel.Do(context, out returnMsgs, relationId); } return null; } #endregion //处理由于序列化导致的返回值接口变化,而进行返回值的实际类型转换处理. private PublicDataTransObj.PublicReturnDTOData GetRealResult(PublicDataTransObj.PublicReturnDTOData result) { return result ; } #region Init KeyList //初始化SKey集合--由于接口不一样.BP.SV都要处理 private void InitKeyList() { System.Collections.Hashtable dict = new System.Collections.Hashtable() ; } #endregion } }
amazingbow/yonyou
创业人/ChuangYeRen_Code/ChuangYeRenBillImportBP/BpAgent/ShipmentRelationBP/ReceivementImportBPAgent.cs
C#
gpl-2.0
3,461
package aufgabe3; import static org.junit.Assert.assertEquals; import org.junit.Test; import computergraphics.math.Vector3; public class ImplicitSphereTest { @Test public void testIsoValues() { ImplicitSphere sphere = new ImplicitSphere(1, new Vector3(1.0, 1.0, 1.0)); // blauer Punkt assertEquals(0.0, sphere.getIsoValueFor(new Vector3(2.0, 1.0, 1.0)), 0.1); // grauer Punkt assertEquals(1.0, sphere.getIsoValueFor(new Vector3(2.0, 2.0, 1.0)), 0.1); // weisser Punkt assertEquals(-0.5, sphere.getIsoValueFor(new Vector3(1.5, 0.5, 1.0)), 0.1); } }
cookiedragon/Computergrafik
Computergrafik/test/aufgabe3/ImplicitSphereTest.java
Java
gpl-2.0
588
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_18) on Tue Nov 02 13:16:29 CET 2010 --> <TITLE> ConfigChannelTag </TITLE> <META NAME="date" CONTENT="2010-11-02"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ConfigChannelTag"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigFileTag.html" title="class in com.redhat.rhn.frontend.configuration.tags"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConfigChannelTag.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.redhat.rhn.frontend.configuration.tags</FONT> <BR> Class ConfigChannelTag</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by ">TagSupport <IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by "><B>com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag</B> </PRE> <HR> <DL> <DT><PRE>public class <B>ConfigChannelTag</B><DT>extends TagSupport</DL> </PRE> <P> ConfigChannelTag <P> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#CENTRAL_ALT_KEY">CENTRAL_ALT_KEY</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#CENTRAL_HEADER_ICON">CENTRAL_HEADER_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#CENTRAL_LIST_ICON">CENTRAL_LIST_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#CHANNEL_URL">CHANNEL_URL</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#LOCAL_ALT_KEY">LOCAL_ALT_KEY</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#LOCAL_HEADER_ICON">LOCAL_HEADER_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#LOCAL_LIST_ICON">LOCAL_LIST_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#SANDBOX_ALT_KEY">SANDBOX_ALT_KEY</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#SANDBOX_HEADER_ICON">SANDBOX_HEADER_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#SANDBOX_LIST_ICON">SANDBOX_LIST_ICON</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#ConfigChannelTag()">ConfigChannelTag</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#doEndTag()">doEndTag</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#getAltKeyFor(java.lang.String)">getAltKeyFor</A></B>(java.lang.String&nbsp;type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the Header alt key for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods..</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#getHeaderIconFor(java.lang.String)">getHeaderIconFor</A></B>(java.lang.String&nbsp;type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the Header icon image path for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods..</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#getListIconFor(java.lang.String)">getListIconFor</A></B>(java.lang.String&nbsp;type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the list icon image path for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods..</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#makeConfigChannelUrl(java.lang.String)">makeConfigChannelUrl</A></B>(java.lang.String&nbsp;ccId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the URL to view a config channel This method may also be used with the el expression ${cfg:channelUrl(ccid)} This method is public static because EL functions defined in a TLD file, need to be public static methods..</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#release()">release</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#setId(java.lang.String)">setId</A></B>(java.lang.String&nbsp;val)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#setName(java.lang.String)">setName</A></B>(java.lang.String&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#setNolink(java.lang.String)">setNolink</A></B>(java.lang.String&nbsp;isNoLink)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html#setType(java.lang.String)">setType</A></B>(java.lang.String&nbsp;tp)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="CENTRAL_ALT_KEY"><!-- --></A><H3> CENTRAL_ALT_KEY</H3> <PRE> public static final java.lang.String <B>CENTRAL_ALT_KEY</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.CENTRAL_ALT_KEY">Constant Field Values</A></DL> </DL> <HR> <A NAME="LOCAL_ALT_KEY"><!-- --></A><H3> LOCAL_ALT_KEY</H3> <PRE> public static final java.lang.String <B>LOCAL_ALT_KEY</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.LOCAL_ALT_KEY">Constant Field Values</A></DL> </DL> <HR> <A NAME="SANDBOX_ALT_KEY"><!-- --></A><H3> SANDBOX_ALT_KEY</H3> <PRE> public static final java.lang.String <B>SANDBOX_ALT_KEY</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.SANDBOX_ALT_KEY">Constant Field Values</A></DL> </DL> <HR> <A NAME="CENTRAL_LIST_ICON"><!-- --></A><H3> CENTRAL_LIST_ICON</H3> <PRE> public static final java.lang.String <B>CENTRAL_LIST_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.CENTRAL_LIST_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="LOCAL_LIST_ICON"><!-- --></A><H3> LOCAL_LIST_ICON</H3> <PRE> public static final java.lang.String <B>LOCAL_LIST_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.LOCAL_LIST_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="SANDBOX_LIST_ICON"><!-- --></A><H3> SANDBOX_LIST_ICON</H3> <PRE> public static final java.lang.String <B>SANDBOX_LIST_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.SANDBOX_LIST_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="CENTRAL_HEADER_ICON"><!-- --></A><H3> CENTRAL_HEADER_ICON</H3> <PRE> public static final java.lang.String <B>CENTRAL_HEADER_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.CENTRAL_HEADER_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="LOCAL_HEADER_ICON"><!-- --></A><H3> LOCAL_HEADER_ICON</H3> <PRE> public static final java.lang.String <B>LOCAL_HEADER_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.LOCAL_HEADER_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="SANDBOX_HEADER_ICON"><!-- --></A><H3> SANDBOX_HEADER_ICON</H3> <PRE> public static final java.lang.String <B>SANDBOX_HEADER_ICON</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.SANDBOX_HEADER_ICON">Constant Field Values</A></DL> </DL> <HR> <A NAME="CHANNEL_URL"><!-- --></A><H3> CHANNEL_URL</H3> <PRE> public static final java.lang.String <B>CHANNEL_URL</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../constant-values.html#com.redhat.rhn.frontend.configuration.tags.ConfigChannelTag.CHANNEL_URL">Constant Field Values</A></DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="ConfigChannelTag()"><!-- --></A><H3> ConfigChannelTag</H3> <PRE> public <B>ConfigChannelTag</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="doEndTag()"><!-- --></A><H3> doEndTag</H3> <PRE> public int <B>doEndTag</B>() throws JspException</PRE> <DL> <DD> <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>JspException</CODE></DL> </DD> </DL> <HR> <A NAME="release()"><!-- --></A><H3> release</H3> <PRE> public void <B>release</B>()</PRE> <DL> <DD> <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="setId(java.lang.String)"><!-- --></A><H3> setId</H3> <PRE> public void <B>setId</B>(java.lang.String&nbsp;val)</PRE> <DL> <DD><DL> <DT><B>Parameters:</B><DD><CODE>val</CODE> - the id to set</DL> </DD> </DL> <HR> <A NAME="setNolink(java.lang.String)"><!-- --></A><H3> setNolink</H3> <PRE> public void <B>setNolink</B>(java.lang.String&nbsp;isNoLink)</PRE> <DL> <DD><DL> <DT><B>Parameters:</B><DD><CODE>isNoLink</CODE> - the nolink to set</DL> </DD> </DL> <HR> <A NAME="setType(java.lang.String)"><!-- --></A><H3> setType</H3> <PRE> public void <B>setType</B>(java.lang.String&nbsp;tp)</PRE> <DL> <DD><DL> <DT><B>Parameters:</B><DD><CODE>tp</CODE> - the type to set</DL> </DD> </DL> <HR> <A NAME="setName(java.lang.String)"><!-- --></A><H3> setName</H3> <PRE> public void <B>setName</B>(java.lang.String&nbsp;value)</PRE> <DL> <DD><DL> <DT><B>Parameters:</B><DD><CODE>value</CODE> - the value to set</DL> </DD> </DL> <HR> <A NAME="makeConfigChannelUrl(java.lang.String)"><!-- --></A><H3> makeConfigChannelUrl</H3> <PRE> public static java.lang.String <B>makeConfigChannelUrl</B>(java.lang.String&nbsp;ccId)</PRE> <DL> <DD>Returns the URL to view a config channel This method may also be used with the el expression ${cfg:channelUrl(ccid)} This method is public static because EL functions defined in a TLD file, need to be public static methods.. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>ccId</CODE> - the id of the given Config Channel <DT><B>Returns:</B><DD>the URL to view a config channel</DL> </DD> </DL> <HR> <A NAME="getHeaderIconFor(java.lang.String)"><!-- --></A><H3> getHeaderIconFor</H3> <PRE> public static final java.lang.String <B>getHeaderIconFor</B>(java.lang.String&nbsp;type)</PRE> <DL> <DD>Returns the Header icon image path for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods.. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>type</CODE> - the config channel type <DT><B>Returns:</B><DD>the image path</DL> </DD> </DL> <HR> <A NAME="getListIconFor(java.lang.String)"><!-- --></A><H3> getListIconFor</H3> <PRE> public static final java.lang.String <B>getListIconFor</B>(java.lang.String&nbsp;type)</PRE> <DL> <DD>Returns the list icon image path for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods.. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>type</CODE> - the config channel type <DT><B>Returns:</B><DD>the image path</DL> </DD> </DL> <HR> <A NAME="getAltKeyFor(java.lang.String)"><!-- --></A><H3> getAltKeyFor</H3> <PRE> public static final java.lang.String <B>getAltKeyFor</B>(java.lang.String&nbsp;type)</PRE> <DL> <DD>Returns the Header alt key for a given channel type This method is public static because EL functions defined in a TLD file, need to be public static methods.. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>type</CODE> - the config channel type <DT><B>Returns:</B><DD>the alt key</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../../../../../../com/redhat/rhn/frontend/configuration/tags/ConfigFileTag.html" title="class in com.redhat.rhn.frontend.configuration.tags"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ConfigChannelTag.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
colloquium/spacewalk
documentation/javadoc/com/redhat/rhn/frontend/configuration/tags/ConfigChannelTag.html
HTML
gpl-2.0
25,451
(function($){ acf.fields.repeater = { // vars o : {}, el : '.acf-repeater', // el $field : null, $el : null, $clone : null, // functions set : function( $field ){ // sel $el this.$field = $field; this.$el = $field.find( this.el ).first(); // find elements this.$clone = this.$el.find('> table > tbody > tr.clone'); // get options this.o = acf.get_data( this.$el ); // return this for chaining return this; }, count : function(){ return this.$el.find('> table > tbody > tr').length - 1; }, init : function(){ // vars var $field = this.$field; // sortable if( this.o.max != 1 ) { this.$el.find('> table > tbody').unbind('sortable').sortable({ items : '> tr', handle : '> td.order', forceHelperSize : true, forcePlaceholderSize : true, scroll : true, start : function (event, ui) { acf.do_action('sortstart', ui.item, ui.placeholder); }, stop : function (event, ui) { acf.do_action('sortstop', ui.item, ui.placeholder); // render acf.fields.repeater.set( $field ).render(); } }); } // set column widths this.render_columns(); // disable clone inputs // Note: Previous attempted to check if input was already disabled, however the browser caches this attribute, // so a refresh would cause the code to fail. this.$clone.find('[name]').attr('disabled', 'disabled'); // render this.render(); }, render_columns : function(){ this.$el.find('.acf-table').each(function(){ // vars var $table = $(this); // validate if( ! $table.hasClass('table-layout') ) { return; } // accomodate for order / remove var column_width = 100; if( $table.find('> thead > tr > th.order').exists() ) { column_width = 93; } // find columns that already have a width and remove these amounts from the column_width var $table.find('> thead > tr > th[width]').each(function(){ column_width -= parseInt( $(this).attr('width') ); }); // selecotr var $selector = $table.find('> thead > tr > th.acf-th').not('[width]'); if( $selector.length > 1 ) { column_width = column_width / $selector.length; $selector.each(function( i ){ // dont add width to last th if( (i+1) == $selector.length ) { return; } $(this).attr('width', column_width + '%'); }); } }); }, render : function(){ // update order numbers this.$el.find('> table > tbody > tr').each(function(i){ $(this).children('td.order').html( i+1 ); }); // empty? if( this.count() == 0 ) { this.$el.addClass('empty'); } else { this.$el.removeClass('empty'); } // row limit reached if( this.o.max > 0 && this.count() >= this.o.max ) { this.$el.addClass('disabled'); this.$el.find('> .acf-hl .acf-button').addClass('disabled'); } else { this.$el.removeClass('disabled'); this.$el.find('> .acf-hl .acf-button').removeClass('disabled'); } }, add : function( $before ){ // vars var $field = this.$field; // validate if( this.o.max > 0 && this.count() >= this.o.max ) { alert( acf._e('repeater','max').replace('{max}', this.o.max) ); return false; } // create and add the new field var new_id = acf.get_uniqid(), html = this.$clone.outerHTML(); // replace acfcloneindex var html = html.replace(/(="[\w-\[\]]+?)(acfcloneindex)/g, '$1' + new_id), $html = $( html ); // remove clone class $html.removeClass('clone'); // enable inputs $html.find('[name]').removeAttr('disabled'); // add row if( !$before.exists() ) { $before = this.$clone; } $before.before( $html ); // trigger mouseenter on parent repeater to work out css margin on add-row button this.$field.parents('.acf-row').trigger('mouseenter'); // update order this.render(); // validation acf.validation.remove_error( this.$field ); // setup fields acf.do_action('append', $html); }, remove : function( $tr ){ // vars var $field = this.$field; // validate if( this.count() <= this.o.min ) { alert( acf._e('repeater','min').replace('{min}', this.o.min) ); return false; } // animate out tr acf.remove_tr( $tr, function(){ // trigger mouseenter on parent repeater to work out css margin on add-row button $field.closest('.acf-row').trigger('mouseenter'); // render acf.fields.repeater.set( $field ).render(); }); } }; /* * acf/setup_fields * * run init function on all elements for this field * * @type event * @date 20/07/13 * * @param {object} e event object * @param {object} el DOM object which may contain new ACF elements * @return N/A */ acf.add_action('ready append', function( $el ){ acf.get_fields({ type : 'repeater'}, $el).each(function(){ acf.fields.repeater.set( $(this) ).init(); }); }); /* * Events * * jQuery events for this field * * @type function * @date 1/03/2011 * * @param N/A * @return N/A */ $(document).on('click', '.acf-repeater .acf-repeater-add-row', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), $before = $(); if( $a.is('.acf-icon') ) { $before = $a.closest('.acf-row'); } // remove acf.fields.repeater.set( $field ).add( $before ); // blur $(this).blur(); }); $(document).on('click', '.acf-repeater .acf-repeater-remove-row', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), $tr = $a.closest('.acf-row'); // remove acf.fields.repeater.set( $field ).remove( $tr ); // blur $(this).blur(); }); $(document).on('mouseenter', '.acf-repeater .acf-row', function( e ){ // vars var $el = $(this).find('> td.remove .acf-repeater-add-row'), margin = ( $el.parent().height() / 2 ) + 9; // 9 = padding + border // css $el.css('margin-top', '-' + margin + 'px' ); }); /* * Flexible Content * * static model for this field * * @type event * @date 18/08/13 * */ acf.fields.flexible_content = { // vars o : {}, el : '.acf-flexible-content', // el $field : null, $el : null, $values : null, $clones : null, // functions set : function( $field ){ // sel $el this.$field = $field; this.$el = $field.find( this.el ).first(); // find elements this.$values = this.$el.children('.values'); this.$clones = this.$el.children('.clones'); // get options this.o = acf.get_data( this.$el ); // min / max this.o.min = this.o.min || 0; this.o.max = this.o.max || 0; // return this for chaining return this; }, count : function(){ return this.$values.children('.layout').length; }, init : function(){ // refernce var _this = this, $field = this.$field; // sortable if( this.o.max != 1 ) { this.$values.unbind('sortable').sortable({ items : '> .layout', handle : '> .acf-fc-layout-handle', forceHelperSize : true, forcePlaceholderSize : true, scroll : true, start : function (event, ui) { acf.do_action('sortstart', ui.item, ui.placeholder); }, stop : function (event, ui) { acf.do_action('sortstop', ui.item, ui.placeholder); // render _this.set( $field ).render(); } }); } // set column widths this.render_columns(); // disable clone inputs // Note: Previous attempted to check if input was already disabled, however the browser caches this attribute, // so a refresh would cause the code to fail. this.$clones.find('[name]').attr('disabled', 'disabled'); // render this.render(); }, render_columns : function(){ this.$el.find('.acf-table').each(function(){ // vars var $table = $(this); // validate if( ! $table.hasClass('table-layout') ) { return; } // accomodate for order / remove var column_width = 100; if( $table.find('> thead > tr > th.order').exists() ) { column_width = 93; } // find columns that already have a width and remove these amounts from the column_width var $table.find('> thead > tr > th[width]').each(function(){ column_width -= parseInt( $(this).attr('width') ); }); // selecotr var $selector = $table.find('> thead > tr > th.acf-th').not('[width]'); if( $selector.length > 1 ) { column_width = column_width / $selector.length; $selector.each(function( i ){ // dont add width to last th if( (i+1) == $selector.length ) { return; } $(this).attr('width', column_width + '%'); }); } }); }, render : function(){ // update order numbers this.$values.children('.layout').each(function( i ){ $(this).find('> .acf-fc-layout-handle .fc-layout-order').html( i+1 ); }); // empty? if( this.count() == 0 ) { this.$el.addClass('empty'); } else { this.$el.removeClass('empty'); } // row limit reached if( this.o.max > 0 && this.count() >= this.o.max ) { this.$el.addClass('disabled'); this.$el.find('> .acf-hl .acf-button').addClass('disabled'); } else { this.$el.removeClass('disabled'); this.$el.find('> .acf-hl .acf-button').removeClass('disabled'); } }, validate_add : function( layout ){ var r = true; // vadiate max if( this.o.max > 0 && this.count() >= this.o.max ) { var identifier = ( this.o.max == 1 ) ? 'layout' : 'layouts', s = acf._e('flexible_content', 'max'); // translate s = s.replace('{max}', this.o.max); s = s.replace('{identifier}', acf._e('flexible_content', identifier)); r = false; alert( s ); } // vadiate max layout var $popup = $( this.$el.children('.tmpl-popup').html() ), $a = $popup.find('[data-layout="' + layout + '"]'), layout_max = $a.attr('data-max'), layout_count = this.$values.children('.layout[data-layout="' + layout + '"]').length; layout_max = parseInt(layout_max); if( layout_max > 0 && layout_count >= layout_max ) { var identifier = ( layout_max == 1 ) ? 'layout' : 'layouts', s = acf._e('flexible_content', 'max_layout'); // translate s = s.replace('{max}', layout_count); s = s.replace('{label}', '"' + $a.text() + '"'); s = s.replace('{identifier}', acf._e('flexible_content', identifier)); r = false; alert( s ); } // return return r; }, validate_remove : function( layout ){ // vadiate min if( this.o.min > 0 && this.count() <= this.o.min ) { var identifier = ( this.o.min == 1 ) ? 'layout' : 'layouts', s = acf._e('flexible_content', 'min') + ', ' + acf._e('flexible_content', 'remove'); // translate s = s.replace('{min}', this.o.min); s = s.replace('{identifier}', acf._e('flexible_content', identifier)); s = s.replace('{layout}', acf._e('flexible_content', 'layout')); return confirm( s ); } // vadiate max layout var $popup = $( this.$el.children('.tmpl-popup').html() ), $a = $popup.find('[data-layout="' + layout + '"]'), layout_min = $a.attr('data-min'), layout_count = this.$values.children('.layout[data-layout="' + layout + '"]').length; layout_min = parseInt(layout_min); if( layout_min > 0 && layout_count <= layout_min ) { var identifier = ( layout_min == 1 ) ? 'layout' : 'layouts', s = acf._e('flexible_content', 'min_layout') + ', ' + acf._e('flexible_content', 'remove'); // translate s = s.replace('{min}', layout_count); s = s.replace('{label}', '"' + $a.text() + '"'); s = s.replace('{identifier}', acf._e('flexible_content', identifier)); s = s.replace('{layout}', acf._e('flexible_content', 'layout')); return confirm( s ); } // return return true; }, add : function( layout, $before ){ // bail early if validation fails if( !this.validate_add( layout ) ) { return; } // create and add the new field var new_id = acf.get_uniqid(), html = this.$clones.children('.layout[data-layout="' + layout + '"]').outerHTML(); // replace acfcloneindex var html = html.replace(/(="[\w-\[\]]+?)(acfcloneindex)/g, '$1' + new_id), $html = $( html ); // enable inputs $html.find('[name]').removeAttr('disabled'); // hide no values message this.$el.children('.no-value-message').hide(); // add row if( $before ) { $before.before( $html ); } else { this.$values.append( $html ); } // setup fields acf.do_action('append', $html); // update order this.render(); // validation acf.validation.remove_error( this.$field ); }, remove : function( $layout ){ // bail early if validation fails if( !this.validate_remove( $layout.attr('data-layout') ) ) { return; } // close field var end_height = 0, $message = this.$el.children('.no-value-message'); if( $layout.siblings('.layout').length == 0 ) { end_height = $message.outerHeight(); } // remove acf.remove_el( $layout, function(){ if( end_height > 0 ) { $message.show(); } }, end_height); }, toggle : function( $layout ){ if( $layout.attr('data-toggle') == 'closed' ) { $layout.attr('data-toggle', 'open'); $layout.children('.acf-input-table').show(); } else { $layout.attr('data-toggle', 'closed'); $layout.children('.acf-input-table').hide(); } // sync local storage (collapsed) this.sync(); }, sync : function(){ // vars var name = 'acf_collapsed_' + acf.get_data(this.$field, 'key'), collapsed = []; this.$values.children('.layout').each(function( i ){ if( $(this).attr('data-toggle') == 'closed' ) { collapsed.push( i ); } }); acf.update_cookie( name, collapsed.join('|') ); }, open_popup : function( $a, in_layout ){ // reference var _this = this; // defaults in_layout = in_layout || false; // vars var $popup = $( this.$el.children('.tmpl-popup').html() ); $popup.find('a').each(function(){ // vars var min = parseInt( $(this).attr('data-min') ), max = parseInt( $(this).attr('data-max') ), name = $(this).attr('data-layout'), label = $(this).text(), count = _this.$values.children('.layout[data-layout="' + name + '"]').length, $status = $(this).children('.status'); if( max > 0 ) { // find diff var available = max - count, s = acf.l10n.flexible_content.available, identifier = ( available == 1 ) ? 'layout' : 'layouts', // translate s = s.replace('{available}', available); s = s.replace('{max}', max); s = s.replace('{label}', '"' + label + '"'); s = s.replace('{identifier}', acf.l10n.flexible_content[ identifier ]); $status.show().text( available ).attr('title', s); // limit reached? if( available == 0 ) { $status.addClass('warning'); } } if( min > 0 ) { // find diff var required = min - count, s = acf.l10n.flexible_content.required, identifier = ( required == 1 ) ? 'layout' : 'layouts', // translate s = s.replace('{required}', required); s = s.replace('{min}', min); s = s.replace('{label}', '"' + label + '"'); s = s.replace('{identifier}', acf.l10n.flexible_content[ identifier ]); if( required > 0 ) { $status.addClass('warning').show().text( required ).attr('title', s); } } }); // add popup $a.after( $popup ); // within layout? if( in_layout ) { $popup.addClass('within-layout'); $popup.closest('.layout').addClass('popup-open'); } // vars $popup.css({ 'margin-top' : 0 - $popup.height() - $a.outerHeight() - 14, 'margin-left' : ( $a.outerWidth() - $popup.width() ) / 2, }); // check distance to top var offset = $popup.offset().top; if( offset < 30 ) { $popup.css({ 'margin-top' : 15 }); $popup.find('.bit').addClass('top'); } $popup.children('.focus').trigger('focus'); } }; /* * acf/setup_fields * * run init function on all elements for this field * * @type event * @date 20/07/13 * * @param {object} e event object * @param {object} el DOM object which may contain new ACF elements * @return N/A */ acf.add_action('ready append', function( $el ){ acf.get_fields({ type : 'flexible_content'}, $el).each(function(){ acf.fields.flexible_content.set( $(this) ).init(); }); }); /* * Events * * jQuery events for this field * * @type function * @date 1/03/2011 * * @param N/A * @return N/A */ $(document).on('click', '.acf-flexible-content .acf-fc-add', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), before = false; // before if( $(this).attr('data-before') ) { before = true; } // open_popup acf.fields.flexible_content.set( $field ).open_popup( $a, before ); // blur $(this).blur(); }); $(document).on('click', '.acf-flexible-content .acf-fc-remove', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), $layout = $a.closest('.layout'); // remove acf.fields.flexible_content.set( $field ).remove( $layout ); // blur $(this).blur(); }); $(document).on('click', '.acf-flexible-content .acf-fc-layout-handle', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), $layout = $a.closest('.layout'); // toggle acf.fields.flexible_content.set( $field ).toggle( $layout ); // blur $(this).blur(); }); $(document).on('click', '.acf-flexible-content .acf-fc-popup li a', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ), $popup = $a.closest('.acf-fc-popup') $layout = null; // $layout if( $popup.hasClass('within-layout') ) { $layout = $popup.closest('.layout'); } // add acf.fields.flexible_content.set( $field ).add( $a.attr('data-layout'), $layout ); // blur $(this).blur(); }); $(document).on('blur', '.acf-flexible-content .acf-fc-popup .focus', function( e ){ var $popup = $(this).parent(); // hide controlls? if( $popup.closest('.layout').exists() ) { $popup.closest('.layout').removeClass('popup-open'); } setTimeout(function(){ $popup.remove(); }, 200); }); /* * Validate * * jQuery events for this field * * @type function * @date 1/03/2011 * * @param N/A * @return N/A */ $(document).on('acf/validate_field', function( e, field ){ // vars var $field = $( field ); // validate if( ! $field.hasClass('field_type-flexible_content') ) { return; } var $el = $field.find('.acf-flexible-content:first'); // required $field.data('validation', false); $field.data('validation_message', false); if( $el.children('.values').children('.layout').exists() ) { $field.data('validation', true); } // min total var min = parseInt( $el.attr('data-min') ); if( min > 0 ) { if( $el.children('.values').children('.layout').length < min ) { var identifier = ( min == 1 ) ? 'layout' : 'layouts', s = acf.l10n.flexible_content.min; // translate s = s.replace('{min}', min); s = s.replace('{identifier}', acf.l10n.flexible_content[ identifier ]); $field.data('validation', false); $field.data('validation_message', s); } } // min layout var $popup = $( $el.children('.tmpl-popup').html() ); $popup.find('a').each(function(){ // vars var min = parseInt( $(this).attr('data-min') ), max = parseInt( $(this).attr('data-max') ), name = $(this).attr('data-layout'), label = $(this).text(), count = $el.children('.values').children('.layout[data-layout="' + name + '"]').length; if( count < min ) { var identifier = ( min == 1 ) ? 'layout' : 'layouts', s = acf.l10n.flexible_content.min_layout; // translate s = s.replace('{min}', min); s = s.replace('{label}', '"' + label + '"'); s = s.replace('{identifier}', acf.l10n.flexible_content[ identifier ]); $field.data('validation', false); $field.data('validation_message', s); } }); }); /* * Gallery * * static model for this field * * @type event * @date 18/08/13 * */ acf.fields.gallery = { // vars o : {}, el : '.acf-gallery', // el $field : null, $el : null, // functions set : function( $field ){ // sel $el this.$field = $field; this.$el = $field.find( this.el ).first(); // get options this.o = acf.get_data( this.$el ); // min / max this.o.min = this.o.min || 0; this.o.max = this.o.max || 0; // return this for chaining return this; }, count : function(){ return this.$el.find('.acf-gallery-attachment').length; }, init : function(){ // sortable this.$el.find('.acf-gallery-attachments').unbind('sortable').sortable({ items : '.acf-gallery-attachment', forceHelperSize : true, forcePlaceholderSize : true, scroll : true, start : function (event, ui) { ui.placeholder.html( ui.item.html() ); ui.placeholder.removeAttr('style'); acf.do_action('sortstart', ui.item, ui.placeholder); }, stop : function (event, ui) { acf.do_action('sortstop', ui.item, ui.placeholder); } }); // render this.render(); // resize this.resize(); }, render : function() { // vars var $select = this.$el.find('[data-name="bulk-actions-select"]'), $a = this.$el.find('[data-name="add-attachment-button"]'); // disable select if( this.o.max > 0 && this.count() >= this.o.max ) { $a.addClass('disabled'); } else { $a.removeClass('disabled'); } }, sort : function( sort ){ // vars var $el = this.$el; // validate if( !sort ) { return; } // vars var data = { action : 'acf/fields/gallery/get_sort_order', field_key : acf.get_data( this.$field, 'key' ), nonce : acf.get('nonce'), post_id : acf.get('post_id'), ids : [], sort : sort }; $el.find('.acf-gallery-attachment').each(function(){ data.ids.push( $(this).attr('data-id') ); }); // get results var xhr = $.ajax({ url : acf.get('ajaxurl'), dataType : 'json', type : 'get', cache : false, data : data, success : function( json ){ // validate if( !json.success ) { return; } // reverse order json.data.reverse(); _.each( json.data, function( id ) { var $attachment = $el.find('.acf-gallery-attachment[data-id="' + id + '"]'); $el.find('.acf-gallery-attachments').prepend( $attachment ); }); } }); }, clear_selection : function( $gallery ){ this.$el.find('.acf-gallery-attachment.active').removeClass('active'); }, select : function( $attachment ){ // vars var id = $attachment.attr('data-id'); // clear selection this.clear_selection(); // add selection $attachment.addClass('active'); // fetch this.fetch( id ); // open sidebar this.open_sidebar(); }, open_sidebar : function(){ this.$el.find('[data-name="bulk-actions-select"]').hide(); this.$el.find('.acf-gallery-main').animate({ right : 350 }, 250); this.$el.find('.acf-gallery-side').animate({ width : 349 }, 250); this.$el.find('.acf-gallery-attachment .acf-icon').addClass('small'); }, close_sidebar : function(){ // vars var $select = this.$el.find('[data-name="bulk-actions-select"]'); // deselect attachmnet this.clear_selection(); // disable sidebar this.$el.find('.acf-gallery-side').find('input, textarea, select').attr('disabled', 'disabled'); // animate this.$el.find('.acf-gallery-main').animate({ right : 0 }, 250); this.$el.find('.acf-gallery-side').animate({ width : 0 }, 250, function(){ $select.show(); $(this).find('.acf-gallery-side-data').html( '' ); }); this.$el.find('.acf-gallery-attachment .acf-icon').removeClass('small'); }, fetch : function( id ){ // reference var _this = this; // vars var data = { action : 'acf/fields/gallery/get_attachment', field_key : acf.get_data( this.$field, 'key' ), nonce : acf.get('nonce'), post_id : acf.get('post_id'), id : id }; // abort XHR if this field is already loading AJAX data if( this.$el.data('xhr') ) { this.$el.data('xhr').abort(); } // get results var xhr = $.ajax({ url : acf.get('ajaxurl'), dataType : 'html', type : 'get', cache : false, data : data, success : function( html ){ // validate if( !html ) { return; } _this.render_fetch( html ); } }); // update el data this.$el.data('xhr', xhr); }, render_fetch : function( html ){ // vars var $side = this.$el.find('.acf-gallery-side-data'); // render $side.html( html ); // remove acf form data $side.find('.compat-field-acf-form-data').remove(); // detach meta tr var $tr = $side.find('> .compat-attachment-fields > tbody > tr').detach(); // add tr $side.find('> table.form-table > tbody').append( $tr ); // remove origional meta table $side.find('> .compat-attachment-fields').remove(); // setup fields acf.do_action('append', $side); }, save : function(){ // vars var $a = this.$el.find('[data-name="save-attachment-button"]') $form = this.$el.find('.acf-gallery-side-data'), data = acf.serialize_form( $form ); // validate if( $a.attr('disabled') ) { return false; } // add attr $a.attr('disabled', 'disabled'); $a.before('<i class="acf-loading"></i>'); // append AJAX action data.action = 'acf/fields/gallery/update_attachment'; data.nonce = acf.get('nonce'); // ajax $.ajax({ url : acf.get('ajaxurl'), data : data, type : 'post', dataType : 'json', success : function( json ){ $a.removeAttr('disabled'); $a.prev('.acf-loading').remove(); } }); }, add : function( image ){ // validate if( this.o.max > 0 && this.count() >= this.o.max ) { acf.validation.add_warning( this.$field, acf._e('gallery', 'max')); return false; } // append to image data image.name = this.$el.find('[data-name="ids"]').attr('name'); // template var tmpl = acf._e('gallery', 'tmpl'), html = _.template(tmpl, image); // append this.$el.find('.acf-gallery-attachments').append( html ); // render this.render(); }, remove : function( id ){ // deselect attachmnet this.clear_selection(); // update sidebar this.$el.find('.acf-gallery-side-data').html(''); // remove image this.$el.find('.acf-gallery-attachment[data-id="' + id + '"]').remove(); // close sidebar if( this.count() == 0 ) { this.close_sidebar(); } // render this.render(); }, render_collection : function( frame, $el ){ // Note: Need to find a differen 'on' event. Now that attachments load custom fields, this function can't rely on a timeout. Instead, hook into a render function foreach item // set timeout for 0, then it will always run last after the add event setTimeout(function(){ // vars var $content = frame.content.get().$el collection = frame.content.get().collection || null; if( collection ) { var i = -1; collection.each(function( item ){ i++; var $li = $content.find('.attachments > .attachment:eq(' + i + ')'); // if image is already inside the gallery, disable it! if( $el.find('.acf-gallery-attachment[data-id="' + item.id + '"]').exists() ) { item.off('selection:single'); $li.addClass('acf-selected'); } }); } }, 10); }, popup : function(){ // validate if( this.o.max > 0 && this.count() >= this.o.max ) { acf.validation.add_warning( this.$field, acf._e('gallery', 'max')); return false; } // vars var library = this.o.library, preview_size = this.o.preview_size; // reference var $field = this.$field, $el = this.$el; // popup var frame = acf.media.upload_popup({ title : acf._e('gallery', 'select'), type : 'image', multiple : 1, uploadedTo : ( library == 'uploadedTo' ) ? acf.get('post_id') : 0, activate : function( frame ){ acf.fields.gallery.render_collection( frame, $el ); frame.content.get().collection.on( 'reset add', function(){ acf.fields.gallery.render_collection( frame, $el ); }); }, select : function( attachment, i ) { // is image already in gallery? if( $el.find('.acf-gallery-attachment[data-id="' + attachment.id + '"]').exists() ) { return; } // vars var image = { id : attachment.id, url : attachment.attributes.url }; // file? if( attachment.attributes.type != 'image' ) { image.url = attachment.attributes.icon; } // is preview size available? if( attachment.attributes.sizes && attachment.attributes.sizes[ preview_size ] ) { image.url = attachment.attributes.sizes[ preview_size ].url; } // add file to field acf.fields.gallery.set( $field ).add( image ); } }); }, resize : function(){ // vars var min = 100, max = 175, columns = 4, width = this.$el.width(); // get width for( var i = 0; i < 10; i++ ) { var w = width/i; if( min < w && w < max ) { columns = i; break; } } // update data this.$el.attr('data-columns', columns); } }; /* * acf/setup_fields * * run init function on all elements for this field * * @type event * @date 20/07/13 * * @param {object} e event object * @param {object} el DOM object which may contain new ACF elements * @return N/A */ acf.add_action('ready append', function( $el ){ acf.get_fields({ type : 'gallery'}, $el).each(function(){ acf.fields.gallery.set( $(this) ).init(); }); }); /* * Events * * jQuery events for this field * * @type function * @date 1/03/2011 * * @param N/A * @return N/A */ acf.add_action('submit', function( $el ){ acf.get_fields({ type : 'gallery'}, $el).each(function(){ acf.fields.gallery.set( $(this) ).close_sidebar(); }); }); $(window).on('resize', function(){ acf.get_fields({ type : 'gallery'}).each(function(){ acf.fields.gallery.set( $(this) ).resize(); }); }); $(document).on('click', '.acf-gallery .acf-gallery-attachment', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ); // select acf.fields.gallery.set( $field ).select( $a ); }); $(document).on('click', '.acf-gallery [data-name="close-attachment-button"]', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ); // close acf.fields.gallery.set( $field ).close_sidebar(); }); $(document).on('click', '.acf-gallery [data-name="save-attachment-button"]', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ); // save acf.fields.gallery.set( $field ).save(); }); $(document).on('click', '.acf-gallery [data-name="remove-attachment-button"]', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ); // remove acf.fields.gallery.set( $field ).remove( $a.attr('data-id') ); }); $(document).on('click', '.acf-gallery [data-name="add-attachment-button"]', function( e ){ e.preventDefault(); // vars var $a = $(this), $field = acf.get_field_wrap( $a ); // popup acf.fields.gallery.set( $field ).popup(); }); $(document).on('change', '.acf-gallery [data-name="bulk-actions-select"]', function( e ){ // vars var $select = $(this), $field = acf.get_field_wrap( $select ); // validate if( ! $select.val() ) { return false; } // sort acf.fields.gallery.set( $field ).sort( $select.val() ); // reset value $(this).val(''); }); })(jQuery);
Graulf/LIA_wordpress
wp-content/plugins/acf5-beta-master/pro/js/pro-input.js
JavaScript
gpl-2.0
35,138
<div class="container-fluid orangish"> <div class="container"> <div class="row"> <ul class="nav nav-justified secondary-nav menu dropit"> <li id="evaluation" class="col-xs dropit-trigger dropit-open" ng-class="{active: getAreasOfFocusValue() == 'Evaluation Capacity Building'}"> <a href="#" ng-click="setAreasOfFocus('Evaluation Capacity Building'); searchResources();"> Evaluation Capacity Building </a> </li> <li id="systems" class="col-xs" ng-class="{active: areasOfFocus == 'Systems-Oriented Evaluation'}"> <a href="" ng-click="setAreasOfFocus('Systems-Oriented Evaluation'); searchResources();"> Systems - Oriented Evaluation</a> </li> <li id="sustainability" class="col-xs" ng-class="{active: areasOfFocus == 'Sustainable Communities'}"> <a href="" ng-click="setAreasOfFocus('Sustainable Communities'); searchResources();"> Sustainability </a> </li> <li id="inclusiveness" class="col-xs" ng-class="{active: areasOfFocus == 'Inclusiveness and Equity'}"> <a href="" ng-click="setAreasOfFocus('Inclusiveness and Equity'); searchResources();"> Inclusiveness Equity </a> </li> </ul> </div> </div> </div>
javierdlahoz/wp-angular-material
wp-content/themes/wp-angular-material/resources-nav.html
HTML
gpl-2.0
1,318
/* arch/arm/mach-omap2/board-espresso10.h * * Copyright (C) 2011 Samsung Electronics Co, Ltd. * * Based on mach-omap2/board-espresso.h * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. */ #ifndef __BOARD_ESPRESSO10_H__ #define __BOARD_ESPRESSO10_H__ #include <linux/serial_core.h> extern struct class *sec_class; /* GT-P5100 / GT-P5110 / GT-5113 */ /* Reference Device */ #define SEC_MACHINE_ESPRESSO10 0x02 /* Non-Modem Device */ #define SEC_MACHINE_ESPRESSO10_WIFI 0x04 /* Non-Modem Device for Best Buy */ #define SEC_MACHINE_ESPRESSO10_USA_BBY 0x06 enum espresso10_adc_ch { REMOTE_SENSE = 0, ADC_CHECK_1, /* TA detection */ ACCESSORY_ID, /* OTG detection */ EAR_ADC_35, /* Earjack detection */ }; /** @category common */ unsigned int omap4_espresso10_get_board_type(void); /** @category LCD, HDMI */ void omap4_espresso10_display_init(void); void omap4_espresso10_display_early_init(void); void omap4_espresso10_memory_display_init(void); /** @category Key, TSP, Touch-Key */ void omap4_espresso10_input_init(void); void omap4_espresso10_tsp_ta_detect(int); /** @category Jack, Dock */ void omap4_espresso10_jack_init(void); /** @category Charger, Battery */ void omap4_espresso10_power_init(void); /** @category Motion Sensor */ void omap4_espresso10_sensors_init(void); void omap4_espresso_set_chager_type(int type); /** @category mUSB-IC, USB-OTG */ void omap4_espresso10_connector_init(void); int omap4_espresso10_get_adc(enum espresso10_adc_ch ch); void omap4_espresso10_usb_detected(int cable_type); /** @category LPDDR2 */ void omap4_espresso10_emif_init(void); /** @category I2c, UART(GPS) */ void omap4_espresso10_serial_init(void); /** @category TWL6030, TWL6040 */ void omap4_espresso10_pmic_init(void); /** @category MMCHS, WiFi */ void omap4_espresso10_sdio_init(void); extern struct mmc_platform_data espresso10_wifi_data; /** @category WiFi */ void omap4_espresso10_wifi_init(void); /** @category Bluetooth */ void bcm_bt_lpm_exit_lpm_locked(struct uart_port *uport); /** @category charger */ void omap4_espresso10_charger_init(void); /** @category modem*/ void omap4_espresso10_none_modem_init(void); void check_jig_status(int status); void notify_dock_status(int status); #endif /* __BOARD_ESPRESSO_H__ */
andi34/android_kernel_samsung_espresso
arch/arm/mach-omap2/board-espresso10.h
C
gpl-2.0
2,665
<html lang="en"> <head> <title>Z80-Chars - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Z80-Syntax.html#Z80-Syntax" title="Z80 Syntax"> <link rel="next" href="Z80_002dRegs.html#Z80_002dRegs" title="Z80-Regs"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991-2015 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Z80-Chars"></a> <a name="Z80_002dChars"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Z80_002dRegs.html#Z80_002dRegs">Z80-Regs</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Z80-Syntax.html#Z80-Syntax">Z80 Syntax</a> <hr> </div> <h5 class="subsubsection">9.53.2.1 Special Characters</h5> <p><a name="index-line-comment-character_002c-Z80-2505"></a><a name="index-Z80-line-comment-character-2506"></a>The semicolon `<samp><span class="samp">;</span></samp>' is the line comment character; <p>If a `<samp><span class="samp">#</span></samp>' appears as the first character of a line then the whole line is treated as a comment, but in this case the line could also be a logical line number directive (see <a href="Comments.html#Comments">Comments</a>) or a preprocessor control command (see <a href="Preprocessing.html#Preprocessing">Preprocessing</a>). <p><a name="index-line-separator_002c-Z80-2507"></a><a name="index-statement-separator_002c-Z80-2508"></a><a name="index-Z80-line-separator-2509"></a>The Z80 assembler does not support a line separator character. <p><a name="index-location-counter_002c-Z80-2510"></a><a name="index-hexadecimal-prefix_002c-Z80-2511"></a><a name="index-Z80-_0024-2512"></a>The dollar sign `<samp><span class="samp">$</span></samp>' can be used as a prefix for hexadecimal numbers and as a symbol denoting the current location counter. <p><a name="index-character-escapes_002c-Z80-2513"></a><a name="index-Z80_002c-_005c-2514"></a>A backslash `<samp><span class="samp">\</span></samp>' is an ordinary character for the Z80 assembler. <p><a name="index-character-constant_002c-Z80-2515"></a><a name="index-single-quote_002c-Z80-2516"></a><a name="index-Z80-_0027-2517"></a>The single quote `<samp><span class="samp">'</span></samp>' must be followed by a closing quote. If there is one character in between, it is a character constant, otherwise it is a string constant. </body></html>
jocelynmass/nrf51
toolchain/arm_cm0_deprecated/share/doc/gcc-arm-none-eabi/html/as.html/Z80_002dChars.html
HTML
gpl-2.0
3,527
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @bug 8008678 * @summary JSR 292: constant pool reconstitution must support pseudo strings * @library /testlibrary * @modules java.base/jdk.internal.misc * java.instrument * java.management * jdk.jartool/sun.tools.jar * @compile -XDignore.symbol.file TestLambdaFormRetransformation.java * @run main TestLambdaFormRetransformation */ import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.ProtectionDomain; import java.util.Arrays; import jdk.test.lib.ExitCode; import jdk.test.lib.OutputAnalyzer; import jdk.test.lib.ProcessTools; public class TestLambdaFormRetransformation { private static String MANIFEST = String.format("Manifest-Version: 1.0\n" + "Premain-Class: %s\n" + "Can-Retransform-Classes: true\n", Agent.class.getName()); private static String CP = System.getProperty("test.classes"); public static void main(String args[]) throws Throwable { Path agent = TestLambdaFormRetransformation.buildAgent(); OutputAnalyzer oa = ProcessTools.executeTestJvm("-javaagent:" + agent.toAbsolutePath().toString(), "-version"); oa.shouldHaveExitValue(ExitCode.OK.value); } private static Path buildAgent() throws IOException { Path manifest = TestLambdaFormRetransformation.createManifest(); Path jar = Files.createTempFile(Paths.get("."), null, ".jar"); String[] args = new String[] { "-cfm", jar.toAbsolutePath().toString(), manifest.toAbsolutePath().toString(), "-C", TestLambdaFormRetransformation.CP, Agent.class.getName() + ".class" }; sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); if (!jarTool.run(args)) { throw new Error("jar failed: args=" + Arrays.toString(args)); } return jar; } private static Path createManifest() throws IOException { Path manifest = Files.createTempFile(Paths.get("."), null, ".mf"); byte[] manifestBytes = TestLambdaFormRetransformation.MANIFEST.getBytes(); Files.write(manifest, manifestBytes); return manifest; } } class Agent implements ClassFileTransformer { private static Runnable lambda = () -> { System.out.println("I'll crash you!"); }; public static void premain(String args, Instrumentation instrumentation) { if (!instrumentation.isRetransformClassesSupported()) { System.out.println("Class retransformation is not supported."); return; } System.out.println("Calling lambda to ensure that lambda forms were created"); Agent.lambda.run(); System.out.println("Registering class file transformer"); instrumentation.addTransformer(new Agent()); for (Class c : instrumentation.getAllLoadedClasses()) { if (c.getName().contains("LambdaForm") && instrumentation.isModifiableClass(c)) { System.out.format("We've found a modifiable lambda form: %s%n", c.getName()); try { instrumentation.retransformClasses(c); } catch (UnmodifiableClassException e) { throw new AssertionError("Modification of modifiable class " + "caused UnmodifiableClassException", e); } } } } public static void main(String args[]) { } @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer ) throws IllegalClassFormatException { System.out.println("Transforming " + className); return classfileBuffer.clone(); } }
FauxFaux/jdk9-hotspot
test/serviceability/jvmti/TestLambdaFormRetransformation.java
Java
gpl-2.0
5,468
/* * libretroshare/src/serialiser: itempriorities.h * * 3P/PQI network interface for RetroShare. * * Copyright 2011-2011 by Cyril Soler * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License Version 2 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * Please report all bugs and problems to "csoler@users.sourceforge.net" * */ #pragma once #include <stdint.h> // This file centralises QoS priorities for all transfer RsItems. // const uint8_t QOS_PRIORITY_UNKNOWN = 0 ; const uint8_t QOS_PRIORITY_DEFAULT = 3 ; const uint8_t QOS_PRIORITY_TOP = 9 ; // Turtle traffic // const uint8_t QOS_PRIORITY_RS_TURTLE_OPEN_TUNNEL = 6 ; const uint8_t QOS_PRIORITY_RS_TURTLE_TUNNEL_OK = 6 ; const uint8_t QOS_PRIORITY_RS_TURTLE_SEARCH_REQUEST = 6 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_CRC_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_CHUNK_CRC_REQUEST= 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_MAP_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_SEARCH_RESULT = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_DATA = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_CRC = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_CHUNK_CRC = 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_MAP = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_GENERIC_ITEM = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FORWARD_FILE_DATA= 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_GENERIC_DATA = 5 ; // File transfer // const uint8_t QOS_PRIORITY_RS_FILE_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_FILE_CRC_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_CHUNK_CRC_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_FILE_MAP_REQUEST = 5 ; const uint8_t QOS_PRIORITY_RS_CACHE_REQUEST = 4 ; const uint8_t QOS_PRIORITY_RS_FILE_DATA = 3 ; const uint8_t QOS_PRIORITY_RS_FILE_CRC = 3 ; const uint8_t QOS_PRIORITY_RS_CHUNK_CRC = 5 ; const uint8_t QOS_PRIORITY_RS_FILE_MAP = 3 ; const uint8_t QOS_PRIORITY_RS_CACHE_ITEM = 3 ; // Discovery // const uint8_t QOS_PRIORITY_RS_DISC_HEART_BEAT = 8 ; const uint8_t QOS_PRIORITY_RS_DISC_ASK_INFO = 2 ; const uint8_t QOS_PRIORITY_RS_DISC_REPLY = 1 ; const uint8_t QOS_PRIORITY_RS_DISC_VERSION = 1 ; const uint8_t QOS_PRIORITY_RS_DISC_CONTACT = 2 ; // CONTACT and PGPLIST must have const uint8_t QOS_PRIORITY_RS_DISC_PGP_LIST = 2 ; // same priority. const uint8_t QOS_PRIORITY_RS_DISC_SERVICES = 2 ; const uint8_t QOS_PRIORITY_RS_DISC_PGP_CERT = 1 ; // Heartbeat. // const uint8_t QOS_PRIORITY_RS_HEARTBEAT_PULSE = 8 ; // Chat/Msgs // const uint8_t QOS_PRIORITY_RS_CHAT_ITEM = 7 ; const uint8_t QOS_PRIORITY_RS_CHAT_AVATAR_ITEM = 2 ; const uint8_t QOS_PRIORITY_RS_MSG_ITEM = 2 ; // depreciated. const uint8_t QOS_PRIORITY_RS_MAIL_ITEM = 2 ; // new mail service const uint8_t QOS_PRIORITY_RS_STATUS_ITEM = 2 ; // RTT // const uint8_t QOS_PRIORITY_RS_RTT_PING = 9 ; // BanList // const uint8_t QOS_PRIORITY_RS_BANLIST_ITEM = 2 ; // Bandwidth Control. // const uint8_t QOS_PRIORITY_RS_BWCTRL_ALLOWED_ITEM = 9 ; // Dsdv Routing // const uint8_t QOS_PRIORITY_RS_DSDV_ROUTE = 4 ; const uint8_t QOS_PRIORITY_RS_DSDV_DATA = 2 ; // GXS // const uint8_t QOS_PRIORITY_RS_GXS_NET = 3 ; // GXS Reputation. const uint8_t QOS_PRIORITY_RS_GXSREPUTATION_ITEM = 2; // Service Info / Control. const uint8_t QOS_PRIORITY_RS_SERVICE_INFO_ITEM = 7;
zeners/RetroShare
libretroshare/src/serialiser/itempriorities.h
C
gpl-2.0
4,201
/* * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "classfile/dictionary.hpp" #include "classfile/loaderConstraints.hpp" #include "classfile/placeholders.hpp" #include "classfile/sharedClassUtil.hpp" #include "classfile/symbolTable.hpp" #include "classfile/systemDictionary.hpp" #include "code/codeCache.hpp" #include "gc/shared/gcLocker.hpp" #include "interpreter/bytecodeStream.hpp" #include "interpreter/bytecodes.hpp" #include "memory/filemap.hpp" #include "memory/metaspace.hpp" #include "memory/metaspaceShared.hpp" #include "oops/objArrayOop.hpp" #include "oops/oop.inline.hpp" #include "runtime/os.hpp" #include "runtime/signature.hpp" #include "runtime/vmThread.hpp" #include "runtime/vm_operations.hpp" #include "utilities/hashtable.inline.hpp" PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC int MetaspaceShared::_max_alignment = 0; ReservedSpace* MetaspaceShared::_shared_rs = NULL; MetaspaceSharedStats MetaspaceShared::_stats; bool MetaspaceShared::_link_classes_made_progress; bool MetaspaceShared::_check_classes_made_progress; bool MetaspaceShared::_has_error_classes; bool MetaspaceShared::_archive_loading_failed = false; // Read/write a data stream for restoring/preserving metadata pointers and // miscellaneous data from/to the shared archive file. void MetaspaceShared::serialize(SerializeClosure* soc) { int tag = 0; soc->do_tag(--tag); // Verify the sizes of various metadata in the system. soc->do_tag(sizeof(Method)); soc->do_tag(sizeof(ConstMethod)); soc->do_tag(arrayOopDesc::base_offset_in_bytes(T_BYTE)); soc->do_tag(sizeof(ConstantPool)); soc->do_tag(sizeof(ConstantPoolCache)); soc->do_tag(objArrayOopDesc::base_offset_in_bytes()); soc->do_tag(typeArrayOopDesc::base_offset_in_bytes(T_BYTE)); soc->do_tag(sizeof(Symbol)); // Dump/restore miscellaneous metadata. Universe::serialize(soc, true); soc->do_tag(--tag); // Dump/restore references to commonly used names and signatures. vmSymbols::serialize(soc); soc->do_tag(--tag); soc->do_tag(666); } // CDS code for dumping shared archive. // Global object for holding classes that have been loaded. Since this // is run at a safepoint just before exit, this is the entire set of classes. static GrowableArray<Klass*>* _global_klass_objects; static void collect_classes(Klass* k) { _global_klass_objects->append_if_missing(k); if (k->oop_is_instance()) { // Add in the array classes too InstanceKlass* ik = InstanceKlass::cast(k); ik->array_klasses_do(collect_classes); } } static void remove_unshareable_in_classes() { for (int i = 0; i < _global_klass_objects->length(); i++) { Klass* k = _global_klass_objects->at(i); k->remove_unshareable_info(); } } static void rewrite_nofast_bytecode(Method* method) { RawBytecodeStream bcs(method); while (!bcs.is_last_bytecode()) { Bytecodes::Code opcode = bcs.raw_next(); switch (opcode) { case Bytecodes::_getfield: *bcs.bcp() = Bytecodes::_nofast_getfield; break; case Bytecodes::_putfield: *bcs.bcp() = Bytecodes::_nofast_putfield; break; case Bytecodes::_aload_0: *bcs.bcp() = Bytecodes::_nofast_aload_0; break; case Bytecodes::_iload: *bcs.bcp() = Bytecodes::_nofast_iload; break; default: break; } } } // Walk all methods in the class list to ensure that they won't be modified at // run time. This includes: // [1] Rewrite all bytecodes as needed, so that the ConstMethod* will not be modified // at run time by RewriteBytecodes/RewriteFrequentPairs // [2] Assign a fingerprint, so one doesn't need to be assigned at run-time. static void rewrite_nofast_bytecodes_and_calculate_fingerprints() { for (int i = 0; i < _global_klass_objects->length(); i++) { Klass* k = _global_klass_objects->at(i); if (k->oop_is_instance()) { InstanceKlass* ik = InstanceKlass::cast(k); for (int i = 0; i < ik->methods()->length(); i++) { Method* m = ik->methods()->at(i); rewrite_nofast_bytecode(m); Fingerprinter fp(m); // The side effect of this call sets method's fingerprint field. fp.fingerprint(); } } } } // Patch C++ vtable pointer in metadata. // Klass and other metadata objects contain references to c++ vtables in the // JVM library. // Fix them to point to our constructed vtables. However, don't iterate // across the space while doing this, as that causes the vtables to be // patched, undoing our useful work. Instead, iterate to make a list, // then use the list to do the fixing. // // Our constructed vtables: // Dump time: // 1. init_self_patching_vtbl_list: table of pointers to current virtual method addrs // 2. generate_vtable_methods: create jump table, appended to above vtbl_list // 3. patch_klass_vtables: for Klass list, patch the vtable entry in klass and // associated metadata to point to jump table rather than to current vtbl // Table layout: NOTE FIXED SIZE // 1. vtbl pointers // 2. #Klass X #virtual methods per Klass // 1 entry for each, in the order: // Klass1:method1 entry, Klass1:method2 entry, ... Klass1:method<num_virtuals> entry // Klass2:method1 entry, Klass2:method2 entry, ... Klass2:method<num_virtuals> entry // ... // Klass<vtbl_list_size>:method1 entry, Klass<vtbl_list_size>:method2 entry, // ... Klass<vtbl_list_size>:method<num_virtuals> entry // Sample entry: (Sparc): // save(sp, -256, sp) // ba,pt common_code // mov XXX, %L0 %L0 gets: Klass index <<8 + method index (note: max method index 255) // // Restore time: // 1. initialize_shared_space: reserve space for table // 2. init_self_patching_vtbl_list: update pointers to NEW virtual method addrs in text // // Execution time: // First virtual method call for any object of these metadata types: // 1. object->klass // 2. vtable entry for that klass points to the jump table entries // 3. branches to common_code with %O0/klass, %L0: Klass index <<8 + method index // 4. common_code: // Get address of new vtbl pointer for this Klass from updated table // Update new vtbl pointer in the Klass: future virtual calls go direct // Jump to method, using new vtbl pointer and method index static void* find_matching_vtbl_ptr(void** vtbl_list, void* new_vtable_start, void* obj) { void* old_vtbl_ptr = *(void**)obj; for (int i = 0; i < MetaspaceShared::vtbl_list_size; i++) { if (vtbl_list[i] == old_vtbl_ptr) { return (void**)new_vtable_start + i * MetaspaceShared::num_virtuals; } } ShouldNotReachHere(); return NULL; } // Assumes the vtable is in first slot in object. static void patch_klass_vtables(void** vtbl_list, void* new_vtable_start) { int n = _global_klass_objects->length(); for (int i = 0; i < n; i++) { Klass* obj = _global_klass_objects->at(i); // Note oop_is_instance() is a virtual call. After patching vtables // all virtual calls on the dummy vtables will restore the original! if (obj->oop_is_instance()) { InstanceKlass* ik = InstanceKlass::cast(obj); *(void**)ik = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, ik); ConstantPool* cp = ik->constants(); *(void**)cp = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, cp); for (int j = 0; j < ik->methods()->length(); j++) { Method* m = ik->methods()->at(j); *(void**)m = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, m); } } else { // Array klasses Klass* k = obj; *(void**)k = find_matching_vtbl_ptr(vtbl_list, new_vtable_start, k); } } } // Closure for serializing initialization data out to a data area to be // written to the shared file. class WriteClosure : public SerializeClosure { private: intptr_t* top; char* end; inline void check_space() { if ((char*)top + sizeof(intptr_t) > end) { report_out_of_shared_space(SharedMiscData); } } public: WriteClosure(char* md_top, char* md_end) { top = (intptr_t*)md_top; end = md_end; } char* get_top() { return (char*)top; } void do_ptr(void** p) { check_space(); *top = (intptr_t)*p; ++top; } void do_tag(int tag) { check_space(); *top = (intptr_t)tag; ++top; } void do_region(u_char* start, size_t size) { if ((char*)top + size > end) { report_out_of_shared_space(SharedMiscData); } assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); assert(size % sizeof(intptr_t) == 0, "bad size"); do_tag((int)size); while (size > 0) { *top = *(intptr_t*)start; ++top; start += sizeof(intptr_t); size -= sizeof(intptr_t); } } bool reading() const { return false; } }; // This is for dumping detailed statistics for the allocations // in the shared spaces. class DumpAllocClosure : public Metaspace::AllocRecordClosure { public: // Here's poor man's enum inheritance #define SHAREDSPACE_OBJ_TYPES_DO(f) \ METASPACE_OBJ_TYPES_DO(f) \ f(SymbolHashentry) \ f(SymbolBucket) \ f(Other) #define SHAREDSPACE_OBJ_TYPE_DECLARE(name) name ## Type, #define SHAREDSPACE_OBJ_TYPE_NAME_CASE(name) case name ## Type: return #name; enum Type { // Types are MetaspaceObj::ClassType, MetaspaceObj::SymbolType, etc SHAREDSPACE_OBJ_TYPES_DO(SHAREDSPACE_OBJ_TYPE_DECLARE) _number_of_types }; static const char * type_name(Type type) { switch(type) { SHAREDSPACE_OBJ_TYPES_DO(SHAREDSPACE_OBJ_TYPE_NAME_CASE) default: ShouldNotReachHere(); return NULL; } } public: enum { RO = 0, RW = 1 }; int _counts[2][_number_of_types]; int _bytes [2][_number_of_types]; int _which; DumpAllocClosure() { memset(_counts, 0, sizeof(_counts)); memset(_bytes, 0, sizeof(_bytes)); }; void iterate_metaspace(Metaspace* space, int which) { assert(which == RO || which == RW, "sanity"); _which = which; space->iterate(this); } virtual void doit(address ptr, MetaspaceObj::Type type, int byte_size) { assert(int(type) >= 0 && type < MetaspaceObj::_number_of_types, "sanity"); _counts[_which][type] ++; _bytes [_which][type] += byte_size; } void dump_stats(int ro_all, int rw_all, int md_all, int mc_all); }; void DumpAllocClosure::dump_stats(int ro_all, int rw_all, int md_all, int mc_all) { rw_all += (md_all + mc_all); // md and mc are all mapped Read/Write int other_bytes = md_all + mc_all; // Calculate size of data that was not allocated by Metaspace::allocate() MetaspaceSharedStats *stats = MetaspaceShared::stats(); // symbols _counts[RW][SymbolHashentryType] = stats->symbol.hashentry_count; _bytes [RW][SymbolHashentryType] = stats->symbol.hashentry_bytes; other_bytes -= stats->symbol.hashentry_bytes; _counts[RW][SymbolBucketType] = stats->symbol.bucket_count; _bytes [RW][SymbolBucketType] = stats->symbol.bucket_bytes; other_bytes -= stats->symbol.bucket_bytes; // TODO: count things like dictionary, vtable, etc _bytes[RW][OtherType] = other_bytes; // prevent divide-by-zero if (ro_all < 1) { ro_all = 1; } if (rw_all < 1) { rw_all = 1; } int all_ro_count = 0; int all_ro_bytes = 0; int all_rw_count = 0; int all_rw_bytes = 0; // To make fmt_stats be a syntactic constant (for format warnings), use #define. #define fmt_stats "%-20s: %8d %10d %5.1f | %8d %10d %5.1f | %8d %10d %5.1f" const char *sep = "--------------------+---------------------------+---------------------------+--------------------------"; const char *hdr = " ro_cnt ro_bytes % | rw_cnt rw_bytes % | all_cnt all_bytes %"; tty->print_cr("Detailed metadata info (rw includes md and mc):"); tty->print_cr("%s", hdr); tty->print_cr("%s", sep); for (int type = 0; type < int(_number_of_types); type ++) { const char *name = type_name((Type)type); int ro_count = _counts[RO][type]; int ro_bytes = _bytes [RO][type]; int rw_count = _counts[RW][type]; int rw_bytes = _bytes [RW][type]; int count = ro_count + rw_count; int bytes = ro_bytes + rw_bytes; double ro_perc = 100.0 * double(ro_bytes) / double(ro_all); double rw_perc = 100.0 * double(rw_bytes) / double(rw_all); double perc = 100.0 * double(bytes) / double(ro_all + rw_all); tty->print_cr(fmt_stats, name, ro_count, ro_bytes, ro_perc, rw_count, rw_bytes, rw_perc, count, bytes, perc); all_ro_count += ro_count; all_ro_bytes += ro_bytes; all_rw_count += rw_count; all_rw_bytes += rw_bytes; } int all_count = all_ro_count + all_rw_count; int all_bytes = all_ro_bytes + all_rw_bytes; double all_ro_perc = 100.0 * double(all_ro_bytes) / double(ro_all); double all_rw_perc = 100.0 * double(all_rw_bytes) / double(rw_all); double all_perc = 100.0 * double(all_bytes) / double(ro_all + rw_all); tty->print_cr("%s", sep); tty->print_cr(fmt_stats, "Total", all_ro_count, all_ro_bytes, all_ro_perc, all_rw_count, all_rw_bytes, all_rw_perc, all_count, all_bytes, all_perc); assert(all_ro_bytes == ro_all, "everything should have been counted"); assert(all_rw_bytes == rw_all, "everything should have been counted"); #undef fmt_stats } // Populate the shared space. class VM_PopulateDumpSharedSpace: public VM_Operation { private: ClassLoaderData* _loader_data; GrowableArray<Klass*> *_class_promote_order; VirtualSpace _md_vs; VirtualSpace _mc_vs; public: VM_PopulateDumpSharedSpace(ClassLoaderData* loader_data, GrowableArray<Klass*> *class_promote_order) : _loader_data(loader_data) { // Split up and initialize the misc code and data spaces ReservedSpace* shared_rs = MetaspaceShared::shared_rs(); size_t metadata_size = SharedReadOnlySize + SharedReadWriteSize; ReservedSpace shared_ro_rw = shared_rs->first_part(metadata_size); ReservedSpace misc_section = shared_rs->last_part(metadata_size); // Now split into misc sections. ReservedSpace md_rs = misc_section.first_part(SharedMiscDataSize); ReservedSpace mc_rs = misc_section.last_part(SharedMiscDataSize); _md_vs.initialize(md_rs, SharedMiscDataSize); _mc_vs.initialize(mc_rs, SharedMiscCodeSize); _class_promote_order = class_promote_order; } VMOp_Type type() const { return VMOp_PopulateDumpSharedSpace; } void doit(); // outline because gdb sucks private: void handle_misc_data_space_failure(bool success) { if (!success) { report_out_of_shared_space(SharedMiscData); } } }; // class VM_PopulateDumpSharedSpace void VM_PopulateDumpSharedSpace::doit() { Thread* THREAD = VMThread::vm_thread(); NOT_PRODUCT(SystemDictionary::verify();) // The following guarantee is meant to ensure that no loader constraints // exist yet, since the constraints table is not shared. This becomes // more important now that we don't re-initialize vtables/itables for // shared classes at runtime, where constraints were previously created. guarantee(SystemDictionary::constraints()->number_of_entries() == 0, "loader constraints are not saved"); guarantee(SystemDictionary::placeholders()->number_of_entries() == 0, "placeholders are not saved"); // Revisit and implement this if we prelink method handle call sites: guarantee(SystemDictionary::invoke_method_table() == NULL || SystemDictionary::invoke_method_table()->number_of_entries() == 0, "invoke method table is not saved"); // At this point, many classes have been loaded. // Gather systemDictionary classes in a global array and do everything to // that so we don't have to walk the SystemDictionary again. _global_klass_objects = new GrowableArray<Klass*>(1000); Universe::basic_type_classes_do(collect_classes); SystemDictionary::classes_do(collect_classes); tty->print_cr("Number of classes %d", _global_klass_objects->length()); { int num_type_array = 0, num_obj_array = 0, num_inst = 0; for (int i = 0; i < _global_klass_objects->length(); i++) { Klass* k = _global_klass_objects->at(i); if (k->oop_is_instance()) { num_inst ++; } else if (k->oop_is_objArray()) { num_obj_array ++; } else { assert(k->oop_is_typeArray(), "sanity"); num_type_array ++; } } tty->print_cr(" instance classes = %5d", num_inst); tty->print_cr(" obj array classes = %5d", num_obj_array); tty->print_cr(" type array classes = %5d", num_type_array); } // Ensure the ConstMethods won't be modified at run-time tty->print("Updating ConstMethods ... "); rewrite_nofast_bytecodes_and_calculate_fingerprints(); tty->print_cr("done. "); // Remove all references outside the metadata tty->print("Removing unshareable information ... "); remove_unshareable_in_classes(); tty->print_cr("done. "); // Set up the share data and shared code segments. char* md_low = _md_vs.low(); char* md_top = md_low; char* md_end = _md_vs.high(); char* mc_low = _mc_vs.low(); char* mc_top = mc_low; char* mc_end = _mc_vs.high(); // Reserve space for the list of Klass*s whose vtables are used // for patching others as needed. void** vtbl_list = (void**)md_top; int vtbl_list_size = MetaspaceShared::vtbl_list_size; Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size); md_top += vtbl_list_size * sizeof(void*); void* vtable = md_top; // Reserve space for a new dummy vtable for klass objects in the // heap. Generate self-patching vtable entries. MetaspaceShared::generate_vtable_methods(vtbl_list, &vtable, &md_top, md_end, &mc_top, mc_end); // Reorder the system dictionary. (Moving the symbols affects // how the hash table indices are calculated.) // Not doing this either. SystemDictionary::reorder_dictionary(); NOT_PRODUCT(SystemDictionary::verify();) // Copy the the symbol table, and the system dictionary to the shared // space in usable form. Copy the hashtable // buckets first [read-write], then copy the linked lists of entries // [read-only]. NOT_PRODUCT(SymbolTable::verify()); handle_misc_data_space_failure(SymbolTable::copy_compact_table(&md_top, md_end)); SystemDictionary::reverse(); SystemDictionary::copy_buckets(&md_top, md_end); ClassLoader::verify(); ClassLoader::copy_package_info_buckets(&md_top, md_end); ClassLoader::verify(); SystemDictionary::copy_table(&md_top, md_end); ClassLoader::verify(); ClassLoader::copy_package_info_table(&md_top, md_end); ClassLoader::verify(); // Write the other data to the output array. WriteClosure wc(md_top, md_end); MetaspaceShared::serialize(&wc); md_top = wc.get_top(); // Print shared spaces all the time // To make fmt_space be a syntactic constant (for format warnings), use #define. #define fmt_space "%s space: %9d [ %4.1f%% of total] out of %9d bytes [%4.1f%% used] at " INTPTR_FORMAT Metaspace* ro_space = _loader_data->ro_metaspace(); Metaspace* rw_space = _loader_data->rw_metaspace(); // Allocated size of each space (may not be all occupied) const size_t ro_alloced = ro_space->capacity_bytes_slow(Metaspace::NonClassType); const size_t rw_alloced = rw_space->capacity_bytes_slow(Metaspace::NonClassType); const size_t md_alloced = md_end-md_low; const size_t mc_alloced = mc_end-mc_low; const size_t total_alloced = ro_alloced + rw_alloced + md_alloced + mc_alloced; // Occupied size of each space. const size_t ro_bytes = ro_space->used_bytes_slow(Metaspace::NonClassType); const size_t rw_bytes = rw_space->used_bytes_slow(Metaspace::NonClassType); const size_t md_bytes = size_t(md_top - md_low); const size_t mc_bytes = size_t(mc_top - mc_low); // Percent of total size const size_t total_bytes = ro_bytes + rw_bytes + md_bytes + mc_bytes; const double ro_t_perc = ro_bytes / double(total_bytes) * 100.0; const double rw_t_perc = rw_bytes / double(total_bytes) * 100.0; const double md_t_perc = md_bytes / double(total_bytes) * 100.0; const double mc_t_perc = mc_bytes / double(total_bytes) * 100.0; // Percent of fullness of each space const double ro_u_perc = ro_bytes / double(ro_alloced) * 100.0; const double rw_u_perc = rw_bytes / double(rw_alloced) * 100.0; const double md_u_perc = md_bytes / double(md_alloced) * 100.0; const double mc_u_perc = mc_bytes / double(mc_alloced) * 100.0; const double total_u_perc = total_bytes / double(total_alloced) * 100.0; tty->print_cr(fmt_space, "ro", ro_bytes, ro_t_perc, ro_alloced, ro_u_perc, ro_space->bottom()); tty->print_cr(fmt_space, "rw", rw_bytes, rw_t_perc, rw_alloced, rw_u_perc, rw_space->bottom()); tty->print_cr(fmt_space, "md", md_bytes, md_t_perc, md_alloced, md_u_perc, md_low); tty->print_cr(fmt_space, "mc", mc_bytes, mc_t_perc, mc_alloced, mc_u_perc, mc_low); tty->print_cr("total : %9d [100.0%% of total] out of %9d bytes [%4.1f%% used]", total_bytes, total_alloced, total_u_perc); // Update the vtable pointers in all of the Klass objects in the // heap. They should point to newly generated vtable. patch_klass_vtables(vtbl_list, vtable); // dunno what this is for. char* saved_vtbl = (char*)os::malloc(vtbl_list_size * sizeof(void*), mtClass); memmove(saved_vtbl, vtbl_list, vtbl_list_size * sizeof(void*)); memset(vtbl_list, 0, vtbl_list_size * sizeof(void*)); // Create and write the archive file that maps the shared spaces. FileMapInfo* mapinfo = new FileMapInfo(); mapinfo->populate_header(MetaspaceShared::max_alignment()); // Pass 1 - update file offsets in header. mapinfo->write_header(); mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true); mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false); mapinfo->write_region(MetaspaceShared::md, _md_vs.low(), pointer_delta(md_top, _md_vs.low(), sizeof(char)), SharedMiscDataSize, false, false); mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(), pointer_delta(mc_top, _mc_vs.low(), sizeof(char)), SharedMiscCodeSize, true, true); // Pass 2 - write data. mapinfo->open_for_write(); mapinfo->set_header_crc(mapinfo->compute_header_crc()); mapinfo->write_header(); mapinfo->write_space(MetaspaceShared::ro, _loader_data->ro_metaspace(), true); mapinfo->write_space(MetaspaceShared::rw, _loader_data->rw_metaspace(), false); mapinfo->write_region(MetaspaceShared::md, _md_vs.low(), pointer_delta(md_top, _md_vs.low(), sizeof(char)), SharedMiscDataSize, false, false); mapinfo->write_region(MetaspaceShared::mc, _mc_vs.low(), pointer_delta(mc_top, _mc_vs.low(), sizeof(char)), SharedMiscCodeSize, true, true); mapinfo->close(); memmove(vtbl_list, saved_vtbl, vtbl_list_size * sizeof(void*)); os::free(saved_vtbl); if (PrintSharedSpaces) { DumpAllocClosure dac; dac.iterate_metaspace(_loader_data->ro_metaspace(), DumpAllocClosure::RO); dac.iterate_metaspace(_loader_data->rw_metaspace(), DumpAllocClosure::RW); dac.dump_stats(int(ro_bytes), int(rw_bytes), int(md_bytes), int(mc_bytes)); } #undef fmt_space } void MetaspaceShared::link_one_shared_class(Klass* obj, TRAPS) { Klass* k = obj; if (k->oop_is_instance()) { InstanceKlass* ik = (InstanceKlass*) k; // Link the class to cause the bytecodes to be rewritten and the // cpcache to be created. Class verification is done according // to -Xverify setting. _link_classes_made_progress |= try_link_class(ik, THREAD); guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); } } void MetaspaceShared::check_one_shared_class(Klass* k) { if (k->oop_is_instance() && InstanceKlass::cast(k)->check_sharing_error_state()) { _check_classes_made_progress = true; } } void MetaspaceShared::link_and_cleanup_shared_classes(TRAPS) { // We need to iterate because verification may cause additional classes // to be loaded. do { _link_classes_made_progress = false; SystemDictionary::classes_do(link_one_shared_class, THREAD); guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); } while (_link_classes_made_progress); if (_has_error_classes) { // Mark all classes whose super class or interfaces failed verification. do { // Not completely sure if we need to do this iteratively. Anyway, // we should come here only if there are unverifiable classes, which // shouldn't happen in normal cases. So better safe than sorry. _check_classes_made_progress = false; SystemDictionary::classes_do(check_one_shared_class); } while (_check_classes_made_progress); if (IgnoreUnverifiableClassesDuringDump) { // This is useful when running JCK or SQE tests. You should not // enable this when running real apps. SystemDictionary::remove_classes_in_error_state(); } else { tty->print_cr("Please remove the unverifiable classes from your class list and try again"); exit(1); } } } void MetaspaceShared::prepare_for_dumping() { ClassLoader::initialize_shared_path(); FileMapInfo::allocate_classpath_entry_table(); } // Preload classes from a list, populate the shared spaces and dump to a // file. void MetaspaceShared::preload_and_dump(TRAPS) { TraceTime timer("Dump Shared Spaces", TraceStartupTime); ResourceMark rm; tty->print_cr("Allocated shared space: %d bytes at " PTR_FORMAT, MetaspaceShared::shared_rs()->size(), MetaspaceShared::shared_rs()->base()); // Preload classes to be shared. // Should use some os:: method rather than fopen() here. aB. const char* class_list_path; if (SharedClassListFile == NULL) { // Construct the path to the class list (in jre/lib) // Walk up two directories from the location of the VM and // optionally tack on "lib" (depending on platform) char class_list_path_str[JVM_MAXPATHLEN]; os::jvm_path(class_list_path_str, sizeof(class_list_path_str)); for (int i = 0; i < 3; i++) { char *end = strrchr(class_list_path_str, *os::file_separator()); if (end != NULL) *end = '\0'; } int class_list_path_len = (int)strlen(class_list_path_str); if (class_list_path_len >= 3) { if (strcmp(class_list_path_str + class_list_path_len - 3, "lib") != 0) { if (class_list_path_len < JVM_MAXPATHLEN - 4) { jio_snprintf(class_list_path_str + class_list_path_len, sizeof(class_list_path_str) - class_list_path_len, "%slib", os::file_separator()); class_list_path_len += 4; } } } if (class_list_path_len < JVM_MAXPATHLEN - 10) { jio_snprintf(class_list_path_str + class_list_path_len, sizeof(class_list_path_str) - class_list_path_len, "%sclasslist", os::file_separator()); } class_list_path = class_list_path_str; } else { class_list_path = SharedClassListFile; } int class_count = 0; GrowableArray<Klass*>* class_promote_order = new GrowableArray<Klass*>(); // sun.io.Converters static const char obj_array_sig[] = "[[Ljava/lang/Object;"; SymbolTable::new_permanent_symbol(obj_array_sig, THREAD); // java.util.HashMap static const char map_entry_array_sig[] = "[Ljava/util/Map$Entry;"; SymbolTable::new_permanent_symbol(map_entry_array_sig, THREAD); tty->print_cr("Loading classes to share ..."); _has_error_classes = false; class_count += preload_and_dump(class_list_path, class_promote_order, THREAD); if (ExtraSharedClassListFile) { class_count += preload_and_dump(ExtraSharedClassListFile, class_promote_order, THREAD); } tty->print_cr("Loading classes to share: done."); if (PrintSharedSpaces) { tty->print_cr("Shared spaces: preloaded %d classes", class_count); } // Rewrite and link classes tty->print_cr("Rewriting and linking classes ..."); // Link any classes which got missed. This would happen if we have loaded classes that // were not explicitly specified in the classlist. E.g., if an interface implemented by class K // fails verification, all other interfaces that were not specified in the classlist but // are implemented by K are not verified. link_and_cleanup_shared_classes(CATCH); tty->print_cr("Rewriting and linking classes: done"); // Create and dump the shared spaces. Everything so far is loaded // with the null class loader. ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); VM_PopulateDumpSharedSpace op(loader_data, class_promote_order); VMThread::execute(&op); // Since various initialization steps have been undone by this process, // it is not reasonable to continue running a java process. exit(0); } int MetaspaceShared::preload_and_dump(const char * class_list_path, GrowableArray<Klass*>* class_promote_order, TRAPS) { FILE* file = fopen(class_list_path, "r"); char class_name[256]; int class_count = 0; if (file != NULL) { while ((fgets(class_name, sizeof class_name, file)) != NULL) { if (*class_name == '#') { // comment continue; } // Remove trailing newline size_t name_len = strlen(class_name); if (class_name[name_len-1] == '\n') { class_name[name_len-1] = '\0'; } // Got a class name - load it. TempNewSymbol class_name_symbol = SymbolTable::new_permanent_symbol(class_name, THREAD); guarantee(!HAS_PENDING_EXCEPTION, "Exception creating a symbol."); Klass* klass = SystemDictionary::resolve_or_null(class_name_symbol, THREAD); CLEAR_PENDING_EXCEPTION; if (klass != NULL) { if (PrintSharedSpaces && Verbose && WizardMode) { tty->print_cr("Shared spaces preloaded: %s", class_name); } InstanceKlass* ik = InstanceKlass::cast(klass); // Should be class load order as per -XX:+TraceClassLoadingPreorder class_promote_order->append(ik); // Link the class to cause the bytecodes to be rewritten and the // cpcache to be created. The linking is done as soon as classes // are loaded in order that the related data structures (klass and // cpCache) are located together. try_link_class(ik, THREAD); guarantee(!HAS_PENDING_EXCEPTION, "exception in link_class"); class_count++; } else { //tty->print_cr("Preload failed: %s", class_name); } } fclose(file); } else { char errmsg[JVM_MAXPATHLEN]; os::lasterror(errmsg, JVM_MAXPATHLEN); tty->print_cr("Loading classlist failed: %s", errmsg); exit(1); } return class_count; } // Returns true if the class's status has changed bool MetaspaceShared::try_link_class(InstanceKlass* ik, TRAPS) { assert(DumpSharedSpaces, "should only be called during dumping"); if (ik->init_state() < InstanceKlass::linked) { bool saved = BytecodeVerificationLocal; if (!SharedClassUtil::is_shared_boot_class(ik)) { // The verification decision is based on BytecodeVerificationRemote // for non-system classes. Since we are using the NULL classloader // to load non-system classes during dumping, we need to temporarily // change BytecodeVerificationLocal to be the same as // BytecodeVerificationRemote. Note this can cause the parent system // classes also being verified. The extra overhead is acceptable during // dumping. BytecodeVerificationLocal = BytecodeVerificationRemote; } ik->link_class(THREAD); if (HAS_PENDING_EXCEPTION) { ResourceMark rm; tty->print_cr("Preload Warning: Verification failed for %s", ik->external_name()); CLEAR_PENDING_EXCEPTION; ik->set_in_error_state(); _has_error_classes = true; } BytecodeVerificationLocal = saved; return true; } else { return false; } } // Closure for serializing initialization data in from a data area // (ptr_array) read from the shared file. class ReadClosure : public SerializeClosure { private: intptr_t** _ptr_array; inline intptr_t nextPtr() { return *(*_ptr_array)++; } public: ReadClosure(intptr_t** ptr_array) { _ptr_array = ptr_array; } void do_ptr(void** p) { assert(*p == NULL, "initializing previous initialized pointer."); intptr_t obj = nextPtr(); assert((intptr_t)obj >= 0 || (intptr_t)obj < -100, "hit tag while initializing ptrs."); *p = (void*)obj; } void do_tag(int tag) { int old_tag; old_tag = (int)(intptr_t)nextPtr(); // do_int(&old_tag); assert(tag == old_tag, "old tag doesn't match"); FileMapInfo::assert_mark(tag == old_tag); } void do_region(u_char* start, size_t size) { assert((intptr_t)start % sizeof(intptr_t) == 0, "bad alignment"); assert(size % sizeof(intptr_t) == 0, "bad size"); do_tag((int)size); while (size > 0) { *(intptr_t*)start = nextPtr(); start += sizeof(intptr_t); size -= sizeof(intptr_t); } } bool reading() const { return true; } }; // Return true if given address is in the mapped shared space. bool MetaspaceShared::is_in_shared_space(const void* p) { return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_space(p); } void MetaspaceShared::print_shared_spaces() { if (UseSharedSpaces) { FileMapInfo::current_info()->print_shared_spaces(); } } // Map shared spaces at requested addresses and return if succeeded. // Need to keep the bounds of the ro and rw space for the Metaspace::contains // call, or is_in_shared_space. bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) { size_t image_alignment = mapinfo->alignment(); #ifndef _WINDOWS // Map in the shared memory and then map the regions on top of it. // On Windows, don't map the memory here because it will cause the // mappings of the regions to fail. ReservedSpace shared_rs = mapinfo->reserve_shared_memory(); if (!shared_rs.is_reserved()) return false; #endif assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces"); char* _ro_base = NULL; char* _rw_base = NULL; char* _md_base = NULL; char* _mc_base = NULL; // Map each shared region if ((_ro_base = mapinfo->map_region(ro)) != NULL && mapinfo->verify_region_checksum(ro) && (_rw_base = mapinfo->map_region(rw)) != NULL && mapinfo->verify_region_checksum(rw) && (_md_base = mapinfo->map_region(md)) != NULL && mapinfo->verify_region_checksum(md) && (_mc_base = mapinfo->map_region(mc)) != NULL && mapinfo->verify_region_checksum(mc) && (image_alignment == (size_t)max_alignment()) && mapinfo->validate_classpath_entry_table()) { // Success (no need to do anything) return true; } else { // If there was a failure in mapping any of the spaces, unmap the ones // that succeeded if (_ro_base != NULL) mapinfo->unmap_region(ro); if (_rw_base != NULL) mapinfo->unmap_region(rw); if (_md_base != NULL) mapinfo->unmap_region(md); if (_mc_base != NULL) mapinfo->unmap_region(mc); #ifndef _WINDOWS // Release the entire mapped region shared_rs.release(); #endif // If -Xshare:on is specified, print out the error message and exit VM, // otherwise, set UseSharedSpaces to false and continue. if (RequireSharedSpaces || PrintSharedArchiveAndExit) { vm_exit_during_initialization("Unable to use shared archive.", "Failed map_region for using -Xshare:on."); } else { FLAG_SET_DEFAULT(UseSharedSpaces, false); } return false; } } // Read the miscellaneous data from the shared file, and // serialize it out to its various destinations. void MetaspaceShared::initialize_shared_spaces() { FileMapInfo *mapinfo = FileMapInfo::current_info(); char* buffer = mapinfo->region_base(md); // Skip over (reserve space for) a list of addresses of C++ vtables // for Klass objects. They get filled in later. void** vtbl_list = (void**)buffer; buffer += MetaspaceShared::vtbl_list_size * sizeof(void*); Universe::init_self_patching_vtbl_list(vtbl_list, vtbl_list_size); // Skip over (reserve space for) dummy C++ vtables Klass objects. // They are used as is. intptr_t vtable_size = *(intptr_t*)buffer; buffer += sizeof(intptr_t); buffer += vtable_size; // Create the shared symbol table using the bucket array at this spot in the // misc data space. (Todo: move this to read-only space. Currently // this is mapped copy-on-write but will never be written into). buffer = (char*)SymbolTable::init_shared_table(buffer); SymbolTable::create_table(); // Create the shared dictionary using the bucket array at this spot in // the misc data space. Since the shared dictionary table is never // modified, this region (of mapped pages) will be (effectively, if // not explicitly) read-only. int sharedDictionaryLen = *(intptr_t*)buffer; buffer += sizeof(intptr_t); int number_of_entries = *(intptr_t*)buffer; buffer += sizeof(intptr_t); SystemDictionary::set_shared_dictionary((HashtableBucket<mtClass>*)buffer, sharedDictionaryLen, number_of_entries); buffer += sharedDictionaryLen; // Create the package info table using the bucket array at this spot in // the misc data space. Since the package info table is never // modified, this region (of mapped pages) will be (effectively, if // not explicitly) read-only. int pkgInfoLen = *(intptr_t*)buffer; buffer += sizeof(intptr_t); number_of_entries = *(intptr_t*)buffer; buffer += sizeof(intptr_t); ClassLoader::create_package_info_table((HashtableBucket<mtClass>*)buffer, pkgInfoLen, number_of_entries); buffer += pkgInfoLen; ClassLoader::verify(); // The following data in the shared misc data region are the linked // list elements (HashtableEntry objects) for the shared dictionary // and package info table. int len = *(intptr_t*)buffer; // skip over shared dictionary entries buffer += sizeof(intptr_t); buffer += len; len = *(intptr_t*)buffer; // skip over package info table entries buffer += sizeof(intptr_t); buffer += len; len = *(intptr_t*)buffer; // skip over package info table char[] arrays. buffer += sizeof(intptr_t); buffer += len; intptr_t* array = (intptr_t*)buffer; ReadClosure rc(&array); serialize(&rc); // Close the mapinfo file mapinfo->close(); if (PrintSharedArchiveAndExit) { if (PrintSharedDictionary) { tty->print_cr("\nShared classes:\n"); SystemDictionary::print_shared(false); } if (_archive_loading_failed) { tty->print_cr("archive is invalid"); vm_exit(1); } else { tty->print_cr("archive is valid"); vm_exit(0); } } } // JVM/TI RedefineClasses() support: bool MetaspaceShared::remap_shared_readonly_as_readwrite() { assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); if (UseSharedSpaces) { // remap the shared readonly space to shared readwrite, private FileMapInfo* mapinfo = FileMapInfo::current_info(); if (!mapinfo->remap_shared_readonly_as_readwrite()) { return false; } } return true; } int MetaspaceShared::count_class(const char* classlist_file) { if (classlist_file == NULL) { return 0; } char class_name[256]; int class_count = 0; FILE* file = fopen(classlist_file, "r"); if (file != NULL) { while ((fgets(class_name, sizeof class_name, file)) != NULL) { if (*class_name == '#') { // comment continue; } class_count++; } fclose(file); } else { char errmsg[JVM_MAXPATHLEN]; os::lasterror(errmsg, JVM_MAXPATHLEN); tty->print_cr("Loading classlist failed: %s", errmsg); exit(1); } return class_count; } // the sizes are good for typical large applications that have a lot of shared // classes void MetaspaceShared::estimate_regions_size() { int class_count = count_class(SharedClassListFile); class_count += count_class(ExtraSharedClassListFile); if (class_count > LargeThresholdClassCount) { if (class_count < HugeThresholdClassCount) { SET_ESTIMATED_SIZE(Large, ReadOnly); SET_ESTIMATED_SIZE(Large, ReadWrite); SET_ESTIMATED_SIZE(Large, MiscData); SET_ESTIMATED_SIZE(Large, MiscCode); } else { SET_ESTIMATED_SIZE(Huge, ReadOnly); SET_ESTIMATED_SIZE(Huge, ReadWrite); SET_ESTIMATED_SIZE(Huge, MiscData); SET_ESTIMATED_SIZE(Huge, MiscCode); } } }
mohlerm/hotspot
src/share/vm/memory/metaspaceShared.cpp
C++
gpl-2.0
42,271
# SQL predicate clauses SQL where clause support 18 predicates ## Comparisons `=` equal to `<>` not equal to `<` less than `>` greater than `<=` less than or equal to `>=` greater than or equal to ## BETWEEN To give a range ## IN To check the value in a list ## LIKE A text pattern match ## IS NULL a value expression that is equal to `NULL`
digible/devible
databases/sql/sql-predicates.md
Markdown
gpl-2.0
350
package com.comphenix.protocol.injector.netty; import java.util.Set; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.concurrency.PacketTypeSet; import com.comphenix.protocol.events.ListenerOptions; import com.comphenix.protocol.injector.packet.PacketInjector; public abstract class AbstractPacketInjector implements PacketInjector { private PacketTypeSet reveivedFilters; public AbstractPacketInjector(PacketTypeSet reveivedFilters) { this.reveivedFilters = reveivedFilters; } @Override public boolean isCancelled(Object packet) { // No, it's never cancelled return false; } @Override public void setCancelled(Object packet, boolean cancelled) { throw new UnsupportedOperationException(); } @Override public boolean addPacketHandler(PacketType type, Set<ListenerOptions> options) { reveivedFilters.addType(type); return true; } @Override public boolean removePacketHandler(PacketType type) { reveivedFilters.removeType(type); return true; } @Override public boolean hasPacketHandler(PacketType type) { return reveivedFilters.contains(type); } @Override public Set<PacketType> getPacketHandlers() { return reveivedFilters.values(); } @Override public void cleanupAll() { reveivedFilters.clear(); } }
aadnk/ProtocolLib
src/main/java/com/comphenix/protocol/injector/netty/AbstractPacketInjector.java
Java
gpl-2.0
1,281