text
stringlengths
2
1.04M
meta
dict
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>buffer (24 of 28 overloads)</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../buffer.html" title="buffer"> <link rel="prev" href="overload23.html" title="buffer (23 of 28 overloads)"> <link rel="next" href="overload25.html" title="buffer (25 of 28 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload23.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../buffer.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload25.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.buffer.overload24"></a><a class="link" href="overload24.html" title="buffer (24 of 28 overloads)">buffer (24 of 28 overloads)</a> </h4></div></div></div> <p> Create a new modifiable buffer that represents the given POD vector. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <span class="identifier">PodType</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">&gt;</span> <span class="identifier">mutable_buffers_1</span> <span class="identifier">buffer</span><span class="special">(</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special">&lt;</span> <span class="identifier">PodType</span><span class="special">,</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">data</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">max_size_in_bytes</span><span class="special">);</span> </pre> <h6> <a name="boost_asio.reference.buffer.overload24.h0"></a> <span><a name="boost_asio.reference.buffer.overload24.return_value"></a></span><a class="link" href="overload24.html#boost_asio.reference.buffer.overload24.return_value">Return Value</a> </h6> <p> A <a class="link" href="../mutable_buffers_1.html" title="mutable_buffers_1"><code class="computeroutput"><span class="identifier">mutable_buffers_1</span></code></a> value equivalent to: </p> <pre class="programlisting"><span class="identifier">mutable_buffers_1</span><span class="special">(</span> <span class="identifier">data</span><span class="special">.</span><span class="identifier">size</span><span class="special">()</span> <span class="special">?</span> <span class="special">&amp;</span><span class="identifier">data</span><span class="special">[</span><span class="number">0</span><span class="special">]</span> <span class="special">:</span> <span class="number">0</span><span class="special">,</span> <span class="identifier">min</span><span class="special">(</span><span class="identifier">data</span><span class="special">.</span><span class="identifier">size</span><span class="special">()</span> <span class="special">*</span> <span class="keyword">sizeof</span><span class="special">(</span><span class="identifier">PodType</span><span class="special">),</span> <span class="identifier">max_size_in_bytes</span><span class="special">));</span> </pre> <h6> <a name="boost_asio.reference.buffer.overload24.h1"></a> <span><a name="boost_asio.reference.buffer.overload24.remarks"></a></span><a class="link" href="overload24.html#boost_asio.reference.buffer.overload24.remarks">Remarks</a> </h6> <p> The buffer is invalidated by any vector operation that would also invalidate iterators. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload23.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../buffer.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload25.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "9a8e72bf3d3c8ab246f93fc1983d4436", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 451, "avg_line_length": 78.58666666666667, "alnum_prop": 0.6511706820495419, "repo_name": "calvinfarias/IC2015-2", "id": "6237d2db908818b1a42b51de315bab783a0da94a", "size": "5894", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "BOOST/boost_1_61_0/libs/asio/doc/html/boost_asio/reference/buffer/overload24.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "223360" }, { "name": "Batchfile", "bytes": "32233" }, { "name": "C", "bytes": "2977162" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "184445796" }, { "name": "CMake", "bytes": "119765" }, { "name": "CSS", "bytes": "427923" }, { "name": "Cuda", "bytes": "111870" }, { "name": "DIGITAL Command Language", "bytes": "6246" }, { "name": "FORTRAN", "bytes": "5291" }, { "name": "Groff", "bytes": "5189" }, { "name": "HTML", "bytes": "234946752" }, { "name": "IDL", "bytes": "14" }, { "name": "JavaScript", "bytes": "682223" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1083443" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "11406" }, { "name": "Objective-C++", "bytes": "630" }, { "name": "PHP", "bytes": "59030" }, { "name": "Perl", "bytes": "39008" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1759984" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Ruby", "bytes": "5532" }, { "name": "Shell", "bytes": "355247" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "126042" }, { "name": "XSLT", "bytes": "552736" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
<!-- This comment will put IE 6, 7 and 8 in quirks mode --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.6.3 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <img id="MSearchSelect" src="search/search.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </div> </li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="contents"> <h1>edge_t Member List</h1>This is the complete list of members for <a class="el" href="structedge__t.html">edge_t</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="structedge__t.html#ad7a1f8ef33df7d97e109e2c8cc0a7061">i</a></td><td><a class="el" href="structedge__t.html">edge_t</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structedge__t.html#a94935293ccdd44ec33d8961b7dac7780">j</a></td><td><a class="el" href="structedge__t.html">edge_t</a></td><td></td></tr> </table></div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&nbsp;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&nbsp;</span>Defines</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address style="text-align: right;"><small>Generated on Wed Apr 18 11:36:55 2012 by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address> </body> </html>
{ "content_hash": "53f57ee38cc90ecfb80b7bb6079f7042", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 957, "avg_line_length": 63, "alnum_prop": 0.665976535541753, "repo_name": "madratman/riss_bingham", "id": "87592bcb6e25a73bd4670d13de88314cdefcd80e", "size": "4347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c/doc/html/structedge__t-members.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "17198129" }, { "name": "C++", "bytes": "22178342" }, { "name": "CSS", "bytes": "14525" }, { "name": "Fortran", "bytes": "285254" }, { "name": "HTML", "bytes": "3452018" }, { "name": "Java", "bytes": "36102" }, { "name": "JavaScript", "bytes": "22349" }, { "name": "Lua", "bytes": "29317" }, { "name": "M", "bytes": "3179" }, { "name": "Makefile", "bytes": "7138" }, { "name": "Mathematica", "bytes": "465" }, { "name": "Matlab", "bytes": "3540588" }, { "name": "Mercury", "bytes": "201" }, { "name": "Perl", "bytes": "2698" }, { "name": "R", "bytes": "2166" } ], "symlink_target": "" }
#ifndef UDP_TESTS_H #define UDP_TESTS_H #include "../test_params.h" #include "mbed_trace.h" #define TRACE_GROUP "GRNT" NetworkInterface *get_interface(); void drop_bad_packets(UDPSocket &sock, int orig_timeout); nsapi_version_t get_ip_version(); bool check_oversized_packets(nsapi_error_t error, int &size); void fill_tx_buffer_ascii(char *buff, size_t len); #if MBED_CONF_NSAPI_SOCKET_STATS_ENABLED extern mbed_stats_socket_t udp_stats[MBED_CONF_NSAPI_SOCKET_STATS_MAX_COUNT]; int fetch_stats(void); #endif /** * Single testcase might take only half of the remaining execution time */ int split2half_rmng_udp_test_time(); // [s] namespace udp_global { #ifdef MBED_GREENTEA_TEST_UDPSOCKET_TIMEOUT_S static const int TESTS_TIMEOUT = MBED_GREENTEA_TEST_UDPSOCKET_TIMEOUT_S; #else #define MESH 3 #define WISUN 0x2345 #if MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == MESH && MBED_CONF_NSAPI_DEFAULT_MESH_TYPE == WISUN static const int TESTS_TIMEOUT = (25 * 60); #else static const int TESTS_TIMEOUT = (20 * 60); #endif #endif static const int MAX_SEND_SIZE_IPV4 = 536; static const int MAX_SEND_SIZE_IPV6 = 1220; } /* * Test cases */ void UDPSOCKET_ECHOTEST(); void UDPSOCKET_ECHOTEST_CONNECT_SEND_RECV(); void UDPSOCKET_ECHOTEST_NONBLOCK(); void UDPSOCKET_ECHOTEST_NONBLOCK_CONNECT_SEND_RECV(); void UDPSOCKET_ECHOTEST_BURST(); void UDPSOCKET_ECHOTEST_BURST_NONBLOCK(); void UDPSOCKET_OPEN_CLOSE_REPEAT(); void UDPSOCKET_OPEN_DESTRUCT(); void UDPSOCKET_OPEN_LIMIT(); void UDPSOCKET_OPEN_TWICE(); void UDPSOCKET_BIND_PORT(); void UDPSOCKET_BIND_PORT_FAIL(); void UDPSOCKET_BIND_ADDRESS_PORT(); void UDPSOCKET_BIND_ADDRESS_NULL(); void UDPSOCKET_BIND_ADDRESS_INVALID(); void UDPSOCKET_BIND_ADDRESS(); void UDPSOCKET_BIND_WRONG_TYPE(); void UDPSOCKET_BIND_UNOPENED(); void UDPSOCKET_RECV_TIMEOUT(); void UDPSOCKET_SENDTO_INVALID(); void UDPSOCKET_SENDTO_REPEAT(); void UDPSOCKET_SENDTO_TIMEOUT(); #endif //UDP_TESTS_H
{ "content_hash": "c2d62691143d9661ddbb56f81adcf2f0", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 105, "avg_line_length": 27.614285714285714, "alnum_prop": 0.7537506466632178, "repo_name": "andcor02/mbed-os", "id": "ed5bba5821d55df5c5b5a544f426b28352ac4747", "size": "2588", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "TESTS/netsocket/udp/udp_tests.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "6601399" }, { "name": "Batchfile", "bytes": "22" }, { "name": "C", "bytes": "295194591" }, { "name": "C++", "bytes": "9038670" }, { "name": "CMake", "bytes": "5285" }, { "name": "HTML", "bytes": "2063156" }, { "name": "Makefile", "bytes": "103497" }, { "name": "Objective-C", "bytes": "460244" }, { "name": "Perl", "bytes": "2589" }, { "name": "Python", "bytes": "38809" }, { "name": "Shell", "bytes": "16862" }, { "name": "XSLT", "bytes": "5596" } ], "symlink_target": "" }
define(['jquery', 'findTableName'], function($, findTableName) { //找到当前选中的table,返回tablename function convert2table() { var tablename; var leftitemsname = $(".clear-backend").children("input.focused").next().text(); tablename = findTableName(leftitemsname); return tablename; } return convert2table; });
{ "content_hash": "77270f5b8ea25945bc0fe6c622d94c7b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 88, "avg_line_length": 35, "alnum_prop": 0.6485714285714286, "repo_name": "xiangsongtao/jikexueyuan_Homework", "id": "5bb57557fe43b24e3ae0cde376a80ad20ca6f77d", "size": "370", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Lesson9-NodeJS_MySQL/1.开发手机版本的百度新闻_NodeJS/public/BgManager/js/basic/convert2table.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "203" }, { "name": "CSS", "bytes": "973622" }, { "name": "HTML", "bytes": "566268" }, { "name": "JavaScript", "bytes": "508441" }, { "name": "PHP", "bytes": "1245127" }, { "name": "Ruby", "bytes": "901" }, { "name": "Smarty", "bytes": "8471" } ], "symlink_target": "" }
using System.Web; using System.Web.Optimization; namespace WebRoleSample { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
{ "content_hash": "a92653e1aa6a8707e4d629e3e41b4f75", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 112, "avg_line_length": 40.064516129032256, "alnum_prop": 0.5740740740740741, "repo_name": "qinxgit/azure-ssl-configure", "id": "2be986231a27ddcc5e50e032b1926dfce5758c76", "size": "1244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AzureCloudServiceSample/WebRoleSample/App_Start/BundleConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "Batchfile", "bytes": "487" }, { "name": "C#", "bytes": "9327" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "21032" }, { "name": "PowerShell", "bytes": "19579" } ], "symlink_target": "" }
<?php namespace spec\PhpSpec\Event; use PhpSpec\ObjectBehavior; use PhpSpec\Event\ExampleEvent as Example; use PhpSpec\Loader\Suite; class SuiteEventSpec extends ObjectBehavior { function let(Suite $suite) { $this->beConstructedWith($suite, 10, Example::FAILED); } function it_is_an_event() { $this->shouldBeAnInstanceOf('Symfony\Component\EventDispatcher\Event'); $this->shouldBeAnInstanceOf('PhpSpec\Event\PhpSpecEvent'); } function it_provides_a_link_to_suite($suite) { $this->getSuite()->shouldReturn($suite); } function it_provides_a_link_to_time() { $this->getTime()->shouldReturn(10); } function it_provides_a_link_to_result() { $this->getResult()->shouldReturn(Example::FAILED); } function it_defaults_to_saying_suite_is_not_worth_rerunning() { $this->isWorthRerunning()->shouldReturn(false); } function it_can_be_told_that_the_suite_is_worth_rerunning() { $this->markAsWorthRerunning(); $this->isWorthRerunning()->shouldReturn(true); } function it_can_be_told_that_the_suite_is_no_longer_worth_rerunning() { $this->markAsWorthRerunning(); $this->markAsNotWorthRerunning(); $this->isWorthRerunning()->shouldReturn(false); } }
{ "content_hash": "ea06e3148bbe4003a7d5ef81039aa471", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 79, "avg_line_length": 23.892857142857142, "alnum_prop": 0.6442451420029895, "repo_name": "Harrisonbro/phpspec", "id": "87c13c345cb0c0289977ea32ee7eec1a5882503b", "size": "1338", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "spec/PhpSpec/Event/SuiteEventSpec.php", "mode": "33188", "license": "mit", "language": [ { "name": "Cucumber", "bytes": "153687" }, { "name": "HTML", "bytes": "6057" }, { "name": "Makefile", "bytes": "412" }, { "name": "PHP", "bytes": "841614" }, { "name": "Smarty", "bytes": "762" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>buffered_write_stream::async_write_some</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../buffered_write_stream.html" title="buffered_write_stream"> <link rel="prev" href="async_read_some.html" title="buffered_write_stream::async_read_some"> <link rel="next" href="buffered_write_stream.html" title="buffered_write_stream::buffered_write_stream"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="async_read_some.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../buffered_write_stream.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="buffered_write_stream.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.buffered_write_stream.async_write_some"></a><a class="link" href="async_write_some.html" title="buffered_write_stream::async_write_some">buffered_write_stream::async_write_some</a> </h4></div></div></div> <p> <a class="indexterm" name="boost_asio.indexterm.buffered_write_stream.async_write_some"></a> Start an asynchronous write. The data being written must be valid for the lifetime of the asynchronous operation. </p> <pre class="programlisting">template&lt; typename <a class="link" href="../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a>, typename <a class="link" href="../WriteHandler.html" title="Write handler requirements">WriteHandler</a>&gt; <a class="link" href="../asynchronous_operations.html#boost_asio.reference.asynchronous_operations.automatic_deduction_of_initiating_function_return_type"><span class="emphasis"><em>DEDUCED</em></span></a> async_write_some( const ConstBufferSequence &amp; buffers, WriteHandler &amp;&amp; handler); </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2018 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="async_read_some.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../buffered_write_stream.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="buffered_write_stream.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "4641ea85a8cec090a0fb046c34ebed79", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 455, "avg_line_length": 70.33928571428571, "alnum_prop": 0.6567656765676567, "repo_name": "c72578/poedit", "id": "d215da695755c80bb0112a4a5dbdfc1da7097ca5", "size": "3939", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "deps/boost/doc/html/boost_asio/reference/buffered_write_stream/async_write_some.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "23633" }, { "name": "C++", "bytes": "1088488" }, { "name": "Inno Setup", "bytes": "11765" }, { "name": "M4", "bytes": "104132" }, { "name": "Makefile", "bytes": "9152" }, { "name": "Objective-C", "bytes": "26402" }, { "name": "Objective-C++", "bytes": "13730" }, { "name": "Python", "bytes": "3081" }, { "name": "Ruby", "bytes": "261" }, { "name": "Shell", "bytes": "10717" }, { "name": "sed", "bytes": "557" } ], "symlink_target": "" }
layout: page title: Shadow Music Award Ceremony date: 2016-05-24 author: Lori Barnes tags: weekly links, java status: published summary: Sed eu risus tellus. Proin. banner: images/banner/meeting-01.jpg booking: startDate: 01/10/2019 endDate: 01/13/2019 ctyhocn: YQGCNHX groupCode: SMAC published: true --- Fusce in rutrum libero. Donec rutrum sem sit amet pharetra hendrerit. In hac habitasse platea dictumst. Integer eget neque dapibus magna venenatis maximus at at enim. Sed non fringilla metus. Nullam luctus ultricies tortor scelerisque molestie. Pellentesque ut vulputate arcu, sed iaculis erat. Donec congue ut nunc a elementum. Etiam dictum augue eu sem ullamcorper finibus. Vestibulum laoreet nibh vitae nunc elementum dapibus. Nulla eget tortor id risus fringilla molestie ut ac mauris. Quisque tortor est, ultricies non mi a, accumsan maximus ligula. Pellentesque auctor consequat efficitur. * Aliquam vitae eros ac libero suscipit scelerisque. Nunc rutrum mattis neque id commodo. Duis sed augue a sem semper lobortis sit amet nec justo. Maecenas eu tristique nibh. Sed id mauris aliquam dui fermentum malesuada vitae a est. Maecenas sed aliquam lorem, vel commodo sapien. In gravida vehicula quam vel viverra. Curabitur rhoncus quam a diam ullamcorper, at fermentum orci mattis. Curabitur sit amet consequat nisi. Fusce elementum dui nisl, sit amet dapibus nunc commodo eu. Aliquam at tristique est. Nulla elementum ligula a sem sagittis, ac tempus ipsum cursus. In in tortor arcu. Integer at leo risus. Sed convallis sapien augue, id finibus ligula viverra nec. Ut lacus tortor, aliquet non aliquam eu, accumsan eget diam. Nulla consequat bibendum odio, vel pretium felis vulputate nec. Fusce pulvinar gravida libero in accumsan. Vivamus consequat vehicula ipsum, vitae tempus purus fringilla ut. Mauris sem odio, cursus lobortis erat sed, mollis efficitur nisl. In porttitor lectus quis pretium sollicitudin. Pellentesque sed maximus nisl. Maecenas maximus consequat interdum. Sed efficitur augue nunc. Praesent justo ipsum, finibus in tincidunt a, facilisis nec justo.
{ "content_hash": "74be392cdbc636831e2f3518a01bc818", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 595, "avg_line_length": 99.71428571428571, "alnum_prop": 0.8089780324737345, "repo_name": "KlishGroup/prose-pogs", "id": "4bb092e5af4dfe4859889a3e59774f5877c5b64d", "size": "2098", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/Y/YQGCNHX/SMAC/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package util import ( "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/url" "os" "strings" "time" "k8s.io/kubernetes/pkg/api" kerrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" utilexec "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/strategicpatch" jsonpatch "github.com/evanphx/json-patch" "github.com/golang/glog" "github.com/spf13/cobra" ) const ( ApplyAnnotationsFlag = "save-config" DefaultErrorExitCode = 1 ) type debugError interface { DebugError() (msg string, args []interface{}) } // AddSourceToErr adds handleResourcePrefix and source string to error message. // verb is the string like "creating", "deleting" etc. // source is the filename or URL to the template file(*.json or *.yaml), or stdin to use to handle the resource. func AddSourceToErr(verb string, source string, err error) error { if source != "" { if statusError, ok := err.(kerrors.APIStatus); ok { status := statusError.Status() status.Message = fmt.Sprintf("error when %s %q: %v", verb, source, status.Message) return &kerrors.StatusError{ErrStatus: status} } return fmt.Errorf("error when %s %q: %v", verb, source, err) } return err } var fatalErrHandler = fatal // BehaviorOnFatal allows you to override the default behavior when a fatal // error occurs, which is to call os.Exit(code). You can pass 'panic' as a function // here if you prefer the panic() over os.Exit(1). func BehaviorOnFatal(f func(string, int)) { fatalErrHandler = f } // DefaultBehaviorOnFatal allows you to undo any previous override. Useful in // tests. func DefaultBehaviorOnFatal() { fatalErrHandler = fatal } // fatal prints the message (if provided) and then exits. If V(2) or greater, // glog.Fatal is invoked for extended information. func fatal(msg string, code int) { if glog.V(2) { glog.FatalDepth(2, msg) } if len(msg) > 0 { // add newline if needed if !strings.HasSuffix(msg, "\n") { msg += "\n" } fmt.Fprint(os.Stderr, msg) } os.Exit(code) } // ErrExit may be passed to CheckError to instruct it to output nothing but exit with // status code 1. var ErrExit = fmt.Errorf("exit") // CheckErr prints a user friendly error to STDERR and exits with a non-zero // exit code. Unrecognized errors will be printed with an "error: " prefix. // // This method is generic to the command in use and may be used by non-Kubectl // commands. func CheckErr(err error) { checkErr("", err, fatalErrHandler) } // checkErrWithPrefix works like CheckErr, but adds a caller-defined prefix to non-nil errors func checkErrWithPrefix(prefix string, err error) { checkErr(prefix, err, fatalErrHandler) } // checkErr formats a given error as a string and calls the passed handleErr // func with that string and an kubectl exit code. func checkErr(prefix string, err error, handleErr func(string, int)) { // unwrap aggregates of 1 if agg, ok := err.(utilerrors.Aggregate); ok && len(agg.Errors()) == 1 { err = agg.Errors()[0] } switch { case err == nil: return case err == ErrExit: handleErr("", DefaultErrorExitCode) return case kerrors.IsInvalid(err): details := err.(*kerrors.StatusError).Status().Details s := fmt.Sprintf("%sThe %s %q is invalid", prefix, details.Kind, details.Name) if len(details.Causes) > 0 { errs := statusCausesToAggrError(details.Causes) handleErr(MultilineError(s+": ", errs), DefaultErrorExitCode) } else { handleErr(s, DefaultErrorExitCode) } case clientcmd.IsConfigurationInvalid(err): handleErr(MultilineError(fmt.Sprintf("%sError in configuration: ", prefix), err), DefaultErrorExitCode) default: switch err := err.(type) { case *meta.NoResourceMatchError: switch { case len(err.PartialResource.Group) > 0 && len(err.PartialResource.Version) > 0: handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in group %q and version %q", prefix, err.PartialResource.Resource, err.PartialResource.Group, err.PartialResource.Version), DefaultErrorExitCode) case len(err.PartialResource.Group) > 0: handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in group %q", prefix, err.PartialResource.Resource, err.PartialResource.Group), DefaultErrorExitCode) case len(err.PartialResource.Version) > 0: handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in version %q", prefix, err.PartialResource.Resource, err.PartialResource.Version), DefaultErrorExitCode) default: handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q", prefix, err.PartialResource.Resource), DefaultErrorExitCode) } case utilerrors.Aggregate: handleErr(MultipleErrors(prefix, err.Errors()), DefaultErrorExitCode) case utilexec.ExitError: // do not print anything, only terminate with given error handleErr("", err.ExitStatus()) default: // for any other error type msg, ok := StandardErrorMessage(err) if !ok { msg = err.Error() if !strings.HasPrefix(msg, "error: ") { msg = fmt.Sprintf("error: %s", msg) } } handleErr(msg, DefaultErrorExitCode) } } } func statusCausesToAggrError(scs []unversioned.StatusCause) utilerrors.Aggregate { errs := make([]error, 0, len(scs)) errorMsgs := sets.NewString() for _, sc := range scs { // check for duplicate error messages and skip them msg := fmt.Sprintf("%s: %s", sc.Field, sc.Message) if errorMsgs.Has(msg) { continue } errorMsgs.Insert(msg) errs = append(errs, errors.New(msg)) } return utilerrors.NewAggregate(errs) } // StandardErrorMessage translates common errors into a human readable message, or returns // false if the error is not one of the recognized types. It may also log extended // information to glog. // // This method is generic to the command in use and may be used by non-Kubectl // commands. func StandardErrorMessage(err error) (string, bool) { if debugErr, ok := err.(debugError); ok { glog.V(4).Infof(debugErr.DebugError()) } status, isStatus := err.(kerrors.APIStatus) switch { case isStatus: switch s := status.Status(); { case s.Reason == unversioned.StatusReasonUnauthorized: return fmt.Sprintf("error: You must be logged in to the server (%s)", s.Message), true case len(s.Reason) > 0: return fmt.Sprintf("Error from server (%s): %s", s.Reason, err.Error()), true default: return fmt.Sprintf("Error from server: %s", err.Error()), true } case kerrors.IsUnexpectedObjectError(err): return fmt.Sprintf("Server returned an unexpected response: %s", err.Error()), true } switch t := err.(type) { case *url.Error: glog.V(4).Infof("Connection error: %s %s: %v", t.Op, t.URL, t.Err) switch { case strings.Contains(t.Err.Error(), "connection refused"): host := t.URL if server, err := url.Parse(t.URL); err == nil { host = server.Host } return fmt.Sprintf("The connection to the server %s was refused - did you specify the right host or port?", host), true } return fmt.Sprintf("Unable to connect to the server: %v", t.Err), true } return "", false } // MultilineError returns a string representing an error that splits sub errors into their own // lines. The returned string will end with a newline. func MultilineError(prefix string, err error) string { if agg, ok := err.(utilerrors.Aggregate); ok { errs := utilerrors.Flatten(agg).Errors() buf := &bytes.Buffer{} switch len(errs) { case 0: return fmt.Sprintf("%s%v\n", prefix, err) case 1: return fmt.Sprintf("%s%v\n", prefix, messageForError(errs[0])) default: fmt.Fprintln(buf, prefix) for _, err := range errs { fmt.Fprintf(buf, "* %v\n", messageForError(err)) } return buf.String() } } return fmt.Sprintf("%s%s\n", prefix, err) } // PrintErrorWithCauses prints an error's kind, name, and each of the error's causes in a new line. // The returned string will end with a newline. // Returns true if a case exists to handle the error type, or false otherwise. func PrintErrorWithCauses(err error, errOut io.Writer) bool { switch t := err.(type) { case *kerrors.StatusError: errorDetails := t.Status().Details if errorDetails != nil { fmt.Fprintf(errOut, "error: %s %q is invalid\n\n", errorDetails.Kind, errorDetails.Name) for _, cause := range errorDetails.Causes { fmt.Fprintf(errOut, "* %s: %s\n", cause.Field, cause.Message) } return true } } fmt.Fprintf(errOut, "error: %v\n", err) return false } // MultipleErrors returns a newline delimited string containing // the prefix and referenced errors in standard form. func MultipleErrors(prefix string, errs []error) string { buf := &bytes.Buffer{} for _, err := range errs { fmt.Fprintf(buf, "%s%v\n", prefix, messageForError(err)) } return buf.String() } // messageForError returns the string representing the error. func messageForError(err error) string { msg, ok := StandardErrorMessage(err) if !ok { msg = err.Error() } return msg } func UsageError(cmd *cobra.Command, format string, args ...interface{}) error { msg := fmt.Sprintf(format, args...) return fmt.Errorf("%s\nSee '%s -h' for help and examples.", msg, cmd.CommandPath()) } func IsFilenameEmpty(filenames []string) bool { if len(filenames) == 0 { return true } return false } // Whether this cmd need watching objects. func isWatch(cmd *cobra.Command) bool { if w, err := cmd.Flags().GetBool("watch"); w && err == nil { return true } if wo, err := cmd.Flags().GetBool("watch-only"); wo && err == nil { return true } return false } func GetFlagString(cmd *cobra.Command, flag string) string { s, err := cmd.Flags().GetString(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return s } // GetFlagStringSlice can be used to accept multiple argument with flag repetition (e.g. -f arg1,arg2 -f arg3 ...) func GetFlagStringSlice(cmd *cobra.Command, flag string) []string { s, err := cmd.Flags().GetStringSlice(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return s } // GetFlagStringArray can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...) func GetFlagStringArray(cmd *cobra.Command, flag string) []string { s, err := cmd.Flags().GetStringArray(flag) if err != nil { glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return s } // GetWideFlag is used to determine if "-o wide" is used func GetWideFlag(cmd *cobra.Command) bool { f := cmd.Flags().Lookup("output") if f.Value.String() == "wide" { return true } return false } func GetFlagBool(cmd *cobra.Command, flag string) bool { b, err := cmd.Flags().GetBool(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return b } // Assumes the flag has a default value. func GetFlagInt(cmd *cobra.Command, flag string) int { i, err := cmd.Flags().GetInt(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return i } // Assumes the flag has a default value. func GetFlagInt64(cmd *cobra.Command, flag string) int64 { i, err := cmd.Flags().GetInt64(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return i } func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration { d, err := cmd.Flags().GetDuration(flag) if err != nil { glog.Fatalf("error accessing flag %s for command %s: %v", flag, cmd.Name(), err) } return d } func AddValidateFlags(cmd *cobra.Command) { cmd.Flags().Bool("validate", true, "If true, use a schema to validate the input before sending it") cmd.Flags().String("schema-cache-dir", fmt.Sprintf("~/%s/%s", clientcmd.RecommendedHomeDir, clientcmd.RecommendedSchemaName), fmt.Sprintf("If non-empty, load/store cached API schemas in this directory, default is '$HOME/%s/%s'", clientcmd.RecommendedHomeDir, clientcmd.RecommendedSchemaName)) cmd.MarkFlagFilename("schema-cache-dir") } func AddFilenameOptionFlags(cmd *cobra.Command, options *resource.FilenameOptions, usage string) { kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, "Filename, directory, or URL to files "+usage) cmd.Flags().BoolVarP(&options.Recursive, "recursive", "R", options.Recursive, "Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.") } // AddDryRunFlag adds dry-run flag to a command. Usually used by mutations. func AddDryRunFlag(cmd *cobra.Command) { cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it.") } func AddApplyAnnotationFlags(cmd *cobra.Command) { cmd.Flags().Bool(ApplyAnnotationsFlag, false, "If true, the configuration of current object will be saved in its annotation. This is useful when you want to perform kubectl apply on this object in the future.") } // AddGeneratorFlags adds flags common to resource generation commands // TODO: need to take a pass at other generator commands to use this set of flags func AddGeneratorFlags(cmd *cobra.Command, defaultGenerator string) { cmd.Flags().String("generator", defaultGenerator, "The name of the API generator to use.") AddDryRunFlag(cmd) } func ReadConfigDataFromReader(reader io.Reader, source string) ([]byte, error) { data, err := ioutil.ReadAll(reader) if err != nil { return nil, err } if len(data) == 0 { return nil, fmt.Errorf("Read from %s but no data found", source) } return data, nil } // Merge requires JSON serialization // TODO: merge assumes JSON serialization, and does not properly abstract API retrieval func Merge(codec runtime.Codec, dst runtime.Object, fragment, kind string) (runtime.Object, error) { // encode dst into versioned json and apply fragment directly too it target, err := runtime.Encode(codec, dst) if err != nil { return nil, err } patched, err := jsonpatch.MergePatch(target, []byte(fragment)) if err != nil { return nil, err } out, err := runtime.Decode(codec, patched) if err != nil { return nil, err } return out, nil } // DumpReaderToFile writes all data from the given io.Reader to the specified file // (usually for temporary use). func DumpReaderToFile(reader io.Reader, filename string) error { f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() if err != nil { return err } buffer := make([]byte, 1024) for { count, err := reader.Read(buffer) if err == io.EOF { break } if err != nil { return err } _, err = f.Write(buffer[:count]) if err != nil { return err } } return nil } // UpdateObject updates resource object with updateFn func UpdateObject(info *resource.Info, codec runtime.Codec, updateFn func(runtime.Object) error) (runtime.Object, error) { helper := resource.NewHelper(info.Client, info.Mapping) if err := updateFn(info.Object); err != nil { return nil, err } // Update the annotation used by kubectl apply if err := kubectl.UpdateApplyAnnotation(info, codec); err != nil { return nil, err } if _, err := helper.Replace(info.Namespace, info.Name, true, info.Object); err != nil { return nil, err } return info.Object, nil } // AddCmdRecordFlag adds --record flag to command func AddRecordFlag(cmd *cobra.Command) { cmd.Flags().Bool("record", false, "Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.") } func GetRecordFlag(cmd *cobra.Command) bool { return GetFlagBool(cmd, "record") } func GetDryRunFlag(cmd *cobra.Command) bool { return GetFlagBool(cmd, "dry-run") } // RecordChangeCause annotate change-cause to input runtime object. func RecordChangeCause(obj runtime.Object, changeCause string) error { accessor, err := meta.Accessor(obj) if err != nil { return err } annotations := accessor.GetAnnotations() if annotations == nil { annotations = make(map[string]string) } annotations[kubectl.ChangeCauseAnnotation] = changeCause accessor.SetAnnotations(annotations) return nil } // ChangeResourcePatch creates a strategic merge patch between the origin input resource info // and the annotated with change-cause input resource info. func ChangeResourcePatch(info *resource.Info, changeCause string) ([]byte, error) { oldData, err := json.Marshal(info.Object) if err != nil { return nil, err } if err := RecordChangeCause(info.Object, changeCause); err != nil { return nil, err } newData, err := json.Marshal(info.Object) if err != nil { return nil, err } return strategicpatch.CreateTwoWayMergePatch(oldData, newData, info.Object) } // containsChangeCause checks if input resource info contains change-cause annotation. func ContainsChangeCause(info *resource.Info) bool { annotations, err := info.Mapping.MetadataAccessor.Annotations(info.Object) if err != nil { return false } return len(annotations[kubectl.ChangeCauseAnnotation]) > 0 } // ShouldRecord checks if we should record current change cause func ShouldRecord(cmd *cobra.Command, info *resource.Info) bool { return GetRecordFlag(cmd) || (ContainsChangeCause(info) && !cmd.Flags().Changed("record")) } func AddInclude3rdPartyFlags(cmd *cobra.Command) { cmd.Flags().Bool("include-extended-apis", true, "If true, include definitions of new APIs via calls to the API server. [default true]") cmd.Flags().MarkDeprecated("include-extended-apis", "No longer required.") } // GetResourcesAndPairs retrieves resources and "KEY=VALUE or KEY-" pair args from given args func GetResourcesAndPairs(args []string, pairType string) (resources []string, pairArgs []string, err error) { foundPair := false for _, s := range args { nonResource := strings.Contains(s, "=") || strings.HasSuffix(s, "-") switch { case !foundPair && nonResource: foundPair = true fallthrough case foundPair && nonResource: pairArgs = append(pairArgs, s) case !foundPair && !nonResource: resources = append(resources, s) case foundPair && !nonResource: err = fmt.Errorf("all resources must be specified before %s changes: %s", pairType, s) return } } return } // ParsePairs retrieves new and remove pairs (if supportRemove is true) from "KEY=VALUE or KEY-" pair args func ParsePairs(pairArgs []string, pairType string, supportRemove bool) (newPairs map[string]string, removePairs []string, err error) { newPairs = map[string]string{} if supportRemove { removePairs = []string{} } var invalidBuf bytes.Buffer for _, pairArg := range pairArgs { if strings.Index(pairArg, "=") != -1 { parts := strings.SplitN(pairArg, "=", 2) if len(parts) != 2 { if invalidBuf.Len() > 0 { invalidBuf.WriteString(", ") } invalidBuf.WriteString(fmt.Sprintf(pairArg)) } else { newPairs[parts[0]] = parts[1] } } else if supportRemove && strings.HasSuffix(pairArg, "-") { removePairs = append(removePairs, pairArg[:len(pairArg)-1]) } else { if invalidBuf.Len() > 0 { invalidBuf.WriteString(", ") } invalidBuf.WriteString(fmt.Sprintf(pairArg)) } } if invalidBuf.Len() > 0 { err = fmt.Errorf("invalid %s format: %s", pairType, invalidBuf.String()) return } return } // MaybeConvertObject attempts to convert an object to a specific group/version. If the object is // a third party resource it is simply passed through. func MaybeConvertObject(obj runtime.Object, gv unversioned.GroupVersion, converter runtime.ObjectConvertor) (runtime.Object, error) { switch obj.(type) { case *extensions.ThirdPartyResourceData: // conversion is not supported for 3rd party objects return obj, nil default: return converter.ConvertToVersion(obj, gv) } } // MustPrintWithKinds determines if printer is dealing // with multiple resource kinds, in which case it will // return true, indicating resource kind will be // included as part of printer output func MustPrintWithKinds(objs []runtime.Object, infos []*resource.Info, sorter *kubectl.RuntimeSort, printAll bool) bool { var lastMap *meta.RESTMapping if len(infos) == 1 && printAll { return true } for ix := range objs { var mapping *meta.RESTMapping if sorter != nil { mapping = infos[sorter.OriginalPosition(ix)].Mapping } else { mapping = infos[ix].Mapping } // display "kind" only if we have mixed resources if lastMap != nil && mapping.Resource != lastMap.Resource { return true } lastMap = mapping } return false } // FilterResourceList receives a list of runtime objects. // If any objects are filtered, that number is returned along with a modified list. func FilterResourceList(obj runtime.Object, filterFuncs kubectl.Filters, filterOpts *kubectl.PrintOptions) (int, []runtime.Object, error) { items, err := meta.ExtractList(obj) if err != nil { return 0, []runtime.Object{obj}, utilerrors.NewAggregate([]error{err}) } if errs := runtime.DecodeList(items, api.Codecs.UniversalDecoder(), runtime.UnstructuredJSONScheme); len(errs) > 0 { return 0, []runtime.Object{obj}, utilerrors.NewAggregate(errs) } filterCount := 0 list := make([]runtime.Object, 0, len(items)) for _, obj := range items { if isFiltered, err := filterFuncs.Filter(obj, filterOpts); !isFiltered { if err != nil { glog.V(2).Infof("Unable to filter resource: %v", err) continue } list = append(list, obj) } else if isFiltered { filterCount++ } } return filterCount, list, nil } func PrintFilterCount(hiddenObjNum int, resource string, options *kubectl.PrintOptions) { if !options.NoHeaders && !options.ShowAll && hiddenObjNum > 0 { glog.V(2).Infof(" info: %d completed object(s) was(were) not shown in %s list. Pass --show-all to see all objects.\n\n", hiddenObjNum, resource) } } // ObjectListToVersionedObject receives a list of api objects and a group version // and squashes the list's items into a single versioned runtime.Object. func ObjectListToVersionedObject(objects []runtime.Object, version unversioned.GroupVersion) (runtime.Object, error) { objectList := &api.List{Items: objects} converted, err := resource.TryConvert(api.Scheme, objectList, version, registered.GroupOrDie(api.GroupName).GroupVersion) if err != nil { return nil, err } return converted, nil } // IsSiblingCommandExists receives a pointer to a cobra command and a target string. // Returns true if the target string is found in the list of sibling commands. func IsSiblingCommandExists(cmd *cobra.Command, targetCmdName string) bool { for _, c := range cmd.Parent().Commands() { if c.Name() == targetCmdName { return true } } return false } // DefaultSubCommandRun prints a command's help string to the specified output if no // arguments (sub-commands) are provided, or a usage error otherwise. func DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string) { return func(c *cobra.Command, args []string) { c.SetOutput(out) RequireNoArguments(c, args) c.Help() } } // RequireNoArguments exits with a usage error if extra arguments are provided. func RequireNoArguments(c *cobra.Command, args []string) { if len(args) > 0 { CheckErr(UsageError(c, fmt.Sprintf(`unknown command %q`, strings.Join(args, " ")))) } }
{ "content_hash": "8b88dc2c97f83a70270702669835bfd4", "timestamp": "", "source": "github", "line_count": 713, "max_line_length": 293, "avg_line_length": 33.23141654978962, "alnum_prop": 0.7127120790073437, "repo_name": "f-higashi/dashboard", "id": "01e34a64edf14b360715032ff81b4d1d59e31e31", "size": "24263", "binary": false, "copies": "22", "ref": "refs/heads/master", "path": "vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/helpers.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "49847" }, { "name": "Go", "bytes": "675631" }, { "name": "HTML", "bytes": "346956" }, { "name": "JavaScript", "bytes": "1237610" }, { "name": "Shell", "bytes": "5736" }, { "name": "XSLT", "bytes": "1119" } ], "symlink_target": "" }
// Generated by CoffeeScript 1.7.1 /* TouchController (stick + buttons) for touch devices Based on the touch demo by Seb Lee-Delisle <http://seb.ly/> @class bkcore.controllers.TouchController @author Thibaut 'BKcore' Despoulain <http://bkcore.com> */ (function() { var TouchController, Vec2, exports, _base; TouchController = (function() { TouchController.isCompatible = function() { return 'ontouchstart' in document.documentElement; }; /* Creates a new TouchController @param dom DOMElement The element that will listen to touch events @param stickMargin int The left margin in px for stick detection @param buttonCallback function Callback for non-stick touches */ function TouchController(dom, stickMargin, buttonCallback) { this.dom = dom; this.stickMargin = stickMargin != null ? stickMargin : 200; this.buttonCallback = buttonCallback != null ? buttonCallback : null; this.active = true; this.touches = null; this.stickID = -1; this.stickPos = new Vec2(0, 0); this.stickStartPos = new Vec2(0, 0); this.stickVector = new Vec2(0, 0); this.dom.addEventListener('touchstart', ((function(_this) { return function(e) { return _this.touchStart(e); }; })(this)), false); this.dom.addEventListener('touchmove', ((function(_this) { return function(e) { return _this.touchMove(e); }; })(this)), false); this.dom.addEventListener('touchend', ((function(_this) { return function(e) { return _this.touchEnd(e); }; })(this)), false); } /* @private */ TouchController.prototype.touchStart = function(event) { var touch, _i, _len, _ref; if (!this.active) { return; } _ref = event.changedTouches; for (_i = 0, _len = _ref.length; _i < _len; _i++) { touch = _ref[_i]; if (this.stickID < 0 && touch.clientX < this.stickMargin) { this.stickID = touch.identifier; this.stickStartPos.set(touch.clientX, touch.clientY); this.stickPos.copy(this.stickStartPos); this.stickVector.set(0, 0); continue; } else { if (typeof this.buttonCallback === "function") { this.buttonCallback(true, touch, event); } } } this.touches = event.touches; return false; }; /* @private */ TouchController.prototype.touchMove = function(event) { var touch, _i, _len, _ref; event.preventDefault(); if (!this.active) { return; } _ref = event.changedTouches; for (_i = 0, _len = _ref.length; _i < _len; _i++) { touch = _ref[_i]; if (this.stickID === touch.identifier && touch.clientX < this.stickMargin) { this.stickPos.set(touch.clientX, touch.clientY); this.stickVector.copy(this.stickPos).substract(this.stickStartPos); break; } } this.touches = event.touches; return false; }; /* @private */ TouchController.prototype.touchEnd = function(event) { var touch, _i, _len, _ref; if (!this.active) { return; } this.touches = event.touches; _ref = event.changedTouches; for (_i = 0, _len = _ref.length; _i < _len; _i++) { touch = _ref[_i]; if (this.stickID === touch.identifier) { this.stickID = -1; this.stickVector.set(0, 0); break; } else { if (typeof this.buttonCallback === "function") { this.buttonCallback(false, touch, event); } } } return false; }; return TouchController; })(); /* Internal class used for vector2 @class Vec2 @private */ Vec2 = (function() { function Vec2(x, y) { this.x = x != null ? x : 0; this.y = y != null ? y : 0; } Vec2.prototype.substract = function(vec) { this.x -= vec.x; this.y -= vec.y; return this; }; Vec2.prototype.copy = function(vec) { this.x = vec.x; this.y = vec.y; return this; }; Vec2.prototype.set = function(x, y) { this.x = x; this.y = y; return this; }; return Vec2; })(); /* Exports @package bkcore */ exports = exports != null ? exports : this; exports.bkcore || (exports.bkcore = {}); (_base = exports.bkcore).controllers || (_base.controllers = {}); exports.bkcore.controllers.TouchController = TouchController; }).call(this);
{ "content_hash": "9dce981922eb5d780c4f49ba671faef6", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 84, "avg_line_length": 24.81382978723404, "alnum_prop": 0.5562700964630225, "repo_name": "BKcore/HexGL", "id": "d8e7f1578b0021d81663622645ebe7a410b0a2cb", "size": "4665", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "bkcore.coffee/controllers/TouchController.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "191" }, { "name": "CSS", "bytes": "12899" }, { "name": "CoffeeScript", "bytes": "22802" }, { "name": "HTML", "bytes": "49500" }, { "name": "JavaScript", "bytes": "286735" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols { // This file contains the legacy FindReferences APIs. The APIs are legacy because they // do not contain enough information for us to effectively remote them over to the OOP // process to do the work. Specifically, they lack the "current project context" necessary // to be able to effectively serialize symbols to/from the remote process. public static partial class SymbolFinder { /// <summary> /// Finds all references to a symbol throughout a solution /// </summary> /// <param name="symbol">The symbol to find references to.</param> /// <param name="solution">The solution to find references within.</param> /// <param name="cancellationToken">A cancellation token.</param> public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken = default) { return FindReferencesAsync(new SymbolAndProjectId(symbol, projectId: null), solution, cancellationToken); } internal static async Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, CancellationToken cancellationToken = default) { var progressCollector = new StreamingProgressCollector(StreamingFindReferencesProgress.Instance); await FindReferencesAsync( symbolAndProjectId, solution, progress: progressCollector, documents: null, options: FindReferencesSearchOptions.Default, cancellationToken: cancellationToken).ConfigureAwait(false); return progressCollector.GetReferencedSymbols(); } /// <summary> /// Finds all references to a symbol throughout a solution /// </summary> /// <param name="symbol">The symbol to find references to.</param> /// <param name="solution">The solution to find references within.</param> /// <param name="documents">A set of documents to be searched. If documents is null, then that means "all documents".</param> /// <param name="cancellationToken">A cancellation token.</param> public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, IImmutableSet<Document> documents, CancellationToken cancellationToken = default) { return FindReferencesAsync(symbol, solution, progress: null, documents: documents, cancellationToken: cancellationToken); } /// <summary> /// Finds all references to a symbol throughout a solution /// </summary> /// <param name="symbol">The symbol to find references to.</param> /// <param name="solution">The solution to find references within.</param> /// <param name="progress">An optional progress object that will receive progress /// information as the search is undertaken.</param> /// <param name="documents">An optional set of documents to be searched. If documents is null, then that means "all documents".</param> /// <param name="cancellationToken">An optional cancellation token.</param> public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, IFindReferencesProgress progress, IImmutableSet<Document> documents, CancellationToken cancellationToken = default) { return FindReferencesAsync( symbol, solution, progress, documents, FindReferencesSearchOptions.Default, cancellationToken); } private static async Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, IFindReferencesProgress progress, IImmutableSet<Document> documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { progress ??= FindReferencesProgress.Instance; var streamingProgress = new StreamingProgressCollector( new StreamingFindReferencesProgressAdapter(progress)); await FindReferencesAsync( SymbolAndProjectId.Create(symbol, projectId: null), solution, streamingProgress, documents, options, cancellationToken).ConfigureAwait(false); return streamingProgress.GetReferencedSymbols(); } internal static class TestAccessor { internal static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, IFindReferencesProgress progress, IImmutableSet<Document> documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return SymbolFinder.FindReferencesAsync(symbol, solution, progress, documents, options, cancellationToken); } } } }
{ "content_hash": "e91a096b6d2a6c72dfee654955b07b1d", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 143, "avg_line_length": 48.31896551724138, "alnum_prop": 0.6603033006244424, "repo_name": "agocke/roslyn", "id": "10e1645fb8c5b9d0026ba7342d3372ee6637fd02", "size": "5607", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_FindReferences_Legacy.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "126326705" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "8276" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "237208" }, { "name": "Shell", "bytes": "94927" }, { "name": "Visual Basic .NET", "bytes": "70527543" } ], "symlink_target": "" }
// This file has been automatically generated by goFB and should not be edited by hand // Compiler written by Hammond Pearce and available at github.com/kiwih/goFB // This file represents the implementation of the Composite Function Block for FlexPRET #include "FlexPRET.h" //When running a composite block, note that you would call the functions in this order (and this is very important) //_preinit(); //_init(); //do { // _syncOutputEvents(); // _syncInputEvents(); // _syncOutputData(); // _syncInputData(); // _run(); //} loop; /* FlexPRET_preinit() is required to be called to * initialise an instance of FlexPRET. * It sets all I/O values to zero. */ int FlexPRET_preinit(FlexPRET_t *me) { //if there are input events, reset them //if there are output events, reset them //if there are input vars with default values, set them //if there are output vars with default values, set them //if there are internal vars with default values, set them (BFBs only) //if there are resource vars with default values, set them //if there are resources with set parameters, set them //if there are fb children (CFBs/Devices/Resources only), call this same function on them if(IOManager_preinit(&me->IO) != 0) { return 1; } if(CanisterCounter_preinit(&me->CCounter) != 0) { return 1; } if(DoorController_preinit(&me->Door) != 0) { return 1; } if(ConveyorController_preinit(&me->Conveyor) != 0) { return 1; } if(RejectArmController_preinit(&me->RejectArm) != 0) { return 1; } if(InjectorPumpsController_preinit(&me->Pumps) != 0) { return 1; } if(InjectorMotorController_preinit(&me->Motor) != 0) { return 1; } //if this is a BFB, set _trigger to be true and start state so that the start state is properly executed return 0; } /* FlexPRET_init() is required to be called to * set up an instance of FlexPRET. * It passes around configuration data. */ int FlexPRET_init(FlexPRET_t *me) { //pass in any parameters on this level //perform a data copy to all children (if any present) (can move config data around, doesn't do anything otherwise) me->Door.EmergencyStop = me->IO.EmergencyStop; me->Conveyor.EmergencyStop = me->IO.EmergencyStop; me->Motor.EmergencyStop = me->IO.EmergencyStop; me->Pumps.EmergencyStop = me->IO.EmergencyStop; me->Pumps.CanisterPressure = me->IO.CanisterPressure; me->Pumps.FillContentsAvailable = me->IO.FillContentsAvailable; me->CCounter.DoorSiteLaser = me->IO.DoorSiteLaser; me->Conveyor.InjectSiteLaser = me->IO.InjectSiteLaser; me->RejectArm.RejectSiteLaser = me->IO.RejectSiteLaser; me->CCounter.RejectBinLaser = me->IO.RejectBinLaser; me->CCounter.AcceptBinLaser = me->IO.AcceptBinLaser; me->IO.CanisterCount = me->CCounter.CanisterCount; me->IO.ConveyorSpeed = me->Conveyor.ConveyorSpeed; me->IO.InjectorContentsValveOpen = me->Pumps.InjectorContentsValveOpen; me->IO.InjectorVacuumRun = me->Pumps.InjectorVacuumRun; me->IO.InjectorPressurePumpRun = me->Pumps.InjectorPressurePumpRun; me->IO.FillContents = me->Pumps.FillContents; me->IO.InjectorPosition = me->Motor.InjectorPosition; //if there are fb children (CFBs/Devices/Resources only), call this same function on them if(IOManager_init(&me->IO) != 0) { return 1; } if(CanisterCounter_init(&me->CCounter) != 0) { return 1; } if(DoorController_init(&me->Door) != 0) { return 1; } if(ConveyorController_init(&me->Conveyor) != 0) { return 1; } if(RejectArmController_init(&me->RejectArm) != 0) { return 1; } if(InjectorPumpsController_init(&me->Pumps) != 0) { return 1; } if(InjectorMotorController_init(&me->Motor) != 0) { return 1; } return 0; } /* FlexPRET_syncOutputEvents() synchronises the output events of an * instance of FlexPRET as required by synchronous semantics. * Notice that it does NOT perform any computation - this occurs in the * _run function. */ void FlexPRET_syncOutputEvents(FlexPRET_t *me) { //first, for all cfb children, call this same function //then, for all connections that are connected to an output on the parent, run their run their copy } /* FlexPRET_syncInputEvents() synchronises the input events of an * instance of FlexPRET as required by synchronous semantics. * Notice that it does NOT perform any computation - this occurs in the * _run function. */ void FlexPRET_syncInputEvents(FlexPRET_t *me) { //first, we explicitly synchronise the children me->IO.inputEvents.event.DoorReleaseCanister = me->Door.outputEvents.event.DoorReleaseCanister; me->IO.inputEvents.event.ConveyorChanged = me->Conveyor.outputEvents.event.ConveyorChanged; me->IO.inputEvents.event.InjectorPositionChanged = me->Motor.outputEvents.event.InjectorPositionChanged; me->IO.inputEvents.event.InjectorControlsChanged = me->Pumps.outputEvents.event.InjectorControlsChanged; me->IO.inputEvents.event.FillContentsChanged = me->Pumps.outputEvents.event.FillContentsChanged; me->IO.inputEvents.event.StartVacuumTimer = me->Pumps.outputEvents.event.StartVacuumTimer; me->IO.inputEvents.event.GoRejectArm = me->RejectArm.outputEvents.event.GoRejectArm; me->IO.inputEvents.event.CanisterCountChanged = me->CCounter.outputEvents.event.CanisterCountChanged; me->IO.inputEvents.event.InjectDone = me->Motor.outputEvents.event.InjectDone; me->CCounter.inputEvents.event.LasersChanged = me->IO.outputEvents.event.LasersChanged; me->Door.inputEvents.event.ReleaseDoorOverride = me->IO.outputEvents.event.DoorOverride; me->Door.inputEvents.event.BottlingDone = me->Motor.outputEvents.event.InjectDone; me->Door.inputEvents.event.EmergencyStopChanged = me->IO.outputEvents.event.EmergencyStopChanged; me->Conveyor.inputEvents.event.InjectDone = me->Motor.outputEvents.event.InjectDone; me->Conveyor.inputEvents.event.EmergencyStopChanged = me->IO.outputEvents.event.EmergencyStopChanged; me->Conveyor.inputEvents.event.LasersChanged = me->IO.outputEvents.event.LasersChanged; me->RejectArm.inputEvents.event.RejectCanister = me->Pumps.outputEvents.event.RejectCanister; me->RejectArm.inputEvents.event.LasersChanged = me->IO.outputEvents.event.LasersChanged; me->Pumps.inputEvents.event.StartPump = me->Motor.outputEvents.event.StartPump; me->Pumps.inputEvents.event.EmergencyStopChanged = me->IO.outputEvents.event.EmergencyStopChanged; me->Pumps.inputEvents.event.CanisterPressureChanged = me->IO.outputEvents.event.CanisterPressureChanged; me->Pumps.inputEvents.event.FillContentsAvailableChanged = me->IO.outputEvents.event.FillContentsAvailableChanged; me->Pumps.inputEvents.event.VacuumTimerElapsed = me->IO.outputEvents.event.VacuumTimerElapsed; me->Motor.inputEvents.event.InjectorArmFinishedMovement = me->IO.outputEvents.event.InjectorArmFinishMovement; me->Motor.inputEvents.event.EmergencyStopChanged = me->IO.outputEvents.event.EmergencyStopChanged; me->Motor.inputEvents.event.ConveyorStoppedForInject = me->Conveyor.outputEvents.event.ConveyorStoppedForInject; me->Motor.inputEvents.event.PumpFinished = me->Pumps.outputEvents.event.PumpFinished; //then, call this same function on all cfb children } /* FlexPRET_syncOutputData() synchronises the output data connections of an * instance of FlexPRET as required by synchronous semantics. * It does the checking to ensure that only connections which have had their * associated event fire are updated. * Notice that it does NOT perform any computation - this occurs in the * _run function. */ void FlexPRET_syncOutputData(FlexPRET_t *me) { //for all composite function block children, call this same function //for data that is sent from child to this CFB (me), always copy (event controlled copies will be resolved at the next level up) //TODO: arrays!? } /* FlexPRET_syncInputData() synchronises the input data connections of an * instance of FlexPRET as required by synchronous semantics. * It does the checking to ensure that only connections which have had their * associated event fire are updated. * Notice that it does NOT perform any computation - this occurs in the * _run function. */ void FlexPRET_syncInputData(FlexPRET_t *me) { //for all basic function block children, perform their synchronisations explicitly //sync for IO (of type IOManager) which is a BFB if(me->IO.inputEvents.event.ConveyorChanged == 1) { me->IO.ConveyorSpeed = me->Conveyor.ConveyorSpeed; } if(me->IO.inputEvents.event.InjectorPositionChanged == 1) { me->IO.InjectorPosition = me->Motor.InjectorPosition; } if(me->IO.inputEvents.event.InjectorControlsChanged == 1) { me->IO.InjectorContentsValveOpen = me->Pumps.InjectorContentsValveOpen; me->IO.InjectorVacuumRun = me->Pumps.InjectorVacuumRun; me->IO.InjectorPressurePumpRun = me->Pumps.InjectorPressurePumpRun; } if(me->IO.inputEvents.event.FillContentsChanged == 1) { me->IO.FillContents = me->Pumps.FillContents; } if(me->IO.inputEvents.event.CanisterCountChanged == 1) { me->IO.CanisterCount = me->CCounter.CanisterCount; } //sync for CCounter (of type CanisterCounter) which is a BFB if(me->CCounter.inputEvents.event.LasersChanged == 1) { me->CCounter.DoorSiteLaser = me->IO.DoorSiteLaser; me->CCounter.RejectBinLaser = me->IO.RejectBinLaser; me->CCounter.AcceptBinLaser = me->IO.AcceptBinLaser; } //sync for Door (of type DoorController) which is a BFB if(me->Door.inputEvents.event.EmergencyStopChanged == 1) { me->Door.EmergencyStop = me->IO.EmergencyStop; } //sync for Conveyor (of type ConveyorController) which is a BFB if(me->Conveyor.inputEvents.event.EmergencyStopChanged == 1) { me->Conveyor.EmergencyStop = me->IO.EmergencyStop; } if(me->Conveyor.inputEvents.event.LasersChanged == 1) { me->Conveyor.InjectSiteLaser = me->IO.InjectSiteLaser; } //sync for RejectArm (of type RejectArmController) which is a BFB if(me->RejectArm.inputEvents.event.LasersChanged == 1) { me->RejectArm.RejectSiteLaser = me->IO.RejectSiteLaser; } //sync for Pumps (of type InjectorPumpsController) which is a BFB if(me->Pumps.inputEvents.event.EmergencyStopChanged == 1) { me->Pumps.EmergencyStop = me->IO.EmergencyStop; } if(me->Pumps.inputEvents.event.CanisterPressureChanged == 1) { me->Pumps.CanisterPressure = me->IO.CanisterPressure; } if(me->Pumps.inputEvents.event.FillContentsAvailableChanged == 1) { me->Pumps.FillContentsAvailable = me->IO.FillContentsAvailable; } //sync for Motor (of type InjectorMotorController) which is a BFB if(me->Motor.inputEvents.event.EmergencyStopChanged == 1) { me->Motor.EmergencyStop = me->IO.EmergencyStop; } //for all composite function block children, call this same function } /* FlexPRET_run() executes a single tick of an * instance of FlexPRET according to synchronise semantics. * Notice that it does NOT perform any I/O - synchronisation * is done using the _syncX functions at this (and any higher) level. */ void FlexPRET_run(FlexPRET_t *me) { IOManager_run(&me->IO); CanisterCounter_run(&me->CCounter); DoorController_run(&me->Door); ConveyorController_run(&me->Conveyor); RejectArmController_run(&me->RejectArm); InjectorPumpsController_run(&me->Pumps); InjectorMotorController_run(&me->Motor); }
{ "content_hash": "fbae10d531f7024632d3ade403e39e7b", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 146, "avg_line_length": 34.82716049382716, "alnum_prop": 0.7479617157036512, "repo_name": "kiwih/goFB", "id": "67f084e5ebc2bf98a0e03c9364d9a52263365ebb", "size": "11284", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "examples/goFB_only/c_tcrest/bottlingplant_single_mem/c/FlexPRET.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "43131" }, { "name": "C++", "bytes": "5595" }, { "name": "Go", "bytes": "176099" }, { "name": "Makefile", "bytes": "158" }, { "name": "Shell", "bytes": "153" }, { "name": "VHDL", "bytes": "15110" } ], "symlink_target": "" }
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() # Installs the Android package. Notice that this method returns a boolean, so you can test # to see if the installation worked. device.installPackage('../app/target/net-d53dev-dslfy-android-1.0.apk') # sets a variable with the package's internal name package = 'net.d53dev.dslfy.android' # sets a variable with the name of an Activity in the package activity = 'net.d53dev.dslfy.android.ui.CarouselActivity' # sets the name of the component to start runComponent = package + '/' + activity # Runs the component device.startActivity(component=runComponent) MonkeyRunner.sleep(5) device.type('example@example.com') # Takes a screenshot result = device.takeSnapshot() # Writes the screenshot to a file result.writeToFile('screenshot.png','png')
{ "content_hash": "418732af8f97a9a2ab958fb6c523943a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 90, "avg_line_length": 30.8, "alnum_prop": 0.7813852813852814, "repo_name": "d53dave/DSLFY-Android", "id": "b9374572e102990fb5735a85b1c956380dcf5865", "size": "980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration-tests/monkeyrunnerTestSuite.py", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "187405" }, { "name": "Python", "bytes": "980" } ], "symlink_target": "" }
Docker image of [ADAM](https://github.com/bigdatagenomics/adam) built with [Linuxbrew](http://brew.sh/linuxbrew/). * docker pull [heuermh/adam](https://registry.hub.docker.com/u/heuermh/adam/)
{ "content_hash": "c83238ba7fd95054cd3190d8a13d0f4b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 114, "avg_line_length": 64.66666666666667, "alnum_prop": 0.7474226804123711, "repo_name": "heuermh/docker-linuxbrew-bio", "id": "2c4a22274bf079243f8468d9c8b48473fd987828", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "adam/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "6840" } ], "symlink_target": "" }
package com.codingpan.leetcode.todo; import java.util.TreeSet; /** * [220. Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/description/) * Given an array of integers, find out whether there are two distinct indices i and j in the array * such that the absolute difference between nums[i] and nums[j] is at most t and the absolute * difference between i and j is at most k. */ public class LC220ContainsDuplicateIII { // Failed at com.codingpan.test case 4 public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { TreeSet<Integer> treeSet = new TreeSet<Integer>(); for (int i = 0; i < nums.length; i++) { Integer max = treeSet.floor(nums[i] + t); Integer min = treeSet.ceiling(nums[i] - t); if (max != null && max >= nums[i]) return true; if (min != null && min <= nums[i]) return true; treeSet.add(nums[i]); if (i >= k) treeSet.remove(nums[i - k]); } return false; } public static void main(String[] args) { LC220ContainsDuplicateIII solu = new LC220ContainsDuplicateIII(); // false // int[] nums = {-1, 2147483647}; // int k = 1; // int t = 2147483647; // true // int[] nums = {-1, -1}; // int k = 1; // int t = 0; // false // int[] nums = {2147483647, -2147483647}; // int k = 1; // int t = 2147483647; // 4 true int[] nums = {-2147483648, -2147483647}; int k = 3; int t = 3; // int[] nums = {-1, -1}; // int k = 1; // int t = -1; System.out.println(solu.containsNearbyAlmostDuplicate(nums, k, t)); } }
{ "content_hash": "3d8d906d34f13a9b7922c35171ac31d4", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 99, "avg_line_length": 33.490566037735846, "alnum_prop": 0.5464788732394367, "repo_name": "wszdwp/AlgorithmPractice", "id": "a7cb5d3aa682e28530d86e765e2ecafe73cd59ab", "size": "1775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/codingpan/leetcode/todo/LC220ContainsDuplicateIII.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "581475" } ], "symlink_target": "" }
package org.kuali.rice.kew.api.doctype; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.mo.AbstractDataTransferObject; import org.kuali.rice.core.api.mo.ModelBuilder; import org.kuali.rice.kew.api.KewApiConstants; import org.w3c.dom.Element; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @XmlRootElement(name = DocumentType.Constants.ROOT_ELEMENT_NAME) @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = DocumentType.Constants.TYPE_NAME, propOrder = { DocumentType.Elements.ID, DocumentType.Elements.NAME, DocumentType.Elements.DOCUMENT_TYPE_VERSION, DocumentType.Elements.LABEL, DocumentType.Elements.DESCRIPTION, DocumentType.Elements.PARENT_ID, DocumentType.Elements.ACTIVE, DocumentType.Elements.UNRESOLVED_DOC_HANDLER_URL, DocumentType.Elements.RESOLVED_DOC_HANDLER_URL, DocumentType.Elements.HELP_DEFINITION_URL, DocumentType.Elements.DOC_SEARCH_HELP_URL, DocumentType.Elements.POST_PROCESSOR_NAME, DocumentType.Elements.APPLICATION_ID, DocumentType.Elements.CURRENT, DocumentType.Elements.BLANKET_APPROVE_GROUP_ID, DocumentType.Elements.SUPER_USER_GROUP_ID, DocumentType.Elements.POLICIES, DocumentType.Elements.DOCUMENT_TYPE_ATTRIBUTES, CoreConstants.CommonElements.VERSION_NUMBER, DocumentType.Elements.AUTHORIZER, CoreConstants.CommonElements.FUTURE_ELEMENTS }) public final class DocumentType extends AbstractDataTransferObject implements DocumentTypeContract { private static final long serialVersionUID = 6866926296038814812L; @XmlElement(name = Elements.ID, required = false) private final String id; @XmlElement(name = Elements.NAME, required = true) private final String name; @XmlElement(name = Elements.DOCUMENT_TYPE_VERSION, required = false) private final Integer documentTypeVersion; @XmlElement(name = Elements.LABEL, required = false) private final String label; @XmlElement(name = Elements.DESCRIPTION, required = false) private final String description; @XmlElement(name = Elements.PARENT_ID, required = false) private final String parentId; @XmlElement(name = Elements.ACTIVE, required = true) private final boolean active; @XmlElement(name = Elements.UNRESOLVED_DOC_HANDLER_URL, required = false) private final String unresolvedDocHandlerUrl; @XmlElement(name = Elements.RESOLVED_DOC_HANDLER_URL, required = false) private final String resolvedDocumentHandlerUrl; @XmlElement(name = Elements.HELP_DEFINITION_URL, required = false) private final String helpDefinitionUrl; @XmlElement(name = Elements.DOC_SEARCH_HELP_URL, required = false) private final String docSearchHelpUrl; @XmlElement(name = Elements.POST_PROCESSOR_NAME, required = false) private final String postProcessorName; @XmlElement(name = Elements.APPLICATION_ID, required = false) private final String applicationId; @XmlElement(name = Elements.CURRENT, required = true) private final boolean current; @XmlElement(name = Elements.BLANKET_APPROVE_GROUP_ID, required = false) private final String blanketApproveGroupId; @XmlElement(name = Elements.SUPER_USER_GROUP_ID, required = false) private final String superUserGroupId; @XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false) private final Long versionNumber; @XmlElement(name = Elements.POLICIES, required = true) @XmlJavaTypeAdapter(DocumentTypePolicyMapAdapter.class) private final Map<DocumentTypePolicy, String> policies; @XmlElementWrapper(name = Elements.DOCUMENT_TYPE_ATTRIBUTES, required = false) @XmlElement(name = Elements.DOCUMENT_TYPE_ATTRIBUTE, required = false) private final List<DocumentTypeAttribute> documentTypeAttributes; /** * @since 2.1.3 */ @XmlElement(name = Elements.AUTHORIZER, required = false) private final String authorizer; @SuppressWarnings("unused") @XmlAnyElement private final Collection<Element> _futureElements = null; /** * Private constructor used only by JAXB. */ private DocumentType() { this.id = null; this.name = null; this.documentTypeVersion = null; this.label = null; this.description = null; this.parentId = null; this.active = false; this.unresolvedDocHandlerUrl = null; this.resolvedDocumentHandlerUrl = null; this.helpDefinitionUrl = null; this.docSearchHelpUrl = null; this.postProcessorName = null; this.applicationId = null; this.current = false; this.blanketApproveGroupId = null; this.superUserGroupId = null; this.policies = null; this.versionNumber = null; this.documentTypeAttributes = null; this.authorizer = null; } private DocumentType(Builder builder) { this.name = builder.getName(); this.id = builder.getId(); this.documentTypeVersion = builder.getDocumentTypeVersion(); this.label = builder.getLabel(); this.description = builder.getDescription(); this.parentId = builder.getParentId(); this.active = builder.isActive(); this.unresolvedDocHandlerUrl = builder.getUnresolvedDocHandlerUrl(); this.resolvedDocumentHandlerUrl = builder.getResolvedDocumentHandlerUrl(); this.helpDefinitionUrl = builder.getHelpDefinitionUrl(); this.docSearchHelpUrl = builder.getDocSearchHelpUrl(); this.postProcessorName = builder.getPostProcessorName(); this.applicationId = builder.getApplicationId(); this.current = builder.isCurrent(); this.blanketApproveGroupId = builder.getBlanketApproveGroupId(); this.superUserGroupId = builder.getSuperUserGroupId(); if (builder.getPolicies() == null) { this.policies = Collections.emptyMap(); } else { this.policies = Collections.unmodifiableMap(new HashMap<DocumentTypePolicy, String>(builder.getPolicies())); } this.versionNumber = builder.getVersionNumber(); List<DocumentTypeAttribute> tempAttributes = new ArrayList<DocumentTypeAttribute>(); if (CollectionUtils.isNotEmpty(builder.getDocumentTypeAttributes())) { for (DocumentTypeAttribute.Builder externalId : builder.getDocumentTypeAttributes()) { tempAttributes.add(externalId.build()); } } this.documentTypeAttributes = Collections.unmodifiableList(tempAttributes); this.authorizer = builder.getAuthorizer(); } @Override public String getId() { return this.id; } @Override public String getName() { return this.name; } @Override public Integer getDocumentTypeVersion() { return this.documentTypeVersion; } @Override public String getLabel() { return this.label; } @Override public String getDescription() { return this.description; } @Override public String getParentId() { return this.parentId; } @Override public boolean isActive() { return this.active; } @Override public String getUnresolvedDocHandlerUrl() { return this.unresolvedDocHandlerUrl; } @Override public String getHelpDefinitionUrl() { return this.helpDefinitionUrl; } @Override public String getDocSearchHelpUrl() { return this.docSearchHelpUrl; } @Override public String getPostProcessorName() { return this.postProcessorName; } @Override public String getApplicationId() { return this.applicationId; } @Override public boolean isCurrent() { return this.current; } @Override public String getBlanketApproveGroupId() { return this.blanketApproveGroupId; } @Override public String getSuperUserGroupId() { return this.superUserGroupId; } @Override public Map<DocumentTypePolicy, String> getPolicies() { return this.policies; } @Override public List<DocumentTypeAttribute> getDocumentTypeAttributes() { return this.documentTypeAttributes; } @Override public Long getVersionNumber() { return this.versionNumber; } @Override public String getResolvedDocumentHandlerUrl() { return this.resolvedDocumentHandlerUrl; } /** * @since 2.1.3 * @ */ @Override public String getAuthorizer() { return this.authorizer; } /** * A builder which can be used to construct {@link DocumentType} instances. Enforces the * constraints of the {@link DocumentTypeContract}. */ public final static class Builder implements Serializable, ModelBuilder, DocumentTypeContract { private static final long serialVersionUID = 1678979180435181578L; private String id; private String name; private Integer documentTypeVersion; private String label; private String description; private String parentId; private boolean active; private String unresolvedDocHandlerUrl; private String resolvedDocumentHandlerUrl; private String helpDefinitionUrl; private String docSearchHelpUrl; private String postProcessorName; private String applicationId; private boolean current; private String blanketApproveGroupId; private String superUserGroupId; private Map<DocumentTypePolicy, String> policies; private List<DocumentTypeAttribute.Builder> documentTypeAttributes; private Long versionNumber; private String authorizer; private Builder(String name) { setName(name); setActive(true); setCurrent(true); this.policies = new HashMap<DocumentTypePolicy, String>(); this.documentTypeAttributes = Collections.emptyList(); } public static Builder create(String name) { return new Builder(name); } public static Builder create(DocumentTypeContract contract) { if (contract == null) { throw new IllegalArgumentException("contract was null"); } Builder builder = create(contract.getName()); builder.setId(contract.getId()); builder.setDocumentTypeVersion(contract.getDocumentTypeVersion()); builder.setLabel(contract.getLabel()); builder.setDescription(contract.getDescription()); builder.setParentId(contract.getParentId()); builder.setActive(contract.isActive()); builder.setUnresolvedDocHandlerUrl(contract.getUnresolvedDocHandlerUrl()); builder.setResolvedDocHandlerUrl(contract.getResolvedDocumentHandlerUrl()); builder.setHelpDefinitionUrl(contract.getHelpDefinitionUrl()); builder.setDocSearchHelpUrl(contract.getDocSearchHelpUrl()); builder.setPostProcessorName(contract.getPostProcessorName()); builder.setApplicationId(contract.getApplicationId()); builder.setCurrent(contract.isCurrent()); builder.setBlanketApproveGroupId(contract.getBlanketApproveGroupId()); builder.setSuperUserGroupId(contract.getSuperUserGroupId()); builder.setPolicies(new HashMap<DocumentTypePolicy, String>(contract.getPolicies())); if (contract.getDocumentTypeAttributes() != null) { List<DocumentTypeAttribute.Builder> tempAttrs = new ArrayList<DocumentTypeAttribute.Builder>(); for (DocumentTypeAttributeContract attrContract : contract.getDocumentTypeAttributes()) { tempAttrs.add(DocumentTypeAttribute.Builder.create(attrContract)); } builder.setDocumentTypeAttributes(tempAttrs); } builder.setVersionNumber(contract.getVersionNumber()); builder.setAuthorizer(contract.getAuthorizer()); return builder; } public DocumentType build() { return new DocumentType(this); } @Override public String getId() { return this.id; } @Override public String getName() { return this.name; } @Override public Integer getDocumentTypeVersion() { return this.documentTypeVersion; } @Override public String getLabel() { return this.label; } @Override public String getDescription() { return this.description; } @Override public String getParentId() { return this.parentId; } @Override public boolean isActive() { return this.active; } @Override public String getUnresolvedDocHandlerUrl() { return this.unresolvedDocHandlerUrl; } @Override public String getResolvedDocumentHandlerUrl() { return this.resolvedDocumentHandlerUrl; } @Override public String getHelpDefinitionUrl() { return this.helpDefinitionUrl; } @Override public String getDocSearchHelpUrl() { return this.docSearchHelpUrl; } @Override public String getPostProcessorName() { return this.postProcessorName; } @Override public String getApplicationId() { return this.applicationId; } @Override public boolean isCurrent() { return this.current; } @Override public String getBlanketApproveGroupId() { return this.blanketApproveGroupId; } @Override public String getSuperUserGroupId() { return this.superUserGroupId; } @Override public Map<DocumentTypePolicy, String> getPolicies() { return this.policies; } @Override public List<DocumentTypeAttribute.Builder> getDocumentTypeAttributes() { return this.documentTypeAttributes; } @Override public Long getVersionNumber() { return this.versionNumber; } /** * @since 2.1.3 * @ */ @Override public String getAuthorizer() { return this.authorizer; } public void setId(String id) { this.id = id; } public void setName(String name) { if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name was null or blank"); } this.name = name; } public void setDocumentTypeVersion(Integer documentTypeVersion) { this.documentTypeVersion = documentTypeVersion; } public void setLabel(String label) { this.label = label; } public void setDescription(String description) { this.description = description; } public void setParentId(String parentId) { this.parentId = parentId; } public void setActive(boolean active) { this.active = active; } public void setUnresolvedDocHandlerUrl(String unresolvedDocHandlerUrl) { this.unresolvedDocHandlerUrl = unresolvedDocHandlerUrl; } public void setResolvedDocHandlerUrl(String resolvedDocumentHandlerUrl) { this.resolvedDocumentHandlerUrl = resolvedDocumentHandlerUrl; } public void setHelpDefinitionUrl(String helpDefinitionUrl) { this.helpDefinitionUrl = helpDefinitionUrl; } public void setDocSearchHelpUrl(String docSearchHelpUrl) { this.docSearchHelpUrl = docSearchHelpUrl; } public void setPostProcessorName(String postProcessorName) { this.postProcessorName = postProcessorName; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } public void setCurrent(boolean current) { this.current = current; } public void setBlanketApproveGroupId(String blanketApproveGroupId) { this.blanketApproveGroupId = blanketApproveGroupId; } public void setSuperUserGroupId(String superUserGroupId) { this.superUserGroupId = superUserGroupId; } public void setPolicies(Map<DocumentTypePolicy, String> policies) { this.policies = policies; } public void setDocumentTypeAttributes(List<DocumentTypeAttribute.Builder> documentTypeAttributes) { this.documentTypeAttributes = documentTypeAttributes; } public void setVersionNumber(Long versionNumber) { this.versionNumber = versionNumber; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } } /** * Defines some internal constants used on this class. */ static class Constants { final static String ROOT_ELEMENT_NAME = "documentType"; final static String TYPE_NAME = "DocumentTypeType"; } /** * A private class which exposes constants which define the XML element names to use when this * object is marshalled to XML. */ static class Elements { final static String ID = "id"; final static String NAME = "name"; final static String DOCUMENT_TYPE_VERSION = "documentTypeVersion"; final static String LABEL = "label"; final static String DESCRIPTION = "description"; final static String PARENT_ID = "parentId"; final static String ACTIVE = "active"; final static String UNRESOLVED_DOC_HANDLER_URL = "unresolvedDocHandlerUrl"; final static String RESOLVED_DOC_HANDLER_URL = "resolvedDocumentHandlerUrl"; final static String HELP_DEFINITION_URL = "helpDefinitionUrl"; final static String DOC_SEARCH_HELP_URL = "docSearchHelpUrl"; final static String POST_PROCESSOR_NAME = "postProcessorName"; final static String APPLICATION_ID = "applicationId"; final static String CURRENT = "current"; final static String BLANKET_APPROVE_GROUP_ID = "blanketApproveGroupId"; final static String SUPER_USER_GROUP_ID = "superUserGroupId"; final static String POLICIES = "policies"; final static String DOCUMENT_TYPE_ATTRIBUTES = "documentTypeAttributes"; final static String DOCUMENT_TYPE_ATTRIBUTE = "documentTypeAttribute"; final static String AUTHORIZER = "authorizer"; } public static class Cache { public static final String NAME = KewApiConstants.Namespaces.KEW_NAMESPACE_2_0 + "/" + DocumentType.Constants.TYPE_NAME; } }
{ "content_hash": "a8584e18c091378ae689c80eab598c31", "timestamp": "", "source": "github", "line_count": 594, "max_line_length": 128, "avg_line_length": 33.42087542087542, "alnum_prop": 0.6600342534757203, "repo_name": "kuali/rice-playground", "id": "6b7da5132b06b23c3c88881b0bc9f355f700babd", "size": "20473", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "rice-middleware/kew/api/src/main/java/org/kuali/rice/kew/api/doctype/DocumentType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "582089" }, { "name": "Groovy", "bytes": "2237959" }, { "name": "Java", "bytes": "35408880" }, { "name": "JavaScript", "bytes": "2665736" }, { "name": "PHP", "bytes": "15766" }, { "name": "Shell", "bytes": "13217" }, { "name": "XSLT", "bytes": "107818" } ], "symlink_target": "" }
package co.cask.cdap.data2.transaction.stream; import co.cask.cdap.api.flow.flowlet.StreamEvent; import co.cask.cdap.data2.queue.ConsumerConfig; import co.cask.cdap.data2.queue.DequeueResult; import co.cask.cdap.proto.Id; import co.cask.tephra.Transaction; import java.io.IOException; import java.util.Collection; import java.util.concurrent.TimeUnit; /** * A {@link StreamConsumer} that forwards every methods to another {@link StreamConsumer}. */ public abstract class ForwardingStreamConsumer implements StreamConsumer { private final StreamConsumer delegate; protected ForwardingStreamConsumer(StreamConsumer delegate) { this.delegate = delegate; } @Override public Id.Stream getStreamId() { return delegate.getStreamId(); } @Override public ConsumerConfig getConsumerConfig() { return delegate.getConsumerConfig(); } @Override public DequeueResult<StreamEvent> poll(int maxEvents, long timeout, TimeUnit timeoutUnit) throws IOException, InterruptedException { return delegate.poll(maxEvents, timeout, timeoutUnit); } @Override public void close() throws IOException { delegate.close(); } @Override public void startTx(Transaction tx) { delegate.startTx(tx); } @Override public void updateTx(Transaction tx) { delegate.updateTx(tx); } @Override public Collection<byte[]> getTxChanges() { return delegate.getTxChanges(); } @Override public boolean commitTx() throws Exception { return delegate.commitTx(); } @Override public void postTxCommit() { delegate.postTxCommit(); } @Override public boolean rollbackTx() throws Exception { return delegate.rollbackTx(); } @Override public String getTransactionAwareName() { return delegate.getTransactionAwareName(); } }
{ "content_hash": "d5739c6eb672475dbe63ffb093a048c5", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 105, "avg_line_length": 23.0625, "alnum_prop": 0.7224932249322493, "repo_name": "chtyim/cdap", "id": "5e7c6f86c20183971e30f463dc7e8d2256629440", "size": "2442", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "cdap-data-fabric/src/main/java/co/cask/cdap/data2/transaction/stream/ForwardingStreamConsumer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13173" }, { "name": "CSS", "bytes": "219754" }, { "name": "HTML", "bytes": "455678" }, { "name": "Java", "bytes": "15847298" }, { "name": "JavaScript", "bytes": "1180404" }, { "name": "Python", "bytes": "102235" }, { "name": "Ruby", "bytes": "3178" }, { "name": "Scala", "bytes": "30340" }, { "name": "Shell", "bytes": "195815" } ], "symlink_target": "" }
package main // import "github.com/hashicorp/consul/connect/certgen" import ( "flag" "fmt" "io/ioutil" "log" "os" "github.com/hashicorp/consul/agent/connect" "github.com/hashicorp/consul/agent/structs" "github.com/mitchellh/go-testing-interface" ) func main() { var numCAs = 2 var services = []string{"web", "db", "cache"} var outDir string flag.StringVar(&outDir, "out-dir", "", "REQUIRED: the dir to write certificates to") flag.Parse() if outDir == "" { flag.PrintDefaults() os.Exit(1) } // Create CA certs var prevCA *structs.CARoot for i := 1; i <= numCAs; i++ { ca := connect.TestCA(&testing.RuntimeT{}, prevCA) prefix := fmt.Sprintf("%s/ca%d-ca", outDir, i) writeFile(prefix+".cert.pem", ca.RootCert) writeFile(prefix+".key.pem", ca.SigningKey) if prevCA != nil { fname := fmt.Sprintf("%s/ca%d-xc-by-ca%d.cert.pem", outDir, i, i-1) writeFile(fname, ca.SigningCert) } prevCA = ca // Create service certs for each CA for _, svc := range services { certPEM, keyPEM := connect.TestLeaf(&testing.RuntimeT{}, svc, ca) prefix := fmt.Sprintf("%s/ca%d-svc-%s", outDir, i, svc) writeFile(prefix+".cert.pem", certPEM) writeFile(prefix+".key.pem", keyPEM) } } } func writeFile(name, content string) { fmt.Println("Writing ", name) err := ioutil.WriteFile(name, []byte(content), 0600) if err != nil { log.Fatalf("failed writing file: %s", err) } }
{ "content_hash": "3dd2f39a6314c7ea5944e09628494d8b", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 70, "avg_line_length": 24.46551724137931, "alnum_prop": 0.6525722339675828, "repo_name": "mhausenblas/burry.sh", "id": "89c424576199943dee9fb91818bfadc59e30fd97", "size": "2549", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/hashicorp/consul/connect/certgen/certgen.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "37075" }, { "name": "Makefile", "bytes": "472" } ], "symlink_target": "" }
namespace Nancy.Templates.CSharp.AspNetHost { using Nancy; public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => { return View["index"]; }; } } }
{ "content_hash": "bb548290627b55ae594b1fec04f35d7a", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 44, "avg_line_length": 19.642857142857142, "alnum_prop": 0.4618181818181818, "repo_name": "tparnell8/Nancy.Templates", "id": "7cb2bc5aaca018a153213f9e2da274fe03027392", "size": "277", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/Nancy.Templates/Nancy.Templates.CSharp.AspNetHost/IndexModule.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "20170" }, { "name": "HTML", "bytes": "3537" }, { "name": "PowerShell", "bytes": "2642" } ], "symlink_target": "" }
/* eslint-disable import/extensions */ const request = require('request') const helpers = require('../../../lib/test_helpers.js') describe('cyclecounter', () => { // The only thing that changes is the form attribute, so why not just re-use the object const fieldsToCheckFor = ['DayCount', 'YearCount', 'Time', 'Date'] it('should return an array of objects containing correct fields', (done) => { const params = helpers.testRequestParams('/cyclecounter') const resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor) request(params, resultHandler) }) })
{ "content_hash": "82272f756d1e875dd9fa161593aa811b", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 89, "avg_line_length": 42.5, "alnum_prop": 0.7142857142857143, "repo_name": "apis-is/apis", "id": "a3bf1a1ef04b8d0846b2b4e0ef2a0fbc40e7eda4", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "endpoints/cyclecounter/tests/integration_test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "160301" } ], "symlink_target": "" }
#import "TiProxy.h" #ifdef USE_TI_UIIPAD // if we use a split window, we need to include the ipad popover #ifdef USE_TI_UIIPADSPLITWINDOW #ifndef USE_TI_UIIPADPOPOVER #define USE_TI_UIIPADPOPOVER #endif #endif #ifdef USE_TI_UIIPADPOPOVER #import "TiUIiPadPopoverProxy.h" #endif #ifdef USE_TI_UIIPADSPLITWINDOW #import "TiUIiPadSplitWindowProxy.h" #endif #ifdef USE_TI_UIIPADDOCUMENTVIEWER #import "TiUIiOSDocumentViewerProxy.h" #endif @interface TiUIiPadProxy : TiProxy { @private } #ifdef USE_TI_UIIPADPOPOVER @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_UP; @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_DOWN; @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_LEFT; @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_RIGHT; @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_ANY; @property(nonatomic,readonly) NSNumber* POPOVER_ARROW_DIRECTION_UNKNOWN; -(id)createPopover:(id)args; #endif #ifdef USE_TI_UIIPADSPLITWINDOW -(id)createSplitWindow:(id)args; #endif #ifdef USE_TI_UIIPADDOCUMENTVIEWER -(id)createDocumentViewer:(id)args; #endif @end #endif
{ "content_hash": "2fdf07dced9e95c00a8dae85d8887765", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 72, "avg_line_length": 21.67924528301887, "alnum_prop": 0.7928633594429939, "repo_name": "AppWerft/KrickelKrake", "id": "1b74f61459908cbcc0239b595e1bc040757ea2fd", "size": "1471", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "build/iphone/Classes/TiUIiPadProxy.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "140292" }, { "name": "C++", "bytes": "56872" }, { "name": "D", "bytes": "893244" }, { "name": "JavaScript", "bytes": "18548" }, { "name": "Objective-C", "bytes": "3325780" }, { "name": "Shell", "bytes": "132" } ], "symlink_target": "" }
mysql_error() --SKIPIF-- <?php require_once('skipif.inc'); require_once('skipifconnectfailure.inc'); ?> --FILE-- <?php include "connect.inc"; $tmp = NULL; $link = NULL; if (false !== ($tmp = @mysql_error())) printf("[001] Expecting boolean/false, got %s/%s\n", gettype($tmp), $tmp); if (NULL !== ($tmp = @mysql_error($link))) printf("[002] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp); if (!is_null($tmp = @mysql_error($link, 'too many args'))) printf("[002b] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp); if (!$link = my_mysql_connect($host, $user, $passwd, $db, $port, $socket)) { printf("[003] Cannot connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host, $user, $db, $port, $socket); } $tmp = mysql_error($link); if (!is_string($tmp) || ('' !== $tmp)) printf("[004] Expecting string/empty, got %s/%s. [%d] %s\n", gettype($tmp), $tmp, mysql_errno($link), mysql_error($link)); if (!mysql_query('DROP TABLE IF EXISTS test', $link)) { printf("[005] Failed to drop old test table: [%d] %s\n", mysql_errno($link), mysql_error($link)); } mysql_query('SELECT * FROM test', $link); $tmp = mysql_error($link); if (!is_string($tmp) || !preg_match("/Table '\w*\.test' doesn't exist/su", $tmp)) printf("[006] Expecting string/[Table... doesn't exit], got %s/%s. [%d] %s\n", gettype($tmp), $tmp, mysql_errno($link), mysql_error($link)); if ((version_compare(PHP_VERSION, '5.9.9', '>') == 1) && !is_unicode($tmp)) { printf("[007] Expecting Unicode error message!\n"); var_inspect($tmp); } mysql_close($link); var_dump(mysql_error($link)); if ($link = @mysql_connect($host . '_unknown', $user . '_unknown', $passwd, true)) { printf("[008] Can connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host . '_unknown', $user . '_unknown', $db, $port, $socket); } if ('' == mysql_error()) printf("[009] Connect error should have been set\n"); print "done!"; ?> --CLEAN-- <?php require_once("clean_table.inc"); ?> --EXPECTF-- Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in %s on line %d Warning: mysql_error(): %d is not a valid MySQL-Link resource in %s on line %d bool(false) done!
{ "content_hash": "32db5ffe75d4618e1b9b8e21668dfcda", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 141, "avg_line_length": 33.470588235294116, "alnum_prop": 0.6221441124780316, "repo_name": "anindoasaha/php_nginx", "id": "a2cf7e003430ae5385c0b225511d10b591141eec", "size": "2285", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "php-5.5.16/ext/mysql/tests/mysql_error.phpt", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1050" }, { "name": "Awk", "bytes": "15007" }, { "name": "Bison", "bytes": "69182" }, { "name": "C", "bytes": "53217026" }, { "name": "C++", "bytes": "2492956" }, { "name": "CMake", "bytes": "28491" }, { "name": "DTrace", "bytes": "2194" }, { "name": "GAP", "bytes": "4" }, { "name": "GLSL", "bytes": "239" }, { "name": "Groff", "bytes": "504611" }, { "name": "HTML", "bytes": "569653" }, { "name": "JavaScript", "bytes": "108172" }, { "name": "Makefile", "bytes": "56241" }, { "name": "Nginx", "bytes": "3817" }, { "name": "Objective-C", "bytes": "7678" }, { "name": "PHP", "bytes": "24647829" }, { "name": "Pascal", "bytes": "26071" }, { "name": "Perl", "bytes": "39455" }, { "name": "Python", "bytes": "165" }, { "name": "Ruby", "bytes": "357716" }, { "name": "Shell", "bytes": "731299" }, { "name": "VimL", "bytes": "32089" }, { "name": "XS", "bytes": "21306" }, { "name": "XSLT", "bytes": "7946" } ], "symlink_target": "" }
import sys number = 0 while number >= 0: print "Enter number:" number = float(sys.stdin.readline()) if number >= 0: if number % 2 == 0: print "Even" else: print "Odd" print "Bye"
{ "content_hash": "82e55ed33e6b245aa18d90b9fe6c3a65", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 40, "avg_line_length": 19.333333333333332, "alnum_prop": 0.5129310344827587, "repo_name": "nathano/Perl_to_Python_Converter", "id": "6adfe6c6e9ace17ee4fbdb2e555bacf164d19366", "size": "256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/subset4/odd0.py", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "20894" }, { "name": "Python", "bytes": "2735" } ], "symlink_target": "" }
content::RegisterIPCLogger(msg_id, logger) #include "content/shell/common/shell_messages.h" #endif #if defined(OS_ANDROID) #include "base/posix/global_descriptors.h" #include "content/shell/android/shell_descriptors.h" #endif #if defined(OS_MACOSX) #include "base/mac/os_crash_dumps.h" #include "components/crash/app/breakpad_mac.h" #include "content/shell/app/paths_mac.h" #include "content/shell/app/shell_main_delegate_mac.h" #endif // OS_MACOSX #if defined(OS_WIN) #include <initguid.h> #include <windows.h> #include "base/logging_win.h" #include "components/crash/app/breakpad_win.h" #include "content/shell/common/v8_breakpad_support_win.h" #endif #if defined(OS_POSIX) && !defined(OS_MACOSX) #include "components/crash/app/breakpad_linux.h" #endif namespace { base::LazyInstance<content::ShellCrashReporterClient>::Leaky g_shell_crash_client = LAZY_INSTANCE_INITIALIZER; #if defined(OS_WIN) // If "Content Shell" doesn't show up in your list of trace providers in // Sawbuck, add these registry entries to your machine (NOTE the optional // Wow6432Node key for x64 machines): // 1. Find: HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers // 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}" // 3. Add these values: // "default_flags"=dword:00000001 // "default_level"=dword:00000004 // @="Content Shell" // {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6} const GUID kContentShellProviderName = { 0x6a3e50a4, 0x7e15, 0x4099, { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } }; #endif void InitLogging() { base::FilePath log_filename; PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("content_shell.log"); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_ALL; settings.log_file = log_filename.value().c_str(); settings.delete_old = logging::DELETE_OLD_LOG_FILE; logging::InitLogging(settings); logging::SetLogItems(true, true, true, true); } } // namespace namespace content { ShellMainDelegate::ShellMainDelegate() { } ShellMainDelegate::~ShellMainDelegate() { } bool ShellMainDelegate::BasicStartupComplete(int* exit_code) { base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); // "dump-render-tree" has been renamed to "run-layout-test", but the old // flag name is still used in some places, so this check will remain until // it is phased out entirely. if (command_line.HasSwitch(switches::kDumpRenderTree)) command_line.AppendSwitch(switches::kRunLayoutTest); #if defined(OS_WIN) // Enable trace control and transport through event tracing for Windows. logging::LogEventProvider::Initialize(kContentShellProviderName); v8_breakpad_support::SetUp(); #endif #if defined(OS_MACOSX) // Needs to happen before InitializeResourceBundle() and before // BlinkTestPlatformInitialize() are called. OverrideFrameworkBundlePath(); OverrideChildProcessPath(); EnsureCorrectResolutionSettings(); #endif // OS_MACOSX InitLogging(); if (command_line.HasSwitch(switches::kCheckLayoutTestSysDeps)) { // If CheckLayoutSystemDeps succeeds, we don't exit early. Instead we // continue and try to load the fonts in BlinkTestPlatformInitialize // below, and then try to bring up the rest of the content module. if (!CheckLayoutSystemDeps()) { if (exit_code) *exit_code = 1; return true; } } if (command_line.HasSwitch(switches::kRunLayoutTest)) { EnableBrowserLayoutTestMode(); command_line.AppendSwitch(switches::kProcessPerTab); command_line.AppendSwitch(switches::kEnableLogging); command_line.AppendSwitch(switches::kAllowFileAccessFromFiles); // only default to osmesa if the flag isn't already specified. if (!command_line.HasSwitch(switches::kUseGL)) { command_line.AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationOSMesaName); } command_line.AppendSwitch(switches::kSkipGpuDataLoading); command_line.AppendSwitchASCII(switches::kTouchEvents, switches::kTouchEventsEnabled); command_line.AppendSwitchASCII(switches::kForceDeviceScaleFactor, "1.0"); #if defined(OS_ANDROID) command_line.AppendSwitch( switches::kDisableGestureRequirementForMediaPlayback); #endif if (!command_line.HasSwitch(switches::kStableReleaseMode)) { command_line.AppendSwitch( switches::kEnableExperimentalWebPlatformFeatures); } if (!command_line.HasSwitch(switches::kEnableThreadedCompositing)) { command_line.AppendSwitch(switches::kDisableThreadedCompositing); command_line.AppendSwitch(cc::switches::kDisableThreadedAnimation); // Text blobs are normally disabled when kDisableImplSidePainting is // present to ensure correct LCD behavior, but for layout tests we want // them on because LCD is always suppressed. command_line.AppendSwitch(switches::kForceTextBlobs); } if (!command_line.HasSwitch(switches::kEnableDisplayList2dCanvas)) { command_line.AppendSwitch(switches::kDisableDisplayList2dCanvas); } command_line.AppendSwitch(switches::kEnableInbandTextTracks); command_line.AppendSwitch(switches::kMuteAudio); // TODO: crbug.com/311404 Make layout tests work w/ delegated renderer. command_line.AppendSwitch(switches::kDisableDelegatedRenderer); command_line.AppendSwitch(cc::switches::kCompositeToMailbox); command_line.AppendSwitch(switches::kEnablePreciseMemoryInfo); command_line.AppendSwitchASCII(switches::kHostResolverRules, "MAP *.test 127.0.0.1"); // TODO(wfh): crbug.com/295137 Remove this when NPAPI is gone. command_line.AppendSwitch(switches::kEnableNpapi); // Unless/until WebM files are added to the media layout tests, we need to // avoid removing MP4/H264/AAC so that layout tests can run on Android. #if !defined(OS_ANDROID) net::RemoveProprietaryMediaTypesAndCodecsForTests(); #endif if (!BlinkTestPlatformInitialize()) { if (exit_code) *exit_code = 1; return true; } } SetContentClient(&content_client_); return false; } void ShellMainDelegate::PreSandboxStartup() { #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX)) // Create an instance of the CPU class to parse /proc/cpuinfo and cache // cpu_brand info. base::CPU cpu_info; #endif if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { std::string process_type = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessType); crash_reporter::SetCrashReporterClient(g_shell_crash_client.Pointer()); #if defined(OS_MACOSX) base::mac::DisableOSCrashDumps(); breakpad::InitCrashReporter(process_type); breakpad::InitCrashProcessInfo(process_type); #elif defined(OS_POSIX) && !defined(OS_MACOSX) if (process_type != switches::kZygoteProcess) { #if defined(OS_ANDROID) if (process_type.empty()) breakpad::InitCrashReporter(process_type); else breakpad::InitNonBrowserCrashReporterForAndroid(process_type); #else breakpad::InitCrashReporter(process_type); #endif } #elif defined(OS_WIN) UINT new_flags = SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX; UINT existing_flags = SetErrorMode(new_flags); SetErrorMode(existing_flags | new_flags); breakpad::InitCrashReporter(process_type); #endif } InitializeResourceBundle(); } int ShellMainDelegate::RunProcess( const std::string& process_type, const MainFunctionParams& main_function_params) { if (!process_type.empty()) return -1; #if !defined(OS_ANDROID) // Android stores the BrowserMainRunner instance as a scoped member pointer // on the ShellMainDelegate class because of different object lifetime. scoped_ptr<BrowserMainRunner> browser_runner_; #endif browser_runner_.reset(BrowserMainRunner::Create()); base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(switches::kRunLayoutTest) || command_line.HasSwitch(switches::kCheckLayoutTestSysDeps) ? LayoutTestBrowserMain(main_function_params, browser_runner_) : ShellBrowserMain(main_function_params, browser_runner_); } #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX) void ShellMainDelegate::ZygoteForked() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { std::string process_type = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessType); breakpad::InitCrashReporter(process_type); } } #endif void ShellMainDelegate::InitializeResourceBundle() { #if defined(OS_ANDROID) // In the Android case, the renderer runs with a different UID and can never // access the file system. So we are passed a file descriptor to the // ResourceBundle pak at launch time. int pak_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor); if (pak_fd >= 0) { // This is clearly wrong. See crbug.com/330930 ui::ResourceBundle::InitSharedInstanceWithPakFileRegion( base::File(pak_fd), base::MemoryMappedFile::Region::kWholeFile); ResourceBundle::GetSharedInstance().AddDataPackFromFile( base::File(pak_fd), ui::SCALE_FACTOR_100P); return; } #endif base::FilePath pak_file; #if defined(OS_MACOSX) pak_file = GetResourcesPakFilePath(); #else base::FilePath pak_dir; #if defined(OS_ANDROID) bool got_path = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_dir); DCHECK(got_path); pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks")); #else PathService::Get(base::DIR_MODULE, &pak_dir); #endif pak_file = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak")); #endif ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file); } ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() { browser_client_.reset(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kRunLayoutTest) ? new LayoutTestContentBrowserClient : new ShellContentBrowserClient); return browser_client_.get(); } ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() { renderer_client_.reset(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kRunLayoutTest) ? new LayoutTestContentRendererClient : new ShellContentRendererClient); return renderer_client_.get(); } } // namespace content
{ "content_hash": "8599341047f23893ef94be370280495e", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 80, "avg_line_length": 35.794701986754966, "alnum_prop": 0.7147086031452359, "repo_name": "mou4e/zirconium", "id": "ee1878ce1a7bad22e42cd6ab38c42dd5c3137ad7", "size": "12638", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "content/shell/app/shell_main_delegate.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23829" }, { "name": "C", "bytes": "4115478" }, { "name": "C++", "bytes": "233013312" }, { "name": "CSS", "bytes": "931463" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "HTML", "bytes": "28131619" }, { "name": "Java", "bytes": "9810569" }, { "name": "JavaScript", "bytes": "19670133" }, { "name": "Makefile", "bytes": "68017" }, { "name": "Objective-C", "bytes": "1475873" }, { "name": "Objective-C++", "bytes": "8640851" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "171186" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "456460" }, { "name": "Python", "bytes": "7958623" }, { "name": "Shell", "bytes": "477153" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
Goal: Show how to use Beam Notebooks for interactive development of pipelines and use the Dataframes API ## Demo Setup and Notes To set up this demo, you will need to create a Dataflow Notebooks environment and clone the training-data-analyst repo. This can be done in advance of the demo for the sake of time, but should only take a couple of minutes if done live. To create the Dataflow Notebooks environment go to the Google Cloud Console, click on the main menu, and then go to **Dataflow > Workbench**. Once in the Dataflow Notebooks UI, click on **New Instance** and select **Apache Beam > Without GPUs**. You do not need to edit anything else about the instance, but just need to click **Create**. Once the notebook is ready, you can click on **Open JupyterLab** to tunnel into the JupyterLab interface. ![Dataflow Notebooks UI](img/notebook_ui.png) Once in the notebook interface, on the Launcher select **Terminal**. ![JupyterLab Launcher](img/launcher.png) In the new terminal session run the following commands to clone the repo, ```bash cd home/jupyter git clone https://github.com/GoogleCloudPlatform/training-data-analyst.git ``` Once the repo is cloned, in the file browser go to **training-data-analyst > courses > dataflow > demos > beam_notebooks** and open the **beam_notebooks_demo.ipynb** file. When asked, select **Apache Beam 2.40.0 for Python 3** as the kernel. Step through the notebook cell by cell to finish the demo! **Note**: Be sure to run the notebook cell by cell and not run the entire notebook in advance. One of the cells is supposed to return an error to discuss a certain concept.
{ "content_hash": "3ae434b2a5030ee9bc85bad9fe9ad96f", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 338, "avg_line_length": 58.285714285714285, "alnum_prop": 0.7640931372549019, "repo_name": "GoogleCloudPlatform/training-data-analyst", "id": "d57b6716ca42f7df309751d7ae2e3acdf3ea5c53", "size": "1675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "courses/dataflow/demos/beam_notebooks/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "39536" }, { "name": "C#", "bytes": "23445" }, { "name": "C++", "bytes": "30926" }, { "name": "CSS", "bytes": "53087" }, { "name": "Dockerfile", "bytes": "90856" }, { "name": "Go", "bytes": "93755" }, { "name": "HCL", "bytes": "73891" }, { "name": "HTML", "bytes": "2342167" }, { "name": "Java", "bytes": "2441030" }, { "name": "JavaScript", "bytes": "3957504" }, { "name": "Jinja", "bytes": "257585" }, { "name": "Jsonnet", "bytes": "5696" }, { "name": "Jupyter Notebook", "bytes": "242016061" }, { "name": "Makefile", "bytes": "12642" }, { "name": "PigLatin", "bytes": "11558" }, { "name": "Pug", "bytes": "457977" }, { "name": "Python", "bytes": "18543833" }, { "name": "R", "bytes": "68" }, { "name": "Scala", "bytes": "27161" }, { "name": "Shell", "bytes": "763259" }, { "name": "TypeScript", "bytes": "66858" } ], "symlink_target": "" }
require 'spec_helper' describe RailsTemplater::Templater do let(:group) { 'sample' } its(:fixture_replacement) { should be_kind_of(RailsTemplater::FixtureReplacement) } its(:javascript_framework) { should be_kind_of(RailsTemplater::JavaScriptFramework) } its(:orm) { should be_kind_of(RailsTemplater::Orm) } its(:testing_framework) { should be_kind_of(RailsTemplater::TestingFramework) } it "generates a recipe path based on a name" do subject.recipe("mongoid").should == File.expand_path('recipes/mongoid.rb', TEMPLATE_FRAMEWORK_PATH) end it "generates a snippet path" do subject.snippet_path("cucumber").should == File.expand_path('snippets/cucumber', TEMPLATE_FRAMEWORK_PATH) end it "generates a template path" do subject.template_path("haml").should == File.expand_path('templates/haml', TEMPLATE_FRAMEWORK_PATH) end describe "#load_snippet" do let(:snippet_name) { 'sample_snippet' } before(:each) do subject.stub(:snippet_path) { FIXTURE_PATH } end it "loads a snippet" do subject.load_snippet(snippet_name, group).should == load_fixture(snippet_name) end end describe "#load_template" do let(:template_name) { 'sample_template.rb' } before(:each) do subject.stub(:template_path) { FIXTURE_PATH } end it "loads a template" do subject.load_template(template_name, group).should == load_fixture(template_name) end end describe "#post_bundler" do it "adds blocks to post_bundler_strategies" do subject.post_bundler do "Hi" end subject.post_bundler_strategies.should have(1).item result = subject.post_bundler_strategies.first.call result.should == 'Hi' end end end
{ "content_hash": "e4f2370e2466ceed29e876ac66caa1ae", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 109, "avg_line_length": 26.83076923076923, "alnum_prop": 0.6863532110091743, "repo_name": "kfaustino/rails-templater", "id": "dc578c19f315a076a2abd5f98ec9186445e7d94e", "size": "1744", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/rails_templater/templater_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "23019" } ], "symlink_target": "" }
<resources> <string name="app_name">Device ID</string> </resources>
{ "content_hash": "3d565d4d5bd4ff465f3b8c97e013d9b6", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 46, "avg_line_length": 24, "alnum_prop": 0.6805555555555556, "repo_name": "joststricker/device-id", "id": "36e9ddfb4251fe99ad759afd49e6d968efafb4f7", "size": "72", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2693" } ], "symlink_target": "" }
""" Snap7 client used for connection to a siemens 7 server. """ import re import logging from ctypes import byref, create_string_buffer, sizeof from ctypes import Array, c_byte, c_char_p, c_int, c_int32, c_uint16, c_ulong, c_void_p from datetime import datetime from typing import List, Optional, Tuple, Union from .common import check_error, ipv4, load_library from .types import S7SZL, Areas, BlocksList, S7CpInfo, S7CpuInfo, S7DataItem from .types import S7OrderCode, S7Protection, S7SZLList, TS7BlockInfo, WordLen from .types import S7Object, buffer_size, buffer_type, cpu_statuses, param_types from .types import S7CpuInfo, RemotePort, wordlen_to_ctypes, block_types logger = logging.getLogger(__name__) def error_wrap(func): """Parses a s7 error code returned the decorated function.""" def f(*args, **kw): code = func(*args, **kw) check_error(code, context="client") return f class Client: """ A snap7 client Examples: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("127.0.0.1", 0, 0, 1012) >>> client.get_connected() True >>> data = client.db_read(1, 0, 4) >>> data bytearray(b"\\x00\\x00\\x00\\x00") >>> data[3] = 0b00000001 >>> data bytearray(b'\\x00\\x00\\x00\\x01') >>> client.db_write(1, 0, data) """ def __init__(self, lib_location: Optional[str] = None): """Creates a new `Client` instance. Args: lib_location: Full path to the snap7.dll file. Optional. Examples: >>> import snap7 >>> client = snap7.client.Client() # If the `snap7.dll` file is in the path location >>> client = snap7.client.Client(lib_location="/path/to/snap7.dll") # If the `snap7.dll` file is in another location >>> client <snap7.client.Client object at 0x0000028B257128E0> """ self._read_callback = None self._callback = None self._pointer = None self._library = load_library(lib_location) self.create() def __del__(self): self.destroy() def create(self): """Creates a SNAP7 client. """ logger.info("creating snap7 client") self._library.Cli_Create.restype = c_void_p self._pointer = S7Object(self._library.Cli_Create()) def destroy(self) -> Optional[int]: """Destroys the Client object. Returns: Error code from snap7 library. Examples: >>> client.destroy() 640719840 """ logger.info("destroying snap7 client") if self._pointer: return self._library.Cli_Destroy(byref(self._pointer)) self._pointer = None return None def plc_stop(self) -> int: """Puts the CPU in STOP mode Returns: Error code from snap7 library. """ logger.info("stopping plc") return self._library.Cli_PlcStop(self._pointer) def plc_cold_start(self) -> int: """Puts the CPU in RUN mode performing a COLD START. Returns: Error code from snap7 library. """ logger.info("cold starting plc") return self._library.Cli_PlcColdStart(self._pointer) def plc_hot_start(self) -> int: """Puts the CPU in RUN mode performing an HOT START. Returns: Error code from snap7 library. """ logger.info("hot starting plc") return self._library.Cli_PlcHotStart(self._pointer) def get_cpu_state(self) -> str: """Returns the CPU status (running/stopped) Returns: Description of the cpu state. Raises: :obj:`ValueError`: if the cpu state is invalid. Examples: >>> client.get_cpu_statE() 'S7CpuStatusRun' """ state = c_int(0) self._library.Cli_GetPlcStatus(self._pointer, byref(state)) try: status_string = cpu_statuses[state.value] except KeyError: raise ValueError(f"The cpu state ({state.value}) is invalid") logger.debug(f"CPU state is {status_string}") return status_string def get_cpu_info(self) -> S7CpuInfo: """Returns some information about the AG. Returns: :obj:`S7CpuInfo`: data structure with the information. Examples: >>> cpu_info = client.get_cpu_info() >>> print(cpu_info) "<S7CpuInfo ModuleTypeName: b'CPU 315-2 PN/DP' SerialNumber: b'S C-C2UR28922012' ASName: b'SNAP7-SERVER' Copyright: b'Original Siemens Equipment' ModuleName: b'CPU 315-2 PN/DP'> """ info = S7CpuInfo() result = self._library.Cli_GetCpuInfo(self._pointer, byref(info)) check_error(result, context="client") return info @error_wrap def disconnect(self) -> int: """Disconnect a client. Returns: Error code from snap7 library. """ logger.info("disconnecting snap7 client") return self._library.Cli_Disconnect(self._pointer) @error_wrap def connect(self, address: str, rack: int, slot: int, tcpport: int = 102) -> int: """Connects a Client Object to a PLC. Args: address: IP address of the PLC. rack: rack number where the PLC is located. slot: slot number where the CPU is located. tcpport: port of the PLC. Returns: Error code from snap7 library. Example: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) # port is implicit = 102. """ logger.info(f"connecting to {address}:{tcpport} rack {rack} slot {slot}") self.set_param(RemotePort, tcpport) return self._library.Cli_ConnectTo( self._pointer, c_char_p(address.encode()), c_int(rack), c_int(slot)) def db_read(self, db_number: int, start: int, size: int) -> bytearray: """Reads a part of a DB from a PLC Note: Use it only for reading DBs, not Marks, Inputs, Outputs. Args: db_number: number of the DB to be read. start: byte index from where is start to read from. size: amount of bytes to be read. Returns: Buffer read. Example: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) >>> buffer = client.db_read(1, 10, 4) # reads the db number 1 starting from the byte 10 until byte 14. >>> buffer bytearray(b'\\x00\\x00') """ logger.debug(f"db_read, db_number:{db_number}, start:{start}, size:{size}") type_ = wordlen_to_ctypes[WordLen.Byte.value] data = (type_ * size)() result = (self._library.Cli_DBRead( self._pointer, db_number, start, size, byref(data))) check_error(result, context="client") return bytearray(data) @error_wrap def db_write(self, db_number: int, start: int, data: bytearray) -> int: """Writes a part of a DB into a PLC. Args: db_number: number of the DB to be read. start: byte index to start writing to. data: buffer to be write. Returns: Buffer written. Example: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) >>> buffer = bytearray([0b00000001]) >>> client.db_write(1, 10, buffer) # writes the bit number 0 from the byte 10 to TRUE. """ wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] size = len(data) cdata = (type_ * size).from_buffer_copy(data) logger.debug(f"db_write db_number:{db_number} start:{start} size:{size} data:{data}") return self._library.Cli_DBWrite(self._pointer, db_number, start, size, byref(cdata)) def delete(self, block_type: str, block_num: int) -> int: """Delete a block into AG. Args: block_type: type of block. block_num: block number. Returns: Error code from snap7 library. """ logger.info("deleting block") blocktype = block_types[block_type] result = self._library.Cli_Delete(self._pointer, blocktype, block_num) return result def full_upload(self, _type: str, block_num: int) -> Tuple[bytearray, int]: """Uploads a block from AG with Header and Footer infos. The whole block (including header and footer) is copied into the user buffer. Args: _type: type of block. block_num: number of block. Returns: Tuple of the buffer and size. """ _buffer = buffer_type() size = c_int(sizeof(_buffer)) block_type = block_types[_type] result = self._library.Cli_FullUpload(self._pointer, block_type, block_num, byref(_buffer), byref(size)) check_error(result, context="client") return bytearray(_buffer)[:size.value], size.value def upload(self, block_num: int) -> bytearray: """Uploads a block from AG. Note: Upload means from the PLC to the PC. Args: block_num: block to be upload. Returns: Buffer with the uploaded block. """ logger.debug(f"db_upload block_num: {block_num}") block_type = block_types['DB'] _buffer = buffer_type() size = c_int(sizeof(_buffer)) result = self._library.Cli_Upload(self._pointer, block_type, block_num, byref(_buffer), byref(size)) check_error(result, context="client") logger.info(f'received {size} bytes') return bytearray(_buffer) @error_wrap def download(self, data: bytearray, block_num: int = -1) -> int: """Download a block into AG. A whole block (including header and footer) must be available into the user buffer. Note: Download means from the PC to the PLC. Args: data: buffer data. block_num: new block number. Returns: Error code from snap7 library. """ type_ = c_byte size = len(data) cdata = (type_ * len(data)).from_buffer_copy(data) return self._library.Cli_Download(self._pointer, block_num, byref(cdata), size) def db_get(self, db_number: int) -> bytearray: """Uploads a DB from AG using DBRead. Note: This method can't be use for 1200/1500 PLCs. Args: db_number: db number to be read from. Returns: Buffer with the data read. Example: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) >>> buffer = client.db_get(1) # reads the db number 1. >>> buffer bytearray(b"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00...<truncated>\\x00\\x00") """ logger.debug(f"db_get db_number: {db_number}") _buffer = buffer_type() result = self._library.Cli_DBGet( self._pointer, db_number, byref(_buffer), byref(c_int(buffer_size))) check_error(result, context="client") return bytearray(_buffer) def read_area(self, area: Areas, dbnumber: int, start: int, size: int) -> bytearray: """Reads a data area from a PLC With it you can read DB, Inputs, Outputs, Merkers, Timers and Counters. Args: area: area to be read from. dbnumber: number of the db to be read from. In case of Inputs, Marks or Outputs, this should be equal to 0. start: byte index to start reading. size: number of bytes to read. Returns: Buffer with the data read. Raises: :obj:`ValueError`: if the area is not defined in the `Areas` Example: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) >>> buffer = client.read_area(Areas.DB, 1, 10, 4) # Reads the DB number 1 from the byte 10 to the byte 14. >>> buffer bytearray(b'\\x00\\x00') """ if area not in Areas: raise ValueError(f"{area} is not implemented in types") elif area == Areas.TM: wordlen = WordLen.Timer elif area == Areas.CT: wordlen = WordLen.Counter else: wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] logger.debug(f"reading area: {area.name} dbnumber: {dbnumber} start: {start}: amount {size}: wordlen: {wordlen.name}={wordlen.value}") data = (type_ * size)() result = self._library.Cli_ReadArea(self._pointer, area.value, dbnumber, start, size, wordlen.value, byref(data)) check_error(result, context="client") return bytearray(data) @error_wrap def write_area(self, area: Areas, dbnumber: int, start: int, data: bytearray) -> int: """Writes a data area into a PLC. Args: area: area to be write. dbnumber: number of the db to be write to. In case of Inputs, Marks or Outputs, this should be equal to 0. start: byte index to start writting. data: buffer to be write. Returns: Snap7 error code. Exmaple: >>> import snap7 >>> client = snap7.client.Client() >>> client.connect("192.168.0.1", 0, 0) >>> buffer = bytearray([0b00000001]) >>> client.write_area(Areas.DB, 1, 10, buffer) # Writes the bit 0 of the byte 10 from the DB number 1 to TRUE. """ if area == Areas.TM: wordlen = WordLen.Timer elif area == Areas.CT: wordlen = WordLen.Counter else: wordlen = WordLen.Byte type_ = wordlen_to_ctypes[WordLen.Byte.value] size = len(data) logger.debug(f"writing area: {area.name} dbnumber: {dbnumber} start: {start}: size {size}: " f"wordlen {wordlen.name}={wordlen.value} type: {type_}") cdata = (type_ * len(data)).from_buffer_copy(data) return self._library.Cli_WriteArea(self._pointer, area.value, dbnumber, start, size, wordlen.value, byref(cdata)) def read_multi_vars(self, items) -> Tuple[int, S7DataItem]: """Reads different kind of variables from a PLC simultaneously. Args: items: list of items to be read. Returns: Tuple with the return code from the snap7 library and the list of items. """ result = self._library.Cli_ReadMultiVars(self._pointer, byref(items), c_int32(len(items))) check_error(result, context="client") return result, items def list_blocks(self) -> BlocksList: """Returns the AG blocks amount divided by type. Returns: Block list structure object. Examples: >>> block_list = client.list_blocks() >>> print(block_list) <block list count OB: 0 FB: 0 FC: 0 SFB: 0 SFC: 0x0 DB: 1 SDB: 0> """ logger.debug("listing blocks") blocksList = BlocksList() result = self._library.Cli_ListBlocks(self._pointer, byref(blocksList)) check_error(result, context="client") logger.debug(f"blocks: {blocksList}") return blocksList def list_blocks_of_type(self, blocktype: str, size: int) -> Union[int, Array]: """This function returns the AG list of a specified block type. Args: blocktype: specified block type. size: size of the block type. Returns: If size is 0, it returns a 0, otherwise an `Array` of specified block type. Raises: :obj:`ValueError`: if the `blocktype` is not valid. """ _blocktype = block_types.get(blocktype) if not _blocktype: raise ValueError("The blocktype parameter was invalid") logger.debug(f"listing blocks of type: {_blocktype} size: {size}") if size == 0: return 0 data = (c_uint16 * size)() count = c_int(size) result = self._library.Cli_ListBlocksOfType( self._pointer, _blocktype, byref(data), byref(count)) logger.debug(f"number of items found: {count}") check_error(result, context="client") return data def get_block_info(self, blocktype: str, db_number: int) -> TS7BlockInfo: """Returns detailed information about a block present in AG. Args: blocktype: specified block type. db_number: number of db to get information from. Returns: Structure of information from block. Raises: :obj:`ValueError`: if the `blocktype` is not valid. Examples: >>> block_info = client.get_block_info("DB", 1) >>> print(block_info) Block type: 10 Block number: 1 Block language: 5 Block flags: 1 MC7Size: 100 Load memory size: 192 Local data: 0 SBB Length: 20 Checksum: 0 Version: 1 Code date: b'1999/11/17' Interface date: b'1999/11/17' Author: b'' Family: b'' Header: b'' """ blocktype_ = block_types.get(blocktype) if not blocktype_: raise ValueError("The blocktype parameter was invalid") logger.debug(f"retrieving block info for block {db_number} of type {blocktype_}") data = TS7BlockInfo() result = self._library.Cli_GetAgBlockInfo(self._pointer, blocktype_, db_number, byref(data)) check_error(result, context="client") return data @error_wrap def set_session_password(self, password: str) -> int: """Send the password to the PLC to meet its security level. Args: password: password to set. Returns: Snap7 code. Raises: :obj:`ValueError`: if the length of the `password` is more than 8 characters. """ if len(password) > 8: raise ValueError("Maximum password length is 8") return self._library.Cli_SetSessionPassword(self._pointer, c_char_p(password.encode())) @error_wrap def clear_session_password(self) -> int: """Clears the password set for the current session (logout). Returns: Snap7 code. """ return self._library.Cli_ClearSessionPassword(self._pointer) def set_connection_params(self, address: str, local_tsap: int, remote_tsap: int) -> None: """Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates. Note: This function must be called just before `Cli_Connect()`. Args: address: PLC/Equipment IPV4 Address, for example "192.168.1.12" local_tsap: Local TSAP (PC TSAP) remote_tsap: Remote TSAP (PLC TSAP) Raises: :obj:`ValueError`: if the `address` is not a valid IPV4. :obj:`ValueError`: if the result of setting the connection params is different than 0. """ if not re.match(ipv4, address): raise ValueError(f"{address} is invalid ipv4") result = self._library.Cli_SetConnectionParams(self._pointer, address, c_uint16(local_tsap), c_uint16(remote_tsap)) if result != 0: raise ValueError("The parameter was invalid") def set_connection_type(self, connection_type: int): """ Sets the connection resource type, i.e the way in which the Clients connects to a PLC. Args: connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic Raises: :obj:`ValueError`: if the result of setting the connection type is different than 0. """ result = self._library.Cli_SetConnectionType(self._pointer, c_uint16(connection_type)) if result != 0: raise ValueError("The parameter was invalid") def get_connected(self) -> bool: """Returns the connection status Note: Sometimes returns True, while connection is lost. Returns: True if is connected, otherwise false. """ connected = c_int32() result = self._library.Cli_GetConnected(self._pointer, byref(connected)) check_error(result, context="client") return bool(connected) def ab_read(self, start: int, size: int) -> bytearray: """Reads a part of IPU area from a PLC. Args: start: byte index from where start to read. size: amount of bytes to read. Returns: Buffer with the data read. """ wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] data = (type_ * size)() logger.debug(f"ab_read: start: {start}: size {size}: ") result = self._library.Cli_ABRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return bytearray(data) def ab_write(self, start: int, data: bytearray) -> int: """Writes a part of IPU area into a PLC. Args: start: byte index from where start to write. data: buffer with the data to be written. Returns: Snap7 code. """ wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] size = len(data) cdata = (type_ * size).from_buffer_copy(data) logger.debug(f"ab write: start: {start}: size: {size}: ") return self._library.Cli_ABWrite( self._pointer, start, size, byref(cdata)) def as_ab_read(self, start: int, size: int, data) -> int: """Reads a part of IPU area from a PLC asynchronously. Args: start: byte index from where start to read. size: amount of bytes to read. data: buffer where the data will be place. Returns: Snap7 code. """ logger.debug(f"ab_read: start: {start}: size {size}: ") result = self._library.Cli_AsABRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return result def as_ab_write(self, start: int, data: bytearray) -> int: """Writes a part of IPU area into a PLC asynchronously. Args: start: byte index from where start to write. data: buffer with the data to be written. Returns: Snap7 code. """ wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] size = len(data) cdata = (type_ * size).from_buffer_copy(data) logger.debug(f"ab write: start: {start}: size: {size}: ") result = self._library.Cli_AsABWrite( self._pointer, start, size, byref(cdata)) check_error(result, context="client") return result def as_compress(self, time: int) -> int: """ Performs the Compress action asynchronously. Args: time: timeout. Returns: Snap7 code. """ result = self._library.Cli_AsCompress(self._pointer, time) check_error(result, context="client") return result def as_copy_ram_to_rom(self, timeout: int = 1) -> int: """Performs the Copy Ram to Rom action asynchronously. Args: timeout: time to wait unly fail. Returns: Snap7 code. """ result = self._library.Cli_AsCopyRamToRom(self._pointer, timeout) check_error(result, context="client") return result def as_ct_read(self, start: int, amount: int, data) -> int: """Reads counters from a PLC asynchronously. Args: start: byte index to start to read from. amount: amount of bytes to read. data: buffer where the value read will be place. Returns: Snap7 code. """ result = self._library.Cli_AsCTRead(self._pointer, start, amount, byref(data)) check_error(result, context="client") return result def as_ct_write(self, start: int, amount: int, data: bytearray) -> int: """Write counters into a PLC. Args: start: byte index to start to write from. amount: amount of bytes to write. data: buffer to be write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Counter.value] cdata = (type_ * amount).from_buffer_copy(data) result = self._library.Cli_AsCTWrite(self._pointer, start, amount, byref(cdata)) check_error(result, context="client") return result def as_db_fill(self, db_number: int, filler) -> int: """Fills a DB in AG with a given byte. Args: db_number: number of DB to fill. filler: buffer to fill with. Returns: Snap7 code. """ result = self._library.Cli_AsDBFill(self._pointer, db_number, filler) check_error(result, context="client") return result def as_db_get(self, db_number: int, _buffer, size) -> bytearray: """Uploads a DB from AG using DBRead. Note: This method will not work in 1200/1500. Args: db_number: number of DB to get. _buffer: buffer where the data read will be place. size: amount of bytes to be read. Returns: Snap7 code. """ result = self._library.Cli_AsDBGet(self._pointer, db_number, byref(_buffer), byref(size)) check_error(result, context="client") return result def as_db_read(self, db_number: int, start: int, size: int, data) -> Array: """Reads a part of a DB from a PLC. Args: db_number: number of DB to be read. start: byte index from where start to read from. size: amount of bytes to read. data: buffer where the data read will be place. Returns: Snap7 code. Examples: >>> import ctypes >>> data = (ctypes.c_uint8 * size_to_read)() # In this ctypes array data will be stored. >>> result = client.as_db_read(1, 0, size_to_read, data) >>> result # 0 = success 0 """ result = self._library.Cli_AsDBRead(self._pointer, db_number, start, size, byref(data)) check_error(result, context="client") return result def as_db_write(self, db_number: int, start: int, size: int, data) -> int: """Writes a part of a DB into a PLC. Args: db_number: number of DB to be write. start: byte index from where start to write to. size: amount of bytes to write. data: buffer to be write. Returns: Snap7 code. """ result = self._library.Cli_AsDBWrite(self._pointer, db_number, start, size, byref(data)) check_error(result, context="client") return result def as_download(self, data: bytearray, block_num: int) -> int: """Download a block into AG asynchronously. Note: A whole block (including header and footer) must be available into the user buffer. Args: block_num: new block number. data: buffer where the data will be place. Returns: Snap7 code. """ size = len(data) type_ = c_byte * len(data) cdata = type_.from_buffer_copy(data) result = self._library.Cli_AsDownload(self._pointer, block_num, byref(cdata), size) check_error(result) return result @error_wrap def compress(self, time: int) -> int: """Performs the Compress action. Args: time: timeout. Returns: Snap7 code. """ return self._library.Cli_Compress(self._pointer, time) @error_wrap def set_param(self, number: int, value: int) -> int: """Writes an internal Server Parameter. Args: number: number of argument to be written. value: value to be written. Returns: Snap7 code. """ logger.debug(f"setting param number {number} to {value}") type_ = param_types[number] return self._library.Cli_SetParam(self._pointer, number, byref(type_(value))) def get_param(self, number: int) -> int: """Reads an internal Server parameter. Args: number: number of argument to be read. Return: Value of the param read. """ logger.debug(f"retreiving param number {number}") type_ = param_types[number] value = type_() code = self._library.Cli_GetParam(self._pointer, c_int(number), byref(value)) check_error(code) return value.value def get_pdu_length(self) -> int: """Returns info about the PDU length (requested and negotiated). Returns: PDU length. Examples: >>> client.get_pdu_length() 480 """ logger.info("getting PDU length") requested_ = c_uint16() negotiated_ = c_uint16() code = self._library.Cli_GetPduLength(self._pointer, byref(requested_), byref(negotiated_)) check_error(code) return negotiated_.value def get_plc_datetime(self) -> datetime: """Returns the PLC date/time. Returns: Date and time as datetime Examples: >>> client.get_plc_datetime() datetime.datetime(2021, 4, 6, 12, 12, 36) """ type_ = c_int32 buffer = (type_ * 9)() result = self._library.Cli_GetPlcDateTime(self._pointer, byref(buffer)) check_error(result, context="client") return datetime( year=buffer[5] + 1900, month=buffer[4] + 1, day=buffer[3], hour=buffer[2], minute=buffer[1], second=buffer[0] ) @error_wrap def set_plc_datetime(self, dt: datetime) -> int: """Sets the PLC date/time with a given value. Args: dt: datetime to be set. Returns: Snap7 code. """ type_ = c_int32 buffer = (type_ * 9)() buffer[0] = dt.second buffer[1] = dt.minute buffer[2] = dt.hour buffer[3] = dt.day buffer[4] = dt.month - 1 buffer[5] = dt.year - 1900 return self._library.Cli_SetPlcDateTime(self._pointer, byref(buffer)) def check_as_completion(self, p_value) -> int: """Method to check Status of an async request. Result contains if the check was successful, not the data value itself Args: p_value: Pointer where result of this check shall be written. Returns: Snap7 code. If 0 - Job is done successfully. If 1 - Job is either pending or contains s7errors """ result = self._library.Cli_CheckAsCompletion(self._pointer, p_value) check_error(result, context="client") return result def set_as_callback(self, pfn_clicompletion, p_usr): # Cli_SetAsCallback result = self._library.Cli_SetAsCallback(self._pointer, pfn_clicompletion, p_usr) check_error(result, context='client') return result def wait_as_completion(self, timeout: int) -> int: """Snap7 Cli_WaitAsCompletion representative. Args: timeout: ms to wait for async job Returns: Snap7 code. """ # Cli_WaitAsCompletion result = self._library.Cli_WaitAsCompletion(self._pointer, c_ulong(timeout)) check_error(result, context="client") return result def _prepare_as_read_area(self, area: Areas, size: int) -> Tuple[WordLen, Array]: if area not in Areas: raise ValueError(f"{area} is not implemented in types") elif area == Areas.TM: wordlen = WordLen.Timer elif area == Areas.CT: wordlen = WordLen.Counter else: wordlen = WordLen.Byte type_ = wordlen_to_ctypes[wordlen.value] usrdata = (type_ * size)() return wordlen, usrdata def as_read_area(self, area: Areas, dbnumber: int, start: int, size: int, wordlen: WordLen, pusrdata) -> int: """Reads a data area from a PLC asynchronously. With it you can read DB, Inputs, Outputs, Merkers, Timers and Counters. Args: area: memory area to be read from. dbnumber: The DB number, only used when area=Areas.DB start: offset to start writing size: number of units to read pusrdata: buffer where the data will be place. wordlen: length of the word to be read. Returns: Snap7 code. """ logger.debug(f"reading area: {area.name} dbnumber: {dbnumber} start: {start}: amount {size}: wordlen: {wordlen.name}={wordlen.value}") result = self._library.Cli_AsReadArea(self._pointer, area.value, dbnumber, start, size, wordlen.value, pusrdata) check_error(result, context="client") return result def _prepare_as_write_area(self, area: Areas, data: bytearray) -> Tuple[WordLen, Array]: if area not in Areas: raise ValueError(f"{area} is not implemented in types") elif area == Areas.TM: wordlen = WordLen.Timer elif area == Areas.CT: wordlen = WordLen.Counter else: wordlen = WordLen.Byte type_ = wordlen_to_ctypes[WordLen.Byte.value] cdata = (type_ * len(data)).from_buffer_copy(data) return wordlen, cdata def as_write_area(self, area: Areas, dbnumber: int, start: int, size: int, wordlen: WordLen, pusrdata) -> int: """Writes a data area into a PLC asynchronously. Args: area: memory area to be written. dbnumber: The DB number, only used when area=Areas.DB start: offset to start writing. size: amount of bytes to be written. wordlen: length of the word to be written. pusrdata: buffer to be written. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] logger.debug(f"writing area: {area.name} dbnumber: {dbnumber} start: {start}: size {size}: " f"wordlen {wordlen} type: {type_}") cdata = (type_ * len(pusrdata)).from_buffer_copy(pusrdata) res = self._library.Cli_AsWriteArea(self._pointer, area.value, dbnumber, start, size, wordlen.value, byref(cdata)) check_error(res, context="client") return res def as_eb_read(self, start: int, size: int, data) -> int: """Reads a part of IPI area from a PLC asynchronously. Args: start: byte index from where to start reading from. size: amount of bytes to read. data: buffer where the data read will be place. Returns: Snap7 code. """ result = self._library.Cli_AsEBRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return result def as_eb_write(self, start: int, size: int, data: bytearray) -> int: """Writes a part of IPI area into a PLC. Args: start: byte index from where to start writing from. size: amount of bytes to write. data: buffer to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] cdata = (type_ * size).from_buffer_copy(data) result = self._library.Cli_AsEBWrite(self._pointer, start, size, byref(cdata)) check_error(result, context="client") return result def as_full_upload(self, _type: str, block_num: int) -> int: """Uploads a block from AG with Header and Footer infos. Note: Upload means from PLC to PC. Args: _type: type of block. block_num: number of block to upload. Returns: Snap7 code. """ _buffer = buffer_type() size = c_int(sizeof(_buffer)) block_type = block_types[_type] result = self._library.Cli_AsFullUpload(self._pointer, block_type, block_num, byref(_buffer), byref(size)) check_error(result, context="client") return result def as_list_blocks_of_type(self, blocktype: str, data, count) -> int: """Returns the AG blocks list of a given type. Args: blocktype: block type. data: buffer where the data will be place. count: pass. Returns: Snap7 code. Raises: :obj:`ValueError`: if the `blocktype` is invalid """ _blocktype = block_types.get(blocktype) if not _blocktype: raise ValueError("The blocktype parameter was invalid") result = self._library.Cli_AsListBlocksOfType(self._pointer, _blocktype, byref(data), byref(count)) check_error(result, context="client") return result def as_mb_read(self, start: int, size: int, data) -> int: """Reads a part of Merkers area from a PLC. Args: start: byte index from where to start to read from. size: amount of byte to read. data: buffer where the data read will be place. Returns: Snap7 code. """ result = self._library.Cli_AsMBRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return result def as_mb_write(self, start: int, size: int, data: bytearray) -> int: """Writes a part of Merkers area into a PLC. Args: start: byte index from where to start to write to. size: amount of byte to write. data: buffer to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] cdata = (type_ * size).from_buffer_copy(data) result = self._library.Cli_AsMBWrite(self._pointer, start, size, byref(cdata)) check_error(result, context="client") return result def as_read_szl(self, ssl_id: int, index: int, s7_szl: S7SZL, size) -> int: """Reads a partial list of given ID and Index. Args: ssl_id: TODO index: TODO s7_szl: TODO size: TODO Returns: Snap7 code. """ result = self._library.Cli_AsReadSZL(self._pointer, ssl_id, index, byref(s7_szl), byref(size)) check_error(result, context="client") return result def as_read_szl_list(self, szl_list, items_count) -> int: """Reads the list of partial lists available in the CPU. Args: szl_list: TODO items_count: TODO Returns: Snap7 code. """ result = self._library.Cli_AsReadSZLList(self._pointer, byref(szl_list), byref(items_count)) check_error(result, context="client") return result def as_tm_read(self, start: int, amount: int, data) -> bytearray: """Reads timers from a PLC. Args: start: byte index to start read from. amount: amount of bytes to read. data: buffer where the data will be placed. Returns: Snap7 code. """ result = self._library.Cli_AsTMRead(self._pointer, start, amount, byref(data)) check_error(result, context="client") return result def as_tm_write(self, start: int, amount: int, data: bytearray) -> int: """Write timers into a PLC. Args: start: byte index to start writing to. amount: amount of bytes to write. data: buffer to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Timer.value] cdata = (type_ * amount).from_buffer_copy(data) result = self._library.Cli_AsTMWrite(self._pointer, start, amount, byref(cdata)) check_error(result) return result def as_upload(self, block_num: int, _buffer, size) -> int: """Uploads a block from AG. Note: Uploads means from PLC to PC. Args: block_num: block number to upload. _buffer: buffer where the data will be place. size: amount of bytes to uplaod. Returns: Snap7 code. """ block_type = block_types['DB'] result = self._library.Cli_AsUpload(self._pointer, block_type, block_num, byref(_buffer), byref(size)) check_error(result, context="client") return result def copy_ram_to_rom(self, timeout: int = 1) -> int: """Performs the Copy Ram to Rom action. Args: timeout: timeout time. Returns: Snap7 code. """ result = self._library.Cli_CopyRamToRom(self._pointer, timeout) check_error(result, context="client") return result def ct_read(self, start: int, amount: int) -> bytearray: """Reads counters from a PLC. Args: start: byte index to start read from. amount: amount of bytes to read. Returns: Buffer read. """ type_ = wordlen_to_ctypes[WordLen.Counter.value] data = (type_ * amount)() result = self._library.Cli_CTRead(self._pointer, start, amount, byref(data)) check_error(result, context="client") return bytearray(data) def ct_write(self, start: int, amount: int, data: bytearray) -> int: """Write counters into a PLC. Args: start: byte index to start write to. amount: amount of bytes to write. data: buffer data to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Counter.value] cdata = (type_ * amount).from_buffer_copy(data) result = self._library.Cli_CTWrite(self._pointer, start, amount, byref(cdata)) check_error(result) return result def db_fill(self, db_number: int, filler: int) -> int: """Fills a DB in AG with a given byte. Args: db_number: db number to fill. filler: value filler. Returns: Snap7 code. """ result = self._library.Cli_DBFill(self._pointer, db_number, filler) check_error(result) return result def eb_read(self, start: int, size: int) -> bytearray: """Reads a part of IPI area from a PLC. Args: start: byte index to start read from. size: amount of bytes to read. Returns: Data read. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] data = (type_ * size)() result = self._library.Cli_EBRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return bytearray(data) def eb_write(self, start: int, size: int, data: bytearray) -> int: """Writes a part of IPI area into a PLC. Args: start: byte index to be written. size: amount of bytes to write. data: data to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] cdata = (type_ * size).from_buffer_copy(data) result = self._library.Cli_EBWrite(self._pointer, start, size, byref(cdata)) check_error(result) return result def error_text(self, error: int) -> str: """Returns a textual explanation of a given error number. Args: error: error number. Returns: Text error. """ text_length = c_int(256) error_code = c_int32(error) text = create_string_buffer(buffer_size) response = self._library.Cli_ErrorText(error_code, byref(text), text_length) check_error(response) result = bytearray(text)[:text_length.value].decode().strip('\x00') return result def get_cp_info(self) -> S7CpInfo: """Returns some information about the CP (communication processor). Returns: Structure object containing the CP information. """ cp_info = S7CpInfo() result = self._library.Cli_GetCpInfo(self._pointer, byref(cp_info)) check_error(result) return cp_info def get_exec_time(self) -> int: """Returns the last job execution time in milliseconds. Returns: Execution time value. """ time = c_int32() result = self._library.Cli_GetExecTime(self._pointer, byref(time)) check_error(result) return time.value def get_last_error(self) -> int: """Returns the last job result. Returns: Returns the last error value. """ last_error = c_int32() result = self._library.Cli_GetLastError(self._pointer, byref(last_error)) check_error(result) return last_error.value def get_order_code(self) -> S7OrderCode: """Returns the CPU order code. Returns: Order of the code in a structure object. """ order_code = S7OrderCode() result = self._library.Cli_GetOrderCode(self._pointer, byref(order_code)) check_error(result) return order_code def get_pg_block_info(self, block: bytearray) -> TS7BlockInfo: """Returns detailed information about a block loaded in memory. Args: block: buffer where the data will be place. Returns: Structure object that contains the block information. """ block_info = TS7BlockInfo() size = c_int(len(block)) buffer = (c_byte * len(block)).from_buffer_copy(block) result = self._library.Cli_GetPgBlockInfo(self._pointer, byref(buffer), byref(block_info), size) check_error(result) return block_info def get_protection(self) -> S7Protection: """Gets the CPU protection level info. Returns: Structure object with protection attributes. """ s7_protection = S7Protection() result = self._library.Cli_GetProtection(self._pointer, byref(s7_protection)) check_error(result) return s7_protection def iso_exchange_buffer(self, data: bytearray) -> bytearray: """Exchanges a given S7 PDU (protocol data unit) with the CPU. Args: data: buffer to exchange. Returns: Snap7 code. """ size = c_int(len(data)) cdata = (c_byte * len(data)).from_buffer_copy(data) response = self._library.Cli_IsoExchangeBuffer(self._pointer, byref(cdata), byref(size)) check_error(response) result = bytearray(cdata)[:size.value] return result def mb_read(self, start: int, size: int) -> bytearray: """Reads a part of Merkers area from a PLC. Args: start: byte index to be read from. size: amount of bytes to read. Returns: Buffer with the data read. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] data = (type_ * size)() result = self._library.Cli_MBRead(self._pointer, start, size, byref(data)) check_error(result, context="client") return bytearray(data) def mb_write(self, start: int, size: int, data: bytearray) -> int: """Writes a part of Merkers area into a PLC. Args: start: byte index to be written. size: amount of bytes to write. data: buffer to write. Returns: Snap7 code. """ type_ = wordlen_to_ctypes[WordLen.Byte.value] cdata = (type_ * size).from_buffer_copy(data) result = self._library.Cli_MBWrite(self._pointer, start, size, byref(cdata)) check_error(result) return result def read_szl(self, ssl_id: int, index: int = 0x0000) -> S7SZL: """Reads a partial list of given ID and Index. Args: ssl_id: ssl id to be read. index: index to be read. Returns: SZL structure object. """ s7_szl = S7SZL() size = c_int(sizeof(s7_szl)) result = self._library.Cli_ReadSZL(self._pointer, ssl_id, index, byref(s7_szl), byref(size)) check_error(result, context="client") return s7_szl def read_szl_list(self) -> bytearray: """Reads the list of partial lists available in the CPU. Returns: Buffer read. """ szl_list = S7SZLList() items_count = c_int(sizeof(szl_list)) response = self._library.Cli_ReadSZLList(self._pointer, byref(szl_list), byref(items_count)) check_error(response, context="client") result = bytearray(szl_list.List)[:items_count.value] return result def set_plc_system_datetime(self) -> int: """Sets the PLC date/time with the host (PC) date/time. Returns: Snap7 code. """ result = self._library.Cli_SetPlcSystemDateTime(self._pointer) check_error(result) return result def tm_read(self, start: int, amount: int) -> bytearray: """Reads timers from a PLC. Args: start: byte index from where is start to read from. amount: amount of byte to be read. Returns: Buffer read. """ wordlen = WordLen.Timer type_ = wordlen_to_ctypes[wordlen.value] data = (type_ * amount)() result = self._library.Cli_TMRead(self._pointer, start, amount, byref(data)) check_error(result, context="client") return bytearray(data) def tm_write(self, start: int, amount: int, data: bytearray) -> int: """Write timers into a PLC. Args: start: byte index from where is start to write to. amount: amount of byte to be written. data: data to be write. Returns: Snap7 code. """ wordlen = WordLen.Timer type_ = wordlen_to_ctypes[wordlen.value] cdata = (type_ * amount).from_buffer_copy(data) result = self._library.Cli_TMWrite(self._pointer, start, amount, byref(cdata)) check_error(result) return result def write_multi_vars(self, items: List[S7DataItem]) -> int: """Writes different kind of variables into a PLC simultaneously. Args: items: list of items to be written. Returns: Snap7 code. """ items_count = c_int32(len(items)) data = bytearray() for item in items: data += bytearray(item) cdata = (S7DataItem * len(items)).from_buffer_copy(data) result = self._library.Cli_WriteMultiVars(self._pointer, byref(cdata), items_count) check_error(result, context="client") return result
{ "content_hash": "c8014c09a10026ef6a60ab84dddf21b5", "timestamp": "", "source": "github", "line_count": 1566, "max_line_length": 142, "avg_line_length": 33.577905491698594, "alnum_prop": 0.5620637848734382, "repo_name": "gijzelaerr/python-snap7", "id": "103d5e553222560b908d12bd0b5935cab020fe73", "size": "52583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snap7/client.py", "mode": "33261", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "288" }, { "name": "Makefile", "bytes": "934" }, { "name": "Python", "bytes": "267248" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <Document> <Header> <SchemaName>Location</SchemaName> <Identifier>location_geonames_2748074</Identifier> <DocumentState>public</DocumentState> <TimeStamp>1390753461702</TimeStamp> <SummaryFields> <Title>NL &gt; North Brabant &gt; Bergeijk &gt; Rijt</Title> </SummaryFields> </Header> <Body> <Location> <GeopoliticalHierarchy>NL,North Brabant,Bergeijk,Rijt</GeopoliticalHierarchy> <LocationName> <Appelation>Rijt</Appelation> <LocationNameType>populated place</LocationNameType> <Comments></Comments> </LocationName> <Coordinates> <Longitude>5.3097199999999996</Longitude> <Latitude>51.29583</Latitude> </Coordinates> <GeonamesURI>http://www.geonames.org/2748074</GeonamesURI> <WikipediaLink/> <DbpediaLink/> </Location> </Body> </Document>
{ "content_hash": "5e98e70d058a06cb6fc50a1a9dfc3999", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 83, "avg_line_length": 31.482758620689655, "alnum_prop": 0.664841182913472, "repo_name": "delving/oscr-data", "id": "3699bd03d56c1668c8158393571dbd3eebb1fbca", "size": "913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/Location/location_geonames_2748074.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package main import ( "fmt" "log" "net/http" "runtime" "strings" "text/template" "github.com/studygolang/mux" ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) } func main() { router := initRouter() http.Handle("/", router) log.Fatal(http.ListenAndServe(":9999", nil)) } // TODO:多人同时请求不同的包,验证可能会失败 var project = "" func initRouter() *mux.Router { router := mux.NewRouter() router.PathPrefix("/x").HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { path := req.URL.Path paths := strings.SplitN(path, "/", 4) if len(paths) < 3 { return parseTmpl(rw) } project = paths[2] parseTmpl(rw) }) return router } func parseTmpl(rw http.ResponseWriter) { tmpl, err := template.New("gox").Parse(tpl) if err != nil { fmt.Fprintln(rw, "error:", err) return } err = tmpl.Execute(rw, project) if err != nil { fmt.Fprintln(rw, "error:", err) return } } var tpl = ` <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta name="go-import" content="golang.org/x/{{.}} git https://github.com/golang/{{.}}"> </head> <body> </body> </html> `
{ "content_hash": "688c858e802db1cca5938a529f54cd10", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 89, "avg_line_length": 15.633802816901408, "alnum_prop": 0.6342342342342342, "repo_name": "xiexingguang/studygolang", "id": "b3d5c919012db7c22933e982c5ddd6e399013318", "size": "1589", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "websites/code/gox_dispatcher/src/gox/main.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1712" }, { "name": "CSS", "bytes": "234616" }, { "name": "Go", "bytes": "388336" }, { "name": "HTML", "bytes": "296414" }, { "name": "JavaScript", "bytes": "309333" }, { "name": "Shell", "bytes": "1994" }, { "name": "XSLT", "bytes": "3842" } ], "symlink_target": "" }
'use strict'; /** * Class representing a AccessPolicyCreateOrUpdateParameters. */ class AccessPolicyCreateOrUpdateParameters { /** * Create a AccessPolicyCreateOrUpdateParameters. * @member {string} [principalObjectId] The objectId of the principal in * Azure Active Directory. * @member {string} [description] An description of the access policy. * @member {array} [roles] The list of roles the principal is assigned on the * environment. */ constructor() { } /** * Defines the metadata of AccessPolicyCreateOrUpdateParameters * * @returns {object} metadata of AccessPolicyCreateOrUpdateParameters * */ mapper() { return { required: false, serializedName: 'AccessPolicyCreateOrUpdateParameters', type: { name: 'Composite', className: 'AccessPolicyCreateOrUpdateParameters', modelProperties: { principalObjectId: { required: false, serializedName: 'properties.principalObjectId', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, roles: { required: false, serializedName: 'properties.roles', type: { name: 'Sequence', element: { required: false, serializedName: 'AccessPolicyRoleElementType', type: { name: 'Enum', allowedValues: [ 'Reader', 'Contributor' ] } } } } } } }; } } module.exports = AccessPolicyCreateOrUpdateParameters;
{ "content_hash": "ddad45f908fef0996eb6a835efc01d00", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 79, "avg_line_length": 26.333333333333332, "alnum_prop": 0.5476059438635112, "repo_name": "xingwu1/azure-sdk-for-node", "id": "077d725860f9e2008f6997b6883f9b22d9b4d8ce", "size": "2134", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/services/timeseriesinsightsManagement/lib/models/accessPolicyCreateOrUpdateParameters.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "661" }, { "name": "JavaScript", "bytes": "122792600" }, { "name": "Shell", "bytes": "437" }, { "name": "TypeScript", "bytes": "2558" } ], "symlink_target": "" }
var fs = require('fs'); /** * Mock Data */ var _tags = 'dev misc etc hello world thoughts'.split(' '); var _lorem = 'Non eram nescius Brute cum quae summis ingeniis exquisitaque' + ' doctrina philosophi Graeco sermone tractavissent ea Latinis litteris mandaremus' + ' fore ut hic noster labor in varias reprehensiones incurreret nam quibusdam et' + ' iis quidem non admodum indoctis totum hoc displicet philosophari quidam autem' + ' non tam id reprehendunt si remissius agatur sed tantum studium tamque multam' + ' operam ponendam in eo non arbitrantur erunt etiam et ii quidem eruditi Graecis' + ' litteris contemnentes Latinas qui se dicant in Graecis legendis operam malle' + ' consumere postremo aliquos futuros suspicor qui me ad alias litteras vocent' + ' genus hoc scribendi etsi sit elegans personae tamen et dignitatis esse negent' + ' Contra quos omnis dicendum breviter existimo Quamquam philosophiae quidem' + ' vituperatoribus satis responsum est eo libro quo a nobis philosophia defensa et' + ' collaudata est cum esset accusata et vituperata ab Hortensio qui liber cum et' + ' tibi probatus videretur et iis quos ego posse iudicare arbitrarer plura suscepi' + ' veritus ne movere hominum studia viderer retinere non posse Qui autem si maxime' + ' hoc placeat moderatius tamen id volunt fieri difficilem quandam temperantiam' + ' postulant in eo quod semel admissum coerceri reprimique non potest ut' + ' propemodum iustioribus utamur illis qui omnino avocent a philosophia quam his' + ' qui rebus infinitis modum constituant in reque eo meliore quo maior sit' + ' mediocritatem desiderent Sive enim ad sapientiam perveniri potest non paranda' + ' nobis solum ea sed fruenda etiam sapientia est sive hoc difficile est tamen nec' + ' modus est ullus investigandi veri nisi inveneris et quaerendi defatigatio' + ' turpis est cum id quod quaeritur sit pulcherrimum etenim si delectamur cum' + ' scribimus quis est tam invidus qui ab eo nos abducat sin laboramus quis est qui' + ' alienae modum statuat industriae nam ut Terentianus Chremes non inhumanus qui' + ' novum vicinum non vult fodere aut arare aut aliquid ferre denique non enim' + ' illum ab industria sed ab inliberali labore deterret sic isti curiosi quos' + ' offendit noster minime nobis iniucundus labor Iis igitur est difficilius satis' + ' facere qui se Latina scripta dicunt contemnere in quibus hoc primum est in quo' + ' admirer cur in gravissimis rebus non delectet eos sermo patrius cum idem' + ' fabellas Latinas ad verbum e Graecis expressas non inviti legant quis enim tam' + ' inimicus paene nomini Romano est qui Ennii Medeam aut Antiopam Pacuvii spernat' + ' aut reiciat quod se isdem Euripidis fabulis delectari dicat Latinas litteras' + ' oderit Quid si nos non interpretum fungimur munere sed tuemur ea quae dicta' + ' sunt ab iis quos probamus eisque nostrum iudicium et nostrum scribendi ordinem' + ' adiungimus quid habent cur Graeca anteponant iis quae et splendide dicta sint' + ' neque sint conversa de Graecis nam si dicent ab illis has res esse tractatas ne' + ' ipsos quidem Graecos est cur tam multos legant quam legendi sunt quid enim est' + ' a Chrysippo praetermissum in Stoicis legimus tamen Diogenem Antipatrum' + ' Mnesarchum Panaetium multos alios in primisque familiarem nostrum Posidonium' + ' quid Theophrastus mediocriterne delectat cum tractat locos ab Aristotele ante' + ' tractatos quid Epicurei num desistunt de isdem de quibus et ab Epicuro scriptum' + ' est et ab antiquis ad arbitrium suum scribere quodsi Graeci leguntur a Graecis' + ' isdem de rebus alia ratione compositis quid est cur nostri a nostris non' + ' legantur'.split(' '); /** * Mock Data Generation */ function ipsum(num) { var lorem = _lorem.sort(function() { return Math.random() > .5 ? -1 : 1; }); var words = [] , i = lorem.length; if (num) { while (i-- && words.length < num) { if (Math.random() > .5) words.push(lorem[i]); } } else { while (i--) { if (Math.random() > .5) words.push(lorem[i]); if (Math.random() > .99) words.push('\n\n'); } } return words.sort(function() { return Math.random() > .5 ? -1 : 1; }).join(' ') .replace(/\n{3,}/g, '\n\n') .replace(/\n | \n/g, '\n') .replace(/(\w)(?=\n|$)/g, '$1.') .replace(/(^|\n)\w/g, function(s) { return s.toUpperCase(); }); } function rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function tag() { var out = [] , i = _tags.length , num = rand(1, 5) , tags = _tags.sort(function() { return Math.random() > .5 ? -1 : 1; }); while (out.length < num) { out.push(tags[--i]); } return out; } module.exports = function(dir, ext) { for (var i = 10, id, title, date; i--;) { title = ipsum(3) .replace('.', '') .replace(/(^|\s)\w/g, function(s) { return s.toUpperCase(); }); id = title.toLowerCase().replace(/\s+/g, '_'); date = new Date(Date.now() - (Math.random() * (1000 * 60 * 60 * 24 * 7 * 10))); return fs.writeFileSync( dir + '/' + id + ext, JSON.stringify({ title: title, timestamp: date.toISOString(), tags: tag(), }, null, 2) + '\n\n' + ipsum() ); } };
{ "content_hash": "398094a02bfe6cb38731332da27f5ebf", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 84, "avg_line_length": 40.412213740458014, "alnum_prop": 0.6885153003400075, "repo_name": "chjj/dilated", "id": "660d321968af3a8c46daff356f566c08ce7a7f43", "size": "5383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mock.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19448" }, { "name": "JavaScript", "bytes": "57410" } ], "symlink_target": "" }
{% extends 'base.html' %} {% block content %} <h2>Register success!</h2> {% endblock %}
{ "content_hash": "f4c0727f0bb83d88c4dd3e63c5f321ec", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 27, "avg_line_length": 13, "alnum_prop": 0.5934065934065934, "repo_name": "jussi-kalliokoski/paul", "id": "6e98667bdd99d9d2216c84ea005413b7ccf1fe50", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "paul/templates/account/register_success.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12191" }, { "name": "JavaScript", "bytes": "7003" }, { "name": "Python", "bytes": "9905" } ], "symlink_target": "" }
package io.druid.segment.realtime.appenderator; import com.google.common.base.Supplier; import io.druid.data.input.InputRow; import javax.annotation.Nullable; /** * Result of {@link AppenderatorDriver#add(InputRow, String, Supplier, boolean)}. It contains the identifier of the * segment which the InputRow is added to, the number of rows in that segment and if persist is required because either * maxRowsInMemory or intermediate persist period threshold is hit. */ public class AppenderatorDriverAddResult { private final SegmentIdentifier segmentIdentifier; private final int numRowsInSegment; private final long totalNumRowsInAppenderator; private final boolean isPersistRequired; public static AppenderatorDriverAddResult ok( SegmentIdentifier segmentIdentifier, int numRowsInSegment, long totalNumRowsInAppenderator, boolean isPersistRequired ) { return new AppenderatorDriverAddResult(segmentIdentifier, numRowsInSegment, totalNumRowsInAppenderator, isPersistRequired); } public static AppenderatorDriverAddResult fail() { return new AppenderatorDriverAddResult(null, 0, 0, false); } private AppenderatorDriverAddResult( @Nullable SegmentIdentifier segmentIdentifier, int numRowsInSegment, long totalNumRowsInAppenderator, boolean isPersistRequired ) { this.segmentIdentifier = segmentIdentifier; this.numRowsInSegment = numRowsInSegment; this.totalNumRowsInAppenderator = totalNumRowsInAppenderator; this.isPersistRequired = isPersistRequired; } public boolean isOk() { return segmentIdentifier != null; } public SegmentIdentifier getSegmentIdentifier() { return segmentIdentifier; } public int getNumRowsInSegment() { return numRowsInSegment; } public long getTotalNumRowsInAppenderator() { return totalNumRowsInAppenderator; } public boolean isPersistRequired() { return isPersistRequired; } }
{ "content_hash": "5d0ddfc279a78ec4c2380705926288ca", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 127, "avg_line_length": 26.675675675675677, "alnum_prop": 0.7689969604863222, "repo_name": "winval/druid", "id": "4838d58a227fcb6f90d9eaac16c98ee99152fd91", "size": "2779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/io/druid/segment/realtime/appenderator/AppenderatorDriverAddResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1406" }, { "name": "CSS", "bytes": "11623" }, { "name": "HTML", "bytes": "26739" }, { "name": "Java", "bytes": "18262421" }, { "name": "JavaScript", "bytes": "295150" }, { "name": "Makefile", "bytes": "659" }, { "name": "PostScript", "bytes": "5" }, { "name": "R", "bytes": "17002" }, { "name": "Roff", "bytes": "3617" }, { "name": "Shell", "bytes": "6103" }, { "name": "TeX", "bytes": "399444" }, { "name": "Thrift", "bytes": "199" } ], "symlink_target": "" }
#include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/systm.h> #include <sys/exec.h> #include <sys/fcntl.h> #include <sys/imgact.h> #include <sys/imgact_aout.h> #include <sys/imgact_elf.h> #include <sys/kernel.h> #include <sys/lock.h> #include <sys/malloc.h> #include <sys/module.h> #include <sys/mutex.h> #include <sys/proc.h> #include <sys/signalvar.h> #include <sys/syscallsubr.h> #include <sys/sysent.h> #include <sys/sysproto.h> #include <sys/vnode.h> #include <sys/eventhandler.h> #include <vm/vm.h> #include <vm/pmap.h> #include <vm/vm_extern.h> #include <vm/vm_map.h> #include <vm/vm_object.h> #include <vm/vm_page.h> #include <vm/vm_param.h> #include <machine/cpu.h> #include <machine/cputypes.h> #include <machine/md_var.h> #include <machine/pcb.h> #include <i386/linux/linux.h> #include <i386/linux/linux_proto.h> #include <compat/linux/linux_emul.h> #include <compat/linux/linux_futex.h> #include <compat/linux/linux_ioctl.h> #include <compat/linux/linux_mib.h> #include <compat/linux/linux_misc.h> #include <compat/linux/linux_signal.h> #include <compat/linux/linux_util.h> MODULE_VERSION(linux, 1); MALLOC_DEFINE(M_LINUX, "linux", "Linux mode structures"); #if BYTE_ORDER == LITTLE_ENDIAN #define SHELLMAGIC 0x2123 /* #! */ #else #define SHELLMAGIC 0x2321 #endif /* * Allow the sendsig functions to use the ldebug() facility * even though they are not syscalls themselves. Map them * to syscall 0. This is slightly less bogus than using * ldebug(sigreturn). */ #define LINUX_SYS_linux_rt_sendsig 0 #define LINUX_SYS_linux_sendsig 0 #define LINUX_PS_STRINGS (LINUX_USRSTACK - sizeof(struct ps_strings)) extern char linux_sigcode[]; extern int linux_szsigcode; extern struct sysent linux_sysent[LINUX_SYS_MAXSYSCALL]; SET_DECLARE(linux_ioctl_handler_set, struct linux_ioctl_handler); SET_DECLARE(linux_device_handler_set, struct linux_device_handler); static int linux_fixup(register_t **stack_base, struct image_params *iparams); static int elf_linux_fixup(register_t **stack_base, struct image_params *iparams); static void linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask); static void exec_linux_setregs(struct thread *td, struct image_params *imgp, u_long stack); static register_t *linux_copyout_strings(struct image_params *imgp); static boolean_t linux_trans_osrel(const Elf_Note *note, int32_t *osrel); static int linux_szplatform; const char *linux_platform; static eventhandler_tag linux_exit_tag; static eventhandler_tag linux_exec_tag; /* * Linux syscalls return negative errno's, we do positive and map them * Reference: * FreeBSD: src/sys/sys/errno.h * Linux: linux-2.6.17.8/include/asm-generic/errno-base.h * linux-2.6.17.8/include/asm-generic/errno.h */ static int bsd_to_linux_errno[ELAST + 1] = { -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -35, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32, -33, -34, -11,-115,-114, -88, -89, -90, -91, -92, -93, -94, -95, -96, -97, -98, -99, -100,-101,-102,-103,-104,-105,-106,-107,-108,-109, -110,-111, -40, -36,-112,-113, -39, -11, -87,-122, -116, -66, -6, -6, -6, -6, -6, -37, -38, -9, -6, -6, -43, -42, -75,-125, -84, -95, -16, -74, -72, -67, -71 }; int bsd_to_linux_signal[LINUX_SIGTBLSZ] = { LINUX_SIGHUP, LINUX_SIGINT, LINUX_SIGQUIT, LINUX_SIGILL, LINUX_SIGTRAP, LINUX_SIGABRT, 0, LINUX_SIGFPE, LINUX_SIGKILL, LINUX_SIGBUS, LINUX_SIGSEGV, LINUX_SIGSYS, LINUX_SIGPIPE, LINUX_SIGALRM, LINUX_SIGTERM, LINUX_SIGURG, LINUX_SIGSTOP, LINUX_SIGTSTP, LINUX_SIGCONT, LINUX_SIGCHLD, LINUX_SIGTTIN, LINUX_SIGTTOU, LINUX_SIGIO, LINUX_SIGXCPU, LINUX_SIGXFSZ, LINUX_SIGVTALRM, LINUX_SIGPROF, LINUX_SIGWINCH, 0, LINUX_SIGUSR1, LINUX_SIGUSR2 }; int linux_to_bsd_signal[LINUX_SIGTBLSZ] = { SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGBUS, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGURG, SIGSYS }; #define LINUX_T_UNKNOWN 255 static int _bsd_to_linux_trapcode[] = { LINUX_T_UNKNOWN, /* 0 */ 6, /* 1 T_PRIVINFLT */ LINUX_T_UNKNOWN, /* 2 */ 3, /* 3 T_BPTFLT */ LINUX_T_UNKNOWN, /* 4 */ LINUX_T_UNKNOWN, /* 5 */ 16, /* 6 T_ARITHTRAP */ 254, /* 7 T_ASTFLT */ LINUX_T_UNKNOWN, /* 8 */ 13, /* 9 T_PROTFLT */ 1, /* 10 T_TRCTRAP */ LINUX_T_UNKNOWN, /* 11 */ 14, /* 12 T_PAGEFLT */ LINUX_T_UNKNOWN, /* 13 */ 17, /* 14 T_ALIGNFLT */ LINUX_T_UNKNOWN, /* 15 */ LINUX_T_UNKNOWN, /* 16 */ LINUX_T_UNKNOWN, /* 17 */ 0, /* 18 T_DIVIDE */ 2, /* 19 T_NMI */ 4, /* 20 T_OFLOW */ 5, /* 21 T_BOUND */ 7, /* 22 T_DNA */ 8, /* 23 T_DOUBLEFLT */ 9, /* 24 T_FPOPFLT */ 10, /* 25 T_TSSFLT */ 11, /* 26 T_SEGNPFLT */ 12, /* 27 T_STKFLT */ 18, /* 28 T_MCHK */ 19, /* 29 T_XMMFLT */ 15 /* 30 T_RESERVED */ }; #define bsd_to_linux_trapcode(code) \ ((code)<sizeof(_bsd_to_linux_trapcode)/sizeof(*_bsd_to_linux_trapcode)? \ _bsd_to_linux_trapcode[(code)]: \ LINUX_T_UNKNOWN) /* * If FreeBSD & Linux have a difference of opinion about what a trap * means, deal with it here. * * MPSAFE */ static int translate_traps(int signal, int trap_code) { if (signal != SIGBUS) return signal; switch (trap_code) { case T_PROTFLT: case T_TSSFLT: case T_DOUBLEFLT: case T_PAGEFLT: return SIGSEGV; default: return signal; } } static int linux_fixup(register_t **stack_base, struct image_params *imgp) { register_t *argv, *envp; argv = *stack_base; envp = *stack_base + (imgp->args->argc + 1); (*stack_base)--; suword(*stack_base, (intptr_t)(void *)envp); (*stack_base)--; suword(*stack_base, (intptr_t)(void *)argv); (*stack_base)--; suword(*stack_base, imgp->args->argc); return (0); } static int elf_linux_fixup(register_t **stack_base, struct image_params *imgp) { struct proc *p; Elf32_Auxargs *args; Elf32_Addr *uplatform; struct ps_strings *arginfo; register_t *pos; int issetugid; KASSERT(curthread->td_proc == imgp->proc, ("unsafe elf_linux_fixup(), should be curproc")); p = imgp->proc; issetugid = imgp->proc->p_flag & P_SUGID ? 1 : 0; arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings; uplatform = (Elf32_Addr *)((caddr_t)arginfo - linux_szplatform); args = (Elf32_Auxargs *)imgp->auxargs; pos = *stack_base + (imgp->args->argc + imgp->args->envc + 2); AUXARGS_ENTRY(pos, LINUX_AT_HWCAP, cpu_feature); /* * Do not export AT_CLKTCK when emulating Linux kernel prior to 2.4.0, * as it has appeared in the 2.4.0-rc7 first time. * Being exported, AT_CLKTCK is returned by sysconf(_SC_CLK_TCK), * glibc falls back to the hard-coded CLK_TCK value when aux entry * is not present. * Also see linux_times() implementation. */ if (linux_kernver(curthread) >= LINUX_KERNVER_2004000) AUXARGS_ENTRY(pos, LINUX_AT_CLKTCK, stclohz); AUXARGS_ENTRY(pos, AT_PHDR, args->phdr); AUXARGS_ENTRY(pos, AT_PHENT, args->phent); AUXARGS_ENTRY(pos, AT_PHNUM, args->phnum); AUXARGS_ENTRY(pos, AT_PAGESZ, args->pagesz); AUXARGS_ENTRY(pos, AT_FLAGS, args->flags); AUXARGS_ENTRY(pos, AT_ENTRY, args->entry); AUXARGS_ENTRY(pos, AT_BASE, args->base); AUXARGS_ENTRY(pos, LINUX_AT_SECURE, issetugid); AUXARGS_ENTRY(pos, AT_UID, imgp->proc->p_ucred->cr_ruid); AUXARGS_ENTRY(pos, AT_EUID, imgp->proc->p_ucred->cr_svuid); AUXARGS_ENTRY(pos, AT_GID, imgp->proc->p_ucred->cr_rgid); AUXARGS_ENTRY(pos, AT_EGID, imgp->proc->p_ucred->cr_svgid); AUXARGS_ENTRY(pos, LINUX_AT_PLATFORM, PTROUT(uplatform)); if (args->execfd != -1) AUXARGS_ENTRY(pos, AT_EXECFD, args->execfd); AUXARGS_ENTRY(pos, AT_NULL, 0); free(imgp->auxargs, M_TEMP); imgp->auxargs = NULL; (*stack_base)--; suword(*stack_base, (register_t)imgp->args->argc); return (0); } /* * Copied from kern/kern_exec.c */ static register_t * linux_copyout_strings(struct image_params *imgp) { int argc, envc; char **vectp; char *stringp, *destp; register_t *stack_base; struct ps_strings *arginfo; struct proc *p; /* * Calculate string base and vector table pointers. * Also deal with signal trampoline code for this exec type. */ p = imgp->proc; arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings; destp = (caddr_t)arginfo - SPARE_USRSPACE - linux_szplatform - roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *)); /* * install LINUX_PLATFORM */ copyout(linux_platform, ((caddr_t)arginfo - linux_szplatform), linux_szplatform); /* * If we have a valid auxargs ptr, prepare some room * on the stack. */ if (imgp->auxargs) { /* * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for * lower compatibility. */ imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size : (LINUX_AT_COUNT * 2); /* * The '+ 2' is for the null pointers at the end of each of * the arg and env vector sets,and imgp->auxarg_size is room * for argument of Runtime loader. */ vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2 + imgp->auxarg_size) * sizeof(char *)); } else { /* * The '+ 2' is for the null pointers at the end of each of * the arg and env vector sets */ vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) * sizeof(char *)); } /* * vectp also becomes our initial stack base */ stack_base = (register_t *)vectp; stringp = imgp->args->begin_argv; argc = imgp->args->argc; envc = imgp->args->envc; /* * Copy out strings - arguments and environment. */ copyout(stringp, destp, ARG_MAX - imgp->args->stringspace); /* * Fill in "ps_strings" struct for ps, w, etc. */ suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp); suword(&arginfo->ps_nargvstr, argc); /* * Fill in argument portion of vector table. */ for (; argc > 0; --argc) { suword(vectp++, (long)(intptr_t)destp); while (*stringp++ != 0) destp++; destp++; } /* a null vector table pointer separates the argp's from the envp's */ suword(vectp++, 0); suword(&arginfo->ps_envstr, (long)(intptr_t)vectp); suword(&arginfo->ps_nenvstr, envc); /* * Fill in environment portion of vector table. */ for (; envc > 0; --envc) { suword(vectp++, (long)(intptr_t)destp); while (*stringp++ != 0) destp++; destp++; } /* end of vector table is a null pointer */ suword(vectp, 0); return (stack_base); } extern unsigned long linux_sznonrtsigcode; static void linux_rt_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask) { struct thread *td = curthread; struct proc *p = td->td_proc; struct sigacts *psp; struct trapframe *regs; struct l_rt_sigframe *fp, frame; int sig, code; int oonstack; sig = ksi->ksi_signo; code = ksi->ksi_code; PROC_LOCK_ASSERT(p, MA_OWNED); psp = p->p_sigacts; mtx_assert(&psp->ps_mtx, MA_OWNED); regs = td->td_frame; oonstack = sigonstack(regs->tf_esp); #ifdef DEBUG if (ldebug(rt_sendsig)) printf(ARGS(rt_sendsig, "%p, %d, %p, %u"), catcher, sig, (void*)mask, code); #endif /* * Allocate space for the signal handler context. */ if ((td->td_pflags & TDP_ALTSTACK) && !oonstack && SIGISMEMBER(psp->ps_sigonstack, sig)) { fp = (struct l_rt_sigframe *)(td->td_sigstk.ss_sp + td->td_sigstk.ss_size - sizeof(struct l_rt_sigframe)); } else fp = (struct l_rt_sigframe *)regs->tf_esp - 1; mtx_unlock(&psp->ps_mtx); /* * Build the argument list for the signal handler. */ if (p->p_sysent->sv_sigtbl) if (sig <= p->p_sysent->sv_sigsize) sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)]; bzero(&frame, sizeof(frame)); frame.sf_handler = catcher; frame.sf_sig = sig; frame.sf_siginfo = &fp->sf_si; frame.sf_ucontext = &fp->sf_sc; /* Fill in POSIX parts */ ksiginfo_to_lsiginfo(ksi, &frame.sf_si, sig); /* * Build the signal context to be used by sigreturn. */ frame.sf_sc.uc_flags = 0; /* XXX ??? */ frame.sf_sc.uc_link = NULL; /* XXX ??? */ frame.sf_sc.uc_stack.ss_sp = td->td_sigstk.ss_sp; frame.sf_sc.uc_stack.ss_size = td->td_sigstk.ss_size; frame.sf_sc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK) ? ((oonstack) ? LINUX_SS_ONSTACK : 0) : LINUX_SS_DISABLE; PROC_UNLOCK(p); bsd_to_linux_sigset(mask, &frame.sf_sc.uc_sigmask); frame.sf_sc.uc_mcontext.sc_mask = frame.sf_sc.uc_sigmask.__bits[0]; frame.sf_sc.uc_mcontext.sc_gs = rgs(); frame.sf_sc.uc_mcontext.sc_fs = regs->tf_fs; frame.sf_sc.uc_mcontext.sc_es = regs->tf_es; frame.sf_sc.uc_mcontext.sc_ds = regs->tf_ds; frame.sf_sc.uc_mcontext.sc_edi = regs->tf_edi; frame.sf_sc.uc_mcontext.sc_esi = regs->tf_esi; frame.sf_sc.uc_mcontext.sc_ebp = regs->tf_ebp; frame.sf_sc.uc_mcontext.sc_ebx = regs->tf_ebx; frame.sf_sc.uc_mcontext.sc_edx = regs->tf_edx; frame.sf_sc.uc_mcontext.sc_ecx = regs->tf_ecx; frame.sf_sc.uc_mcontext.sc_eax = regs->tf_eax; frame.sf_sc.uc_mcontext.sc_eip = regs->tf_eip; frame.sf_sc.uc_mcontext.sc_cs = regs->tf_cs; frame.sf_sc.uc_mcontext.sc_eflags = regs->tf_eflags; frame.sf_sc.uc_mcontext.sc_esp_at_signal = regs->tf_esp; frame.sf_sc.uc_mcontext.sc_ss = regs->tf_ss; frame.sf_sc.uc_mcontext.sc_err = regs->tf_err; frame.sf_sc.uc_mcontext.sc_cr2 = (register_t)ksi->ksi_addr; frame.sf_sc.uc_mcontext.sc_trapno = bsd_to_linux_trapcode(code); #ifdef DEBUG if (ldebug(rt_sendsig)) printf(LMSG("rt_sendsig flags: 0x%x, sp: %p, ss: 0x%x, mask: 0x%x"), frame.sf_sc.uc_stack.ss_flags, td->td_sigstk.ss_sp, td->td_sigstk.ss_size, frame.sf_sc.uc_mcontext.sc_mask); #endif if (copyout(&frame, fp, sizeof(frame)) != 0) { /* * Process has trashed its stack; give it an illegal * instruction to halt it in its tracks. */ #ifdef DEBUG if (ldebug(rt_sendsig)) printf(LMSG("rt_sendsig: bad stack %p, oonstack=%x"), fp, oonstack); #endif PROC_LOCK(p); sigexit(td, SIGILL); } /* * Build context to run handler in. */ regs->tf_esp = (int)fp; regs->tf_eip = p->p_sysent->sv_sigcode_base + linux_sznonrtsigcode; regs->tf_eflags &= ~(PSL_T | PSL_VM | PSL_D); regs->tf_cs = _ucodesel; regs->tf_ds = _udatasel; regs->tf_es = _udatasel; regs->tf_fs = _udatasel; regs->tf_ss = _udatasel; PROC_LOCK(p); mtx_lock(&psp->ps_mtx); } /* * Send an interrupt to process. * * Stack is set up to allow sigcode stored * in u. to call routine, followed by kcall * to sigreturn routine below. After sigreturn * resets the signal mask, the stack, and the * frame pointer, it returns to the user * specified pc, psl. */ static void linux_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask) { struct thread *td = curthread; struct proc *p = td->td_proc; struct sigacts *psp; struct trapframe *regs; struct l_sigframe *fp, frame; l_sigset_t lmask; int sig, code; int oonstack, i; PROC_LOCK_ASSERT(p, MA_OWNED); psp = p->p_sigacts; sig = ksi->ksi_signo; code = ksi->ksi_code; mtx_assert(&psp->ps_mtx, MA_OWNED); if (SIGISMEMBER(psp->ps_siginfo, sig)) { /* Signal handler installed with SA_SIGINFO. */ linux_rt_sendsig(catcher, ksi, mask); return; } regs = td->td_frame; oonstack = sigonstack(regs->tf_esp); #ifdef DEBUG if (ldebug(sendsig)) printf(ARGS(sendsig, "%p, %d, %p, %u"), catcher, sig, (void*)mask, code); #endif /* * Allocate space for the signal handler context. */ if ((td->td_pflags & TDP_ALTSTACK) && !oonstack && SIGISMEMBER(psp->ps_sigonstack, sig)) { fp = (struct l_sigframe *)(td->td_sigstk.ss_sp + td->td_sigstk.ss_size - sizeof(struct l_sigframe)); } else fp = (struct l_sigframe *)regs->tf_esp - 1; mtx_unlock(&psp->ps_mtx); PROC_UNLOCK(p); /* * Build the argument list for the signal handler. */ if (p->p_sysent->sv_sigtbl) if (sig <= p->p_sysent->sv_sigsize) sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)]; bzero(&frame, sizeof(frame)); frame.sf_handler = catcher; frame.sf_sig = sig; bsd_to_linux_sigset(mask, &lmask); /* * Build the signal context to be used by sigreturn. */ frame.sf_sc.sc_mask = lmask.__bits[0]; frame.sf_sc.sc_gs = rgs(); frame.sf_sc.sc_fs = regs->tf_fs; frame.sf_sc.sc_es = regs->tf_es; frame.sf_sc.sc_ds = regs->tf_ds; frame.sf_sc.sc_edi = regs->tf_edi; frame.sf_sc.sc_esi = regs->tf_esi; frame.sf_sc.sc_ebp = regs->tf_ebp; frame.sf_sc.sc_ebx = regs->tf_ebx; frame.sf_sc.sc_edx = regs->tf_edx; frame.sf_sc.sc_ecx = regs->tf_ecx; frame.sf_sc.sc_eax = regs->tf_eax; frame.sf_sc.sc_eip = regs->tf_eip; frame.sf_sc.sc_cs = regs->tf_cs; frame.sf_sc.sc_eflags = regs->tf_eflags; frame.sf_sc.sc_esp_at_signal = regs->tf_esp; frame.sf_sc.sc_ss = regs->tf_ss; frame.sf_sc.sc_err = regs->tf_err; frame.sf_sc.sc_cr2 = (register_t)ksi->ksi_addr; frame.sf_sc.sc_trapno = bsd_to_linux_trapcode(ksi->ksi_trapno); for (i = 0; i < (LINUX_NSIG_WORDS-1); i++) frame.sf_extramask[i] = lmask.__bits[i+1]; if (copyout(&frame, fp, sizeof(frame)) != 0) { /* * Process has trashed its stack; give it an illegal * instruction to halt it in its tracks. */ PROC_LOCK(p); sigexit(td, SIGILL); } /* * Build context to run handler in. */ regs->tf_esp = (int)fp; regs->tf_eip = p->p_sysent->sv_sigcode_base; regs->tf_eflags &= ~(PSL_T | PSL_VM | PSL_D); regs->tf_cs = _ucodesel; regs->tf_ds = _udatasel; regs->tf_es = _udatasel; regs->tf_fs = _udatasel; regs->tf_ss = _udatasel; PROC_LOCK(p); mtx_lock(&psp->ps_mtx); } /* * System call to cleanup state after a signal * has been taken. Reset signal mask and * stack state from context left by sendsig (above). * Return to previous pc and psl as specified by * context left by sendsig. Check carefully to * make sure that the user has not modified the * psl to gain improper privileges or to cause * a machine fault. */ int linux_sigreturn(struct thread *td, struct linux_sigreturn_args *args) { struct l_sigframe frame; struct trapframe *regs; l_sigset_t lmask; sigset_t bmask; int eflags, i; ksiginfo_t ksi; regs = td->td_frame; #ifdef DEBUG if (ldebug(sigreturn)) printf(ARGS(sigreturn, "%p"), (void *)args->sfp); #endif /* * The trampoline code hands us the sigframe. * It is unsafe to keep track of it ourselves, in the event that a * program jumps out of a signal handler. */ if (copyin(args->sfp, &frame, sizeof(frame)) != 0) return (EFAULT); /* * Check for security violations. */ #define EFLAGS_SECURE(ef, oef) ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0) eflags = frame.sf_sc.sc_eflags; if (!EFLAGS_SECURE(eflags, regs->tf_eflags)) return(EINVAL); /* * Don't allow users to load a valid privileged %cs. Let the * hardware check for invalid selectors, excess privilege in * other selectors, invalid %eip's and invalid %esp's. */ #define CS_SECURE(cs) (ISPL(cs) == SEL_UPL) if (!CS_SECURE(frame.sf_sc.sc_cs)) { ksiginfo_init_trap(&ksi); ksi.ksi_signo = SIGBUS; ksi.ksi_code = BUS_OBJERR; ksi.ksi_trapno = T_PROTFLT; ksi.ksi_addr = (void *)regs->tf_eip; trapsignal(td, &ksi); return(EINVAL); } lmask.__bits[0] = frame.sf_sc.sc_mask; for (i = 0; i < (LINUX_NSIG_WORDS-1); i++) lmask.__bits[i+1] = frame.sf_extramask[i]; linux_to_bsd_sigset(&lmask, &bmask); kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0); /* * Restore signal context. */ /* %gs was restored by the trampoline. */ regs->tf_fs = frame.sf_sc.sc_fs; regs->tf_es = frame.sf_sc.sc_es; regs->tf_ds = frame.sf_sc.sc_ds; regs->tf_edi = frame.sf_sc.sc_edi; regs->tf_esi = frame.sf_sc.sc_esi; regs->tf_ebp = frame.sf_sc.sc_ebp; regs->tf_ebx = frame.sf_sc.sc_ebx; regs->tf_edx = frame.sf_sc.sc_edx; regs->tf_ecx = frame.sf_sc.sc_ecx; regs->tf_eax = frame.sf_sc.sc_eax; regs->tf_eip = frame.sf_sc.sc_eip; regs->tf_cs = frame.sf_sc.sc_cs; regs->tf_eflags = eflags; regs->tf_esp = frame.sf_sc.sc_esp_at_signal; regs->tf_ss = frame.sf_sc.sc_ss; return (EJUSTRETURN); } /* * System call to cleanup state after a signal * has been taken. Reset signal mask and * stack state from context left by rt_sendsig (above). * Return to previous pc and psl as specified by * context left by sendsig. Check carefully to * make sure that the user has not modified the * psl to gain improper privileges or to cause * a machine fault. */ int linux_rt_sigreturn(struct thread *td, struct linux_rt_sigreturn_args *args) { struct l_ucontext uc; struct l_sigcontext *context; sigset_t bmask; l_stack_t *lss; stack_t ss; struct trapframe *regs; int eflags; ksiginfo_t ksi; regs = td->td_frame; #ifdef DEBUG if (ldebug(rt_sigreturn)) printf(ARGS(rt_sigreturn, "%p"), (void *)args->ucp); #endif /* * The trampoline code hands us the ucontext. * It is unsafe to keep track of it ourselves, in the event that a * program jumps out of a signal handler. */ if (copyin(args->ucp, &uc, sizeof(uc)) != 0) return (EFAULT); context = &uc.uc_mcontext; /* * Check for security violations. */ #define EFLAGS_SECURE(ef, oef) ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0) eflags = context->sc_eflags; if (!EFLAGS_SECURE(eflags, regs->tf_eflags)) return(EINVAL); /* * Don't allow users to load a valid privileged %cs. Let the * hardware check for invalid selectors, excess privilege in * other selectors, invalid %eip's and invalid %esp's. */ #define CS_SECURE(cs) (ISPL(cs) == SEL_UPL) if (!CS_SECURE(context->sc_cs)) { ksiginfo_init_trap(&ksi); ksi.ksi_signo = SIGBUS; ksi.ksi_code = BUS_OBJERR; ksi.ksi_trapno = T_PROTFLT; ksi.ksi_addr = (void *)regs->tf_eip; trapsignal(td, &ksi); return(EINVAL); } linux_to_bsd_sigset(&uc.uc_sigmask, &bmask); kern_sigprocmask(td, SIG_SETMASK, &bmask, NULL, 0); /* * Restore signal context */ /* %gs was restored by the trampoline. */ regs->tf_fs = context->sc_fs; regs->tf_es = context->sc_es; regs->tf_ds = context->sc_ds; regs->tf_edi = context->sc_edi; regs->tf_esi = context->sc_esi; regs->tf_ebp = context->sc_ebp; regs->tf_ebx = context->sc_ebx; regs->tf_edx = context->sc_edx; regs->tf_ecx = context->sc_ecx; regs->tf_eax = context->sc_eax; regs->tf_eip = context->sc_eip; regs->tf_cs = context->sc_cs; regs->tf_eflags = eflags; regs->tf_esp = context->sc_esp_at_signal; regs->tf_ss = context->sc_ss; /* * call sigaltstack & ignore results.. */ lss = &uc.uc_stack; ss.ss_sp = lss->ss_sp; ss.ss_size = lss->ss_size; ss.ss_flags = linux_to_bsd_sigaltstack(lss->ss_flags); #ifdef DEBUG if (ldebug(rt_sigreturn)) printf(LMSG("rt_sigret flags: 0x%x, sp: %p, ss: 0x%x, mask: 0x%x"), ss.ss_flags, ss.ss_sp, ss.ss_size, context->sc_mask); #endif (void)kern_sigaltstack(td, &ss, NULL); return (EJUSTRETURN); } static int linux_fetch_syscall_args(struct thread *td, struct syscall_args *sa) { struct proc *p; struct trapframe *frame; p = td->td_proc; frame = td->td_frame; sa->code = frame->tf_eax; sa->args[0] = frame->tf_ebx; sa->args[1] = frame->tf_ecx; sa->args[2] = frame->tf_edx; sa->args[3] = frame->tf_esi; sa->args[4] = frame->tf_edi; sa->args[5] = frame->tf_ebp; /* Unconfirmed */ if (sa->code >= p->p_sysent->sv_size) sa->callp = &p->p_sysent->sv_table[0]; else sa->callp = &p->p_sysent->sv_table[sa->code]; sa->narg = sa->callp->sy_narg; td->td_retval[0] = 0; td->td_retval[1] = frame->tf_edx; return (0); } /* * If a linux binary is exec'ing something, try this image activator * first. We override standard shell script execution in order to * be able to modify the interpreter path. We only do this if a linux * binary is doing the exec, so we do not create an EXEC module for it. */ static int exec_linux_imgact_try(struct image_params *iparams); static int exec_linux_imgact_try(struct image_params *imgp) { const char *head = (const char *)imgp->image_header; char *rpath; int error = -1; /* * The interpreter for shell scripts run from a linux binary needs * to be located in /compat/linux if possible in order to recursively * maintain linux path emulation. */ if (((const short *)head)[0] == SHELLMAGIC) { /* * Run our normal shell image activator. If it succeeds attempt * to use the alternate path for the interpreter. If an alternate * path is found, use our stringspace to store it. */ if ((error = exec_shell_imgact(imgp)) == 0) { linux_emul_convpath(FIRST_THREAD_IN_PROC(imgp->proc), imgp->interpreter_name, UIO_SYSSPACE, &rpath, 0, AT_FDCWD); if (rpath != NULL) imgp->args->fname_buf = imgp->interpreter_name = rpath; } } return (error); } /* * exec_setregs may initialize some registers differently than Linux * does, thus potentially confusing Linux binaries. If necessary, we * override the exec_setregs default(s) here. */ static void exec_linux_setregs(struct thread *td, struct image_params *imgp, u_long stack) { struct pcb *pcb = td->td_pcb; exec_setregs(td, imgp, stack); /* Linux sets %gs to 0, we default to _udatasel */ pcb->pcb_gs = 0; load_gs(0); pcb->pcb_initial_npxcw = __LINUX_NPXCW__; } static void linux_get_machine(const char **dst) { switch (cpu_class) { case CPUCLASS_686: *dst = "i686"; break; case CPUCLASS_586: *dst = "i586"; break; case CPUCLASS_486: *dst = "i486"; break; default: *dst = "i386"; } } struct sysentvec linux_sysvec = { .sv_size = LINUX_SYS_MAXSYSCALL, .sv_table = linux_sysent, .sv_mask = 0, .sv_sigsize = LINUX_SIGTBLSZ, .sv_sigtbl = bsd_to_linux_signal, .sv_errsize = ELAST + 1, .sv_errtbl = bsd_to_linux_errno, .sv_transtrap = translate_traps, .sv_fixup = linux_fixup, .sv_sendsig = linux_sendsig, .sv_sigcode = linux_sigcode, .sv_szsigcode = &linux_szsigcode, .sv_prepsyscall = NULL, .sv_name = "Linux a.out", .sv_coredump = NULL, .sv_imgact_try = exec_linux_imgact_try, .sv_minsigstksz = LINUX_MINSIGSTKSZ, .sv_pagesize = PAGE_SIZE, .sv_minuser = VM_MIN_ADDRESS, .sv_maxuser = VM_MAXUSER_ADDRESS, .sv_usrstack = LINUX_USRSTACK, .sv_psstrings = PS_STRINGS, .sv_stackprot = VM_PROT_ALL, .sv_copyout_strings = exec_copyout_strings, .sv_setregs = exec_linux_setregs, .sv_fixlimit = NULL, .sv_maxssiz = NULL, .sv_flags = SV_ABI_LINUX | SV_AOUT | SV_IA32 | SV_ILP32, .sv_set_syscall_retval = cpu_set_syscall_retval, .sv_fetch_syscall_args = linux_fetch_syscall_args, .sv_syscallnames = NULL, .sv_shared_page_base = LINUX_SHAREDPAGE, .sv_shared_page_len = PAGE_SIZE, .sv_schedtail = linux_schedtail, }; INIT_SYSENTVEC(aout_sysvec, &linux_sysvec); struct sysentvec elf_linux_sysvec = { .sv_size = LINUX_SYS_MAXSYSCALL, .sv_table = linux_sysent, .sv_mask = 0, .sv_sigsize = LINUX_SIGTBLSZ, .sv_sigtbl = bsd_to_linux_signal, .sv_errsize = ELAST + 1, .sv_errtbl = bsd_to_linux_errno, .sv_transtrap = translate_traps, .sv_fixup = elf_linux_fixup, .sv_sendsig = linux_sendsig, .sv_sigcode = linux_sigcode, .sv_szsigcode = &linux_szsigcode, .sv_prepsyscall = NULL, .sv_name = "Linux ELF", .sv_coredump = elf32_coredump, .sv_imgact_try = exec_linux_imgact_try, .sv_minsigstksz = LINUX_MINSIGSTKSZ, .sv_pagesize = PAGE_SIZE, .sv_minuser = VM_MIN_ADDRESS, .sv_maxuser = VM_MAXUSER_ADDRESS, .sv_usrstack = LINUX_USRSTACK, .sv_psstrings = LINUX_PS_STRINGS, .sv_stackprot = VM_PROT_ALL, .sv_copyout_strings = linux_copyout_strings, .sv_setregs = exec_linux_setregs, .sv_fixlimit = NULL, .sv_maxssiz = NULL, .sv_flags = SV_ABI_LINUX | SV_IA32 | SV_ILP32 | SV_SHP, .sv_set_syscall_retval = cpu_set_syscall_retval, .sv_fetch_syscall_args = linux_fetch_syscall_args, .sv_syscallnames = NULL, .sv_shared_page_base = LINUX_SHAREDPAGE, .sv_shared_page_len = PAGE_SIZE, .sv_schedtail = linux_schedtail, }; INIT_SYSENTVEC(elf_sysvec, &elf_linux_sysvec); static char GNU_ABI_VENDOR[] = "GNU"; static int GNULINUX_ABI_DESC = 0; static boolean_t linux_trans_osrel(const Elf_Note *note, int32_t *osrel) { const Elf32_Word *desc; uintptr_t p; p = (uintptr_t)(note + 1); p += roundup2(note->n_namesz, sizeof(Elf32_Addr)); desc = (const Elf32_Word *)p; if (desc[0] != GNULINUX_ABI_DESC) return (FALSE); /* * For linux we encode osrel as follows (see linux_mib.c): * VVVMMMIII (version, major, minor), see linux_mib.c. */ *osrel = desc[1] * 1000000 + desc[2] * 1000 + desc[3]; return (TRUE); } static Elf_Brandnote linux_brandnote = { .hdr.n_namesz = sizeof(GNU_ABI_VENDOR), .hdr.n_descsz = 16, /* XXX at least 16 */ .hdr.n_type = 1, .vendor = GNU_ABI_VENDOR, .flags = BN_TRANSLATE_OSREL, .trans_osrel = linux_trans_osrel }; static Elf32_Brandinfo linux_brand = { .brand = ELFOSABI_LINUX, .machine = EM_386, .compat_3_brand = "Linux", .emul_path = "/compat/linux", .interp_path = "/lib/ld-linux.so.1", .sysvec = &elf_linux_sysvec, .interp_newpath = NULL, .brand_note = &linux_brandnote, .flags = BI_CAN_EXEC_DYN | BI_BRAND_NOTE }; static Elf32_Brandinfo linux_glibc2brand = { .brand = ELFOSABI_LINUX, .machine = EM_386, .compat_3_brand = "Linux", .emul_path = "/compat/linux", .interp_path = "/lib/ld-linux.so.2", .sysvec = &elf_linux_sysvec, .interp_newpath = NULL, .brand_note = &linux_brandnote, .flags = BI_CAN_EXEC_DYN | BI_BRAND_NOTE }; Elf32_Brandinfo *linux_brandlist[] = { &linux_brand, &linux_glibc2brand, NULL }; static int linux_elf_modevent(module_t mod, int type, void *data) { Elf32_Brandinfo **brandinfo; int error; struct linux_ioctl_handler **lihp; struct linux_device_handler **ldhp; error = 0; switch(type) { case MOD_LOAD: for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL; ++brandinfo) if (elf32_insert_brand_entry(*brandinfo) < 0) error = EINVAL; if (error == 0) { SET_FOREACH(lihp, linux_ioctl_handler_set) linux_ioctl_register_handler(*lihp); SET_FOREACH(ldhp, linux_device_handler_set) linux_device_register_handler(*ldhp); mtx_init(&emul_lock, "emuldata lock", NULL, MTX_DEF); sx_init(&emul_shared_lock, "emuldata->shared lock"); LIST_INIT(&futex_list); mtx_init(&futex_mtx, "ftllk", NULL, MTX_DEF); linux_exit_tag = EVENTHANDLER_REGISTER(process_exit, linux_proc_exit, NULL, 1000); linux_exec_tag = EVENTHANDLER_REGISTER(process_exec, linux_proc_exec, NULL, 1000); linux_get_machine(&linux_platform); linux_szplatform = roundup(strlen(linux_platform) + 1, sizeof(char *)); linux_osd_jail_register(); stclohz = (stathz ? stathz : hz); if (bootverbose) printf("Linux ELF exec handler installed\n"); } else printf("cannot insert Linux ELF brand handler\n"); break; case MOD_UNLOAD: for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL; ++brandinfo) if (elf32_brand_inuse(*brandinfo)) error = EBUSY; if (error == 0) { for (brandinfo = &linux_brandlist[0]; *brandinfo != NULL; ++brandinfo) if (elf32_remove_brand_entry(*brandinfo) < 0) error = EINVAL; } if (error == 0) { SET_FOREACH(lihp, linux_ioctl_handler_set) linux_ioctl_unregister_handler(*lihp); SET_FOREACH(ldhp, linux_device_handler_set) linux_device_unregister_handler(*ldhp); mtx_destroy(&emul_lock); sx_destroy(&emul_shared_lock); mtx_destroy(&futex_mtx); EVENTHANDLER_DEREGISTER(process_exit, linux_exit_tag); EVENTHANDLER_DEREGISTER(process_exec, linux_exec_tag); linux_osd_jail_deregister(); if (bootverbose) printf("Linux ELF exec handler removed\n"); } else printf("Could not deinstall ELF interpreter entry\n"); break; default: return EOPNOTSUPP; } return error; } static moduledata_t linux_elf_mod = { "linuxelf", linux_elf_modevent, 0 }; DECLARE_MODULE_TIED(linuxelf, linux_elf_mod, SI_SUB_EXEC, SI_ORDER_ANY);
{ "content_hash": "3da574bd6121674bf89fe4be596baf91", "timestamp": "", "source": "github", "line_count": 1135, "max_line_length": 78, "avg_line_length": 28.01762114537445, "alnum_prop": 0.6517295597484277, "repo_name": "jrobhoward/SCADAbase", "id": "ab46672b9d87c6874ec8d2de888c48fdd91827b2", "size": "33311", "binary": false, "copies": "1", "ref": "refs/heads/SCADAbase", "path": "sys/i386/linux/linux_sysvec.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4615704" }, { "name": "Awk", "bytes": "273794" }, { "name": "Batchfile", "bytes": "20333" }, { "name": "C", "bytes": "457666547" }, { "name": "C++", "bytes": "91495356" }, { "name": "CMake", "bytes": "17632" }, { "name": "CSS", "bytes": "104220" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "6321" }, { "name": "DIGITAL Command Language", "bytes": "10638" }, { "name": "DTrace", "bytes": "1904158" }, { "name": "Emacs Lisp", "bytes": "32010" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "204603" }, { "name": "GAP", "bytes": "72078" }, { "name": "Groff", "bytes": "32376243" }, { "name": "HTML", "bytes": "5776268" }, { "name": "Haskell", "bytes": "2458" }, { "name": "IGOR Pro", "bytes": "6510" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "425858" }, { "name": "Limbo", "bytes": "4037" }, { "name": "Logos", "bytes": "179088" }, { "name": "Makefile", "bytes": "12750766" }, { "name": "Mathematica", "bytes": "21782" }, { "name": "Max", "bytes": "4105" }, { "name": "Module Management System", "bytes": "816" }, { "name": "Objective-C", "bytes": "1571960" }, { "name": "PHP", "bytes": "2471" }, { "name": "PLSQL", "bytes": "96552" }, { "name": "PLpgSQL", "bytes": "2212" }, { "name": "Perl", "bytes": "3947402" }, { "name": "Perl6", "bytes": "122803" }, { "name": "PostScript", "bytes": "152255" }, { "name": "Prolog", "bytes": "42792" }, { "name": "Protocol Buffer", "bytes": "54964" }, { "name": "Python", "bytes": "381066" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "67015" }, { "name": "Scheme", "bytes": "5087" }, { "name": "Scilab", "bytes": "196" }, { "name": "Shell", "bytes": "10963470" }, { "name": "SourcePawn", "bytes": "2293" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "7102" }, { "name": "TeX", "bytes": "720582" }, { "name": "VimL", "bytes": "19597" }, { "name": "XS", "bytes": "17496" }, { "name": "XSLT", "bytes": "4564" }, { "name": "Yacc", "bytes": "1881915" } ], "symlink_target": "" }
import { dirname, join, normalize } from '@angular-devkit/core'; import { Rule, SchematicContext, SchematicsException, Tree, chain, noop, schematic, } from '@angular-devkit/schematics'; import { Schema as ComponentOptions } from '../component/schema'; import * as ts from '../third_party/github.com/Microsoft/TypeScript/lib/typescript'; import { addImportToModule, addSymbolToNgModuleMetadata, findNode, getDecoratorMetadata, getSourceNodes, insertImport, isImported, } from '../utility/ast-utils'; import { Change, InsertChange } from '../utility/change'; import { getAppModulePath } from '../utility/ng-ast-utils'; import { targetBuildNotFoundError } from '../utility/project-targets'; import { getWorkspace, updateWorkspace } from '../utility/workspace'; import { BrowserBuilderOptions, Builders, ServerBuilderOptions } from '../utility/workspace-models'; import { Schema as AppShellOptions } from './schema'; function getSourceFile(host: Tree, path: string): ts.SourceFile { const buffer = host.read(path); if (!buffer) { throw new SchematicsException(`Could not find ${path}.`); } const content = buffer.toString(); const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); return source; } function getServerModulePath( host: Tree, sourceRoot: string, mainPath: string, ): string | null { const mainSource = getSourceFile(host, join(normalize(sourceRoot), mainPath)); const allNodes = getSourceNodes(mainSource); const expNode = allNodes.find(node => ts.isExportDeclaration(node)); if (!expNode) { return null; } const relativePath = (expNode as ts.ExportDeclaration).moduleSpecifier as ts.StringLiteral; const modulePath = normalize(`/${sourceRoot}/${relativePath.text}.ts`); return modulePath; } interface TemplateInfo { templateProp?: ts.PropertyAssignment; templateUrlProp?: ts.PropertyAssignment; } function getComponentTemplateInfo(host: Tree, componentPath: string): TemplateInfo { const compSource = getSourceFile(host, componentPath); const compMetadata = getDecoratorMetadata(compSource, 'Component', '@angular/core')[0]; return { templateProp: getMetadataProperty(compMetadata, 'template'), templateUrlProp: getMetadataProperty(compMetadata, 'templateUrl'), }; } function getComponentTemplate(host: Tree, compPath: string, tmplInfo: TemplateInfo): string { let template = ''; if (tmplInfo.templateProp) { template = tmplInfo.templateProp.getFullText(); } else if (tmplInfo.templateUrlProp) { const templateUrl = (tmplInfo.templateUrlProp.initializer as ts.StringLiteral).text; const dir = dirname(normalize(compPath)); const templatePath = join(dir, templateUrl); const buffer = host.read(templatePath); if (buffer) { template = buffer.toString(); } } return template; } function getBootstrapComponentPath( host: Tree, mainPath: string, ): string { const modulePath = getAppModulePath(host, mainPath); const moduleSource = getSourceFile(host, modulePath); const metadataNode = getDecoratorMetadata(moduleSource, 'NgModule', '@angular/core')[0]; const bootstrapProperty = getMetadataProperty(metadataNode, 'bootstrap'); const arrLiteral = (bootstrapProperty as ts.PropertyAssignment) .initializer as ts.ArrayLiteralExpression; const componentSymbol = arrLiteral.elements[0].getText(); const relativePath = getSourceNodes(moduleSource) .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration) .filter(imp => { return findNode(imp, ts.SyntaxKind.Identifier, componentSymbol); }) .map((imp: ts.ImportDeclaration) => { const pathStringLiteral = imp.moduleSpecifier as ts.StringLiteral; return pathStringLiteral.text; })[0]; return join(dirname(normalize(modulePath)), relativePath + '.ts'); } // end helper functions. function validateProject(mainPath: string): Rule { return (host: Tree, context: SchematicContext) => { const routerOutletCheckRegex = /<router\-outlet.*?>([\s\S]*?)<\/router\-outlet>/; const componentPath = getBootstrapComponentPath(host, mainPath); const tmpl = getComponentTemplateInfo(host, componentPath); const template = getComponentTemplate(host, componentPath, tmpl); if (!routerOutletCheckRegex.test(template)) { const errorMsg = `Prerequisite for app shell is to define a router-outlet in your root component.`; context.logger.error(errorMsg); throw new SchematicsException(errorMsg); } }; } function addUniversalTarget(options: AppShellOptions): Rule { return () => { // Copy options. const universalOptions = { ...options, }; // Delete non-universal options. delete universalOptions.universalProject; delete universalOptions.route; delete universalOptions.name; delete universalOptions.outDir; delete universalOptions.root; delete universalOptions.index; delete universalOptions.sourceDir; return schematic('universal', universalOptions); }; } function addAppShellConfigToWorkspace(options: AppShellOptions): Rule { return () => { if (!options.route) { throw new SchematicsException(`Route is not defined`); } return updateWorkspace(workspace => { const project = workspace.projects.get(options.clientProject); if (!project) { return; } project.targets.add({ name: 'app-shell', builder: Builders.AppShell, options: { browserTarget: `${options.clientProject}:build`, serverTarget: `${options.clientProject}:server`, route: options.route, }, configurations: { production: { browserTarget: `${options.clientProject}:build:production`, serverTarget: `${options.clientProject}:server:production`, }, }, }); }); }; } function addRouterModule(mainPath: string): Rule { return (host: Tree) => { const modulePath = getAppModulePath(host, mainPath); const moduleSource = getSourceFile(host, modulePath); const changes = addImportToModule(moduleSource, modulePath, 'RouterModule', '@angular/router'); const recorder = host.beginUpdate(modulePath); changes.forEach((change: Change) => { if (change instanceof InsertChange) { recorder.insertLeft(change.pos, change.toAdd); } }); host.commitUpdate(recorder); return host; }; } function getMetadataProperty(metadata: ts.Node, propertyName: string): ts.PropertyAssignment { const properties = (metadata as ts.ObjectLiteralExpression).properties; const property = properties .filter(prop => prop.kind === ts.SyntaxKind.PropertyAssignment) .filter((prop: ts.PropertyAssignment) => { const name = prop.name; switch (name.kind) { case ts.SyntaxKind.Identifier: return (name as ts.Identifier).getText() === propertyName; case ts.SyntaxKind.StringLiteral: return (name as ts.StringLiteral).text === propertyName; } return false; })[0]; return property as ts.PropertyAssignment; } function addServerRoutes(options: AppShellOptions): Rule { return async (host: Tree) => { // The workspace gets updated so this needs to be reloaded const workspace = await getWorkspace(host); const clientProject = workspace.projects.get(options.clientProject); if (!clientProject) { throw new Error('Universal schematic removed client project.'); } const clientServerTarget = clientProject.targets.get('server'); if (!clientServerTarget) { throw new Error('Universal schematic did not add server target to client project.'); } const clientServerOptions = clientServerTarget.options as unknown as ServerBuilderOptions; if (!clientServerOptions) { throw new SchematicsException('Server target does not contain options.'); } const modulePath = getServerModulePath(host, clientProject.sourceRoot || 'src', options.main as string); if (modulePath === null) { throw new SchematicsException('Universal/server module not found.'); } let moduleSource = getSourceFile(host, modulePath); if (!isImported(moduleSource, 'Routes', '@angular/router')) { const recorder = host.beginUpdate(modulePath); const routesChange = insertImport(moduleSource, modulePath, 'Routes', '@angular/router') as InsertChange; if (routesChange.toAdd) { recorder.insertLeft(routesChange.pos, routesChange.toAdd); } const imports = getSourceNodes(moduleSource) .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration) .sort((a, b) => a.getStart() - b.getStart()); const insertPosition = imports[imports.length - 1].getEnd(); const routeText = `\n\nconst routes: Routes = [ { path: '${options.route}', component: AppShellComponent }];`; recorder.insertRight(insertPosition, routeText); host.commitUpdate(recorder); } moduleSource = getSourceFile(host, modulePath); if (!isImported(moduleSource, 'RouterModule', '@angular/router')) { const recorder = host.beginUpdate(modulePath); const routerModuleChange = insertImport(moduleSource, modulePath, 'RouterModule', '@angular/router') as InsertChange; if (routerModuleChange.toAdd) { recorder.insertLeft(routerModuleChange.pos, routerModuleChange.toAdd); } const metadataChange = addSymbolToNgModuleMetadata( moduleSource, modulePath, 'imports', 'RouterModule.forRoot(routes)'); if (metadataChange) { metadataChange.forEach((change: InsertChange) => { recorder.insertRight(change.pos, change.toAdd); }); } host.commitUpdate(recorder); } }; } function addShellComponent(options: AppShellOptions): Rule { const componentOptions: ComponentOptions = { name: 'app-shell', module: options.rootModuleFileName, project: options.clientProject, }; return schematic('component', componentOptions); } export default function (options: AppShellOptions): Rule { return async tree => { const workspace = await getWorkspace(tree); const clientProject = workspace.projects.get(options.clientProject); if (!clientProject || clientProject.extensions.projectType !== 'application') { throw new SchematicsException(`A client project type of "application" is required.`); } const clientBuildTarget = clientProject.targets.get('build'); if (!clientBuildTarget) { throw targetBuildNotFoundError(); } const clientBuildOptions = (clientBuildTarget.options || {}) as unknown as BrowserBuilderOptions; return chain([ validateProject(clientBuildOptions.main), clientProject.targets.has('server') ? noop() : addUniversalTarget(options), addAppShellConfigToWorkspace(options), addRouterModule(clientBuildOptions.main), addServerRoutes(options), addShellComponent(options), ]); }; }
{ "content_hash": "2358f50847501bb1d1f9ebc7574969dc", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 108, "avg_line_length": 34.90402476780186, "alnum_prop": 0.684761397906688, "repo_name": "hansl/angular-cli", "id": "a2d661abf5659c4ed69d6008336911264069cb06", "size": "11476", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "packages/schematics/angular/app-shell/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "734" }, { "name": "Dockerfile", "bytes": "36" }, { "name": "HTML", "bytes": "36848" }, { "name": "JavaScript", "bytes": "59268" }, { "name": "Shell", "bytes": "7396" }, { "name": "Starlark", "bytes": "46242" }, { "name": "TypeScript", "bytes": "3412424" } ], "symlink_target": "" }
package tests.integration.Trees.cartesianTree; import org.junit.Assert; import org.junit.Test; import SLPs.SLPExtractor; import cartesianTree.CartesianTreeManagerFactory; import cartesianTree.slpBuilders.CartesianSlpTreeBuilder; import cartesianTree.slpBuilders.ICartesianSlpTreeBuilder; import commons.settings.ISettings; import dataContracts.DataFactoryType; import dataContracts.LZFactorDef; import dataContracts.SLPModel; import dataContracts.statistics.Statistics; import helpers.FactorizationScenarios; import serialization.products.IProductSerializer; import tests.integration.IntegrationTestBase; public class CartesianSLPBuilderTests extends IntegrationTestBase { @Test public void test() { LZFactorDef[] factors = FactorizationScenarios.generate(200000); IProductSerializer productSerializer = container.get(IProductSerializer.class); ICartesianSlpTreeBuilder slpTreeBuilder = new CartesianSlpTreeBuilder(new CartesianTreeManagerFactory(container.get(ISettings.class), DataFactoryType.memory), new SLPExtractor(), productSerializer); SLPModel slpModel = slpTreeBuilder.buildSlp(factors, new Statistics()); String expected = FactorizationScenarios.stringify(factors); String actuals = slpModel.toString(); Assert.assertEquals(expected, actuals); } }
{ "content_hash": "3e8a5e11dcde3581c2ba1e4eade8d277", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 206, "avg_line_length": 44.193548387096776, "alnum_prop": 0.7905109489051095, "repo_name": "jaamal/overclocking", "id": "40bd889ece914f1060f9cf78df92e1163e112d93", "size": "1370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sources/Tests/src/tests/integration/Trees/cartesianTree/CartesianSLPBuilderTests.java", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2990" }, { "name": "C++", "bytes": "8729" }, { "name": "Java", "bytes": "926976" }, { "name": "TeX", "bytes": "6505694" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tlc: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js 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="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.5.0 / tlc - 20171128</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tlc <small> 20171128 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-19 08:48:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-19 08:48:41 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.5.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;francois.pottier@inria.fr&quot; authors: [ &quot;Arthur Charguéraud &lt;arthur.chargueraud@inria.fr&gt;&quot; ] homepage: &quot;https://gitlab.inria.fr/charguer/tlc&quot; dev-repo: &quot;git+https://gitlab.inria.fr/charguer/tlc.git&quot; bug-reports: &quot;tlc-users@lists.gforge.inria.fr&quot; license: &quot;CeCILL-B&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] synopsis: &quot;A general-purpose library&quot; url { src: &quot;https://github.com/charguer/tlc/archive/refs/tags/20171128.tar.gz&quot; checksum: &quot;md5=f1036a9aa16fd3b081395717dcccd7d3&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tlc.20171128 coq.8.5.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0). The following dependencies couldn&#39;t be met: - coq-tlc -&gt; coq &gt;= 8.6 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tlc.20171128</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "cdb245e7ad78e70d7fd86994c76abb7a", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 159, "avg_line_length": 39.616766467065865, "alnum_prop": 0.5309854897218863, "repo_name": "coq-bench/coq-bench.github.io", "id": "6ea18b7501c7391743f77e2cf3293e4cef9349fe", "size": "6642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.5.0/tlc/20171128.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from django.forms.models import ModelForm, model_to_dict from moderation.models import MODERATION_STATUS_PENDING,\ MODERATION_STATUS_REJECTED from django.core.exceptions import ObjectDoesNotExist class BaseModeratedObjectForm(ModelForm): def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) if instance: try: if instance.moderated_object.moderation_status in\ [MODERATION_STATUS_PENDING, MODERATION_STATUS_REJECTED] and\ not instance.moderated_object.moderator.\ visible_until_rejected: initial =\ model_to_dict(instance.moderated_object.changed_object) kwargs.setdefault('initial', {}) kwargs['initial'].update(initial) except ObjectDoesNotExist: pass super(BaseModeratedObjectForm, self).__init__(*args, **kwargs)
{ "content_hash": "f68dac2c244a621c7676c08e9ea49ee8", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 79, "avg_line_length": 38.8, "alnum_prop": 0.6113402061855671, "repo_name": "ebrelsford/django-moderation", "id": "c352b6d4d92d1064992910fab7f8c068c1bcc264", "size": "970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/moderation/forms.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "150827" }, { "name": "Shell", "bytes": "425" } ], "symlink_target": "" }
layout: guide --- React exports a handful of utility types that may be useful to you when typing advanced React patterns. In previous sections we have seen a few of them. The following is a complete reference for each of these types along with some examples for how/where to use them. Table of contents: - [`React.Node`](#toc-react-node) - [`React.Element<typeof Component>`](#toc-react-element) - [`React.ChildrenArray<T>`](#toc-react-childrenarray) - [`React.ComponentType<Props>`](#toc-react-componenttype) - [`React.StatelessFunctionalComponent<Props>`](#toc-react-statelessfunctionalcomponent) - [`React.ElementType`](#toc-react-elementtype) - [`React.Key`](#toc-react-key) - [`React.Ref<typeof Component>`](#toc-react-ref) - [`React.ElementProps<typeof Component>`](#toc-react-elementprops) - [`React.ElementConfig<typeof Component>`](#toc-react-elementconfig) - [`React.ElementRef<typeof Component>`](#toc-react-elementref) These types are all exported as named type exports from the `react` module. If you want to access them as members on the `React` object (e.g. [`React.Node`](#toc-react-node) or [`React.StatelessFunctionalComponent`](#toc-react-statelessfunctionalcomponent)) and you are importing React as an ES module then you should import `React` as a namespace: ```js import * as React from 'react'; ``` If you are using CommonJS you can also require React: ```js const React = require('react'); ``` You can also use named type imports in either an ES module environment or a CommonJS environment: ```js import type {Node} from 'react'; ``` We will refer to all the types in the following reference as if we imported them with: ```js import * as React from 'react'; ``` > **Note:** While importing React with a default import works: > > ``` > import React from 'react'; > ``` > > You will have access to all of the values that React exports, but you will > **not** have access to the types documented below! This is because Flow will > not add types to a default export since the default export could be any value > (like a number). Flow will add exported named types to an ES namespace object > which you can get with `import * as React from 'react'` since Flow knows if > you export a value with the same name as an exported type. > > Again, if you import React with: `import React from 'react'` you will be able > to access `React.Component`, `React.createElement()`, `React.Children`, and > other JavaScript *values*. However, you will not be able to access > [`React.Node`](#toc-react-node), [`React.ChildrenArray`](#toc-react-childrenarray) or > other Flow *types*. You will need to use a named type import like: > `import type {Node} from 'react'` in addition to your default import. ## `React.Node` <a class="toc" id="toc-react-node" href="#toc-react-node"></a> This represents any node that can be rendered in a React application. `React.Node` can be undefined, null, a boolean, a number, a string, a React element, or an array of any of those types recursively. If you need a return type for your component `render()` methods or you need a generic type for a children prop then you should use `React.Node`. Here is an example of `React.Node` being used as the return type to `render()`: ```js class MyComponent extends React.Component<{}> { render(): React.Node { // ... } } ``` It may also be used as the return type of a stateless functional component: ```js function MyComponent(props: {}): React.Node { // ... } ``` You don't need to annotate the return type of either your `render()` method or a stateless functional component. However, if you want to annotate the return type then `React.Node` is the generic to use. Here is an example of `React.Node` as the prop type for children: ```js function MyComponent({ children }: { children: React.Node }) { return <div>{children}</div>; } ``` All `react-dom` JSX intrinsics have `React.Node` as their children type. `<div>`, `<span>`, and all the rest. The definition of `React.Node` can be roughly approximated with a [`React.ChildrenArray<T>`](#toc-react-childrenarray): ```js type Node = React.ChildrenArray<void | null | boolean | string | number | React.Element<any>>; ``` ## `React.Element<typeof Component>` <a class="toc" id="toc-react-element" href="#toc-react-element"></a> A React element is the type for the value of a JSX element: ```js const element: React.Element<'div'> = <div />; ``` `React.Element<typeof Component>` is also the return type of `React.createElement()`. A `React.Element<typeof Component>` takes a single type argument, `typeof Component`. `typeof Component` is the component type of the React element. For an intrinsic element, `typeof Component` will be the string literal for the intrinsic you used. Here are a few examples with DOM intrinsics: ```js (<div />: React.Element<'div'>); // OK (<span />: React.Element<'span'>); // OK (<div />: React.Element<'span'>); // Error: div is not a span. ``` `typeof Component` can also be your React class component or stateless functional component. ```js class Foo extends React.Component<{}> {} function Bar(props: {}) {} (<Foo />: React.Element<typeof Foo>); // OK (<Bar />: React.Element<typeof Bar>); // OK (<Foo />: React.Element<typeof Bar>); // Error: Foo is not Bar ``` Take note of the `typeof`, it is required! `Foo` without `typeof` would be the type of an instance of `Foo`. So: `(new Foo(): Foo)`. We want the type *of* `Foo` not the type of an instance of `Foo`. So: `(Foo: typeof Foo)`. `Class<Foo>` would also work here, but we prefer `typeof` for consistency with stateless functional components. We also need `typeof` for `Bar` because `Bar` is a value. So we want to get the type *of* the value `Bar`. `(Bar: Bar)` is an error because `Bar` cannot be used as a type, so the following is correct: `(Bar: typeof Bar)`. ## `React.ChildrenArray<T>` <a class="toc" id="toc-react-childrenarray" href="#toc-react-childrenarray"></a> A React children array can be a single value or an array nested to any level. It is designed to be used with the [`React.Children` API][]. [`React.Children` API]: https://facebook.github.io/react/docs/react-api.html#react.children For example if you want to get a normal JavaScript array from a `React.ChildrenArray<T>` see the following example: ```js import * as React from 'react'; // A children array can be a single value... const children: React.ChildrenArray<number> = 42; // ...or an arbitrarily nested array. const children: React.ChildrenArray<number> = [[1, 2], 3, [4, 5]]; // Using the `React.Children` API can flatten the array. const array: Array<number> = React.Children.toArray(children); ``` ## `React.ComponentType<Props>` <a class="toc" id="toc-react-componenttype" href="#toc-react-componenttype"></a> This is a union of a class component or a stateless functional component. This is the type you want to use for functions that receive or return React components such as higher-order components or other utilities. Here is how you may use `React.ComponentType<Props>` with [`React.Element<typeof Component>`](#toc-react-element) to construct a component with a specific set of props: ```js type Props = { foo: number, bar: number, }; function createMyElement<C: React.ComponentType<Props>>( Component: C, ): React.Element<C> { return <Component foo={1} bar={2} />; } ``` `React.ComponentType<Props>` does not include intrinsic JSX element types like `div` or `span`. See [`React.ElementType`](#toc-react-elementtype) if you also want to include JSX intrinsics. The definition for `React.ComponentType<Props>` is roughly: ```js type ComponentType<Props> = | React.StatelessFunctionalComponent<Props> | Class<React.Component<Props, any>>; ``` ## `React.StatelessFunctionalComponent<Props>` <a class="toc" id="toc-react-statelessfunctionalcomponent" href="#toc-react-statelessfunctionalcomponent"></a> This is the type of a React stateless functional component. The definition for `React.StatelessFunctionalComponent<Props>` is roughly: ```js type StatelessFunctionalComponent<Props> = (props: Props) => React.Node; ``` There is a little bit more to the definition of `React.StatelessFunctionalComponent<Props>` for context and props. ## `React.ElementType` <a class="toc" id="toc-react-elementtype" href="#toc-react-elementtype"></a> Similar to [`React.ComponentType<Props>`](#toc-react-componenttype) except it also includes JSX intrinsics (strings). The definition for `React.ElementType` is roughly: ```js type ElementType = | string | React.ComponentType<any>; ``` ## `React.Key` <a class="toc" id="toc-react-key" href="#toc-react-key"></a> The type of the key prop on React elements. It is a union of strings and numbers defined as: ```js type Key = string | number; ``` ## `React.Ref<typeof Component>` <a class="toc" id="toc-react-ref" href="#toc-react-ref"></a> The type of the [ref prop on React elements][]. `React.Ref<typeof Component>` could be a string or a ref function. [ref prop on React elements]: https://facebook.github.io/react/docs/refs-and-the-dom.html The ref function will take one and only argument which will be the element instance which is retrieved using [`React.ElementRef<typeof Component>`](#toc-react-elementref) or null since [React will pass null into a ref function when unmounting][]. [React will pass null into a ref function when unmounting]: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element Like [`React.Element<typeof Component>`](#toc-react-element), `typeof Component` must be the type *of* a React component so you need to use `typeof` as in `React.Ref<typeof MyComponent>`. The definition for `React.Ref<typeof Component>` is roughly: ```js type Ref<C> = | string | (instance: React.ElementRef<C> | null) => mixed; ``` ## `React.ElementProps<typeof Component>` <a class="toc" id="toc-react-elementprops" href="#toc-react-elementprops"></a> Gets the props for a React element type, *without* preserving the optionality of `defaultProps`. `Type` could be a React class component, a stateless functional component, or a JSX intrinsic string. This type is used for the `props` property on [`React.Element<typeof Component>`](#toc-react-element). Like [`React.Element<typeof Component>`](#toc-react-element), `Type` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`. > **Note:** Because [`React.ElementProps`](#toc-react-elementprops) does not preserve the optionality of `defaultProps`, [`React.ElementConfig`](#toc-react-elementconfig) (which does) is more often the right choice, especially for simple props pass-through as with [higher-order components](../hoc/#toc-supporting-defaultprops-with-react-elementconfig). ## `React.ElementConfig<typeof Component>` <a class="toc" id="toc-react-elementconfig" href="#toc-react-elementconfig"></a> Like `React.ElementProps<typeof Component>` this utility gets the type of a component's props but *preserves* the optionality of `defaultProps`! For example, ```js import * as React from 'react'; class MyComponent extends React.Component<{foo: number}> { static defaultProps = {foo: 42}; render() { return this.props.foo; } } // `React.ElementProps<>` requires `foo` even though it has a `defaultProp`. ({foo: 42}: React.ElementProps<typeof MyComponent>); // `React.ElementConfig<>` does not require `foo` since it has a `defaultProp`. ({}: React.ElementConfig<typeof MyComponent>); ``` Like [`React.Element<typeof Component>`](#toc-react-element), `Type` must be the type *of* a React component so you need to use `typeof` as in `React.ElementProps<typeof MyComponent>`. ## `React.ElementRef<typeof Component>` <a class="toc" id="toc-react-elementref" href="#toc-react-elementref"></a> Gets the instance type for a React element. The instance will be different for various component types: - React class components will be the class instance. So if you had `class Foo extends React.Component<{}> {}` and used `React.ElementRef<typeof Foo>` then the type would be the instance of `Foo`. - React stateless functional components do not have a backing instance and so `React.ElementRef<typeof Bar>` (when `Bar` is `function Bar() {}`) will give you the undefined type. - JSX intrinsics like `div` will give you their DOM instance. For `React.ElementRef<'div'>` that would be `HTMLDivElement`. For `React.ElementRef<'input'>` that would be `HTMLInputElement`. Like [`React.Element<typeof Component>`](#toc-react-element), `Type` must be the type *of* a React component so you need to use `typeof` as in `React.ElementRef<typeof MyComponent>`.
{ "content_hash": "83954184c09dd018cb0d0180595d925c", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 353, "avg_line_length": 36.901162790697676, "alnum_prop": 0.7271151725224515, "repo_name": "claudiopro/flow", "id": "8b7e81b4f830bb676b0fe3bc7454b2a9b8914c33", "size": "12698", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "website/en/docs/react/types.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "117458" }, { "name": "CSS", "bytes": "47820" }, { "name": "HTML", "bytes": "36429" }, { "name": "JavaScript", "bytes": "2074042" }, { "name": "Liquid", "bytes": "13216" }, { "name": "Makefile", "bytes": "18100" }, { "name": "OCaml", "bytes": "3544394" }, { "name": "PowerShell", "bytes": "1031" }, { "name": "Ruby", "bytes": "24723" }, { "name": "Shell", "bytes": "72437" }, { "name": "Standard ML", "bytes": "7257" } ], "symlink_target": "" }
package org.apache.flink.graph.asm.degree.filter.undirected; import org.apache.flink.graph.Graph; import org.apache.flink.graph.asm.AsmTestBase; import org.apache.flink.graph.asm.dataset.ChecksumHashCode.Checksum; import org.apache.flink.graph.library.metric.ChecksumHashCode; import org.apache.flink.test.util.TestBaseUtils; import org.apache.flink.types.IntValue; import org.apache.flink.types.NullValue; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Tests for {@link MaximumDegree}. */ public class MaximumDegreeTest extends AsmTestBase { @Test public void testWithSimpleGraph() throws Exception { Graph<IntValue, NullValue, NullValue> graph = undirectedSimpleGraph .run(new MaximumDegree<>(3)); String expectedVerticesResult = "(0,(null))\n" + "(1,(null))\n" + "(2,(null))\n" + "(4,(null))\n" + "(5,(null))"; TestBaseUtils.compareResultAsText(graph.getVertices().collect(), expectedVerticesResult); String expectedEdgesResult = "(0,1,(null))\n" + "(0,2,(null))\n" + "(1,0,(null))\n" + "(1,2,(null))\n" + "(2,0,(null))\n" + "(2,1,(null))"; TestBaseUtils.compareResultAsText(graph.getEdges().collect(), expectedEdgesResult); } @Test public void testWithRMatGraph() throws Exception { Checksum checksum = undirectedRMatGraph(10, 16) .run(new MaximumDegree<>(16)) .run(new ChecksumHashCode<>()) .execute(); assertEquals(805, checksum.getCount()); assertEquals(0x0000000008028b43L, checksum.getChecksum()); } }
{ "content_hash": "e425fa81f62cdca2e3a3a515f25b3e4b", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 91, "avg_line_length": 25.433333333333334, "alnum_prop": 0.7077326343381389, "repo_name": "zohar-mizrahi/flink", "id": "51e7712f5893a69cd25e25c847f63d898600102f", "size": "2331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-libraries/flink-gelly/src/test/java/org/apache/flink/graph/asm/degree/filter/undirected/MaximumDegreeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4792" }, { "name": "CSS", "bytes": "18100" }, { "name": "CoffeeScript", "bytes": "89007" }, { "name": "HTML", "bytes": "86524" }, { "name": "Java", "bytes": "31605216" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "240673" }, { "name": "Scala", "bytes": "5925253" }, { "name": "Shell", "bytes": "93241" } ], "symlink_target": "" }
package org.waveprotocol.wave.client.common.util; import com.google.gwt.core.client.GWT; /** * Collection of constants defining various browser quirky behaviours. * * Each constant should be accompanied by a detailed comment, and a "Tested:" * section detailing which browsers and operating systems the quirk has been * tested on, so that it's easy to know what's untested as new browser versions * come out, etc. * * Sometimes an "Untested exceptions:" field is appropriate, to note exceptions * to the "Tested:" field, in particular if they are concerning and represent a * reasonable doubt as to the correctness of the field's value. * * It is preferable to use the constants in this class than to have logic that * switches on explicit browser checks. * * @author danilatos@google.com (Daniel Danilatos) */ public final class QuirksConstants { /** * Whether we get DOM Mutation events * * Tested: * Safari 3-4, Firefox 3-3.5, Chrome 1-2, IE7, IE8 * * Will IE9 give us mutation events? probably not. */ public static final boolean PROVIDES_MUTATION_EVENTS = UserAgent.isFirefox() || UserAgent.isWebkit(); /** * Whether the browser left normalises the caret in most cases (There are * exceptions, usually to do with links). * * Tested: * Safari 3*, Safari 4 beta, Firefox 3.0, IE7, IE8 */ public static final boolean USUALLY_LEFT_NORMALISES = UserAgent.isWebkit() || UserAgent.isWebkit(); /** * Certain versions of webkit have a specific hack implemented in them, where * they go against the regular left-normalised behaviour at the end of an * anchor boundary, if it has an href. They still report the cursor as being * left-normalised, but if the user types, text goes to the right, outside the * link. * * Tested: * All OS: Safari 3.2.1, Safari 4 beta, Chrome 1.0, Chrome 2.0 special sauce */ public static final boolean LIES_ABOUT_CARET_AT_LINK_END_BOUNDARY = UserAgent.isWebkit() && UserAgent.isAtLeastVersion(528, 0); /** * Similar to {@link #LIES_ABOUT_CARET_AT_LINK_END_BOUNDARY}, but does not * actually lie, just doesn't like reporting carets as being inside link * boundaries, and typing occurs outside as well. * * Tested: IE8 beta * * TODO(danilatos): check IE7 */ public static final boolean DOES_NOT_LEFT_NORMALISE_AT_LINK_END_BOUNDARY = UserAgent.isIE(); /** * If the user is typing, we always get a key event before the browser changes * the dom. * * Tested: * All OS: Safari 3.2.1, 4 beta, Chrome 1, 2, Firefox 3, IE7, IE8 * * Untested exceptions: Any IME on Linux! */ public static final boolean ALWAYS_GIVES_KEY_EVENT_BEFORE_CHANGING_DOM = UserAgent.isFirefox() || UserAgent.isIE7(); /** * Whether we get the magic 229 keycode for IME key events, at least for the * first one (sometimes we don't get key events for subsequent mutations). * * Tested: * All OS: Safari 3.2.1, 4 beta, Chrome 1, 2, Firefox 3.0 * * Untested exceptions: Any IME on Linux! */ public static final boolean CAN_TELL_WHEN_FIRST_KEY_EVENT_IS_IME = UserAgent.isIE() || UserAgent.isWebkit() || UserAgent.isWin(); /** * Whether the old school Ctrl+Insert, Shift+Delete, Shift+Insert shortcuts * for Copy, Cut, Paste work. * * Tested: All OS: Firefox 3, IE 7/8, Safari 3, Chrome 2 * * Untested exceptions: Safari on Windows */ public static final boolean HAS_OLD_SCHOOL_CLIPBOARD_SHORTCUTS = UserAgent.isWin() || UserAgent.isLinux(); // NOTE(danilatos): These selection constants, unless mentioned otherwise, // refer to selection boundaries (e.g. the start, or end, of a ranged // selection, or a collapsed selection). /** * Whether the selection is either cleared or correctly transformed by the * browser in at least the following scenarios: * - textNode.insertData adds to the cursor location, if it is after the * deletion point * - textNode.deleteData subtracts from the cursor location, if it is after * the deletion point * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES = UserAgent.isFirefox() || UserAgent.isIE(); /** * Whether the selection is either cleared or correctly transformed by the * browser when text nodes are deleted. * * Gecko/IE preserve, Webkit clears selection. Both OK behaviours. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_NODE_REMOVALS = true; /** * Whether the browser moves the selection into the neighbouring text node * after a text node split before the selection point, or at least clears the * selection. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_TEXT_NODE_SPLITS = UserAgent.isIE(); /** * In this case, only clearing occurs by Webkit. Other two browsers move the * selection to the point where the moved node was. Which is BAD for wrapping! * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 * * @see #PRESERVES_SEMANTIC_SELECTION_ACROSS_MUTATIONS_OR_CLEARS_IT */ public static final boolean OK_SELECTION_ACROSS_MOVES = UserAgent.isWebkit(); /** * Preserves changes to text nodes made by calling methods on the text nodes * directly (i.e. not moving or deleting the text nodes). */ public static final boolean PRESERVES_SEMANTIC_SELECTION_ACROSS_INTRINSIC_TEXT_NODE_CHANGES = OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES && OK_SELECTION_ACROSS_TEXT_NODE_SPLITS; /** * Whether the selection preservation is completely reliable across mutations * in terms of correctness. It might get cleared in some circumstances, but * that's OK, we can just check if the selection is gone and restore it. We * don't need to transform it for correctness. * * The biggest problem here is wrap. Currently implemented with insertBefore, * it breaks selections in all browsers, even IE, AND IE doesn't clear the * selection, just moves it. Damn! Anyway, there might be a smarter way to * implement wrap - perhaps using an exec command to apply a styling to a * region and using the resulting wrapper nodes... but that's a long way off. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean PRESERVES_SEMANTIC_SELECTION_ACROSS_MUTATIONS_OR_CLEARS_IT = OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES && OK_SELECTION_ACROSS_TEXT_NODE_SPLITS && OK_SELECTION_ACROSS_MOVES; /** * Whether changing stuff in the middle of a ranged selection (that doesn't * affect the selection end points in any way), such as splitting some * entirely contained text node, affects the ranged selection. With firefox, * it appears that the selection is still "correct", but visually new text * nodes inserted don't get highlighted as selected, which is bad. * * Tested: Safari 3.2.1, FF 3.0, IE8 */ public static final boolean RANGED_SELECTION_AFFECTED_BY_INTERNAL_CHANGED = UserAgent.isFirefox(); /** * True if IME input in not totally munged by adjacent text node mutations * * Tested: * Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean PRESERVES_IME_STATE_ACROSS_ADJACENT_CHANGES = UserAgent.isIE(); /** * True if we can do the __proto__ override trick to remove defaults method * in a JSO. * WARNING(dnailatos/reuben) Should be kept as static constant for * speed reasons in string map implementation. * * Tested: Safari 4, FF 3.0, 3.5, Chrome 3-4, IE8 */ public static final boolean DOES_NOT_SUPPORT_JSO_PROTO_FIELD = UserAgent.isIE(); /** * It appears that in some browsers, if you stopPropagation() an IME * composition or contextmenu event, the default action for the event is not * executed (as if you had cancelled it) * * TODO(danilatos): File a bug * * Tested: * FF 3.0 * * Untested: * Everything else (at time of writing, nothing else has composition * events...) */ public static final boolean CANCEL_BUBBLING_CANCELS_IME_COMPOSITION_AND_CONTEXTMENU = UserAgent.isFirefox(); /** * True if mouse events have rangeParent and rangeOffset fields. * * Tested: * FF 3.0, 3.6 * Safari 4 * Chrome 5 */ public static final boolean SUPPORTS_EVENT_GET_RANGE_METHODS = UserAgent.isFirefox(); /** * True if preventDefault stops a native context menu from being shown. In * firefox this is not the case when dom.event.contextmenu.enabled is set. * * Tested: * FF 3.0, 3.6 */ public static final boolean PREVENT_DEFAULT_STOPS_CONTEXTMENT = !UserAgent.isFirefox(); /** * True if displaying a context menu updates the current selection. Safari selects * the word clicked unless you click on the current selection, Firefox does not * change the selection and Chrome and IE clears the selection unless you click * on the current selection. * * The selection that is active on mousedown will, in all browsers, be the * original selection and the selection on the contextmenu event will be the new * one. * * Tested: * FF 3.0, 3.5 * Chrome 5 * Safari 4 * IE 8 */ public static final boolean CONTEXTMENU_SETS_SELECTION = !UserAgent.isFirefox(); /** * True if the browser has the setBaseAndExtent JS method to allow better setting of * the selection within the browser. * * So far, only webkit browsers have this in their API, and documentation is scarce. See: * http://developer.apple.com/DOCUMENTATION/AppleApplications/Reference/WebKitDOMRef * /DOMSelection_idl/Classes/DOMSelection/index.html#//apple_ref/idl/instm * /DOMSelection/setBaseAndExtent/void/(inNode,inlong,inNode,inlong) */ public static final boolean HAS_BASE_AND_EXTENT = UserAgent.isWebkit(); /** * Chrome on Mac generates doesn't keypress for command combos, only keydown. * * In general, it makes sense to only fire the keypress event if the combo * generates content. https://bugs.webkit.org/show_bug.cgi?id=30397 * * However since it is the odd one out here, it is listed as a * quirk. */ public static final boolean COMMAND_COMBO_DOESNT_GIVE_KEYPRESS = UserAgent.isMac() && UserAgent.isChrome(); /** * True if the browser has native support for getElementsByClassName. * * Tested: * Chrome, Safari 3.1, Firefox 3.0 */ public static final boolean SUPPORTS_GET_ELEMENTS_BY_CLASSNAME = GWT.isScript() && checkGetElementsByClassNameSupport(); /** * True if the browser supports composition events. * * (This does not differentiate between the per-browser composition event quirks, * such as whether they provide a text vs a compositionupdate event, or other * glitches). * * Tested: * Chrome 3.0, 4.0; Safari 4; FF 3.0, 3.5; IE 7,8 */ public static final boolean SUPPORTS_COMPOSITION_EVENTS = UserAgent.isFirefox() || (UserAgent.isWebkit() && UserAgent.isAtLeastVersion(532, 5)); /** * True if the browser does an extra modification of the DOM after the * compositionend event, and also fires a text input event if the composition * was not cancelled. * * Tested: Chrome 4.0; FF 3.0, 3.5; */ public static final boolean MODIFIES_DOM_AND_FIRES_TEXTINPUT_AFTER_COMPOSITION = UserAgent.isWebkit(); // Put an upper bound on the version here when it's fixed... /** * True if the browser keeps the selection in an empty span after the * app has programmatically set it there. * * Tested: * Chrome 3.0, 4.0; Safari 3, 4; FF 3.0, 3.5; IE 7,8 */ public static final boolean SUPPORTS_CARET_IN_EMPTY_SPAN = UserAgent.isFirefox(); /** * True if the browser automatically scrolls a contentEditable element * into view when we set focus on the element * * Tested: * Chrome 5.0.307.11 beta / linux, Safari 4.0.4 / mac, Firefox 3.0.7 + 3.6 / linux */ public static final boolean ADJUSTS_SCROLL_TOP_WHEN_FOCUSING = UserAgent.isWebkit(); /** * True if the browser does not emit a paste event for plaintext paste. * This was a bug on Webkit and has been fixed and pushed to Chrome 4+ * * Tested: * Chrome 4.0.302.3; Safari 4.05 Mac */ public static final boolean PLAINTEXT_PASTE_DOES_NOT_EMIT_PASTE_EVENT = UserAgent.isSafari(); /** * True if the browser supports input type 'search'. * * Tested: * Chrome 9.0, Chrome 4.0 */ public static final boolean SUPPORTS_SEARCH_INPUT = UserAgent.isWebkit(); /** * True if the browser sanitizes pasted content to contenteditable to * prevent script execution. * * Tested: * Chrome 9.0, Safari 5, FF 3.5, FF 4.0 */ public static final boolean SANITIZES_PASTED_CONTENT = (UserAgent.isWebkit() && UserAgent.isAtLeastVersion(533, 16)) || (UserAgent.isFirefox() && UserAgent.isAtLeastVersion(4, 0)); private static native boolean checkGetElementsByClassNameSupport() /*-{ return !!document.body.getElementsByClassName; }-*/; private QuirksConstants(){} }
{ "content_hash": "fa423acbcc89249022d3b60bc13e642d", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 95, "avg_line_length": 34.802083333333336, "alnum_prop": 0.6865459443280455, "repo_name": "somehume/wavefu", "id": "378e93dd7a84e003936436baac38f0a7c5d86609", "size": "13963", "binary": false, "copies": "5", "ref": "refs/heads/trunk", "path": "src/org/waveprotocol/wave/client/common/util/QuirksConstants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "12952668" }, { "name": "JavaScript", "bytes": "2691" }, { "name": "Python", "bytes": "356911" }, { "name": "Shell", "bytes": "7099" }, { "name": "Smalltalk", "bytes": "44615" } ], "symlink_target": "" }
import {IStructure} from "./_structure"; import {StructureNode, StatementNode} from "../../nodes"; import {INode} from "../../nodes/_inode"; import {IStatement, MacroCall, NativeSQL} from "../../2_statements/statements/_statement"; import {IStructureRunnable} from "./_structure_runnable"; import {IMatch} from "./_match"; class Sequence implements IStructureRunnable { private readonly list: IStructureRunnable[]; public constructor(list: IStructureRunnable[]) { if (list.length < 2) { throw new Error("Sequence, length error"); } this.list = list; } public toRailroad() { const children = this.list.map((e) => { return e.toRailroad(); }); return "Railroad.Sequence(" + children.join() + ")"; } public getUsing(): string[] { return this.list.reduce((a, c) => { return a.concat(c.getUsing()); }, [] as string[]); } public first() { return this.list[0].first(); } public run(statements: StatementNode[], parent: INode): IMatch { let inn = statements; const out: StatementNode[] = []; for (const i of this.list) { const match = i.run(inn, parent); if (match.error) { return { matched: [], unmatched: statements, error: true, errorDescription: match.errorDescription, errorMatched: out.length, }; } out.push(...match.matched); inn = match.unmatched; } return { matched: out, unmatched: inn, error: false, errorDescription: "", errorMatched: 0, }; } } // Note that the Alternative does not nessesarily return the first in the alternative // as a map is used for better performance class Alternative implements IStructureRunnable { private readonly list: IStructureRunnable[]; private map: {[index: string]: IStructureRunnable[]}; public constructor(list: IStructureRunnable[]) { if (list.length < 2) { throw new Error("Alternative, length error"); } this.list = list; } private setupMap() { // dont call from constructor, it will cause infinite loop if (this.map === undefined) { this.map = {}; for (const i of this.list) { for (const first of i.first()) { if (this.map[first]) { this.map[first].push(i); } else { this.map[first] = [i]; } } } } } public first() { return [""]; } public toRailroad() { const children = this.list.map((e) => { return e.toRailroad(); }); return "Railroad.Choice(0, " + children.join() + ")"; } public getUsing() { return this.list.reduce((a, c) => { return a.concat(c.getUsing()); }, [] as string[]); } public run(statements: StatementNode[], parent: INode): IMatch { this.setupMap(); let count = 0; let countError = ""; if (statements.length === 0) { return { matched: [], unmatched: statements, error: true, errorDescription: countError, errorMatched: count, }; } const token = statements[0].getFirstToken().getStr().toUpperCase(); for (const i of this.map[token] || []) { const match = i.run(statements, parent); if (match.error === false) { return match; } if (match.errorMatched > count) { countError = match.errorDescription; count = match.errorMatched; } } for (const i of this.map[""] || []) { const match = i.run(statements, parent); if (match.error === false) { return match; } if (match.errorMatched > count) { countError = match.errorDescription; count = match.errorMatched; } } if (count === 0) { return { matched: [], unmatched: statements, error: true, errorDescription: "Unexpected code structure", errorMatched: count, }; } else { return { matched: [], unmatched: statements, error: true, errorDescription: countError, errorMatched: count, }; } } } class Optional implements IStructureRunnable { private readonly obj: IStructureRunnable; public constructor(obj: IStructureRunnable) { this.obj = obj; } public toRailroad() { return "Railroad.Optional(" + this.obj.toRailroad() + ")"; } public getUsing() { return this.obj.getUsing(); } public run(statements: StatementNode[], parent: INode): IMatch { const ret = this.obj.run(statements, parent); ret.error = false; return ret; } public first() { return [""]; } } class Star implements IStructureRunnable { private readonly obj: IStructureRunnable; public constructor(obj: IStructureRunnable) { this.obj = obj; } public toRailroad() { return "Railroad.ZeroOrMore(" + this.obj.toRailroad() + ")"; } public getUsing() { return this.obj.getUsing(); } public run(statements: StatementNode[], parent: INode): IMatch { let inn = statements; const out: StatementNode[] = []; while (true) { if (inn.length === 0) { return { matched: out, unmatched: inn, error: false, errorDescription: "", errorMatched: 0, }; } const match = this.obj.run(inn, parent); if (match.error === true) { if (match.errorMatched > 0) { return { matched: out, unmatched: inn, error: true, errorDescription: match.errorDescription, errorMatched: match.errorMatched, }; } else { return { matched: out, unmatched: inn, error: false, errorDescription: "", errorMatched: 0, }; } } out.push(...match.matched); inn = match.unmatched; } } public first() { return [""]; } } class SubStructure implements IStructureRunnable { private readonly s: IStructure; private matcher: IStructureRunnable; public constructor(s: IStructure) { this.s = s; } public toRailroad() { return "Railroad.NonTerminal('" + this.s.constructor.name + "', {href: '#/structure/" + this.s.constructor.name + "'})"; } public getUsing() { return ["structure/" + this.s.constructor.name]; } public first() { this.setupMatcher(); return this.matcher.first(); } private setupMatcher() { if (this.matcher === undefined) { // SubStructures are singletons, so the getMatcher can be saved, its expensive to create // dont move this to the constructor, as it might trigger infinite recursion this.matcher = this.s.getMatcher(); } } public run(statements: StatementNode[], parent: INode): IMatch { const nparent = new StructureNode(this.s); this.setupMatcher(); const ret = this.matcher.run(statements, nparent); if (ret.matched.length === 0) { ret.error = true; } else { parent.addChild(nparent); } return ret; } } class SubStatement implements IStructureRunnable { private readonly obj: new () => IStatement; public constructor(obj: new () => IStatement) { this.obj = obj; } public first() { const o = new this.obj(); if (o instanceof MacroCall || o instanceof NativeSQL) { return [""]; } return o.getMatcher().first(); } public toRailroad() { return "Railroad.Terminal('" + this.className() + "', {href: '#/statement/" + this.className() + "'})"; } public getUsing() { return ["statement/" + this.className()]; } private className() { return this.obj.name; } public run(statements: StatementNode[], parent: INode): IMatch { if (statements.length === 0) { return { matched: [], unmatched: [], error: true, errorDescription: "Expected " + this.className().toUpperCase(), errorMatched: 0, }; } else if (statements[0].get() instanceof this.obj) { parent.addChild(statements[0]); return { matched: [statements[0]], unmatched: statements.splice(1), error: false, errorDescription: "", errorMatched: 0, }; } else { return { matched: [], unmatched: statements, error: true, errorDescription: "Expected " + this.className().toUpperCase(), errorMatched: 0, }; } } } export function seq(first: IStructureRunnable, ...rest: IStructureRunnable[]): IStructureRunnable { return new Sequence([first].concat(rest)); } export function alt(first: IStructureRunnable, ...rest: IStructureRunnable[]): IStructureRunnable { return new Alternative([first].concat(rest)); } export function beginEnd(begin: IStructureRunnable, body: IStructureRunnable, end: IStructureRunnable): IStructureRunnable { return new Sequence([begin, body, end]); } export function opt(o: IStructureRunnable): IStructureRunnable { return new Optional(o); } export function star(s: IStructureRunnable): IStructureRunnable { return new Star(s); } export function sta(s: new () => IStatement): IStructureRunnable { return new SubStatement(s); } const singletons: {[index: string]: SubStructure} = {}; export function sub(s: new () => IStructure): IStructureRunnable { if (singletons[s.name] === undefined) { singletons[s.name] = new SubStructure(new s()); } return singletons[s.name]; }
{ "content_hash": "18a079d86682e0cfd7c6afaf37e74223", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 124, "avg_line_length": 25.353887399463808, "alnum_prop": 0.5945860209368722, "repo_name": "larshp/abapOpenChecksJS", "id": "85cc92a8a9ecf8f54d32dc9eafc877a7111200d3", "size": "9457", "binary": false, "copies": "2", "ref": "refs/heads/hvam/upd0910", "path": "packages/core/src/abap/3_structures/structures/_combi.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "7026" }, { "name": "CSS", "bytes": "51" }, { "name": "HTML", "bytes": "1211" }, { "name": "JavaScript", "bytes": "1049" }, { "name": "TypeScript", "bytes": "122500" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Generated by Apache Maven Doxia at Jul 16, 2012 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title> The <javaClientGenerator> Element</title> <link rel="stylesheet" href="../css/apache-maven-fluido.min.css" /> <link rel="stylesheet" href="../css/site.css" /> <link rel="stylesheet" href="../css/print.css" media="print" /> <style>body{padding-top: 20px;}</style> <script type="text/javascript" src="../js/apache-maven-fluido.min.js"></script> <meta name="Date-Revision-yyyymmdd" content="20120716" /> <meta http-equiv="Content-Language" content="en" /> <link rel="stylesheet" type="text/css" href="../mbgstyle.css" /> </head> <body> <div class="container-fluid"> <div id="banner"> <div class="pull-left"> <a href="../index.html" id="bannerLeft" title="MyBatis logo"> <img src="../images/logo.png" alt="MyBatis logo"/> </a> </div> <div class="pull-right"> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 16 July 2012</li> <li class="divider">|</li> <li id="projectVersion">Version: 1.3.2</li> </ul> </div> <div id="leftColumn" class="sidebar"> <div class="well"> <h5>User's Guide</h5> <ul> <li class="none"> <a href="../index.html" title="Introduction">Introduction</a> </li> <li class="none"> <a href="../whatsNew.html" title="What's New?">What's New?</a> </li> <li class="none"> <a href="../quickstart.html" title="Quick Start Guide">Quick Start Guide</a> </li> <li class="collapsed"> <a href="../running/running.html" title="Running MyBatis Generator">Running MyBatis Generator</a> </li> <li class="none"> <a href="../afterRunning.html" title="Tasks After Running MyBatis Generator">Tasks After Running MyBatis Generator</a> </li> <li class="none"> <a href="../migratingFromIbator.html" title="Migrating from Ibator">Migrating from Ibator</a> </li> <li class="none"> <a href="../migratingFromAbator.html" title="Migrating from Abator">Migrating from Abator</a> </li> <li class="expanded"> <a href="../configreference/xmlconfig.html" title="XML Configuration Reference">XML Configuration Reference</a> <ul> <li class="none"> <a href="../configreference/classPathEntry.html" title="&lt;classPathEntry&gt;">&lt;classPathEntry&gt;</a> </li> <li class="none"> <a href="../configreference/columnOverride.html" title="&lt;columnOverride&gt;">&lt;columnOverride&gt;</a> </li> <li class="none"> <a href="../configreference/columnRenamingRule.html" title="&lt;columnRenamingRule&gt;">&lt;columnRenamingRule&gt;</a> </li> <li class="none"> <a href="../configreference/commentGenerator.html" title="&lt;commentGenerator&gt;">&lt;commentGenerator&gt;</a> </li> <li class="none"> <a href="../configreference/context.html" title="&lt;context&gt;">&lt;context&gt;</a> </li> <li class="none"> <a href="../configreference/generatedKey.html" title="&lt;generatedKey&gt;">&lt;generatedKey&gt;</a> </li> <li class="none"> <a href="../configreference/generatorConfiguration.html" title="&lt;generatorConfiguration&gt;">&lt;generatorConfiguration&gt;</a> </li> <li class="none"> <a href="../configreference/ignoreColumn.html" title="&lt;ignoreColumn&gt;">&lt;ignoreColumn&gt;</a> </li> <li class="none"> <strong>&lt;javaClientGenerator&gt;</strong> </li> <li class="none"> <a href="../configreference/javaModelGenerator.html" title="&lt;javaModelGenerator&gt;">&lt;javaModelGenerator&gt;</a> </li> <li class="none"> <a href="../configreference/javaTypeResolver.html" title="&lt;javaTypeResolver&gt;">&lt;javaTypeResolver&gt;</a> </li> <li class="none"> <a href="../configreference/jdbcConnection.html" title="&lt;jdbcConnection&gt;">&lt;jdbcConnection&gt;</a> </li> <li class="none"> <a href="../configreference/plugin.html" title="&lt;plugin&gt;">&lt;plugin&gt;</a> </li> <li class="none"> <a href="../configreference/properties.html" title="&lt;properties&gt;">&lt;properties&gt;</a> </li> <li class="none"> <a href="../configreference/property.html" title="&lt;property&gt;">&lt;property&gt;</a> </li> <li class="none"> <a href="../configreference/sqlMapGenerator.html" title="&lt;sqlMapGenerator&gt;">&lt;sqlMapGenerator&gt;</a> </li> <li class="none"> <a href="../configreference/table.html" title="&lt;table&gt;">&lt;table&gt;</a> </li> </ul> </li> <li class="collapsed"> <a href="../generatedobjects/results.html" title="Using the Generated Objects">Using the Generated Objects</a> </li> <li class="collapsed"> <a href="../usage/intro.html" title="Database Specific Information">Database Specific Information</a> </li> <li class="collapsed"> <a href="../reference/intro.html" title="Other Reference Information">Other Reference Information</a> </li> </ul> <h5>Project Documentation</h5> <ul> <li class="collapsed"> <a href="../project-info.html" title="Project Information">Project Information</a> </li> </ul> <div id="poweredBy"> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"> <img class="poweredBy" alt="Built by Maven" src="../images/logos/maven-feather.png" /> </a> </div> </div> </div> <div id="bodyColumn" class="content"> <div id="contentBox"> <h1>The &lt;javaClientGenerator&gt; Element</h1> <p>The &lt;javaClientGenerator&gt; element is used to define properties of the Java client generator. The Java client Generator builds Java interfaces and classes that allow easy use of the generated Java model and XML map files. For iBATIS2 target environments, these generated objects take the form of DAO interface and implementation classes. For MyBatis, the generated objects take the form of mapper interfaces. This element is a optional child element of the <a href="context.html">&lt;context&gt;</a> element. If you do not specify this element, then MyBatis Generator (MBG) will not generate Java client interfaces and classes.</p> <div class="section"><h2>Required Attributes<a name="Required_Attributes"></a></h2> <table class="zebra-striped" border="1" cellspacing="0" cellpadding="5"> <tr class="a"> <th>Attribute</th> <th>Description</th> </tr> <tr class="b"> <td valign="top">type</td> <td>This attribute is used to select one of the predefined Java Client generators, or to specify a user provided Java Client generator. Any user provided DAO generator must extend the class <tt>org.mybatis.generator.codegen.AbstractJavaClientGenerator</tt> class, and must have a public default constructor. <p>The attribute accepts the following values for selecting one of the predefined generators:</p> <table border="0" class="zebra-striped" cellpadding="5"> <tr class="a"> <td colspan="2">If the &lt;context&gt; targetRuntime is <b>MyBatis3</b>:</td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">ANNOTATEDMAPPER</th> <td>The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on annotations and MyBatis 3.x SqlProviders. No XML mapper files will be generated. <p>The ANNOTATEDMAPPER requires MyBatis version 3.0.4 or higher.</p> </td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">MIXEDMAPPER</th> <td>The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on a mix of annotations and XML. An annotation will be used where a simple annotation will work. This client will not generate and Sql Provider, so all complex dynamic SQL will be generated in XML. <p>The MIXEDMAPPER requires MyBatis version 3.0.4 or higher.</p> </td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">XMLMAPPER</th> <td>The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be dependent on generated XML mapper files.</td> </tr> <tr class="a"> <td colspan="2">If the &lt;context&gt; targetRuntime is <b>MyBatis3Simple</b>:</td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">ANNOTATEDMAPPER</th> <td>The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on annotations and MyBatis 3.x SqlProviders. No XML mapper files will be generated. <p>The ANNOTATEDMAPPER requires MyBatis version 3.0.4 or higher.</p> </td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">XMLMAPPER</th> <td>The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be dependent on generated XML mapper files.</td> </tr> <tr class="b"> <td colspan="2">If the &lt;context&gt; targetRuntime is <b>Ibatis2Java2</b> or <b>Ibatis2Java5</b>:</td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">IBATIS</th> <td>The generated objects will conform to the (deprecated) iBATIS DAO framework.</td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">GENERIC-CI</th> <td>The generated objects will rely only on the SqlMapClient. The SqlMapClient will be supplied by constructor dependency injection. The generated objects will be in the form of DAO interfaces amd implementation classes. </td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">GENERIC-SI</th> <td>The generated objects will rely only on the SqlMapClient. The SqlMapClient will be supplied by setter dependency injection. The generated objects will be in the form of DAO interfaces amd implementation classes. </td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">SPRING</th> <td>The generated objects will conform to the Spring DAO framework.</td> </tr> </table> </td> </tr> <tr class="a"> <td valign="top">targetPackage</td> <td>This is the package where the generated interfaces and implementation classes will be placed. In the default generators, the property &quot;enableSubPackages&quot; controls how the actual package is calculated. If true, then the calculated package will be the targetPackage plus sub packages for the table's catalog and schema if they exist. If &quot;enableSubPackages&quot; is false (the default) then the calculated package will be exactly what is specified in the targetPackage attribute. MBG will create folders as required for the generated packages. <p><b>Note:</b> the package for implementation classes may be overridden by specifying the optional <tt>implementationPackage</tt> attribute as shown below.</p></td> </tr> <tr class="b"> <td valign="top">targetProject</td> <td>This is used to specify a target project for the generated interfaces and classes. When running in the Eclipse environment, this specifies the project and source folder where the objects will be saved. In other environments, this value should be an existing directory on the local file system. MBG will not create this directory if it does not exist.</td> </tr> </table> </div><div class="section"><h2>Optional Attributes<a name="Optional_Attributes"></a></h2> <table class="zebra-striped" border="1" cellspacing="0" cellpadding="5"> <tr class="a"> <th>Attribute</th> <th>Description</th> </tr> <tr class="b"> <td valign="top">implementationPackage</td> <td>If specified, implementation classes will be placed in this package. In the default generators, the property &quot;enableSubPackages&quot; controls how the actual package is calculated. If true, then the calculated package will be the implementationPackage plus sub packages for the table's catalog and schema if they exist. If &quot;enableSubPackages&quot; is false (the default) then the calculated package will be exactly what is specified in the implementationPackage attribute. MBG will create folders as required for the generated packages.</td> </tr> </table> </div><div class="section"><h2>Child Elements<a name="Child_Elements"></a></h2> <ul> <li><a href="property.html">&lt;property&gt;</a> (0..N)</li> </ul> </div><div class="section"><h2>Supported Properties<a name="Supported_Properties"></a></h2> <p>This table lists the properties of the default SQL Map generators that can be specified with the <a href="property.html">&lt;property&gt;</a> child element:</p> <table class="zebra-striped" border="1" cellspacing="0" cellpadding="5"> <tr class="a"> <th>Property Name</th> <th>Property Values</th> </tr> <tr class="b"> <td valign="top">enableSubPackages</td> <td>This property is used to select whether MBG will generate different Java packages for the objects based on the catalog and schema of the introspected table. <p>For example, suppose a table MYTABLE in schema MYSCHMA. Also suppose that the targetPackage attribute is set to &quot;com.mycompany&quot;. If this property is true, the generated DAO interface and class for the table will be placed in the package &quot;com.mycompany.myschema&quot;. If the property is false, the generated SQL Map will be placed in the &quot;com.mycompany&quot; schema.</p> <p><i>The default value is false.</i></p></td> </tr> <tr class="a"> <td valign="top">exampleMethodVisibility</td> <td>This property is used to set the visibility of the different &quot;ByExample&quot; methods - selectByExample, deleteByExample, etc. If not specified, the methods will be public and will be declared in the interface. This property allows you to hide these methods if you only want to use them to implement other specialized methods. <table border="0" class="zebra-striped" cellpadding="5"> <tr class="b"> <th nowrap="nowrap" valign="top">public</th> <td><i>This is the default value</i><br /> The generated methods in the implementation class will be public, and the methods will be declared in the interface.</td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">private</th> <td>The generated methods in the implementation class will be private, and the methods will not be declared in the interface </td> </tr> <tr class="b"> <th nowrap="nowrap" valign="top">protected</th> <td>The generated methods in the implementation class will be protected, and the methods will not be declared in the interface </td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">default</th> <td>The generated methods in the implementation class will have default (package) visibility, and the methods will not be declared in the interface </td> </tr> </table> <p><b>Important note:</b> this property is ignored if the target runtime is MyBatis3.</p> </td> </tr> <tr class="a"> <td valign="top">methodNameCalculator</td> <td>This property is used to select a method name calculator. A method name calculator can be used to provide different names for the DAO methods. You can select one of the predefined values, or you can specify the fully qualified name of a class that implements the <tt>org.mybatis.generator.api.DAOMethodNameCalculator</tt> interface if neither of the supplied options are appropriate in your environment. <table border="0" class="zebra-striped" cellpadding="5"> <tr class="b"> <th nowrap="nowrap" valign="top">default</th> <td><i>This is the default value</i><br /> The generated methods names will be very simple (&quot;insert&quot;, &quot;updateByPrimaryKey&quot;, etc.)</td> </tr> <tr class="a"> <th nowrap="nowrap" valign="top">extended</th> <td>The generated method names will include the name of the domain object associated with the method (&quot;insertWidget&quot;, &quot;updateWidgetByPrimaryKey&quot;, etc.) </td> </tr> </table> <p><b>Important note:</b> this property is ignored if the target runtime is MyBatis3.</p> </td> </tr> <tr class="a"> <td valign="top">rootInterface</td> <td>This property can be used to specify a super interface for all generated interface objects. This value may be overridden by specifying the <tt>rootInterface</tt> property on a Table configuration. <p><b>Important:</b> MBG does not verify that the interface exists, or is a valid Java interface.</p> <p>If specified, the value of this property should be a fully qualified interface name (like com.mycompany.MyRootInterface).</p></td> </tr> </table> </div><div class="section"><h2>Example<a name="Example"></a></h2> <p>This element specifies that we always want to place generated interfaces and objects in the &quot;'test.model&quot; package and that we want to use subpackages based on the table schema and catalog. It also specifies that we want to generate mapper interfaces that reference an XML configuration file for MyBatis3.</p> <div><pre> &lt;javaClientGenerator targetPackage=&quot;test.model&quot; targetProject=&quot;\MyProject\src&quot; type=&quot;XMLMAPPER&quot;&gt; &lt;property name=&quot;enableSubPackages&quot; value=&quot;true&quot; /&gt; &lt;/javaClientGenerator&gt; </pre></div> </div> </div> </div> </div> <footer class="footer"> <div class="container-fluid"> <div class="row span16">Copyright &copy; 2010-2012 <a href="http://www.mybatis.org/">MyBatis.org</a>. All Rights Reserved. </div> </div> </footer> </body> </html>
{ "content_hash": "fb96d09adce5646e907d26b1263690ae", "timestamp": "", "source": "github", "line_count": 443, "max_line_length": 387, "avg_line_length": 51.59367945823928, "alnum_prop": 0.5402957647882394, "repo_name": "hemingwang0902/mochasoft-framework", "id": "b6b30c4af90b070641f7ce7c2c98473b0c304236", "size": "22856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/mybatis-generator/docs/configreference/javaClientGenerator.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1665" }, { "name": "Java", "bytes": "235598" }, { "name": "JavaScript", "bytes": "2410" }, { "name": "Shell", "bytes": "981" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package p_ServidorUDP; import java.net.InetAddress; /** * Clase creada para almacenar la informacion de cada cliente, en la lista de grupos. * Como no hay Structs en Java (MAL), usamos una clase * * @author Jose Lluch */ public class Clientecillo { private int id, stock, grupo, puerto; private InetAddress address; public Clientecillo(int id, int stock, int grupo, int puerto, InetAddress address) { this.id = id; this.stock = stock; this.grupo = grupo; this.puerto = puerto; this.address = address; } public int getGrupo() { return grupo; } public int getId() { return id; } public int getPuerto() { return puerto; } public InetAddress getAddress() { return address; } public int getStock() { return stock; } }
{ "content_hash": "0aba2c4f4ebdf411bdda45da690cd1be", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 88, "avg_line_length": 20.653846153846153, "alnum_prop": 0.6154562383612663, "repo_name": "Joselluchp/ARC_Sesiones", "id": "665ea49f38721f5cf1757a79372091d5beb39f16", "size": "1074", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ARC_Multicomputador_S4/src/p_ServidorUDP/Clientecillo.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "77810" } ], "symlink_target": "" }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * ActivateLabels.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v202205; /** * The action used for activating {@link Label} objects. */ public class ActivateLabels extends com.google.api.ads.admanager.axis.v202205.LabelAction implements java.io.Serializable { public ActivateLabels() { } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .toString(); } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ActivateLabels)) return false; ActivateLabels other = (ActivateLabels) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ActivateLabels.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202205", "ActivateLabels")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
{ "content_hash": "05d2f683ca967b6f0ae7111a037b42ec", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 130, "avg_line_length": 31.240384615384617, "alnum_prop": 0.6398891966759003, "repo_name": "googleads/googleads-java-lib", "id": "4102578b90189f55b134d4e7db6025a208ef0d63", "size": "3249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202205/ActivateLabels.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "81068791" } ], "symlink_target": "" }
<?php namespace Dashboard; use ManageComponent\Model\DepartmentTable; use ManageComponent\Model\DesignationTable; use ManageComponent\Model\SkillTable; use ManageComponent\Model\TopicTable; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getViewHelperConfig() { return array( 'invokables' => array( 'SpecialPurpose' => 'Dashboard\View\Helper\SpecialPurpose', ), ); } public function getServiceConfig() { return array( 'factories' => array( 'DepartmentTable' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new DepartmentTable($dbAdapter); return $table; }, 'DesignationTable' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new DesignationTable($dbAdapter); return $table; }, 'SkillTable' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new SkillTable($dbAdapter); return $table; }, 'TopicTable' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new TopicTable($dbAdapter); return $table; }, ), ); } }
{ "content_hash": "7b57e9823f674fd03a5c1e0cf876433c", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 73, "avg_line_length": 25.868852459016395, "alnum_prop": 0.5716096324461344, "repo_name": "narwaria/test", "id": "a3d8dfd79913ed0c58e142940400e09b60812951", "size": "1578", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "module/Dashboard/Module.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "28351" }, { "name": "JavaScript", "bytes": "153314" }, { "name": "PHP", "bytes": "170945" } ], "symlink_target": "" }
Your program should display the outputs shown in this table for the given inputs provided: | Input | Output | | ------------- | --------------------- | | 50184385 | Valid product code! | | 036000241457 | Valid product code! | | 50174385 | Invalid product code! | | 9330462119318 | Valid product code! | | 9330463119318 | Invalid product code! | | 036002241457 | Invalid product code! |
{ "content_hash": "1086d8e2a477689f42014c7f6ac27755", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 38.90909090909091, "alnum_prop": 0.5934579439252337, "repo_name": "uccser/cs-unplugged", "id": "2bd4cb463ba882817ca7fc9c039702f9d817b1d0", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "csunplugged/topics/content/en/error-detection-and-correction/programming-challenges/product-code-check-valid-any-length/testing-examples.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "7927" }, { "name": "HTML", "bytes": "432891" }, { "name": "JavaScript", "bytes": "104806" }, { "name": "Python", "bytes": "1257568" }, { "name": "SCSS", "bytes": "67560" }, { "name": "Shell", "bytes": "12461" } ], "symlink_target": "" }
/** * This file is provided by Facebook for testing and evaluation purposes * only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React from 'react'; import Relay from 'react-relay'; import AddMessageMutation from '../mutations/AddMessageMutation'; var ENTER_KEY_CODE = 13; class MessageComposer extends React.Component { constructor(props, context) { super(props, context); this.state = {text: ''}; } render() { return ( <textarea className="message-composer" name="message" value={this.state.text} onChange={this._onChange} onKeyDown={this._onKeyDown} /> ); } _onChange = (event) => { this.setState({text: event.target.value}); } _onKeyDown = (event) => { if (event.keyCode === ENTER_KEY_CODE) { event.preventDefault(); var text = this.state.text.trim(); if (text) { Relay.Store.update(new AddMessageMutation({ text, viewer: this.props.viewer, thread: this.props.thread })); } this.setState({text: ''}); } } } export default Relay.createContainer(MessageComposer, { fragments: { thread: () => Relay.QL` fragment on Thread { ${AddMessageMutation.getFragment('thread')} } `, viewer: () => Relay.QL` fragment on User { ${AddMessageMutation.getFragment('viewer')} } `, } });
{ "content_hash": "3531d720fb0fb232f0c2e6ef92d686c1", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 77, "avg_line_length": 26.26388888888889, "alnum_prop": 0.6351136964569011, "repo_name": "chentsulin/relay-chat", "id": "d1aefcd5c21eecfec244e6a423f24c4ac2fe0733", "size": "1891", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "js/components/MessageComposer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1977" }, { "name": "HTML", "bytes": "911" }, { "name": "JavaScript", "bytes": "34848" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script type="text/javascript" src="cordova.js"></script> <script src="js/api-key.js"></script> <script src="js/mustache.js"></script> <script src="js/recipe.js"></script> <script src="js/app.js"></script> <script src="js/favorites.js"></script> <link rel="stylesheet" href="css/application.css"> <link rel="stylesheet" href="css/home.css"> <!-- Search Results Template --> <script id="search-results" type="x-tmpl-mustache"> <div class="list-group"> {{#recipes}} <div class="recipe-container list-group-item" data-recipeId="{{id}}" style="background-image: url({{imageUrl}})"> <h3 class="list-group-item-heading">{{title}}</h3> <p class="left list-group-item-text">{{stars}}</p> <p class="right list-group-item-text">{{prepTime}}</p> </div> {{/recipes}} </div> </script> <!-- Recipe Show Template --> <script id="recipe-show" type="x-tmpl-mustache"> <div class="recipe"> <div id="recipe-pic" style="background-image: url({{imageUrl}})"> <p>{{stars}}</p> </div> <div class="left" id="serving">{{yieldNumber}} {{yieldUnit}}</div> <div class="right" id="prep-time">{{prepTime}}</div> <h3>{{title}}</h3> </div> <button type="button" id="cook-button">Start Cooking</button> </script> <!-- Ingredients Template --> <script id="ingredients-template" type="x-tmpl-mustache"> <div class="panel panel-default"> <div class="panel-heading">Ingredients</div> <div class="panel-body"> <ul id="ingredients"> {{#ingredients}} <li>{{quantity}} {{unit}} {{name}}</li> {{/ingredients}} </ul> </div> </div> </div> </script> <!-- Instructions Template --> <script id="instructions-template" type="x-tmpl-mustache"> <ol class="list-group" id="instructions"> {{#instructions}} <li class="list-group-item">{{content}}</li> {{/instructions}} </ol> </script> <!-- Logged In Template --> <script id="logged-in" type="x-tmpl-mustache"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <ul class="nav-icons nav nav-pills"> <li><a class="nav-brand navbar-brand" href="#">Line Cook</a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-home"></span></a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-user"></span></a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-heart"></span></a></li> </ul> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a class="signout-link" href="#">Signout</a></li> </ul> </div> <form class="navbar-form" id="search-form" role="search"> <div class="row"> <div class="form-group col-xs-10"> <input id="search" type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-info"> <span class="glyphicon glyphicon-search"></span> </button> </div> </form> </div> </nav> <div class="content-container"> </div> </script> <!-- Logged Out Template --> <script id="logged-out" type="x-tmpl-mustache"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <ul class="nav-icons nav nav-pills"> <li><a class="nav-brand navbar-brand" href="#">Line Cook</a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-home"></span></a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-user"></span></a></li> <li><a class="nav-icon" href="#"><span class="glyphicon glyphicon-heart"></span></a></li> </ul> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <form class="navbar-form navbar-right signin-form"> <div class="form-group"> <input type="text" name="user[name]" class="form-control" placeholder="name"> </div> <div class="form-group"> <input type="password" name="user[password]" class="form-control" placeholder="password"> </div> <div> <button type="submit" class="btn btn-success">Sign in</button> <a class="signup-link pull-right" href="#">Not a user? Sign Up</a> </div> </form> </div> <form class="navbar-form" id="search-form" role="search"> <div class="row"> <div class="form-group col-xs-10"> <input id="search" type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-info"> <span class="glyphicon glyphicon-search"></span> </button> </div> </form> </div> </nav> <div class="content-container"> </div> </script> <!-- Sign Up Template --> <script id="sign-up-template" type="x-tmpl-mustache"> <div id="signup-container"> <form class="signup-form auth-form"> <h2 class="text-center">Sign Up</h2> <div class="form-group"> <input type="text" name="user[name]" class="form-control" placeholder="name"> </div> <div class="form-group"> <input type="password" name="user[password]" class="form-control" placeholder="password"> </div> <div class="form-group"> <input type="password" name="user[password_confirmation]" class="form-control" placeholder="password confirmation"> </div> <button type="submit" class="btn btn-success">Sign Up</button> </form> </div> </script> </head> <body> <div class="container"> </div> </body> </html>
{ "content_hash": "46f1010f61482492ba0b18df389def62", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 133, "avg_line_length": 41.54696132596685, "alnum_prop": 0.542686170212766, "repo_name": "danasselin/line-cook", "id": "841ecbc5431dd96113011f482168753441ff0049", "size": "7520", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "workshop/platforms/ios/www/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3009" }, { "name": "C", "bytes": "5598682" }, { "name": "C#", "bytes": "5291" }, { "name": "C++", "bytes": "89158" }, { "name": "CSS", "bytes": "2896" }, { "name": "HTML", "bytes": "35448" }, { "name": "Java", "bytes": "11310" }, { "name": "JavaScript", "bytes": "128230" }, { "name": "Objective-C", "bytes": "510868" }, { "name": "Ruby", "bytes": "15425" }, { "name": "Scheme", "bytes": "102" }, { "name": "Shell", "bytes": "4592" } ], "symlink_target": "" }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package org.opencv.samples.myarm; public final class R { public static final class attr { } public static final class drawable { public static final int c=0x7f020000; public static final int fang=0x7f020001; public static final int icon=0x7f020002; public static final int l=0x7f020003; public static final int r=0x7f020004; public static final int up=0x7f020005; public static final int zhua=0x7f020006; } public static final class id { public static final int fang_Button=0x7f050005; public static final int foward_Button=0x7f050001; public static final int leftfoward_Button=0x7f050002; public static final int mid_Button=0x7f050000; public static final int rightfoward_Button=0x7f050003; public static final int zhua_Button=0x7f050004; } public static final class layout { public static final int color_blob_detection_surface_view=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; public static final int connect=0x7f040002; public static final int hello=0x7f040001; public static final int send=0x7f040003; } }
{ "content_hash": "41add641502c7f7b4cfc12273ab258ec", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 77, "avg_line_length": 36.58974358974359, "alnum_prop": 0.6951646811492642, "repo_name": "SWJTUyuhui/RoboticArm-", "id": "aeb09dbdeb4a8db7fc8f5e9b5f7f76580c20bf75", "size": "1427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "myarmapp/gen/org/opencv/samples/myarm/R.java", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "7314" }, { "name": "Java", "bytes": "13686" } ], "symlink_target": "" }
"""Helper classes that list&validate all attributes to serialize to SavedModel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six from tensorflow.python.keras.saving.saved_model import json_utils from tensorflow.python.training.tracking import tracking @six.add_metaclass(abc.ABCMeta) class SavedModelSaver(object): """Saver defining the methods and properties used to serialize Keras objects. """ def __init__(self, obj): self.obj = obj @abc.abstractproperty def object_identifier(self): """String stored in object identifier field in the SavedModel proto. Returns: A string with the object identifier, which is used at load time. """ raise NotImplementedError @property def tracking_metadata(self): """String stored in metadata field in the SavedModel proto. Returns: A serialized JSON storing information necessary for recreating this layer. """ # TODO(kathywu): check that serialized JSON can be loaded (e.g., if an # object is in the python property) return json_utils.Encoder().encode(self.python_properties) def list_extra_dependencies_for_serialization(self, serialization_cache): """Lists extra dependencies to serialize to SavedModel. By overriding this method, extra dependencies can be attached to the serialized Layer. For example, this is used to save the list of `variables` and `trainable_variables`, which are python properties in a Layer object, but are represented as a static list in the SavedModel. Args: serialization_cache: A dictionary shared between all objects in the same object graph. This object is passed to both `_list_extra_dependencies_for_serialization` and `_list_functions_for_serialization`. Returns: A dictionary mapping attribute names to trackable objects. The entire list of attributes are listed in the `saved_model._LayerAttributes` class. """ return self.objects_to_serialize(serialization_cache) def list_functions_for_serialization(self, serialization_cache): """Lists extra functions to serialize to the SavedModel. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to `Function` or `ConcreteFunction`. """ fns = self.functions_to_serialize(serialization_cache) # The parent AutoTrackable class saves all user-defined tf.functions, and # returns them in _list_functions_for_serialization(). Add these functions # to the dict. fns.update( tracking.AutoTrackable._list_functions_for_serialization( # pylint:disable=protected-access self.obj, serialization_cache)) return fns @abc.abstractproperty def python_properties(self): """Returns dictionary of python properties to save in the metadata. This dictionary must be serializable and deserializable to/from JSON. When loading, the items in this dict are used to initialize the object and define attributes in the revived object. """ raise NotImplementedError @abc.abstractmethod def objects_to_serialize(self, serialization_cache): """Returns dictionary of extra checkpointable objects to serialize. See `functions_to_serialize` for an explanation of this function's effects. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to checkpointable objects. """ raise NotImplementedError @abc.abstractmethod def functions_to_serialize(self, serialization_cache): """Returns extra functions to include when serializing a Keras object. Normally, when calling exporting an object to SavedModel, only the functions and objects defined by the user are saved. For example: ``` obj = tf.Module() obj.v = tf.Variable(1.) @tf.function def foo(...): ... obj.foo = foo w = tf.Variable(1.) tf.saved_model.save(obj, 'path/to/saved/model') loaded = tf.saved_model.load('path/to/saved/model') loaded.v # Variable with the same value as obj.v loaded.foo # Equivalent to obj.foo loaded.w # AttributeError ``` Assigning trackable objects to attributes creates a graph, which is used for both checkpointing and SavedModel serialization. When the graph generated from attribute tracking is insufficient, extra objects and functions may be added at serialization time. For example, most models do not have their call function wrapped with a @tf.function decorator. This results in `model.call` not being saved. Since Keras objects should be revivable from the SavedModel format, the call function is added as an extra function to serialize. This function and `objects_to_serialize` is called multiple times when exporting to SavedModel. Please use the cache to avoid generating new functions and objects. A fresh cache is created for each SavedModel export. Args: serialization_cache: Dictionary passed to all objects in the same object graph during serialization. Returns: A dictionary mapping attribute names to `Function` or `ConcreteFunction`. """ raise NotImplementedError
{ "content_hash": "4894553db2e3400db1fac952867dc151", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 100, "avg_line_length": 34.56962025316456, "alnum_prop": 0.7226290735994141, "repo_name": "gunan/tensorflow", "id": "0065e6d786e95bed952abb1ca730c3f3cd19ff56", "size": "6151", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tensorflow/python/keras/saving/saved_model/base_serialization.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5003" }, { "name": "Batchfile", "bytes": "45924" }, { "name": "C", "bytes": "774953" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "77908225" }, { "name": "CMake", "bytes": "6500" }, { "name": "Dockerfile", "bytes": "104215" }, { "name": "Go", "bytes": "1841471" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "962443" }, { "name": "Jupyter Notebook", "bytes": "556650" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1479029" }, { "name": "Makefile", "bytes": "58603" }, { "name": "Objective-C", "bytes": "104667" }, { "name": "Objective-C++", "bytes": "297830" }, { "name": "PHP", "bytes": "23994" }, { "name": "Pascal", "bytes": "3739" }, { "name": "Pawn", "bytes": "17039" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "39476740" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Roff", "bytes": "2472" }, { "name": "Ruby", "bytes": "7459" }, { "name": "Shell", "bytes": "650007" }, { "name": "Smarty", "bytes": "34649" }, { "name": "Swift", "bytes": "62814" }, { "name": "Vim Snippet", "bytes": "58" } ], "symlink_target": "" }
using EPiServer.Cms.UI.AspNetIdentity; using EPiServer.Core; using EPiServer.Reference.Commerce.Shared.Identity; using EPiServer.Reference.Commerce.Site.Features.Login.Services; using EPiServer.Reference.Commerce.Site.Features.Shared.Extensions; using EPiServer.Web; using EPiServer.Web.Mvc; using System.Collections.Generic; using System.Web.Mvc; namespace EPiServer.Reference.Commerce.Site.Features.Shared.Controllers { /// <summary> /// Base class for controllers related to ASP.NET Identity. This controller can be used both for /// pages and blocks. /// </summary> /// <typeparam name="T">The contextual IContent related to the current page or block.</typeparam> [AuthorizeContent] [VisitorGroupImpersonation] public abstract class IdentityControllerBase<T> : ActionControllerBase, IRenderTemplate<T> where T : IContentData { protected IdentityControllerBase(ApplicationSignInManager<SiteUser> applicationSignInManager, ApplicationUserManager<SiteUser> applicationUserManager, UserService userService) { SignInManager = applicationSignInManager; UserManager = applicationUserManager; UserService = userService; } public UserService UserService { get; } public ApplicationSignInManager<SiteUser> SignInManager { get; } public ApplicationUserManager<SiteUser> UserManager { get; } /// <summary> /// Redirects the request to the original URL. /// </summary> /// <param name="returnUrl">The URL to be redirected to.</param> /// <returns>The ActionResult of the URL if it is within the current application, else it /// redirects to the web application start page.</returns> public ActionResult RedirectToLocal(string returnUrl) { if (returnUrl.IsLocalUrl(Request)) { return Redirect(returnUrl); } return RedirectToAction("Index", new { node = ContentReference.StartPage }); } [HttpGet] public ActionResult SignOut() { UserService.SignOut(); return RedirectToAction("Index", new { node = ContentReference.StartPage }); } public void AddErrors(IEnumerable<string> errors) { foreach (var error in errors) { ModelState.AddModelError(string.Empty, error); } } private bool _disposed; protected override void Dispose(bool disposing) { if (!disposing || _disposed) { return; } UserManager?.Dispose(); SignInManager?.Dispose(); UserService?.Dispose(); base.Dispose(true); _disposed = true; } } }
{ "content_hash": "24f4fa896b050fd146aca9f33929d1da", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 183, "avg_line_length": 34.573170731707314, "alnum_prop": 0.6373897707231041, "repo_name": "Geta/SEO.Sitemaps", "id": "dc64570daa4aaf9e7a8376dd61444d6bde3151cf", "size": "2837", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "samples/Quicksilver/EPiServer.Reference.Commerce.Site/Features/Shared/Controllers/IdentityControllerBase.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "12363" }, { "name": "C#", "bytes": "128426" }, { "name": "HTML", "bytes": "771" }, { "name": "JavaScript", "bytes": "4548" }, { "name": "PowerShell", "bytes": "427" } ], "symlink_target": "" }
<?php $this->load->view('admin/header'); ?> <div id="content"> <div class="inner"> <div class="topcolumn"> <div class="logo"></div> <ul id="shortcut"> <li> <a href="<?php echo base_url('admin/dashboard'); ?>" title="Back To home"> <img src="<?php echo base_url('static/admin'); ?>/images/icon/shortcut/home.png" alt="home"/><strong>Home</strong> </a> </li> <li> <a href="#" title="Website Graph"> <img src="<?php echo base_url('static/admin'); ?>/images/icon/shortcut/graph.png" alt="graph"/><strong>Graph</strong> </a> </li> <li> <a href="#" title="Setting" > <img src="<?php echo base_url('static/admin'); ?>/images/icon/shortcut/setting.png" alt="setting" /><strong>Setting</strong></a> </li> <li> <a href="#" title="Messages"> <img src="<?php echo base_url('static/admin'); ?>/images/icon/shortcut/mail.png" alt="messages" /><strong>Message</strong></a><div class="notification" >10</div></li> </ul> </div> <div class="clear"></div> <?php $this->load->view('admin/'.$content); ?> <?php $this->load->view('admin/footer'); ?>
{ "content_hash": "bd6f9d0f3c241a3b57bb84295d54207c", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 221, "avg_line_length": 78, "alnum_prop": 0.558974358974359, "repo_name": "Arkeon-net/bandung", "id": "09ae422dd194c596a6840abec97db6d35016f8fd", "size": "1170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/admin/main.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "626638" }, { "name": "CSS", "bytes": "1046320" }, { "name": "JavaScript", "bytes": "2425179" }, { "name": "PHP", "bytes": "1493049" }, { "name": "Python", "bytes": "85164" } ], "symlink_target": "" }
package com.blazebit.persistence.view.impl.objectbuilder; import com.blazebit.persistence.view.impl.collection.PluralObjectFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * * @author Christian Beikov * @since 1.5.0 */ public class SimpleCollectionAccumulator implements ContainerAccumulator<Collection<Object>> { private final PluralObjectFactory<Collection<Object>> pluralObjectFactory; private final boolean forceUnique; private final Comparator<Object> comparator; public SimpleCollectionAccumulator(PluralObjectFactory<? extends Collection<?>> pluralObjectFactory, boolean forceUnique, Comparator<Object> comparator) { this.pluralObjectFactory = (PluralObjectFactory<Collection<Object>>) pluralObjectFactory; this.forceUnique = forceUnique; this.comparator = comparator; } @Override public Collection<Object> createContainer(boolean recording, int size) { return pluralObjectFactory.createCollection(size); } @Override public void add(Collection<Object> container, Object indexObject, Object value, boolean recording) { container.add(value); } @Override public void addAll(Collection<Object> container, Collection<Object> collection, boolean recording) { container.addAll(collection); } @Override public boolean requiresPostConstruct() { return forceUnique || comparator != null; } @Override public void postConstruct(Collection<Object> collection) { ArrayList<Object> list = (ArrayList<Object>) collection; if (forceUnique) { Set<Object> set = new HashSet<>(list.size()); Iterator<Object> iter = list.iterator(); while (iter.hasNext()) { Object o = iter.next(); if (!set.add(o)) { iter.remove(); } } } if (comparator != null) { Collections.sort(list, comparator); } } }
{ "content_hash": "700081c16d471ae04abad83d0ddc9789", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 158, "avg_line_length": 30.757142857142856, "alnum_prop": 0.6758012076172782, "repo_name": "Blazebit/blaze-persistence", "id": "95b9c145058da039febaf09ae341234f1cb046ff", "size": "2753", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "entity-view/impl/src/main/java/com/blazebit/persistence/view/impl/objectbuilder/SimpleCollectionAccumulator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "44368" }, { "name": "Batchfile", "bytes": "727" }, { "name": "CSS", "bytes": "85149" }, { "name": "FreeMarker", "bytes": "16964" }, { "name": "HTML", "bytes": "8988" }, { "name": "Java", "bytes": "20068561" }, { "name": "JavaScript", "bytes": "7022" }, { "name": "Shell", "bytes": "12643" } ], "symlink_target": "" }
.class public final enum Lcom/android/internal/telephony/PhoneConstants$State; .super Ljava/lang/Enum; .source "PhoneConstants.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/internal/telephony/PhoneConstants; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x4019 name = "State" .end annotation .annotation system Ldalvik/annotation/Signature; value = { "Ljava/lang/Enum", "<", "Lcom/android/internal/telephony/PhoneConstants$State;", ">;" } .end annotation # static fields .field private static final synthetic $VALUES:[Lcom/android/internal/telephony/PhoneConstants$State; .field public static final enum IDLE:Lcom/android/internal/telephony/PhoneConstants$State; .field public static final enum OFFHOOK:Lcom/android/internal/telephony/PhoneConstants$State; .field public static final enum RINGING:Lcom/android/internal/telephony/PhoneConstants$State; # direct methods .method static constructor <clinit>()V .locals 5 .prologue const/4 v4, 0x2 const/4 v3, 0x1 const/4 v2, 0x0 .line 35 new-instance v0, Lcom/android/internal/telephony/PhoneConstants$State; const-string v1, "IDLE" invoke-direct {v0, v1, v2}, Lcom/android/internal/telephony/PhoneConstants$State;-><init>(Ljava/lang/String;I)V sput-object v0, Lcom/android/internal/telephony/PhoneConstants$State;->IDLE:Lcom/android/internal/telephony/PhoneConstants$State; new-instance v0, Lcom/android/internal/telephony/PhoneConstants$State; const-string v1, "RINGING" invoke-direct {v0, v1, v3}, Lcom/android/internal/telephony/PhoneConstants$State;-><init>(Ljava/lang/String;I)V sput-object v0, Lcom/android/internal/telephony/PhoneConstants$State;->RINGING:Lcom/android/internal/telephony/PhoneConstants$State; new-instance v0, Lcom/android/internal/telephony/PhoneConstants$State; const-string v1, "OFFHOOK" invoke-direct {v0, v1, v4}, Lcom/android/internal/telephony/PhoneConstants$State;-><init>(Ljava/lang/String;I)V sput-object v0, Lcom/android/internal/telephony/PhoneConstants$State;->OFFHOOK:Lcom/android/internal/telephony/PhoneConstants$State; .line 34 const/4 v0, 0x3 new-array v0, v0, [Lcom/android/internal/telephony/PhoneConstants$State; sget-object v1, Lcom/android/internal/telephony/PhoneConstants$State;->IDLE:Lcom/android/internal/telephony/PhoneConstants$State; aput-object v1, v0, v2 sget-object v1, Lcom/android/internal/telephony/PhoneConstants$State;->RINGING:Lcom/android/internal/telephony/PhoneConstants$State; aput-object v1, v0, v3 sget-object v1, Lcom/android/internal/telephony/PhoneConstants$State;->OFFHOOK:Lcom/android/internal/telephony/PhoneConstants$State; aput-object v1, v0, v4 sput-object v0, Lcom/android/internal/telephony/PhoneConstants$State;->$VALUES:[Lcom/android/internal/telephony/PhoneConstants$State; return-void .end method .method private constructor <init>(Ljava/lang/String;I)V .locals 0 .annotation system Ldalvik/annotation/Signature; value = { "()V" } .end annotation .prologue .line 34 invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V return-void .end method .method public static valueOf(Ljava/lang/String;)Lcom/android/internal/telephony/PhoneConstants$State; .locals 1 .param p0, "name" # Ljava/lang/String; .prologue .line 34 const-class v0, Lcom/android/internal/telephony/PhoneConstants$State; invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum; move-result-object v0 check-cast v0, Lcom/android/internal/telephony/PhoneConstants$State; return-object v0 .end method .method public static values()[Lcom/android/internal/telephony/PhoneConstants$State; .locals 1 .prologue .line 34 sget-object v0, Lcom/android/internal/telephony/PhoneConstants$State;->$VALUES:[Lcom/android/internal/telephony/PhoneConstants$State; invoke-virtual {v0}, [Lcom/android/internal/telephony/PhoneConstants$State;->clone()Ljava/lang/Object; move-result-object v0 check-cast v0, [Lcom/android/internal/telephony/PhoneConstants$State; return-object v0 .end method
{ "content_hash": "f58daa5634023bef791593085f494a35", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 137, "avg_line_length": 31.15, "alnum_prop": 0.7418023389130933, "repo_name": "Liberations/Flyme5_devices_base_cm", "id": "283a0b7bf4e63744946e88148b84a3c59b6600c9", "size": "4361", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/aosp/framework.jar.out/smali_classes2/com/android/internal/telephony/PhoneConstants$State.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "1500" }, { "name": "HTML", "bytes": "96769" }, { "name": "Makefile", "bytes": "11209" }, { "name": "Python", "bytes": "1195" }, { "name": "Shell", "bytes": "55270" }, { "name": "Smali", "bytes": "160321888" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jctools.queues; import static org.jctools.queues.CircularArrayOffsetCalculator.allocate; import static org.jctools.queues.CircularArrayOffsetCalculator.calcElementOffset; import static org.jctools.util.UnsafeRefArrayAccess.lvElement; import org.jctools.util.Pow2; public class SpscChunkedArrayQueue<E> extends BaseSpscLinkedArrayQueue<E> { private int maxQueueCapacity; private long producerQueueLimit; public SpscChunkedArrayQueue(final int capacity) { this(Math.max(8, Pow2.roundToPowerOfTwo(capacity / 8)), capacity); } public SpscChunkedArrayQueue(final int chunkSize, final int capacity) { if (capacity < 16) { throw new IllegalArgumentException("Max capacity must be 4 or more"); } // minimal chunk size of eight makes sure minimal lookahead step is 2 if (chunkSize < 8) { throw new IllegalArgumentException("Chunk size must be 2 or more"); } maxQueueCapacity = Pow2.roundToPowerOfTwo(capacity); int chunkCapacity = Pow2.roundToPowerOfTwo(chunkSize); if (chunkCapacity >= maxQueueCapacity) { throw new IllegalArgumentException( "Initial capacity cannot exceed maximum capacity(both rounded up to a power of 2)"); } long mask = chunkCapacity - 1; // need extra element to point at next array E[] buffer = allocate(chunkCapacity + 1); producerBuffer = buffer; producerMask = mask; consumerBuffer = buffer; consumerMask = mask; producerBufferLimit = mask - 1; // we know it's all empty to start with producerQueueLimit = maxQueueCapacity; soProducerIndex(0L);// serves as a StoreStore barrier to support correct publication } @Override protected final boolean offerColdPath(E[] buffer, long mask, E e, long pIndex, long offset) { // use a fixed lookahead step based on buffer capacity final long lookAheadStep = (mask + 1) / 4; long pBufferLimit = pIndex + lookAheadStep; long pQueueLimit = producerQueueLimit; if (pIndex >= pQueueLimit) { // we tested against a potentially out of date queue limit, refresh it long cIndex = lvConsumerIndex(); producerQueueLimit = pQueueLimit = cIndex + maxQueueCapacity; // if we're full we're full if (pIndex >= pQueueLimit) { return false; } } // if buffer limit is after queue limit we use queue limit. We need to handle overflow so // cannot use Math.min if (pBufferLimit - pQueueLimit > 0) { pBufferLimit = pQueueLimit; } // go around the buffer or add a new buffer if (pBufferLimit > pIndex + 1 && // there's sufficient room in buffer/queue to use pBufferLimit null == lvElement(buffer, calcElementOffset(pBufferLimit, mask))) { producerBufferLimit = pBufferLimit - 1; // joy, there's plenty of room writeToQueue(buffer, e, pIndex, offset); } else if (null == lvElement(buffer, calcElementOffset(pIndex + 1, mask))) { // buffer is not full writeToQueue(buffer, e, pIndex, offset); } else { // we got one slot left to write into, and we are not full. Need to link new buffer. // allocate new buffer of same length final E[] newBuffer = allocate((int)(mask + 2)); producerBuffer = newBuffer; linkOldToNew(pIndex, buffer, offset, newBuffer, offset, e); } return true; } }
{ "content_hash": "85b49924674b04d009b36289f5c05af5", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 104, "avg_line_length": 41.62376237623762, "alnum_prop": 0.6527117031398668, "repo_name": "franz1981/JCTools", "id": "9a581f5992eed880e2018ac27f153f5fc2538b6b", "size": "4204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jctools-core/src/main/java/org/jctools/queues/SpscChunkedArrayQueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1120334" } ], "symlink_target": "" }
extern crate sdl2; fn main() { // start sdl2 let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut timer = ctx.timer().unwrap(); // Create a window let mut window = match video_ctx.window("eg01", 640, 480).position_centered().opengl().build() { Ok(window) => window, Err(err) => panic!("failed to create window: {}", err) }; // Display the window for 3 seconds window.show(); timer.delay(3000); }
{ "content_hash": "2959eeec69ef058b34199f6e96faa826", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 100, "avg_line_length": 22.136363636363637, "alnum_prop": 0.5749486652977412, "repo_name": "jdeseno/rs-sdl2-examples", "id": "fb4c7489358083ffad8e590f63ac6f74d9e2b31f", "size": "487", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/eg01.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "6552" } ], "symlink_target": "" }
import numpy as np import os import sys import matplotlib.pyplot as plt import json from mpl_toolkits.mplot3d import Axes3D #sys.path.append(os.path.join(os.path.dirname(__file__),"../")) from crowdsourcing.interfaces.mechanical_turk import * from crowdsourcing.interfaces.local_webserver import * from crowdsourcing.util.image_search import * from crowdsourcing.annotation_types.classification import * from crowdsourcing.annotation_types.bbox import * from crowdsourcing.annotation_types.part import * # directory containing the images we want to annotate IMAGE_DIR = 'data/classification/imagenet' OUTPUT_FOLDER = 'ImageNet4' USE_MTURK = True ONLINE = True WORKERS_PER_IMAGE = 0 with open('keys.json') as f: keys = json.load(f) # Amazon account information for paying for mturk tasks, see # http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.htm AWS_ACCESS_KEY = keys.AWS_ACCESS_KEY AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY SANDBOX = False # API key for Flickr image search, see https://www.flickr.com/services/api/misc.api_keys.html FLICKR_API_KEY = keys.FLICKR_API_KEY FLICKR_API_SECRET_KEY = keys.FLICKR_API_SECRET_KEY MAX_PHOTOS = 4000 HOST = 'sbranson.no-ip.org' # The name of the objects we want to collect. Images will be obtained by crawling flickr # image search for each object, and we want to use mturk to filter out images that # don't contain the object of interest CLASSES = [ { 'object_name' : 'beaker', 'definition' : 'A flatbottomed jar made of glass or plastic; used for chemistry', 'search' : ['beaker', 'beaker chemistry', 'beaker lab'], 'wikipedia_url' : 'https://en.wikipedia.org/wiki/Beaker_(glassware)', 'example_image_urls' : ['http://imagenet.stanford.edu/nodes/12/02815834/99/998d93ef3fdd9a30034cda8f0ce246b7bb13ebc4.thumb', 'http://imagenet.stanford.edu/nodes/12/02815834/51/5171dde0d020b00923d4297d88d427326846efb2.thumb', 'http://imagenet.stanford.edu/nodes/12/02815834/d0/d06ccaf38a410e0b59bfe73819eb7bd0028bb8f1.thumb', 'https://sbranson.no-ip.org/online_crowdsourcing/not_beaker.jpg' ] }, { 'object_name' : 'scorpion', 'definition' : 'Arachnid of warm dry regions having a long segmented tail ending in a venomous stinger', 'search' : ['scorpion', 'scorpion arachnid'], 'wikipedia_url' : 'https://en.wikipedia.org/wiki/Scorpion', 'example_image_urls' : ['http://imagenet.stanford.edu/nodes/2/01770393/b0/b02dcf2c1d8c7a735b52ab74300c342124e4be5c.thumb', 'http://imagenet.stanford.edu/nodes/2/01770393/31/31af6ea97dd040ec2ddd6ae86fe1f601ecfc8c02.thumb', 'http://imagenet.stanford.edu/nodes/2/01770393/38/382e998365d5667fc333a7c8f5f6e74e3c1fe164.thumb', 'http://imagenet.stanford.edu/nodes/2/01770393/88/88bc0f14c9779fad2bc364f5f4d8269d452e26c2.thumb'] }, { 'object_name' : 'apiary', 'definition' : 'A shed containing a number of beehives', 'search' : ['apiary'], 'wikipedia_url' : 'https://en.wikipedia.org/wiki/Apiary', 'example_image_urls' : ['http://imagenet.stanford.edu/nodes/10/02727426/1f/1f6f71add82d10edad8b3630ec26490055c70a5d.thumb', 'http://imagenet.stanford.edu/nodes/10/02727426/94/94a3624ff3e639fe2d8ae836e91ca7e8fcdd0ed7.thumb', 'http://imagenet.stanford.edu/nodes/10/02727426/15/15a37da46bddd5010d3f1d1996899b8472c9556b.thumb', 'http://imagenet.stanford.edu/nodes/10/02727426/01/013b499a063b6ea83218c5ed63ea811bce5a9974.thumb'] }, { 'object_name' : 'cardigan', 'definition' : 'Knitted jacket that is fastened up the front with buttons or a zipper', 'search' : ['cardigan'], 'wikipedia_url' : 'https://en.wikipedia.org/wiki/Cardigan_(sweater)', 'example_image_urls' : ['http://imagenet.stanford.edu/nodes/9/02963159/d7/d7419041a96e8baf9a870c81d549ad0b345c8127.thumb', 'http://imagenet.stanford.edu/nodes/9/02963159/34/34256aaf7b10073ec16dc5ddb0b31305878de875.thumb', 'http://imagenet.stanford.edu/nodes/9/02963159/e8/e8a50045dd40da5299ee8817052edfc090b05355.thumb', 'http://imagenet.stanford.edu/nodes/9/02963159/38/38216bf40fafe4bb526fabb430188c24b968a152.thumb'] } ] for c in CLASSES: # directories to store images and results output_folder = os.path.join(OUTPUT_FOLDER, c['object_name']) image_folder = os.path.join('output', output_folder, 'flickr') if not os.path.exists(image_folder): os.makedirs(image_folder) # Download images from Flickr FlickrImageSearch(c['search'], image_folder, FLICKR_API_KEY, FLICKR_API_SECRET_KEY, max_photos=MAX_PHOTOS) # Load an unlabelled dataset by scanning a directory of images dataset = CrowdDatasetBinaryClassification(name=c['object_name']) dataset.scan_image_directory(os.path.join(image_folder, 'images')) if USE_MTURK: crowdsource = MTurkCrowdsourcer(dataset, AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY, HOST, output_folder, sandbox=SANDBOX, hit_params = c, online = ONLINE, thumbnail_size = (100,100), initial_assignments_per_image=WORKERS_PER_IMAGE) else: crowdsource = LocalCrowdsourcer(dataset, HOST, output_folder, hit_params = c, online = ONLINE, thumbnail_size = (100,100), initial_assignments_per_image=WORKERS_PER_IMAGE, port=8080) crowdsource.run()
{ "content_hash": "f5401d1cf82b1db8149333eb79cd82be", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 675, "avg_line_length": 73.37142857142857, "alnum_prop": 0.7610981308411215, "repo_name": "sbranson/online_crowdsourcing", "id": "9353ada9e3fba211f9f107c0a3fd4e8811908e3a", "size": "5136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "experiments/collect_annotations_imagenet3.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "15706" }, { "name": "Python", "bytes": "444456" } ], "symlink_target": "" }
if VERSION < v"0.4.0-dev" Base.copy{T,A,uplo}(t::Triangular{T,A,uplo}) = Triangular(copy(t.data), uplo) typealias AbstractTriangular Triangular typealias UpperTriangular{T,M} Triangular{T,M,:U,false} set_zero_subnormals(yes::Bool) = ccall(:jl_zero_subnormals, Bool, (Bool,), yes) else import Base.LinAlg.AbstractTriangular end ## this we need for xμTΛxμ! #Base.A_mul_Bc!(A::StridedMatrix{Float64}, B::AbstractTriangular{Float32}) = A_mul_Bc!(A, convert(AbstractMatrix{Float64}, B)) #Base.A_mul_Bc!(A::Matrix{Float32}, B::AbstractTriangular{Float64}) = A_mul_Bc!(A, convert(AbstractMatrix{Float32}, B)) ## this for diagstats #Base.BLAS.gemm!(a::Char, b::Char, alpha::Float64, A::Matrix{Float32}, B::Matrix{Float64}, beta::Float64, C::Matrix{Float64}) = Base.BLAS.gemm!(a, b, alpha, float64(A), B, beta, C)
{ "content_hash": "cfbd5a0a273bc7ea5e858504eea5b5f7", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 180, "avg_line_length": 59, "alnum_prop": 0.7046004842615012, "repo_name": "tkelman/GaussianMixtures.jl", "id": "a58ec080d64c601d0f7041c7465f2efa0c8b84ae", "size": "863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/compat.jl", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "58967" } ], "symlink_target": "" }
name 'test_java' maintainer 'test cookbook' license 'All rights reserved' description 'A test cookbook to land testing jar for java cookbook' version '0.1.0'
{ "content_hash": "7f40aca32c6a717fffb2dd37942a2dea", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 72, "avg_line_length": 39.8, "alnum_prop": 0.6180904522613065, "repo_name": "kruzda/elasticsearch", "id": "38d8b72fa1ac7dcc683d022218ffde2fd8dcc7bf", "size": "199", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "cookbooks/java/test/fixtures/cookbooks/test_java/metadata.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "55551" }, { "name": "Java", "bytes": "1162" }, { "name": "Python", "bytes": "3210" }, { "name": "Ruby", "bytes": "504466" }, { "name": "Shell", "bytes": "36394" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Web; namespace AThousandCounts.Models { public class CountContext : DbContext { public CountContext() : base("AzureSqlConnection") { } public DbSet<CountModel> Counts { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }
{ "content_hash": "6f65cdc27e0c094aa28c5121598ba9fd", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 78, "avg_line_length": 25.782608695652176, "alnum_prop": 0.6677908937605397, "repo_name": "erooijak/athousandcounts", "id": "6ff77c6adbc3a13c527ddf46738b508ca5e5f217", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AThousandCounts/Models/CountContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "107" }, { "name": "C#", "bytes": "41186" }, { "name": "CSS", "bytes": "549427" }, { "name": "JavaScript", "bytes": "205317" }, { "name": "Ruby", "bytes": "270" } ], "symlink_target": "" }
#ifndef INTEGRATOR_HPP #define INTEGRATOR_HPP #include "../rhs/rhs.h" #include "../engine/item.h" #include "engine/item_dim.h" #include "utils/vartype.hpp" #include "utils/ptr_passer.hpp" //!This class defines the integration base class /*! * This class defines the base integration class, the interface that is used by * the engine to integrate differential equations */ class integrator:public item_dim, public vartype{ protected: rhs* rh_val; std::shared_ptr<integrator> actual; public: virtual void initial_condition(ptr_passer in, size_t len); inline void initial_condition(ptr_passer in){ initial_condition(in, dimension); } virtual void postprocess(input& inval); virtual std::vector<std::string> dependencies() const; //!returns the vtype of the actual integrator. Expect infinite loop if implementation doesn't override virtual const std::type_info& vtype() const; //!Integrates the function rh /*! * This function integrates the equation du/dt=rh->dxdt(u) from t0 to tf * @param rh The function being integrated * @param u A pointer to the initial condition, also stores the final condition * @param t0 The initial time * @param tf The ending time * * The default definition calls the integrator of the actual type. * If this isn't overridden, expect an infinite loop */ virtual int integrate(ptr_passer u, double t0, double tf); //!Blank destructor for integrator virtual ~integrator(){} }; #endif
{ "content_hash": "c95a92a0a1f70bade563ba61515c98e8", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 110, "avg_line_length": 37, "alnum_prop": 0.6597051597051597, "repo_name": "UW-Kutz-Lab/lilac", "id": "820433e12a89c3c1ebc46a4792870efc10fa613f", "size": "3182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/integrator/integrator.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "21958" }, { "name": "C++", "bytes": "439116" }, { "name": "Haskell", "bytes": "2848" }, { "name": "Python", "bytes": "73538" }, { "name": "Shell", "bytes": "2777" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Glonium lineare f. angustissimum De Not. ### Remarks null
{ "content_hash": "00393e36c4e82decc610cf73c0a1942e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 40, "avg_line_length": 11.153846153846153, "alnum_prop": 0.7103448275862069, "repo_name": "mdoering/backbone", "id": "968522aecc2984e7dadb2b6795606621df8fdbe0", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Hysteriales/Hysteriaceae/Glonium/Glonium lineare/Glonium lineare angustissimum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/*global loadFixtures: true, waits:true, beforeEach: true, it: true, expect: true, describe:true, spyOn: true, white: true, vars: true, jQuery:true, $:true*/ /*jslint browser: true, devel: true, bitwise: true, debug: true, nomen: true, sloppy: false, indent: 2*/ describe("Array Prototypes", function () { "use strict"; beforeEach(function () { }); });
{ "content_hash": "c6ff425494a960bf6eeb0aabb7d196a8", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 157, "avg_line_length": 36.2, "alnum_prop": 0.6740331491712708, "repo_name": "dperrymorrow/lil-p", "id": "edf7b361e3644c0faa4f90df3e6b718024325d1a", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/ArraySpec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "19690" } ], "symlink_target": "" }
"""This application demonstrates how to perform basic operations with the Google Cloud Translate API For more information, the documentation at https://cloud.google.com/translate/docs. """ import argparse from google.cloud import translate import six def detect_language(text): """Detects the text's language.""" translate_client = translate.Client() # Text can also be a sequence of strings, in which case this method # will return a sequence of results for each text. result = translate_client.detect_language(text) print('Text: {}'.format(text)) print('Confidence: {}'.format(result['confidence'])) print('Language: {}'.format(result['language'])) def list_languages(): """Lists all available languages.""" translate_client = translate.Client() results = translate_client.get_languages() for language in results: print(u'{name} ({language})'.format(**language)) def list_languages_with_target(target): """Lists all available languages and localizes them to the target language. Target must be an ISO 639-1 language code. See https://g.co/cloud/translate/v2/translate-reference#supported_languages """ translate_client = translate.Client() results = translate_client.get_languages(target_language=target) for language in results: print(u'{name} ({language})'.format(**language)) def translate_text_with_model(target, text, model=translate.NMT): """Translates text into the target language. Make sure your project is whitelisted. Target must be an ISO 639-1 language code. See https://g.co/cloud/translate/v2/translate-reference#supported_languages """ translate_client = translate.Client() if isinstance(text, six.binary_type): text = text.decode('utf-8') # Text can also be a sequence of strings, in which case this method # will return a sequence of results for each text. result = translate_client.translate( text, target_language=target, model=model) print(u'Text: {}'.format(result['input'])) print(u'Translation: {}'.format(result['translatedText'])) print(u'Detected source language: {}'.format( result['detectedSourceLanguage'])) def translate_text(target, text): """Translates text into the target language. Target must be an ISO 639-1 language code. See https://g.co/cloud/translate/v2/translate-reference#supported_languages """ translate_client = translate.Client() if isinstance(text, six.binary_type): text = text.decode('utf-8') # Text can also be a sequence of strings, in which case this method # will return a sequence of results for each text. result = translate_client.translate( text, target_language=target) print(u'Text: {}'.format(result['input'])) print(u'Translation: {}'.format(result['translatedText'])) print(u'Detected source language: {}'.format( result['detectedSourceLanguage'])) if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) subparsers = parser.add_subparsers(dest='command') detect_langage_parser = subparsers.add_parser( 'detect-language', help=detect_language.__doc__) detect_langage_parser.add_argument('text') list_languages_parser = subparsers.add_parser( 'list-languages', help=list_languages.__doc__) list_languages_with_target_parser = subparsers.add_parser( 'list-languages-with-target', help=list_languages_with_target.__doc__) list_languages_with_target_parser.add_argument('target') translate_text_parser = subparsers.add_parser( 'translate-text', help=translate_text.__doc__) translate_text_parser.add_argument('target') translate_text_parser.add_argument('text') args = parser.parse_args() if args.command == 'detect-language': detect_language(args.text) elif args.command == 'list-languages': list_languages() elif args.command == 'list-languages-with-target': list_languages_with_target(args.target) elif args.command == 'translate-text': translate_text(args.target, args.text)
{ "content_hash": "bd15ed9ab28536f5318f5c3b79b14878", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 79, "avg_line_length": 33.109375, "alnum_prop": 0.6882963662104766, "repo_name": "sharbison3/python-docs-samples", "id": "91aef63d5c849f7a804e892742b330c9f01bb9c3", "size": "4837", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "translate/cloud-client/snippets.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2924" }, { "name": "HTML", "bytes": "26110" }, { "name": "JavaScript", "bytes": "11222" }, { "name": "Makefile", "bytes": "881" }, { "name": "Python", "bytes": "994536" }, { "name": "Shell", "bytes": "9331" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.ablx</groupId> <artifactId>currency-ws-client</artifactId> <version>0.0.1-SNAPSHOT</version> <url>https://github.com/mikrethor/currency-ws-client</url> <developers> <developer> <name>Xavier Bouclet</name> <email>mikrethor@gmail.com</email> </developer> </developers> <dependencies> <dependency> <groupId>org.springframework.ws</groupId> <artifactId>spring-ws-core</artifactId> <version>2.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.4.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>xjc</id> <goals> <goal>xjc</goal> </goals> </execution> </executions> <configuration> <!-- Package to store the generated file --> <packageName>org.ablx.currency.wsdl.binding</packageName> <!-- Treat the input as WSDL --> <wsdl>true</wsdl> <!-- Input is not XML schema --> <xmlschema>false</xmlschema> <!-- The WSDL file that you saved earlier --> <schemaFiles>CurrencyConvertor.wsdl</schemaFiles> <!-- The location of the WSDL file --> <schemaDirectory>${project.basedir}/src/main/resources</schemaDirectory> <!-- The output directory to store the generated Java files --> <outputDirectory>${project.basedir}/src/main/java</outputDirectory> <!-- Don't clear output directory on each run --> <clearOutputDir>false</clearOutputDir> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "75a801e5599a3be338953096c6a791da", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 104, "avg_line_length": 31.582417582417584, "alnum_prop": 0.6826722338204593, "repo_name": "mikrethor/samples", "id": "6e174aa096010865942bb233fec7c8c81a034330", "size": "2874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "currency-ws-client/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18962" } ], "symlink_target": "" }
package com.google.common.util.concurrent; public abstract class AbstractExecutionThreadService implements com.google.common.base.Service { // Constructors public AbstractExecutionThreadService(){ } // Methods protected abstract void run() throws java.lang.Exception; public java.lang.String toString(){ return (java.lang.String) null; } public final java.util.concurrent.Future<com.google.common.base.Service.State> start(){ return (java.util.concurrent.Future) null; } public final java.util.concurrent.Future<com.google.common.base.Service.State> stop(){ return (java.util.concurrent.Future) null; } public final com.google.common.base.Service.State state(){ return (com.google.common.base.Service.State) null; } public final boolean isRunning(){ return false; } protected void startUp() throws java.lang.Exception{ } protected void shutDown() throws java.lang.Exception{ } protected void triggerShutdown(){ } protected java.util.concurrent.Executor executor(){ return (java.util.concurrent.Executor) null; } public final com.google.common.base.Service.State startAndWait(){ return (com.google.common.base.Service.State) null; } public final com.google.common.base.Service.State stopAndWait(){ return (com.google.common.base.Service.State) null; } }
{ "content_hash": "50df6f1026bc4887f44bfbbe02e40c0b", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 89, "avg_line_length": 29.282608695652176, "alnum_prop": 0.7371937639198218, "repo_name": "Orange-OpenSource/matos-profiles", "id": "1f2bb7e1fc31ba25fc35810a390e9fa12ed78bff", "size": "2008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "matos-android/src/main/java/com/google/common/util/concurrent/AbstractExecutionThreadService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13536133" } ], "symlink_target": "" }
// Code generated by client-gen. DO NOT EDIT. package v1 import ( "context" "time" v1 "k8s.io/api/admissionregistration/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) // MutatingWebhookConfigurationsGetter has a method to return a MutatingWebhookConfigurationInterface. // A group's client should implement this interface. type MutatingWebhookConfigurationsGetter interface { MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface } // MutatingWebhookConfigurationInterface has methods to work with MutatingWebhookConfiguration resources. type MutatingWebhookConfigurationInterface interface { Create(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.CreateOptions) (*v1.MutatingWebhookConfiguration, error) Update(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.UpdateOptions) (*v1.MutatingWebhookConfiguration, error) Delete(ctx context.Context, name string, opts *metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts *metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.MutatingWebhookConfiguration, error) List(ctx context.Context, opts metav1.ListOptions) (*v1.MutatingWebhookConfigurationList, error) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MutatingWebhookConfiguration, err error) MutatingWebhookConfigurationExpansion } // mutatingWebhookConfigurations implements MutatingWebhookConfigurationInterface type mutatingWebhookConfigurations struct { client rest.Interface } // newMutatingWebhookConfigurations returns a MutatingWebhookConfigurations func newMutatingWebhookConfigurations(c *AdmissionregistrationV1Client) *mutatingWebhookConfigurations { return &mutatingWebhookConfigurations{ client: c.RESTClient(), } } // Get takes name of the mutatingWebhookConfiguration, and returns the corresponding mutatingWebhookConfiguration object, and an error if there is any. func (c *mutatingWebhookConfigurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.MutatingWebhookConfiguration, err error) { result = &v1.MutatingWebhookConfiguration{} err = c.client.Get(). Resource("mutatingwebhookconfigurations"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of MutatingWebhookConfigurations that match those selectors. func (c *mutatingWebhookConfigurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.MutatingWebhookConfigurationList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1.MutatingWebhookConfigurationList{} err = c.client.Get(). Resource("mutatingwebhookconfigurations"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested mutatingWebhookConfigurations. func (c *mutatingWebhookConfigurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("mutatingwebhookconfigurations"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a mutatingWebhookConfiguration and creates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any. func (c *mutatingWebhookConfigurations) Create(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.CreateOptions) (result *v1.MutatingWebhookConfiguration, err error) { result = &v1.MutatingWebhookConfiguration{} err = c.client.Post(). Resource("mutatingwebhookconfigurations"). VersionedParams(&opts, scheme.ParameterCodec). Body(mutatingWebhookConfiguration). Do(ctx). Into(result) return } // Update takes the representation of a mutatingWebhookConfiguration and updates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any. func (c *mutatingWebhookConfigurations) Update(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.UpdateOptions) (result *v1.MutatingWebhookConfiguration, err error) { result = &v1.MutatingWebhookConfiguration{} err = c.client.Put(). Resource("mutatingwebhookconfigurations"). Name(mutatingWebhookConfiguration.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(mutatingWebhookConfiguration). Do(ctx). Into(result) return } // Delete takes name of the mutatingWebhookConfiguration and deletes it. Returns an error if one occurs. func (c *mutatingWebhookConfigurations) Delete(ctx context.Context, name string, options *metav1.DeleteOptions) error { return c.client.Delete(). Resource("mutatingwebhookconfigurations"). Name(name). Body(options). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *mutatingWebhookConfigurations) DeleteCollection(ctx context.Context, options *metav1.DeleteOptions, listOptions metav1.ListOptions) error { var timeout time.Duration if listOptions.TimeoutSeconds != nil { timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("mutatingwebhookconfigurations"). VersionedParams(&listOptions, scheme.ParameterCodec). Timeout(timeout). Body(options). Do(ctx). Error() } // Patch applies the patch and returns the patched mutatingWebhookConfiguration. func (c *mutatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MutatingWebhookConfiguration, err error) { result = &v1.MutatingWebhookConfiguration{} err = c.client.Patch(pt). Resource("mutatingwebhookconfigurations"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
{ "content_hash": "52ab2347163b5c082364c71705f2bd57", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 217, "avg_line_length": 42.91558441558441, "alnum_prop": 0.7999697382357391, "repo_name": "davidz627/kubernetes", "id": "e9787bf408f5894ebea978d3b665f50b13fc4119", "size": "7173", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2840" }, { "name": "Dockerfile", "bytes": "49820" }, { "name": "Go", "bytes": "54599083" }, { "name": "HTML", "bytes": "38" }, { "name": "Lua", "bytes": "17200" }, { "name": "Makefile", "bytes": "65536" }, { "name": "PowerShell", "bytes": "118255" }, { "name": "Python", "bytes": "23490" }, { "name": "Ruby", "bytes": "413" }, { "name": "Shell", "bytes": "1609250" }, { "name": "Starlark", "bytes": "3806986" }, { "name": "sed", "bytes": "1390" } ], "symlink_target": "" }
require 'torch' require 'nn' require 'nngraph' require 'optim' require('pl.stringx').import() require 'pl.seq' require 'utils/SymbolsManager' include "../utils/utils.lua" local MinibatchLoader = require 'utils.MinibatchLoader' function transfer_data(x) if opt.gpuid>=0 then return x:cuda() end return x end function lstm(x, prev_c, prev_h) -- Calculate all four gates in one go local i2h = nn.Linear(opt.rnn_size, 4 * opt.rnn_size)(x) local h2h = nn.Linear(opt.rnn_size, 4 * opt.rnn_size)(prev_h) local gates = nn.CAddTable()({i2h, h2h}) -- Reshape to (batch_size, n_gates, hid_size) -- Then slize the n_gates dimension local reshaped_gates = nn.Reshape(4, opt.rnn_size)(gates) local sliced_gates = nn.SplitTable(2)(reshaped_gates) -- Use select gate to fetch each gate and apply nonlinearity local in_gate = nn.Sigmoid()(nn.SelectTable(1)(sliced_gates)):annotate{name='in_gate'} local in_transform = nn.Tanh()(nn.SelectTable(2)(sliced_gates)):annotate{name='in_transform'} local forget_gate = nn.Sigmoid()(nn.SelectTable(3)(sliced_gates)):annotate{name='forget_gate'} local out_gate = nn.Sigmoid()(nn.SelectTable(4)(sliced_gates)):annotate{name='out_gate'} if opt.dropoutrec > 0 then in_transform = nn.Dropout(opt.dropoutrec)(in_transform) end local next_c = nn.CAddTable()({ nn.CMulTable()({forget_gate, prev_c}):annotate{name='next_c_1'}, nn.CMulTable()({in_gate, in_transform}):annotate{name='next_c_2'} }) local next_h = nn.CMulTable()({out_gate, nn.Tanh()(next_c)}):annotate{name='next_h'} return next_c, next_h end function create_lstm_unit(w_size) -- input local x = nn.Identity()() local prev_s = nn.Identity()() local i = {[0] = nn.LookupTable(w_size, opt.rnn_size)(x):annotate{name='lstm'}} local next_s = {} local splitted = {prev_s:split(2 * opt.num_layers)} for layer_idx = 1, opt.num_layers do local prev_c = splitted[2 * layer_idx - 1] local prev_h = splitted[2 * layer_idx] local x_in = i[layer_idx - 1] if opt.dropout > 0 then x_in = nn.Dropout(opt.dropout)(x_in) end local next_c, next_h = lstm(x_in, prev_c, prev_h) table.insert(next_s, next_c) table.insert(next_s, next_h) i[layer_idx] = next_h end local m = nn.gModule({x, prev_s}, {nn.Identity()(next_s)}) return transfer_data(m) end function create_attention_unit(w_size) -- input local enc_s_top = nn.Identity()() local dec_s_top = nn.Identity()() -- (batch*length*H) * (batch*H*1) = (batch*length*1) local dot = nn.MM()({enc_s_top, nn.View(opt.rnn_size,1):setNumInputDims(1)(dec_s_top)}) local attention = nn.SoftMax()(nn.Sum(3)(dot)) -- (batch*length*H)^T * (batch*length*1) = (batch*H*1) local enc_attention = nn.MM(true, false)({enc_s_top, nn.View(-1, 1):setNumInputDims(1)(attention)}) local hid = nn.Tanh()(nn.Linear(2*opt.rnn_size, opt.rnn_size)(nn.JoinTable(2)({nn.Sum(3)(enc_attention), dec_s_top}))) local h2y_in = hid if opt.dropout > 0 then h2y_in = nn.Dropout(opt.dropout)(h2y_in) end local h2y = nn.Linear(opt.rnn_size, w_size)(h2y_in) local pred = nn.LogSoftMax()(h2y) local m = nn.gModule({enc_s_top, dec_s_top}, {pred}) return transfer_data(m) end function setup() -- initialize model model = {} model.enc_s = {} model.dec_s = {} model.ds = {} model.save_enc_ds = {} model.enc_s_top = transfer_data(torch.Tensor(opt.batch_size, opt.enc_seq_length, opt.rnn_size)) model.enc_ds_top = transfer_data(torch.Tensor(opt.batch_size, opt.enc_seq_length, opt.rnn_size)) for j = 0, opt.enc_seq_length do model.enc_s[j] = {} for d = 1, 2 * opt.num_layers do model.enc_s[j][d] = transfer_data(torch.zeros(opt.batch_size, opt.rnn_size)) end end for j = 0, opt.dec_seq_length do model.dec_s[j] = {} for d = 1, 2 * opt.num_layers do model.dec_s[j][d] = transfer_data(torch.zeros(opt.batch_size, opt.rnn_size)) end end for d = 1, 2 * opt.num_layers do model.ds[d] = transfer_data(torch.zeros(opt.batch_size, opt.rnn_size)) model.save_enc_ds[d] = transfer_data(torch.zeros(opt.batch_size, opt.rnn_size)) end local word_manager, form_manager = unpack(torch.load(path.join(opt.data_dir, 'map.t7'))) print("Creating encoder") model.enc_rnn_unit = create_lstm_unit(word_manager.vocab_size) model.enc_rnn_unit:training() print("Creating decoder") model.dec_rnn_unit = create_lstm_unit(form_manager.vocab_size) model.dec_rnn_unit:training() model.dec_att_unit = create_attention_unit(form_manager.vocab_size) model.criterions={} for i = 1, opt.dec_seq_length do table.insert(model.criterions, transfer_data(nn.ClassNLLCriterion())) end -- collect all parameters to a vector param_x, param_dx = combine_all_parameters(model.enc_rnn_unit, model.dec_rnn_unit, model.dec_att_unit) print('number of parameters in the model: ' .. param_x:nElement()) param_x:uniform(-opt.init_weight, opt.init_weight) -- make a bunch of clones after flattening, as that reallocates memory (tips from char-rnn) model.enc_rnns = cloneManyTimes(model.enc_rnn_unit, opt.enc_seq_length) model.dec_rnns = cloneManyTimes(model.dec_rnn_unit, opt.dec_seq_length) model.dec_atts = cloneManyTimes(model.dec_att_unit, opt.dec_seq_length) end function reset_ds() for d = 1, #model.ds do model.ds[d]:zero() end end function eval_training(param_x_) model.enc_rnn_unit:training() model.dec_rnn_unit:training() model.dec_att_unit:training() for i = 1, #model.enc_rnns do model.enc_rnns[i]:training() end for i = 1, #model.dec_rnns do model.dec_rnns[i]:training() end for i = 1, #model.dec_atts do model.dec_atts[i]:training() end -- load batch data local enc_batch, enc_len_batch, dec_batch = train_loader:random_batch() -- ship batch data to gpu if opt.gpuid >= 0 then enc_batch = enc_batch:float():cuda() dec_batch = dec_batch:float():cuda() end -- do not predict after <E> local enc_max_len = enc_batch:size(2) local dec_max_len = dec_batch:size(2) - 1 -- forward propagation =============================== if param_x_ ~= param_x then param_x:copy(param_x_) end -- encode for i = 1, #model.enc_s[0] do model.enc_s[0][i]:zero() end for i = 1, enc_max_len do model.enc_s[i] = model.enc_rnns[i]:forward({enc_batch[{{}, i}], model.enc_s[i - 1]}) if opt.gpuid >= 0 then cutorch.synchronize() end end -- initialize decoder using encoding results for i = 1, opt.batch_size do for j = 1, #model.dec_s[0] do model.dec_s[0][j][{i,{}}]:copy(model.enc_s[enc_len_batch[i]][j][{i,{}}]) end end -- build (batch*length*H) for attention score computation model.enc_s_top:zero() for i = 1, enc_max_len do model.enc_s_top[{{},i,{}}]:copy(model.enc_s[i][2*opt.num_layers]) end local enc_s_top_view = model.enc_s_top[{{},{1, enc_max_len},{}}] -- decode local softmax_predictions = {} local loss = 0 for i = 1, dec_max_len do model.dec_s[i] = model.dec_rnns[i]:forward({dec_batch[{{}, i}], model.dec_s[i - 1]}) softmax_predictions[i] = model.dec_atts[i]:forward({enc_s_top_view, model.dec_s[i][2*opt.num_layers]}) loss = loss + model.criterions[i]:forward(softmax_predictions[i], dec_batch[{{}, i+1}]) if opt.gpuid >= 0 then cutorch.synchronize() end end loss = loss / opt.batch_size -- backward propagation =============================== param_dx:zero() local enc_ds_top_view = model.enc_ds_top[{{},{1, enc_max_len},{}}] enc_ds_top_view:zero() reset_ds() for i = dec_max_len, 1, -1 do local crit_dx = model.criterions[i]:backward(softmax_predictions[i], dec_batch[{{}, i+1}]) local tmp1, tmp2 = unpack(model.dec_atts[i]:backward({enc_s_top_view, model.dec_s[i][2*opt.num_layers]}, crit_dx)) enc_ds_top_view:add(tmp1) model.ds[2*opt.num_layers]:add(tmp2) local tmp = model.dec_rnns[i]:backward({dec_batch[{{}, i}], model.dec_s[i - 1]}, model.ds)[2] copy_table(model.ds, tmp) if opt.gpuid >= 0 then cutorch.synchronize() end end -- back-propagate to encoder copy_table(model.save_enc_ds, model.ds) local no_blank = false for i = enc_max_len, 1, -1 do -- mask, or not if (not no_blank) then no_blank = true for j = 1, opt.batch_size do if i > enc_len_batch[j] then for k = 1, #model.ds do model.ds[k][{j,{}}]:zero() end no_blank = false elseif i == enc_len_batch[j] then for k = 1, #model.ds do model.ds[k][{j,{}}]:copy(model.save_enc_ds[k][{j,{}}]) end end end end -- add gradient from attention layer if no_blank then model.ds[2*opt.num_layers]:add(model.enc_ds_top[{{},i,{}}]) else for j = 1, opt.batch_size do if i <= enc_len_batch[j] then model.ds[2*opt.num_layers][{j,{}}]:add(model.enc_ds_top[{j,i,{}}]) end end end -- bp local tmp = model.enc_rnns[i]:backward({enc_batch[{{}, i}], model.enc_s[i - 1]}, model.ds)[2] copy_table(model.ds, tmp) if opt.gpuid >= 0 then cutorch.synchronize() end end -- clip gradient element-wise param_dx:clamp(-opt.grad_clip, opt.grad_clip) return loss, param_dx end function main() local cmd = torch.CmdLine() cmd:option('-gpuid', 0, 'which gpu to use. -1 = use CPU') cmd:option('-data_dir', '', 'data path') -- bookkeeping cmd:option('-seed',123,'torch manual random number generator seed') cmd:option('-checkpoint_dir', '', 'output directory where checkpoints get written') cmd:option('-savefile','save','filename to autosave the checkpont to. Will be inside checkpoint_dir/') cmd:option('-print_every',2000,'how many steps/minibatches between printing out the loss') -- model params cmd:option('-rnn_size', 200, 'size of LSTM internal state') cmd:option('-num_layers', 1, 'number of layers in the LSTM') cmd:option('-dropout',0.4,'dropout for regularization, used after each RNN hidden layer. 0 = no dropout') cmd:option('-dropoutrec',0,'dropout for regularization, used after each c_i. 0 = no dropout') cmd:option('-enc_seq_length',50,'number of timesteps to unroll for') cmd:option('-dec_seq_length',100,'number of timesteps to unroll for') cmd:option('-batch_size',20,'number of sequences to train on in parallel') cmd:option('-max_epochs',80,'number of full passes through the training data') -- optimization cmd:option('-opt_method', 0, 'optimization method: 0-rmsprop 1-sgd') cmd:option('-learning_rate',0.01,'learning rate') cmd:option('-init_weight',0.08,'initailization weight') cmd:option('-learning_rate_decay',0.98,'learning rate decay') cmd:option('-learning_rate_decay_after',5,'in number of epochs, when to start decaying the learning rate') cmd:option('-restart',-1,'in number of epochs, when to restart the optimization') cmd:option('-decay_rate',0.95,'decay rate for rmsprop') cmd:option('-grad_clip',5,'clip gradients at this value') cmd:text() opt = cmd:parse(arg) -- initialize gpu/cpu init_device(opt) -- setup network setup() -- load data train_loader = MinibatchLoader.create(opt, 'train') -- make sure output directory exists if not path.exists(opt.checkpoint_dir) then lfs.mkdir(opt.checkpoint_dir) end -- start training local step = 0 local epoch = 0 local optim_state = {learningRate = opt.learning_rate, alpha = opt.decay_rate} print("Starting training.") local iterations = opt.max_epochs * train_loader.num_batch for i = 1, iterations do local epoch = i / train_loader.num_batch local timer = torch.Timer() local loss = 0 if opt.opt_method == 0 then _, loss = optim.rmsprop(eval_training, param_x, optim_state) elseif opt.opt_method == 1 then _, loss = optim.sgd(eval_training, param_x, optim_state) end local time = timer:time().real local train_loss = loss[1] -- the loss is inside a list, pop it -- exponential learning rate decay if opt.opt_method == 0 then if i % train_loader.num_batch == 0 and opt.learning_rate_decay < 1 then if epoch >= opt.learning_rate_decay_after then local decay_factor = opt.learning_rate_decay optim_state.learningRate = optim_state.learningRate * decay_factor -- decay it end end end if (epoch == opt.restart) and (optim_state.m) then optim_state.m:zero() optim_state.learningRate = opt.learning_rate end if i % opt.print_every == 0 then print(string.format("%d/%d, train_loss = %6.8f, time/batch = %.2fs", i, iterations, train_loss, time)) end -- on last iteration if i == iterations then local checkpoint = {} checkpoint.enc_rnn_unit = model.enc_rnn_unit checkpoint.dec_rnn_unit = model.dec_rnn_unit checkpoint.dec_att_unit = model.dec_att_unit checkpoint.opt = opt checkpoint.i = i checkpoint.epoch = epoch torch.save(string.format('%s/model.t7', opt.checkpoint_dir), checkpoint) end if i % 30 == 0 then collectgarbage() end -- handle early stopping if things are going really bad if loss[1] ~= loss[1] then print('loss is NaN. This usually indicates a bug.') break -- halt end end end main()
{ "content_hash": "dea0ef40c5c80bfb01d99445f98ab85b", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 120, "avg_line_length": 33.576441102756895, "alnum_prop": 0.6396954542061656, "repo_name": "donglixp/lang2logic", "id": "d61e61f232e71ad77f96b1a76b22260c766203d0", "size": "13397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "seq2seq/atis/attention/main.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Cuda", "bytes": "7882" }, { "name": "Lua", "bytes": "395284" }, { "name": "Python", "bytes": "510" }, { "name": "Shell", "bytes": "1032" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_72) on Wed Nov 05 20:55:19 EST 2014 --> <title>Cassandra.AsyncClient.get_indexed_slices_call (apache-cassandra API)</title> <meta name="date" content="2014-11-05"> <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="Cassandra.AsyncClient.get_indexed_slices_call (apache-cassandra 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/Cassandra.AsyncClient.get_indexed_slices_call.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="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_count_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_multi_slice_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html" target="_top">Frames</a></li> <li><a href="Cassandra.AsyncClient.get_indexed_slices_call.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><a href="#nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&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">org.apache.cassandra.thrift</div> <h2 title="Class Cassandra.AsyncClient.get_indexed_slices_call" class="title">Class Cassandra.AsyncClient.get_indexed_slices_call</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.thrift.async.TAsyncMethodCall</li> <li> <ul class="inheritance"> <li>org.apache.cassandra.thrift.Cassandra.AsyncClient.get_indexed_slices_call</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.html" title="class in org.apache.cassandra.thrift">Cassandra.AsyncClient</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">Cassandra.AsyncClient.get_indexed_slices_call</span> extends org.apache.thrift.async.TAsyncMethodCall</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>org.apache.thrift.async.TAsyncMethodCall.State</code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>client, transport</code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html#Cassandra.AsyncClient.get_indexed_slices_call(org.apache.cassandra.thrift.ColumnParent,%20org.apache.cassandra.thrift.IndexClause,%20org.apache.cassandra.thrift.SlicePredicate,%20org.apache.cassandra.thrift.ConsistencyLevel,%20org.apache.thrift.async.AsyncMethodCallback,%20org.apache.thrift.async.TAsyncClient,%20org.apache.thrift.protocol.TProtocolFactory,%20org.apache.thrift.transport.TNonblockingTransport)">Cassandra.AsyncClient.get_indexed_slices_call</a></strong>(<a href="../../../../org/apache/cassandra/thrift/ColumnParent.html" title="class in org.apache.cassandra.thrift">ColumnParent</a>&nbsp;column_parent, <a href="../../../../org/apache/cassandra/thrift/IndexClause.html" title="class in org.apache.cassandra.thrift">IndexClause</a>&nbsp;index_clause, <a href="../../../../org/apache/cassandra/thrift/SlicePredicate.html" title="class in org.apache.cassandra.thrift">SlicePredicate</a>&nbsp;column_predicate, <a href="../../../../org/apache/cassandra/thrift/ConsistencyLevel.html" title="enum in org.apache.cassandra.thrift">ConsistencyLevel</a>&nbsp;consistency_level, org.apache.thrift.async.AsyncMethodCallback&nbsp;resultHandler, org.apache.thrift.async.TAsyncClient&nbsp;client, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory, org.apache.thrift.transport.TNonblockingTransport&nbsp;transport)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== 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>java.util.List&lt;<a href="../../../../org/apache/cassandra/thrift/KeySlice.html" title="class in org.apache.cassandra.thrift">KeySlice</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html#getResult()">getResult</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html#write_args(org.apache.thrift.protocol.TProtocol)">write_args</a></strong>(org.apache.thrift.protocol.TProtocol&nbsp;prot)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>getClient, getFrameBuffer, getSequenceId, getStartTime, getState, getTimeoutTimestamp, hasTimeout, isFinished, onError, prepareMethodCall, transition</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Cassandra.AsyncClient.get_indexed_slices_call(org.apache.cassandra.thrift.ColumnParent, org.apache.cassandra.thrift.IndexClause, org.apache.cassandra.thrift.SlicePredicate, org.apache.cassandra.thrift.ConsistencyLevel, org.apache.thrift.async.AsyncMethodCallback, org.apache.thrift.async.TAsyncClient, org.apache.thrift.protocol.TProtocolFactory, org.apache.thrift.transport.TNonblockingTransport)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Cassandra.AsyncClient.get_indexed_slices_call</h4> <pre>public&nbsp;Cassandra.AsyncClient.get_indexed_slices_call(<a href="../../../../org/apache/cassandra/thrift/ColumnParent.html" title="class in org.apache.cassandra.thrift">ColumnParent</a>&nbsp;column_parent, <a href="../../../../org/apache/cassandra/thrift/IndexClause.html" title="class in org.apache.cassandra.thrift">IndexClause</a>&nbsp;index_clause, <a href="../../../../org/apache/cassandra/thrift/SlicePredicate.html" title="class in org.apache.cassandra.thrift">SlicePredicate</a>&nbsp;column_predicate, <a href="../../../../org/apache/cassandra/thrift/ConsistencyLevel.html" title="enum in org.apache.cassandra.thrift">ConsistencyLevel</a>&nbsp;consistency_level, org.apache.thrift.async.AsyncMethodCallback&nbsp;resultHandler, org.apache.thrift.async.TAsyncClient&nbsp;client, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory, org.apache.thrift.transport.TNonblockingTransport&nbsp;transport) throws org.apache.thrift.TException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="write_args(org.apache.thrift.protocol.TProtocol)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>write_args</h4> <pre>public&nbsp;void&nbsp;write_args(org.apache.thrift.protocol.TProtocol&nbsp;prot) throws org.apache.thrift.TException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>write_args</code>&nbsp;in class&nbsp;<code>org.apache.thrift.async.TAsyncMethodCall</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd></dl> </li> </ul> <a name="getResult()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getResult</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../org/apache/cassandra/thrift/KeySlice.html" title="class in org.apache.cassandra.thrift">KeySlice</a>&gt;&nbsp;getResult() throws <a href="../../../../org/apache/cassandra/thrift/InvalidRequestException.html" title="class in org.apache.cassandra.thrift">InvalidRequestException</a>, <a href="../../../../org/apache/cassandra/thrift/UnavailableException.html" title="class in org.apache.cassandra.thrift">UnavailableException</a>, <a href="../../../../org/apache/cassandra/thrift/TimedOutException.html" title="class in org.apache.cassandra.thrift">TimedOutException</a>, org.apache.thrift.TException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../org/apache/cassandra/thrift/InvalidRequestException.html" title="class in org.apache.cassandra.thrift">InvalidRequestException</a></code></dd> <dd><code><a href="../../../../org/apache/cassandra/thrift/UnavailableException.html" title="class in org.apache.cassandra.thrift">UnavailableException</a></code></dd> <dd><code><a href="../../../../org/apache/cassandra/thrift/TimedOutException.html" title="class in org.apache.cassandra.thrift">TimedOutException</a></code></dd> <dd><code>org.apache.thrift.TException</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/Cassandra.AsyncClient.get_indexed_slices_call.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="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_count_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.get_multi_slice_call.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html" target="_top">Frames</a></li> <li><a href="Cassandra.AsyncClient.get_indexed_slices_call.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><a href="#nested_classes_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_org.apache.thrift.async.TAsyncMethodCall">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&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>Copyright &copy; 2014 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "9d39e4d6a0e88423540367452e91b370", "timestamp": "", "source": "github", "line_count": 348, "max_line_length": 754, "avg_line_length": 48.27298850574713, "alnum_prop": 0.6555747365914638, "repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet", "id": "7b2ced2e0993c6052bcca2cedb0779b25e075084", "size": "16799", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apache-cassandra-2.1.2/javadoc/org/apache/cassandra/thrift/Cassandra.AsyncClient.get_indexed_slices_call.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "59670" }, { "name": "PowerShell", "bytes": "37758" }, { "name": "Python", "bytes": "622552" }, { "name": "Shell", "bytes": "100474" }, { "name": "Thrift", "bytes": "78926" } ], "symlink_target": "" }
package engine.gui; import java.awt.Color; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import engine.GameEngine; import model.unit.Unit; public class ActionPanel extends JPanel { private Dimension mySize = new Dimension(300, 230); private JButton myNextTurnButton; private JPanel myUnitListArea; private JohnTestAbilityArea myAbilityListArea; //private AbilityListArea myAbilityListArea; private GameEngine myGameEngine; public ActionPanel(GameEngine ge) { myGameEngine = ge; //setPreferredSize(mySize); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); TitledBorder titledBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Actions"); titledBorder.setTitleJustification(TitledBorder.LEFT); setBorder(titledBorder); myUnitListArea = new UnitListArea(myGameEngine); myAbilityListArea = new JohnTestAbilityArea(myGameEngine); //myAbilityListArea = new AbilityListArea(myGameEngine); add(new ButtonArea(myGameEngine)); add(myUnitListArea); add(myAbilityListArea); } public JPanel getUnitListArea() { return myUnitListArea; } public JohnTestAbilityArea getAbilityListArea() { return myAbilityListArea; } public void setSelectedUnit(Unit u){ myAbilityListArea.setUnit(u); } }
{ "content_hash": "fe185e13a62ce059ff218b1f0c9b9d5a", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 119, "avg_line_length": 26, "alnum_prop": 0.790521978021978, "repo_name": "bradleysykes/game_leprechaun", "id": "c2278be8fd9a779d991fd4a84c56128f1ee03294", "size": "1456", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/engine/gui/ActionPanel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "338938" } ], "symlink_target": "" }
var Garam = require(process.cwd()+'/server/lib/Garam') , _ = require('underscore') ,BaseTransaction = require(process.cwd()+'/server/lib/BaseTransaction'); module.exports = BaseTransaction.extend({ pid:'ServerLoginWorkerStatusRes', create : function() { this._packet = { state : false } }, addEvent : function(client) { client.on('ServerReConnectionWorkerRes',function (state) { //DC 가 떨어지고 자동으로 재접속에 성공했을때의 처리 Garam.getCtl('dc_worker').setConnectionStatus(); Garam.logger().info('reconnection dc-worker',client.getHostname()); }) } });
{ "content_hash": "88ddb97b2c6f81f7683ebe2ba9af9abe", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 79, "avg_line_length": 19, "alnum_prop": 0.5894736842105263, "repo_name": "ssdosso/garam", "id": "f9b36224a44be9a92fbfca2ca286d0849e07cba7", "size": "707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/transactions/dc_worker/login/ServerReConnectionWorkerRes.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "24851" }, { "name": "JavaScript", "bytes": "367378" } ], "symlink_target": "" }
package com.plugin.content; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import com.plugin.util.LogUtil; import android.app.Application; import android.content.Context; import dalvik.system.DexClassLoader; /** * <Pre> * @author cailiming * </Pre> */ public class PluginDescriptor implements Serializable { private static final long serialVersionUID = -7545734825911798344L; public static final int UNKOWN = 0; public static final int BROADCAST = 1; public static final int ACTIVITY = 2; public static final int SERVICE = 4; public static final int PROVIDER = 6; public static final int FRAGMENT = 8; public static final int FUNCTION = 9; private String packageName; private String version; private String description; private boolean isStandalone; private boolean isEnabled; private String applicationName; private HashMap<String, PluginProviderInfo> providerInfos = new HashMap<String, PluginProviderInfo>(); /** * key: fragment id, * value: fragment class */ private HashMap<String, String> fragments = new HashMap<String, String>(); /** * key: activity class name * value: intentfilter list */ private HashMap<String, ArrayList<PluginIntentFilter>> activitys = new HashMap<String, ArrayList<PluginIntentFilter>>(); /** * key: service class name * value: intentfilter list */ private HashMap<String, ArrayList<PluginIntentFilter>> services = new HashMap<String, ArrayList<PluginIntentFilter>>(); /** * key: receiver class name * value: intentfilter list */ private HashMap<String, ArrayList<PluginIntentFilter>> receivers = new HashMap<String, ArrayList<PluginIntentFilter>>(); private String installedPath; private transient Application pluginApplication; private transient DexClassLoader pluginClassLoader; private transient Context pluginContext; //=============getter and setter====================== public Context getPluginContext() { return pluginContext; } public void setPluginContext(Context pluginContext) { this.pluginContext = pluginContext; } public DexClassLoader getPluginClassLoader() { return pluginClassLoader; } public void setPluginClassLoader(DexClassLoader pluginLoader) { this.pluginClassLoader = pluginLoader; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public HashMap<String, String> getFragments() { return fragments; } public void setfragments(HashMap<String, String> fragments) { this.fragments = fragments; } public HashMap<String, ArrayList<PluginIntentFilter>> getReceivers() { return receivers; } public void setReceivers(HashMap<String, ArrayList<PluginIntentFilter>> receivers) { this.receivers = receivers; } public HashMap<String, ArrayList<PluginIntentFilter>> getActivitys() { return activitys; } public void setActivitys(HashMap<String, ArrayList<PluginIntentFilter>> activitys) { this.activitys = activitys; } public HashMap<String, ArrayList<PluginIntentFilter>> getServices() { return services; } public void setServices(HashMap<String, ArrayList<PluginIntentFilter>> services) { this.services = services; } public String getInstalledPath() { return installedPath; } public void setInstalledPath(String installedPath) { this.installedPath = installedPath; } public void setDescription(String description) { this.description = description; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public Application getPluginApplication() { return pluginApplication; } public void setPluginApplication(Application pluginApplication) { this.pluginApplication = pluginApplication; } public boolean isStandalone() { return isStandalone; } public void setStandalone(boolean isStandalone) { this.isStandalone = isStandalone; } public HashMap<String, PluginProviderInfo> getProviderInfos() { return providerInfos; } public void setProviderInfos(HashMap<String, PluginProviderInfo> providerInfos) { this.providerInfos = providerInfos; } public String getDescription() { if (description != null && description.startsWith("@") && description.length() == 9) { String idHex = description.replace("@", ""); try { int id = Integer.parseInt(idHex, 16); //此时context可能还没有初始化 if (pluginContext != null) { String des = pluginContext.getString(id); return des; } } catch (Exception e) { e.printStackTrace(); } } return description; } /** * 需要根据id查询的只有fragment * @param clazzId * @return */ public String getPluginClassNameById(String clazzId) { String clazzName = getFragments().get(clazzId); if (clazzName == null) { LogUtil.d("PluginDescriptor", "clazzName not found for classId ", clazzId); } else { LogUtil.d("PluginDescriptor", "clazzName found ", clazzName); } return clazzName; } /** * 需要根据Id查询的只有fragment * @param clazzId * @return */ public boolean containsFragment(String clazzId) { if (getFragments().containsKey(clazzId) && isEnabled()) { return true; } return false; } /** * 根据className查询 * @param clazzName * @return */ public boolean containsName(String clazzName) { if (getFragments().containsValue(clazzName) && isEnabled()) { return true; } else if (getActivitys().containsKey(clazzName) && isEnabled()) { return true; } else if (getReceivers().containsKey(clazzName) && isEnabled()) { return true; } else if (getServices().containsKey(clazzName) && isEnabled()) { return true; } else if (getProviderInfos().containsKey(clazzName) && isEnabled()) { return true; } return false; } /** * 获取class的类型: activity * @return */ public int getType(String clazzName) { if (getFragments().containsValue(clazzName) && isEnabled()) { return FRAGMENT; } else if (getActivitys().containsKey(clazzName) && isEnabled()) { return ACTIVITY; } else if (getReceivers().containsKey(clazzName) && isEnabled()) { return BROADCAST; } else if (getServices().containsKey(clazzName) && isEnabled()) { return SERVICE; } else if (getProviderInfos().containsKey(clazzName) && isEnabled()) { return PROVIDER; } return UNKOWN; } }
{ "content_hash": "6bcc5204bff1e1d96af098b2fb5d967a", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 121, "avg_line_length": 23.774193548387096, "alnum_prop": 0.7227498869289914, "repo_name": "GKerison/Android-Plugin-Framework", "id": "d1e5e69e2bca4084e9820d0ac3d3912fa25fccf7", "size": "6709", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "PluginCore/src/com/plugin/content/PluginDescriptor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "272659" } ], "symlink_target": "" }
namespace Springboard.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class ForeignKeyFix : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(ForeignKeyFix)); string IMigrationMetadata.Id { get { return "201602272239156_ForeignKeyFix"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
{ "content_hash": "fa535f7193835d84ffe02da899e16335", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 96, "avg_line_length": 28.571428571428573, "alnum_prop": 0.6225, "repo_name": "CSC394-Springboard/Springboard", "id": "ea4b9cdb9ab29bc45c2f852c967e90b12661583a", "size": "822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Springboard/Springboard/Migrations/201602272239156_ForeignKeyFix.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "218051" }, { "name": "CSS", "bytes": "82456" }, { "name": "HTML", "bytes": "7027" }, { "name": "JavaScript", "bytes": "293476" }, { "name": "PowerShell", "bytes": "135839" } ], "symlink_target": "" }
""" Collects Web IDL definitions in IDL files into a Python object per Blink component. Collected IDL definitions are parsed into ASTs and saved into a file with a label of Blink component. """ import optparse import utilities import web_idl from idl_parser import idl_parser from idl_parser import idl_lexer _VALID_COMPONENTS = ('core', 'modules', 'extensions_chromeos') def parse_options(): parser = optparse.OptionParser() parser.add_option( '--idl_list_file', type='string', help="a file path which lists IDL file paths to process") parser.add_option( '--component', type='choice', choices=_VALID_COMPONENTS, help="specify a component name") parser.add_option( '--for_testing', action='store_true', help=("specify this option if the IDL definitions are meant for " "testing only")) parser.add_option('--output', type='string', help="the output file path") options, args = parser.parse_args() required_option_names = ('idl_list_file', 'component', 'output') for opt_name in required_option_names: if getattr(options, opt_name) is None: parser.error("--{} is a required option.".format(opt_name)) if args: parser.error("Unknown arguments {}".format(args)) return options, args def main(): options, _ = parse_options() filepaths = utilities.read_idl_files_list_from_file(options.idl_list_file) lexer = idl_lexer.IDLLexer() parser = idl_parser.IDLParser(lexer) ast_group = web_idl.AstGroup( component=web_idl.Component(options.component), for_testing=bool(options.for_testing)) for filepath in filepaths: ast_group.add_ast_node(idl_parser.ParseFile(parser, filepath)) ast_group.write_to_file(options.output) if __name__ == '__main__': main()
{ "content_hash": "8fe1a96a4840617d3ed484177499ecac", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 78, "avg_line_length": 28.846153846153847, "alnum_prop": 0.6544, "repo_name": "nwjs/chromium.src", "id": "750304dd2492835f6e3dd81d4720935ff21b54d9", "size": "2037", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "third_party/blink/renderer/bindings/scripts/collect_idl_files.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'spec_helper' describe Target do # pending "add some examples to (or delete) #{__FILE__}" end
{ "content_hash": "9f765ef31ad41371a4fe65b508964129", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 58, "avg_line_length": 21, "alnum_prop": 0.6857142857142857, "repo_name": "TonFw/Pinger", "id": "7e366835b9ecd180aed4fc8f8763c250ccfa3e33", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/target_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3050" }, { "name": "CoffeeScript", "bytes": "844" }, { "name": "JavaScript", "bytes": "697" }, { "name": "Ruby", "bytes": "84300" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Today - Sunny - 83/63" android:id="@+id/list_item_forecast_textview" android:minHeight="?android:attr/listPreferredItemHeight" android:gravity="center" />
{ "content_hash": "9265d79f23d54a96c95fd26d031c1363", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 68, "avg_line_length": 49.625, "alnum_prop": 0.672544080604534, "repo_name": "voxelgenesis/Sunshine-Version-2", "id": "5f59cdcb942ed933c103d52ef483d10a408195ce", "size": "397", "binary": false, "copies": "1", "ref": "refs/heads/1.01_hello_world", "path": "app/src/main/res/layout/list_item_forecast.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6379" } ], "symlink_target": "" }
set `planner.slice_target`=1; select cast(t.data.p_partkey as varchar) from schema_change_empty_batch_part t order by t.data.p_partkey limit 5; reset `planner.slice_target`;
{ "content_hash": "b75e04f12f23a10d053f99bad06bf143", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 113, "avg_line_length": 58, "alnum_prop": 0.7701149425287356, "repo_name": "cchang738/drill-test-framework", "id": "f87b6560d83521c88dc03c82177813b310228e8d", "size": "174", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "framework/resources/Functional/schema_change_empty_batch/hbase/emptyHbaseScan2.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "E", "bytes": "19826071" }, { "name": "Eiffel", "bytes": "68483171" }, { "name": "Forth", "bytes": "87" }, { "name": "HiveQL", "bytes": "781960" }, { "name": "Java", "bytes": "185017" }, { "name": "OpenEdge ABL", "bytes": "1590703" }, { "name": "PLSQL", "bytes": "58311" }, { "name": "PLpgSQL", "bytes": "72111" }, { "name": "Python", "bytes": "15030" }, { "name": "Shell", "bytes": "107060" }, { "name": "q", "bytes": "3508170" } ], "symlink_target": "" }
module Rails module Paths # This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system. # It allows you to collect information about how you want to structure your application # paths by a Hash like API. It requires you to give a physical path on initialization. # # root = Root.new "/rails" # root.add "app/controllers", eager_load: true # # The command above creates a new root object and adds "app/controllers" as a path. # This means we can get a <tt>Rails::Paths::Path</tt> object back like below: # # path = root["app/controllers"] # path.eager_load? # => true # path.is_a?(Rails::Paths::Path) # => true # # The +Path+ object is simply an enumerable and allows you to easily add extra paths: # # path.is_a?(Enumerable) # => true # path.to_ary.inspect # => ["app/controllers"] # # path << "lib/controllers" # path.to_ary.inspect # => ["app/controllers", "lib/controllers"] # # Notice that when you add a path using +add+, the path object created already # contains the path with the same path value given to +add+. In some situations, # you may not want this behavior, so you can give <tt>:with</tt> as option. # # root.add "config/routes", with: "config/routes.rb" # root["config/routes"].inspect # => ["config/routes.rb"] # # The +add+ method accepts the following options as arguments: # eager_load, autoload, autoload_once, and glob. # # Finally, the +Path+ object also provides a few helpers: # # root = Root.new "/rails" # root.add "app/controllers" # # root["app/controllers"].expanded # => ["/rails/app/controllers"] # root["app/controllers"].existent # => ["/rails/app/controllers"] # # Check the <tt>Rails::Paths::Path</tt> documentation for more information. class Root attr_accessor :path def initialize(path) @path = path @root = {} end def []=(path, value) glob = self[path] ? self[path].glob : nil add(path, with: value, glob: glob) end def add(path, options = {}) with = Array(options.fetch(:with, path)) @root[path] = Path.new(self, path, with, options) end def [](path) @root[path] end def values @root.values end def keys @root.keys end def values_at(*list) @root.values_at(*list) end def all_paths values.tap(&:uniq!) end def autoload_once filter_by(&:autoload_once?) end def eager_load filter_by(&:eager_load?) end def autoload_paths filter_by(&:autoload?) end def load_paths filter_by(&:load_path?) end private def filter_by(&block) all_paths.find_all(&block).flat_map { |path| paths = path.existent paths - path.children.flat_map { |p| yield(p) ? [] : p.existent } }.uniq end end class Path include Enumerable attr_accessor :glob def initialize(root, current, paths, options = {}) @paths = paths @current = current @root = root @glob = options[:glob] options[:autoload_once] ? autoload_once! : skip_autoload_once! options[:eager_load] ? eager_load! : skip_eager_load! options[:autoload] ? autoload! : skip_autoload! options[:load_path] ? load_path! : skip_load_path! end def absolute_current # :nodoc: File.expand_path(@current, @root.path) end def children keys = @root.keys.find_all { |k| k.start_with?(@current) && k != @current } @root.values_at(*keys.sort) end def first expanded.first end def last expanded.last end %w(autoload_once eager_load autoload load_path).each do |m| class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{m}! # def eager_load! @#{m} = true # @eager_load = true end # end # def skip_#{m}! # def skip_eager_load! @#{m} = false # @eager_load = false end # end # def #{m}? # def eager_load? @#{m} # @eager_load end # end RUBY end def each(&block) @paths.each(&block) end def <<(path) @paths << path end alias :push :<< def concat(paths) @paths.concat paths end def unshift(*paths) @paths.unshift(*paths) end def to_ary @paths end def extensions # :nodoc: $1.split(",") if @glob =~ /\{([\S]+)\}/ end # Expands all paths against the root and return all unique values. def expanded raise "You need to set a path root" unless @root.path result = [] each do |p| path = File.expand_path(p, @root.path) if @glob && File.directory?(path) Dir.chdir(path) do result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort) end else result << path end end result.uniq! result end # Returns all expanded paths but only if they exist in the filesystem. def existent expanded.select { |f| File.exist?(f) } end def existent_directories expanded.select { |d| File.directory?(d) } end alias to_a expanded end end end
{ "content_hash": "ec5c596f2ebe1653d2b43ce6225fb8a5", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 95, "avg_line_length": 26.58256880733945, "alnum_prop": 0.5287316652286453, "repo_name": "tijwelch/rails", "id": "10925de8b20407ac876bd9dde7e2d8514ba46e50", "size": "5795", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "railties/lib/rails/paths.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33444" }, { "name": "CoffeeScript", "bytes": "41914" }, { "name": "HTML", "bytes": "195552" }, { "name": "JavaScript", "bytes": "86514" }, { "name": "Ruby", "bytes": "10496098" }, { "name": "Yacc", "bytes": "965" } ], "symlink_target": "" }
namespace bookmarks { class BookmarkModel; } // ChromeHistoryBackendClient implements history::HistoryBackendClient interface // to provides access to embedder-specific features. class ChromeHistoryBackendClient : public history::HistoryBackendClient { public: explicit ChromeHistoryBackendClient(bookmarks::BookmarkModel* bookmark_model); ~ChromeHistoryBackendClient() override; // history::HistoryBackendClient implementation. bool IsBookmarked(const GURL& url) override; void GetBookmarks(std::vector<history::URLAndTitle>* bookmarks) override; bool ShouldReportDatabaseError() override; bool IsWebSafe(const GURL& url) override; #if defined(OS_ANDROID) void OnHistoryBackendInitialized( history::HistoryBackend* history_backend, history::HistoryDatabase* history_database, history::ThumbnailDatabase* thumbnail_database, const base::FilePath& history_dir) override; void OnHistoryBackendDestroyed(history::HistoryBackend* history_backend, const base::FilePath& history_dir) override; #endif // defined(OS_ANDROID) private: // BookmarkModel instance providing access to bookmarks. May be null during // testing but must outlive ChromeHistoryBackendClient if non-null. bookmarks::BookmarkModel* bookmark_model_; DISALLOW_COPY_AND_ASSIGN(ChromeHistoryBackendClient); }; #endif // CHROME_BROWSER_HISTORY_CHROME_HISTORY_BACKEND_CLIENT_H_
{ "content_hash": "32adcf1541bb7e077d3a75c42a5ffb8a", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 80, "avg_line_length": 40.82857142857143, "alnum_prop": 0.7739678096571029, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "7d689f5db35d7f7a9e9a0000eaa622ce3d51255b", "size": "1850", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "chrome/browser/history/chrome_history_backend_client.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.intuit.ipp.serialization.custom; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.intuit.ipp.data.DeliveryErrorTypeEnum; /** * Custom JsonSerializer for reading DeliveryErrorTypeEnum values * */ public class DeliveryErrorTypeEnumJsonSerializer extends JsonSerializer<DeliveryErrorTypeEnum> { /** * {@inheritDoc} */ @Override public void serialize(DeliveryErrorTypeEnum value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeString(value.value()); } }
{ "content_hash": "015346fc514be18fa793dba6a4d92dd6", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 121, "avg_line_length": 26.64, "alnum_prop": 0.8063063063063063, "repo_name": "intuit/QuickBooks-V3-Java-SDK", "id": "a0f6f84cac94053666c5e80deca598e8b37a4e86", "size": "1412", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/custom/DeliveryErrorTypeEnumJsonSerializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4762384" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style> body {font: normal 12px arial;} td, th {padding: 5px 15px 5px 5px; border: 1px solid #eee; font: normal 12px arial; text-align: left;} td {vertical-align: top;} input[type=text] {width: 120px;} textarea {width: 100%; height: 500px;} a {text-decoration: none;} #ajaxResponse {position: fixed; top: 0; right: 0; padding: 5px 10px; background: #000; color: #fff; font-weight: bold;} label {white-space: nowrap;} </style> </head> <body> <div id="ajaxResponse"></div> {exp:channel:entries channel="articles" limit="1" disable="categories|category_fields|member_data" search:article_content="blockquote"} {title} <table cellspacing="0" style="width: 100%"> {exp:safecracker channel="articles" include_jquery="no" json="yes" safecracker_head="no" class="editForm" id="editForm{entry_id}" entry_id="{entry_id}"} <tr> <td style="width: 60%;"><textarea name="article_content">{article_content}</textarea></td> <td style="width: 40%;"><textarea name="article_opening_blockquote">{article_opening_blockquote}</textarea></td> <td><input type="submit" name="submit" value="Submit"></td> </tr> {/exp:safecracker} </table> {paginate} <p> {if previous_page} <a href="{auto_path}">Previous Page</a> &nbsp; {/if} {current_page} of {total_pages} {if next_page} &nbsp; <a href="{auto_path}" id="nextLink">Next Page</a> {/if} </p> {/paginate} {/exp:channel:entries} <textarea> <figure> <blockquote></blockquote> <figcaption><cite></cite></figcaption> </figure> </textarea> <!-- javascript starts here --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> // remap jQuery to $ (function($){})(window.jQuery); // ASSIGN FUNCTIONS ON DOMREADY $(document).ready(function (){ $('.editForm').ajaxForm({ target: '#ajaxResponse', beforeSubmit: showRequest, success: showResponse, dataType: 'json' }); }); // pre-submit callback function showRequest(formData, jqForm, options) { // alert(); return true; }; function showResponse(responseText, statusText, xhr, $form) { location.reload(); }; /*! * jQuery Form Plugin * version: 3.09 (16-APR-2012) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses: * http://malsup.github.com/mit-license.txt * http://malsup.github.com/gpl-license-v2.txt */ /*global ActiveXObject alert */ ;(function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr('method'); action = this.attr('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file:enabled[value]', this); // [value] (issue #113) var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { fileUploadIframe(a); }); } else { fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { fileUploadXhr(a); } else { $.ajax(options); } // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { for (var p in options.extraData) if (options.extraData.hasOwnProperty(p)) formdata.append(p, options.extraData[p]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.onprogress = function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }; } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { o.data = formdata; if(beforeSend) beforeSend.call(o, xhr, options); }; $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var useProp = !!$.fn.prop; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( useProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (!n) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { extraInputs.push( $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n]) .appendTo(form)[0]); } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } try { doc = getDoc(io); } catch(ex) { log('cannot access response document: ', ex); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught: ',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file' && !el.disabled) { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (includeHidden) { // includeHidden can be the valud true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })(jQuery); </script> </body> </html>
{ "content_hash": "825443092445b76e7d5c7fe7598b5c97", "timestamp": "", "source": "github", "line_count": 1182, "max_line_length": 152, "avg_line_length": 33.423857868020306, "alnum_prop": 0.5116814741691346, "repo_name": "MikaCaldera/AListApart", "id": "f2647fed117780e7fc57a9f42719d098d522ec1e", "size": "39507", "binary": false, "copies": "1", "ref": "refs/heads/components", "path": "templates/default_site/utilities.group/blockquotes.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "143702" }, { "name": "HTML", "bytes": "444650" }, { "name": "JavaScript", "bytes": "154967" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Logging in...</title> </head> <body> <script> var token = window.location.toString().replace(/.+token=/, ''); window.opener.postMessage({token: token}, window.location); window.close(); </script> </body> </html>
{ "content_hash": "8d956a8ad69edbe578367bf3fa112f23", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 63, "avg_line_length": 19.923076923076923, "alnum_prop": 0.640926640926641, "repo_name": "macropodhq/gitr-client", "id": "57ebcc5c62ee758b9e2f6dd6aae3ee575920a7ba", "size": "259", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "login-callback.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18667" }, { "name": "JavaScript", "bytes": "57045" }, { "name": "Shell", "bytes": "1208" } ], "symlink_target": "" }
module ActiveRecord module Associations # = Active Record Has One Association class HasOneAssociation < SingularAssociation #:nodoc: include ForeignAssociation def handle_dependency case options[:dependent] when :restrict_with_exception raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target when :restrict_with_error if load_target record = owner.class.human_attribute_name(reflection.name).downcase owner.errors.add(:base, :'restrict_dependent_destroy.has_one', record: record) throw(:abort) end else delete end end def delete(method = options[:dependent]) if load_target case method when :delete target.delete when :destroy target.destroyed_by_association = reflection target.destroy throw(:abort) unless target.destroyed? when :destroy_async primary_key_column = target.class.primary_key.to_sym id = target.public_send(primary_key_column) enqueue_destroy_association( owner_model_name: owner.class.to_s, owner_id: owner.id, association_class: reflection.klass.to_s, association_ids: [id], association_primary_key_column: primary_key_column, ensuring_owner_was_method: options.fetch(:ensuring_owner_was, nil) ) when :nullify target.update_columns(nullified_owner_attributes) if target.persisted? end end end private def replace(record, save = true) raise_on_type_mismatch!(record) if record return target unless load_target || record assigning_another_record = target != record if assigning_another_record || record.has_changes_to_save? save &&= owner.persisted? transaction_if(save) do remove_target!(options[:dependent]) if target && !target.destroyed? && assigning_another_record if record set_owner_attributes(record) set_inverse_instance(record) if save && !record.save nullify_owner_attributes(record) set_owner_attributes(target) if target raise RecordNotSaved, "Failed to save the new associated #{reflection.name}." end end end end self.target = record end # The reason that the save param for replace is false, if for create (not just build), # is because the setting of the foreign keys is actually handled by the scoping when # the record is instantiated, and so they are set straight away and do not need to be # updated within replace. def set_new_record(record) replace(record, false) end def remove_target!(method) case method when :delete target.delete when :destroy target.destroyed_by_association = reflection if target.persisted? target.destroy end else nullify_owner_attributes(target) remove_inverse_instance(target) if target.persisted? && owner.persisted? && !target.save set_owner_attributes(target) raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " \ "The record failed to save after its foreign key was set to nil." end end end def nullify_owner_attributes(record) record[reflection.foreign_key] = nil end def transaction_if(value) if value reflection.klass.transaction { yield } else yield end end def _create_record(attributes, raise_error = false, &block) unless owner.persisted? raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" end super end end end end
{ "content_hash": "c3375d607f982c929df90a6cfd5df30b", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 109, "avg_line_length": 32.815384615384616, "alnum_prop": 0.5745428973277075, "repo_name": "vipulnsward/rails", "id": "d25f0fa55a863229370bf549fd094e0fe8dbf9c1", "size": "4297", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "activerecord/lib/active_record/associations/has_one_association.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "47086" }, { "name": "CoffeeScript", "bytes": "24534" }, { "name": "HTML", "bytes": "495148" }, { "name": "JavaScript", "bytes": "185195" }, { "name": "Ruby", "bytes": "13331204" }, { "name": "Shell", "bytes": "4531" }, { "name": "Yacc", "bytes": "983" } ], "symlink_target": "" }
<div class="product"> <img src="image/test.jpg"> <p>this is product named <?php echo $name; ?></p> </div>
{ "content_hash": "fd9b2093c2da9a9514bc711aaa4d3c59", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 53, "avg_line_length": 28.25, "alnum_prop": 0.5929203539823009, "repo_name": "darkty2009/html-layout-tool", "id": "2843462baf3098aecea0cee0bd979682e0d5e14b", "size": "113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/page_compile/module/product-item.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "69945" } ], "symlink_target": "" }
package uk.co.yottr.model; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SailingPurposeTest { @Test public void testGetDisplayName() throws Exception { assertEquals("Cruising", SailingPurpose.CRUISING.getDisplayName()); assertEquals("Racing", SailingPurpose.RACING.getDisplayName()); assertEquals("Long Term", SailingPurpose.LONG_TERM.getDisplayName()); assertEquals("Delivery", SailingPurpose.DELIVERY.getDisplayName()); assertEquals("Course", SailingPurpose.COURSE.getDisplayName()); } }
{ "content_hash": "7f68c136f0c2ea1fc42fd5833f638a3c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 77, "avg_line_length": 32.27777777777778, "alnum_prop": 0.7314974182444062, "repo_name": "mikehartley/yottr", "id": "3a85d37d2cc97c99c5aac9faf594963a54d5c91c", "size": "661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/uk/co/yottr/model/SailingPurposeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20426" }, { "name": "Java", "bytes": "209412" }, { "name": "JavaScript", "bytes": "1506" } ], "symlink_target": "" }
package com.sri.ai.praise.core.representation.interfacebased.factor.api; import java.util.List; public interface Variable { List<? extends Object> getValues(); }
{ "content_hash": "fdb76751c883fb9a20b7954c0b503d4c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 72, "avg_line_length": 20.625, "alnum_prop": 0.7818181818181819, "repo_name": "aic-sri-international/aic-praise", "id": "583a176fc17d123c05ad2517681d6eb3152977c5", "size": "1950", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sri/ai/praise/core/representation/interfacebased/factor/api/Variable.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "24960" }, { "name": "CSS", "bytes": "1076" }, { "name": "Java", "bytes": "1518608" }, { "name": "MATLAB", "bytes": "166392" } ], "symlink_target": "" }
package org.sleuthkit.autopsy.commonfilessearch; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.netbeans.junit.NbTestCase; import org.openide.util.Exceptions; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.ImageDSProcessor; import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbException; import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbPlatformEnum; import org.sleuthkit.autopsy.centralrepository.datamodel.EamDbUtil; import org.sleuthkit.autopsy.centralrepository.datamodel.SqliteEamDbSettings; import org.sleuthkit.autopsy.ingest.IngestJobSettings; import org.sleuthkit.autopsy.ingest.IngestJobSettings.IngestType; import org.sleuthkit.autopsy.ingest.IngestModuleTemplate; import org.sleuthkit.autopsy.modules.filetypeid.FileTypeIdModuleFactory; import org.sleuthkit.autopsy.modules.hashdatabase.HashLookupModuleFactory; import org.sleuthkit.autopsy.testutils.CaseUtils; import org.sleuthkit.autopsy.testutils.IngestUtils; import org.sleuthkit.datamodel.TskCoreException; import junit.framework.Assert; import org.sleuthkit.autopsy.casemodule.CaseActionException; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance; import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase; import org.sleuthkit.autopsy.centralrepository.datamodel.EamDb; import org.sleuthkit.autopsy.commonfilesearch.AbstractCommonAttributeInstance; import org.sleuthkit.autopsy.commonfilesearch.CaseDBCommonAttributeInstanceNode; import org.sleuthkit.autopsy.commonfilesearch.CentralRepoCommonAttributeInstance; import org.sleuthkit.autopsy.commonfilesearch.CentralRepoCommonAttributeInstanceNode; import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeSearchResults; import org.sleuthkit.autopsy.commonfilesearch.DataSourceLoader; import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeValue; import org.sleuthkit.autopsy.commonfilesearch.CommonAttributeValueList; import org.sleuthkit.autopsy.datamodel.DisplayableItemNode; import org.sleuthkit.autopsy.modules.e01verify.E01VerifierModuleFactory; import org.sleuthkit.autopsy.modules.embeddedfileextractor.EmbeddedFileExtractorModuleFactory; import org.sleuthkit.autopsy.modules.exif.ExifParserModuleFactory; import org.sleuthkit.autopsy.modules.fileextmismatch.FileExtMismatchDetectorModuleFactory; import org.sleuthkit.autopsy.modules.iOS.iOSModuleFactory; import org.sleuthkit.autopsy.modules.interestingitems.InterestingItemsIngestModuleFactory; import org.sleuthkit.autopsy.modules.photoreccarver.PhotoRecCarverIngestModuleFactory; import org.sleuthkit.autopsy.modules.vmextractor.VMExtractorIngestModuleFactory; import org.sleuthkit.datamodel.AbstractFile; /** * Utilities for testing intercase correlation feature. * * This will be more useful when we add more flesh out the intercase correlation * features and need to add more tests. In particular, testing scenarios where * we need different cases to be the current case will suggest that we create * additional test classes, and we will want to import this utility in each new * intercase test file. * * Description of Test Data: (Note: files of the same name and extension are * identical; files of the same name and differing extension are not identical.) * * Case 1 +Data Set 1 - Hash-0.dat [testFile of size 0] - Hash-A.jpg - * Hash-A.pdf * * +Data Set2 - Hash-0.dat [testFile of size 0] - Hash-A.jpg - Hash-A.pdf * * Case 2 +Data Set 1 - Hash-B.jpg - Hash-B.pdf +Data Set 2 - Hash-A.jpg - * Hash-A.pdf - Hash_D.doc * * Case 3 +Data Set 1 - Hash-A.jpg - Hash-A.pdf - Hash-C.jpg - Hash-C.pdf - * Hash-D.jpg +Data Set 2 - Hash-C.jpg - Hash-C.pdf - Hash-D.doc * * Frequency Breakdown (ratio of datasources a given file appears in to total * number of datasources): * * Hash-0.dat - moot; these are always excluded Hash-A.jpg - 4/6 Hash-A.pdf - * 4/6 Hash-B.jpg - 1/6 Hash-B.pdf - 1/6 Hash-C.jpg - 2/6 Hash-C.pdf - 2/6 * Hash_D.doc - 2/6 Hash-D.jpg - 1/6 * */ class InterCaseTestUtils { private static final Path CENTRAL_REPO_DIRECTORY_PATH = Paths.get(System.getProperty("java.io.tmpdir"), "InterCaseCommonFilesSearchTest"); private static final String CR_DB_NAME = "testcentralrepo.db"; static final String CASE1 = "Case1"; static final String CASE2 = "Case2"; static final String CASE3 = "Case3"; static final String CASE4 = "Case4"; final Path case1DataSet1Path; final Path case1DataSet2Path; final Path case2DataSet1Path; final Path case2DataSet2Path; final Path case3DataSet1Path; final Path case3DataSet2Path; static final String HASH_0_DAT = "Hash-0.dat"; static final String HASH_A_JPG = "Hash-A.jpg"; static final String HASH_A_PDF = "Hash-A.pdf"; static final String HASH_B_JPG = "Hash-B.jpg"; static final String HASH_B_PDF = "Hash-B.pdf"; static final String HASH_C_JPG = "Hash-C.jpg"; static final String HASH_C_PDF = "Hash-C.pdf"; static final String HASH_D_JPG = "Hash-D.jpg"; static final String HASH_D_DOC = "Hash-D.doc"; static final String CASE1_DATASET_1 = "c1ds1_v1.vhd"; static final String CASE1_DATASET_2 = "c1ds2_v1.vhd"; static final String CASE2_DATASET_1 = "c2ds1_v1.vhd"; static final String CASE2_DATASET_2 = "c2ds2_v1.vhd"; static final String CASE3_DATASET_1 = "c3ds1_v1.vhd"; static final String CASE3_DATASET_2 = "c3ds2_v1.vhd"; final Path attrCase1Path; final Path attrCase2Path; final Path attrCase3Path; final Path attrCase4Path; static final String ATTR_CASE1 = "CommonFilesAttrs_img1_v1.vhd"; static final String ATTR_CASE2 = "CommonFilesAttrs_img2_v1.vhd"; static final String ATTR_CASE3 = "CommonFilesAttrs_img3_v1.vhd"; static final String ATTR_CASE4 = "CommonFilesAttrs_img4_v1.vhd"; private final ImageDSProcessor imageDSProcessor; private final IngestJobSettings hashAndFileType; private final IngestJobSettings hashAndNoFileType; private final IngestJobSettings kitchenShink; private final DataSourceLoader dataSourceLoader; CorrelationAttributeInstance.Type FILE_TYPE; CorrelationAttributeInstance.Type DOMAIN_TYPE; CorrelationAttributeInstance.Type USB_ID_TYPE; CorrelationAttributeInstance.Type EMAIL_TYPE; CorrelationAttributeInstance.Type PHONE_TYPE; InterCaseTestUtils(NbTestCase testCase) { this.case1DataSet1Path = Paths.get(testCase.getDataDir().toString(), CASE1_DATASET_1); this.case1DataSet2Path = Paths.get(testCase.getDataDir().toString(), CASE1_DATASET_2); this.case2DataSet1Path = Paths.get(testCase.getDataDir().toString(), CASE1_DATASET_1); this.case2DataSet2Path = Paths.get(testCase.getDataDir().toString(), CASE2_DATASET_2); this.case3DataSet1Path = Paths.get(testCase.getDataDir().toString(), CASE3_DATASET_1); this.case3DataSet2Path = Paths.get(testCase.getDataDir().toString(), CASE3_DATASET_2); this.attrCase1Path = Paths.get(testCase.getDataDir().toString(), ATTR_CASE1); this.attrCase2Path = Paths.get(testCase.getDataDir().toString(), ATTR_CASE2); this.attrCase3Path = Paths.get(testCase.getDataDir().toString(), ATTR_CASE3); this.attrCase4Path = Paths.get(testCase.getDataDir().toString(), ATTR_CASE4); this.imageDSProcessor = new ImageDSProcessor(); final IngestModuleTemplate exifTemplate = IngestUtils.getIngestModuleTemplate(new ExifParserModuleFactory()); final IngestModuleTemplate iOsTemplate = IngestUtils.getIngestModuleTemplate(new iOSModuleFactory()); final IngestModuleTemplate embeddedFileExtractorTemplate = IngestUtils.getIngestModuleTemplate(new EmbeddedFileExtractorModuleFactory()); final IngestModuleTemplate interestingItemsTemplate = IngestUtils.getIngestModuleTemplate(new InterestingItemsIngestModuleFactory()); final IngestModuleTemplate mimeTypeLookupTemplate = IngestUtils.getIngestModuleTemplate(new FileTypeIdModuleFactory()); final IngestModuleTemplate hashLookupTemplate = IngestUtils.getIngestModuleTemplate(new HashLookupModuleFactory()); final IngestModuleTemplate vmExtractorTemplate = IngestUtils.getIngestModuleTemplate(new VMExtractorIngestModuleFactory()); final IngestModuleTemplate photoRecTemplate = IngestUtils.getIngestModuleTemplate(new PhotoRecCarverIngestModuleFactory()); final IngestModuleTemplate e01VerifierTemplate = IngestUtils.getIngestModuleTemplate(new E01VerifierModuleFactory()); final IngestModuleTemplate eamDbTemplate = IngestUtils.getIngestModuleTemplate(new org.sleuthkit.autopsy.centralrepository.ingestmodule.IngestModuleFactory()); final IngestModuleTemplate fileExtMismatchDetectorTemplate = IngestUtils.getIngestModuleTemplate(new FileExtMismatchDetectorModuleFactory()); //TODO we need to figure out how to get ahold of these objects because they are required for properly filling the CR with test data // final IngestModuleTemplate objectDetectorTemplate = IngestUtils.getIngestModuleTemplate(new org.sleuthkit.autopsy.experimental.objectdetection.ObjectDetectionModuleFactory()); // final IngestModuleTemplate emailParserTemplate = IngestUtils.getIngestModuleTemplate(new org.sleuthkit.autopsy.thunderbirdparser.EmailParserModuleFactory()); // final IngestModuleTemplate recentActivityTemplate = IngestUtils.getIngestModuleTemplate(new org.sleuthkit.autopsy.recentactivity.RecentActivityExtracterModuleFactory()); // final IngestModuleTemplate keywordSearchTemplate = IngestUtils.getIngestModuleTemplate(new org.sleuthkit.autopsy.keywordsearch.KeywordSearchModuleFactory()); //hash and mime ArrayList<IngestModuleTemplate> hashAndMimeTemplate = new ArrayList<>(2); hashAndMimeTemplate.add(hashLookupTemplate); hashAndMimeTemplate.add(mimeTypeLookupTemplate); hashAndMimeTemplate.add(eamDbTemplate); this.hashAndFileType = new IngestJobSettings(InterCaseTestUtils.class.getCanonicalName(), IngestType.FILES_ONLY, hashAndMimeTemplate); //hash and no mime ArrayList<IngestModuleTemplate> hashAndNoMimeTemplate = new ArrayList<>(1); hashAndNoMimeTemplate.add(hashLookupTemplate); hashAndMimeTemplate.add(eamDbTemplate); this.hashAndNoFileType = new IngestJobSettings(InterCaseTestUtils.class.getCanonicalName(), IngestType.FILES_ONLY, hashAndNoMimeTemplate); //kitchen sink ArrayList<IngestModuleTemplate> kitchenSink = new ArrayList<>(); kitchenSink.add(exifTemplate); kitchenSink.add(iOsTemplate); kitchenSink.add(embeddedFileExtractorTemplate); kitchenSink.add(interestingItemsTemplate); kitchenSink.add(mimeTypeLookupTemplate); kitchenSink.add(hashLookupTemplate); kitchenSink.add(vmExtractorTemplate); kitchenSink.add(photoRecTemplate); kitchenSink.add(e01VerifierTemplate); kitchenSink.add(eamDbTemplate); kitchenSink.add(fileExtMismatchDetectorTemplate); //TODO this list should probably be populated by way of loading the appropriate modules based on finding all of the @ServiceProvider(service = IngestModuleFactory.class) types // kitchenSink.add(objectDetectorTemplate); // kitchenSink.add(emailParserTemplate); // kitchenSink.add(recentActivityTemplate); // kitchenSink.add(keywordSearchTemplate); this.kitchenShink = new IngestJobSettings(InterCaseTestUtils.class.getCanonicalName(), IngestType.ALL_MODULES, kitchenSink); this.dataSourceLoader = new DataSourceLoader(); try { Collection<CorrelationAttributeInstance.Type> types = CorrelationAttributeInstance.getDefaultCorrelationTypes(); //TODO use ids instead of strings FILE_TYPE = types.stream().filter(type -> type.getDisplayName().equals("Files")).findAny().get(); DOMAIN_TYPE = types.stream().filter(type -> type.getDisplayName().equals("Domains")).findAny().get(); USB_ID_TYPE = types.stream().filter(type -> type.getDisplayName().equals("USB Devices")).findAny().get(); EMAIL_TYPE = types.stream().filter(type -> type.getDisplayName().equals("Email Addresses")).findAny().get(); PHONE_TYPE = types.stream().filter(type -> type.getDisplayName().equals("Phone Numbers")).findAny().get(); } catch (EamDbException ex) { Assert.fail(ex.getMessage()); //none of this really matters but satisfies the compiler FILE_TYPE = null; DOMAIN_TYPE = null; USB_ID_TYPE = null; EMAIL_TYPE = null; PHONE_TYPE = null; } } void clearTestDir() { if (CENTRAL_REPO_DIRECTORY_PATH.toFile().exists()) { try { if (EamDb.isEnabled()) { EamDb.getInstance().shutdownConnections(); } FileUtils.deleteDirectory(CENTRAL_REPO_DIRECTORY_PATH.toFile()); } catch (IOException | EamDbException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex.getMessage()); } } } Map<Long, String> getDataSourceMap() throws NoCurrentCaseException, TskCoreException, SQLException { return this.dataSourceLoader.getDataSourceMap(); } Map<String, Integer> getCaseMap() throws EamDbException { if (EamDb.isEnabled()) { Map<String, Integer> mapOfCaseIdsToCase = new HashMap<>(); for (CorrelationCase caze : EamDb.getInstance().getCases()) { mapOfCaseIdsToCase.put(caze.getDisplayName(), caze.getID()); } return mapOfCaseIdsToCase; } else { //it is reasonable that this might happen... // for example when we test the feature in the absence of an enabled eamdb return new HashMap<>(0); } } IngestJobSettings getIngestSettingsForHashAndFileType() { return this.hashAndFileType; } IngestJobSettings getIngestSettingsForHashAndNoFileType() { return this.hashAndNoFileType; } IngestJobSettings getIngestSettingsForKitchenSink() { return this.kitchenShink; } void enableCentralRepo() throws EamDbException { SqliteEamDbSettings crSettings = new SqliteEamDbSettings(); crSettings.setDbName(CR_DB_NAME); crSettings.setDbDirectory(CENTRAL_REPO_DIRECTORY_PATH.toString()); if (!crSettings.dbDirectoryExists()) { crSettings.createDbDirectory(); } crSettings.initializeDatabaseSchema(); crSettings.insertDefaultDatabaseContent(); crSettings.saveSettings(); EamDbUtil.setUseCentralRepo(true); EamDbPlatformEnum.setSelectedPlatform(EamDbPlatformEnum.SQLITE.name()); EamDbPlatformEnum.saveSelectedPlatform(); } /** * Create the cases defined by caseNames and caseDataSourcePaths and ingest * each with the given settings. Null settings are permitted but IngestUtils * will not be run. * * The length of caseNames and caseDataSourcePaths should be the same, and * cases should appear in the same order. * * @param caseNames list case names * @param caseDataSourcePaths two dimensional array listing the datasources * in each case * @param ingestJobSettings HashLookup FileType etc... * @param caseReferenceToStore */ Case createCases(String[] caseNames, Path[][] caseDataSourcePaths, IngestJobSettings ingestJobSettings, String caseReferenceToStore) throws TskCoreException { Case currentCase = null; if (caseNames.length != caseDataSourcePaths.length) { Assert.fail(new IllegalArgumentException("caseReferenceToStore should be one of the values given in the 'cases' parameter.").getMessage()); } String lastCaseName = null; Path[] lastPathsForCase = null; //iterate over the collections above, creating cases, and storing // just one of them for future reference for (int i = 0; i < caseNames.length; i++) { String caseName = caseNames[i]; Path[] pathsForCase = caseDataSourcePaths[i]; if (caseName.equals(caseReferenceToStore)) { //put aside and do this one last so we can hang onto the case lastCaseName = caseName; lastPathsForCase = pathsForCase; } else { //dont hang onto this case; close it this.createCase(caseName, ingestJobSettings, false, pathsForCase); } } if (lastCaseName != null && lastPathsForCase != null) { //hang onto this case and dont close it currentCase = this.createCase(lastCaseName, ingestJobSettings, true, lastPathsForCase); } if (currentCase == null) { Assert.fail(new IllegalArgumentException("caseReferenceToStore should be one of the values given in the 'cases' parameter.").getMessage()); return null; } else { return currentCase; } } private Case createCase(String caseName, IngestJobSettings ingestJobSettings, boolean keepAlive, Path... dataSetPaths) throws TskCoreException { /* * TODO (JIRA-4241): If the case already exists, do not recreate it. * Delete this code when the Image Gallery tool cleans up its drawable * database connection deterministically, instead of in a finalizer. As * it is now, case deletion can fail due to an open drawable database * file handles, so this unchanging case may still be hanging around. */ Case existingCase = null; Path caseDirectoryPath = Paths.get(System.getProperty("java.io.tmpdir"), caseName); File caseDirectory = caseDirectoryPath.toFile(); if (caseDirectory.exists()) { if (keepAlive) { String metadataFileName = caseName + ".aut"; Path metadataFilePath = Paths.get(caseDirectoryPath.toString(), metadataFileName); try { Case.openAsCurrentCase(metadataFilePath.toString()); existingCase = Case.getCurrentCaseThrows(); } catch (CaseActionException | NoCurrentCaseException ex) { Exceptions.printStackTrace(ex); Assert.fail(String.format("Failed to open case %s at %s: %s", caseName, caseDirectoryPath, ex.getMessage())); } } return existingCase; } Case caze = CaseUtils.createAsCurrentCase(caseName); for (Path dataSetPath : dataSetPaths) { IngestUtils.addDataSource(this.imageDSProcessor, dataSetPath); } if (ingestJobSettings != null) { IngestUtils.runIngestJob(caze.getDataSources(), ingestJobSettings); } if (keepAlive) { return caze; } else { CaseUtils.closeCurrentCase(false); return null; } } static boolean verifyInstanceCount(CommonAttributeSearchResults searchDomain, int instanceCount) { try { int tally = 0; for (Map.Entry<Integer, CommonAttributeValueList> entry : searchDomain.getMetadata().entrySet()) { entry.getValue().displayDelayedMetadata(); for (CommonAttributeValue value : entry.getValue().getMetadataList()) { tally += value.getInstanceCount(); } } return tally == instanceCount; } catch (EamDbException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex.getMessage()); return false; } } static boolean verifyInstanceExistenceAndCount(CommonAttributeSearchResults searchDomain, String fileName, String dataSource, String crCase, int instanceCount) { try { int tally = 0; for (Map.Entry<Integer, CommonAttributeValueList> entry : searchDomain.getMetadata().entrySet()) { entry.getValue().displayDelayedMetadata(); for (CommonAttributeValue value : entry.getValue().getMetadataList()) { for (AbstractCommonAttributeInstance commonAttribute : value.getInstances()) { if (commonAttribute instanceof CentralRepoCommonAttributeInstance) { CentralRepoCommonAttributeInstance results = (CentralRepoCommonAttributeInstance) commonAttribute; for (DisplayableItemNode din : results.generateNodes()) { if (din instanceof CentralRepoCommonAttributeInstanceNode) { CentralRepoCommonAttributeInstanceNode node = (CentralRepoCommonAttributeInstanceNode) din; CorrelationAttributeInstance instance = node.getCorrelationAttributeInstance(); final String fullPath = instance.getFilePath(); final File testFile = new File(fullPath); final String testCaseName = instance.getCorrelationCase().getDisplayName(); final String testFileName = testFile.getName(); final String testDataSource = instance.getCorrelationDataSource().getName(); boolean sameFileName = testFileName.equalsIgnoreCase(fileName); boolean sameDataSource = testDataSource.equalsIgnoreCase(dataSource); boolean sameCrCase = testCaseName.equalsIgnoreCase(crCase); if (sameFileName && sameDataSource && sameCrCase) { tally++; } } if (din instanceof CaseDBCommonAttributeInstanceNode) { CaseDBCommonAttributeInstanceNode node = (CaseDBCommonAttributeInstanceNode) din; AbstractFile file = node.getContent(); final String testFileName = file.getName(); final String testCaseName = node.getCase(); final String testDataSource = node.getDataSource(); boolean sameFileName = testFileName.equalsIgnoreCase(fileName); boolean sameCaseName = testCaseName.equalsIgnoreCase(crCase); boolean sameDataSource = testDataSource.equalsIgnoreCase(dataSource); if (sameFileName && sameDataSource && sameCaseName) { tally++; } } } } else { Assert.fail("Unable to cast AbstractCommonAttributeInstanceNode to InterCaseCommonAttributeSearchResults."); } } } } return tally == instanceCount; } catch (EamDbException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex.getMessage()); return false; } } /** * Close the currently open case, delete the case directory, delete the * central repo db. */ void tearDown() { CaseUtils.closeCurrentCase(false); } /** * Is everything in metadata a result of the given attribute type? * * @param metadata * @param attributeType * * @return true if yes, else false */ boolean areAllResultsOfType(CommonAttributeSearchResults metadata, CorrelationAttributeInstance.Type attributeType) { try { for (CommonAttributeValueList matches : metadata.getMetadata().values()) { for (CommonAttributeValue value : matches.getMetadataList()) { return value .getInstances() .stream() .allMatch(inst -> inst.getCorrelationAttributeInstanceType().equals(attributeType)); } return false; } return false; } catch (EamDbException ex) { Assert.fail(ex.getMessage()); return false; } } }
{ "content_hash": "640e7e7c365dc8539f34d66bc3158003", "timestamp": "", "source": "github", "line_count": 522, "max_line_length": 185, "avg_line_length": 48.024904214559385, "alnum_prop": 0.6756551916709881, "repo_name": "millmanorama/autopsy", "id": "e4d6ae5dd8597e59fa3afb8f4999c3d2a4d43114", "size": "25757", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Core/test/qa-functional/src/org/sleuthkit/autopsy/commonfilessearch/InterCaseTestUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4467" }, { "name": "HTML", "bytes": "9644" }, { "name": "Java", "bytes": "11348573" }, { "name": "Python", "bytes": "297069" }, { "name": "Shell", "bytes": "9705" } ], "symlink_target": "" }
using System; namespace Structural.Facade { public interface IAuthorization { Guid Authorize(string userName, string password); void SignOut(Guid userToken); } }
{ "content_hash": "c5f062082d318d900afa58712f44feb2", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 57, "avg_line_length": 19.1, "alnum_prop": 0.680628272251309, "repo_name": "pavelekNET/DesignPatterns", "id": "321e013e7338766c451f7d8c2338dccb5f852639", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DesignPatterns/Structural/Facade/IAuthorization.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "35009" } ], "symlink_target": "" }
<?php namespace Mautic\Api; /** * Contacts Context */ class Contacts extends Api { /** * Contact unsubscribed themselves. */ const UNSUBSCRIBED = 1; /** * Contact was unsubscribed due to an unsuccessful send. */ const BOUNCED = 2; /** * Contact was manually unsubscribed by user. */ const MANUAL = 3; /** * {@inheritdoc} */ protected $endpoint = 'contacts'; /** * {@inheritdoc} */ protected $listName = 'contacts'; /** * {@inheritdoc} */ protected $itemName = 'contact'; /** * @var array */ protected $bcRegexEndpoints = array( 'contacts/(.*?)/dnc/(.*?)/add' => 'contacts/$1/dnc/add/$2', // 2.6.0 'contacts/(.*?)/dnc/(.*?)/remove' => 'contacts/$1/dnc/remove/$2' // 2.6.0 ); /** * {@inheritdoc} */ protected $searchCommands = array( 'ids', 'is:anonymous', 'is:unowned', 'is:mine', 'name', 'email', 'segment', 'company', 'onwer', 'ip', 'common', ); /** * @param string $search * @param int $start * @param int $limit * @param string $orderBy * @param string $orderByDir * @param bool $publishedOnly * @param bool $minimal * * @return array|mixed */ public function getIdentified($search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC', $publishedOnly = false, $minimal = false) { $search .= ($search) ? "$search !is:anonymous" : '!is:anonymous'; return $this->getList($search, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal); } /** * Get a list of users available as contact owners * * @return array|mixed */ public function getOwners() { return $this->makeRequest($this->endpoint.'/list/owners'); } /** * Get a list of custom fields * * @return array|mixed */ public function getFieldList() { return $this->makeRequest($this->endpoint.'/list/fields'); } /** * Get a list of contact segments * * @return array|mixed */ public function getSegments() { return $this->makeRequest($this->endpoint.'/list/segments'); } /** * Get a list of a contact's engagement events * * @param int $id Contact ID * @param string $search * @param array $includeEvents * @param array $excludeEvents * @param string $orderBy * @param string $orderByDir * @param int $page * * @return array|mixed */ public function getEvents( $id, $search = '', array $includeEvents = array(), array $excludeEvents = array(), $orderBy = '', $orderByDir = 'ASC', $page = 1 ) { $parameters = array( 'filters' => array( 'search' => $search, 'includeEvents' => $includeEvents, 'excludeEvents' => $excludeEvents, ), 'order' => array( $orderBy, $orderByDir, ), 'page' => $page ); return $this->makeRequest( $this->endpoint.'/'.$id.'/events', $parameters ); } /** * Get a list of a contact's notes * * @param int $id Contact ID * @param string $search * @param int $start * @param int $limit * @param string $orderBy * @param string $orderByDir * * @return array|mixed */ public function getContactNotes($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC') { $parameters = array( 'search' => $search, 'start' => $start, 'limit' => $limit, 'orderBy' => $orderBy, 'orderByDir' => $orderByDir, ); $parameters = array_filter($parameters); return $this->makeRequest($this->endpoint.'/'.$id.'/notes', $parameters); } /** * Get a list of a contact's devices * * @param int $id Contact ID * @param string $search * @param int $start * @param int $limit * @param string $orderBy * @param string $orderByDir * * @return array|mixed */ public function getContactDevices($id, $search = '', $start = 0, $limit = 0, $orderBy = '', $orderByDir = 'ASC') { $parameters = array( 'search' => $search, 'start' => $start, 'limit' => $limit, 'orderBy' => $orderBy, 'orderByDir' => $orderByDir, ); $parameters = array_filter($parameters); return $this->makeRequest($this->endpoint.'/'.$id.'/devices', $parameters); } /** * Get a list of smart segments the contact is in * * @param $id * * @return array|mixed */ public function getContactSegments($id) { return $this->makeRequest($this->endpoint.'/'.$id.'/segments'); } /** * Get a list of companies the contact is in * * @param $id * * @return array|mixed */ public function getContactCompanies($id) { return $this->makeRequest($this->endpoint.'/'.$id.'/companies'); } /** * Get a list of campaigns the contact is in * * @param $id * * @return array|mixed */ public function getContactCampaigns($id) { return $this->makeRequest($this->endpoint.'/'.$id.'/campaigns'); } /** * Add the points to a contact * * @param int $id * @param int $points * @param array $parameters 'eventName' and 'actionName' * * @return mixed */ public function addPoints($id, $points, array $parameters = array()) { return $this->makeRequest('contacts/'.$id.'/points/plus/'.$points, $parameters, 'POST'); } /** * Subtract points from a contact * * @param int $id * @param int $points * @param array $parameters 'eventName' and 'actionName' * * @return mixed */ public function subtractPoints($id, $points, array $parameters = array()) { return $this->makeRequest('contacts/'.$id.'/points/minus/'.$points, $parameters, 'POST'); } /** * Adds Do Not Contact * * @param int $id * @param string $channel * @param int $reason * @param null $channelId * @param string $comments * * @return array|mixed */ public function addDnc($id, $channel = 'email', $reason = Contacts::MANUAL, $channelId = null, $comments = 'via API') { return $this->makeRequest( 'contacts/'.$id.'/dnc/'.$channel.'/add', array( 'reason' => $reason, 'channelId' => $channelId, 'comments' => $comments, ), 'POST' ); } /** * Removes Do Not Contact * * @param int $id * @param string $channel * * @return mixed */ public function removeDnc($id, $channel) { return $this->makeRequest( 'contacts/'.$id.'/dnc/'.$channel.'/remove', array(), 'POST' ); } }
{ "content_hash": "8075adab8822aabdc1afcf749d877d83", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 149, "avg_line_length": 23.75796178343949, "alnum_prop": 0.4957104557640751, "repo_name": "mandino/nu", "id": "41587d68a198b859857739917335f8f1b2b9f070", "size": "7656", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "wp-content/plugins/hustle/vendor/mautic/api-library/lib/Api/Contacts.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2534865" }, { "name": "HTML", "bytes": "131438" }, { "name": "JavaScript", "bytes": "3766596" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "19289064" }, { "name": "Perl", "bytes": "2554" }, { "name": "Shell", "bytes": "1145" } ], "symlink_target": "" }
<!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_26) on Sat May 04 06:14:39 PDT 2013 --> <TITLE> org.jivesoftware.smackx.workgroup.ext.forms (Smack 3.3.0 Documentation) </TITLE> <META NAME="date" CONTENT="2013-05-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../../org/jivesoftware/smackx/workgroup/ext/forms/package-summary.html" target="classFrame">org.jivesoftware.smackx.workgroup.ext.forms</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="WorkgroupForm.html" title="class in org.jivesoftware.smackx.workgroup.ext.forms" target="classFrame">WorkgroupForm</A> <BR> <A HREF="WorkgroupForm.InternalProvider.html" title="class in org.jivesoftware.smackx.workgroup.ext.forms" target="classFrame">WorkgroupForm.InternalProvider</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "3ff797ffa72d1e1610d6992781adf497", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 173, "avg_line_length": 34.55882352941177, "alnum_prop": 0.6987234042553192, "repo_name": "UzxMx/java-bells", "id": "83b42b32e1272c43a38b590792a23f249aedfe8d", "size": "1175", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib-src/smack_src_3_3_0/javadoc/org/jivesoftware/smackx/workgroup/ext/forms/package-frame.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "446956" }, { "name": "C++", "bytes": "1572" }, { "name": "HTML", "bytes": "38549" }, { "name": "Java", "bytes": "11455869" }, { "name": "Objective-C", "bytes": "44632" } ], "symlink_target": "" }
package org.skk.tide; /** * The runtime exception thrown when a registered handler does handle the specified event. * * When a handler registers for an event, the handle method needs to be annotated with {@link org.skk.tide.HandleEvent}. * If it does not, {@link org.skk.tide.HandlerMethodNotFoundException} is thrown at runtime */ public class HandlerMethodNotFoundException extends Exception { private final Class<? extends EventHandler> handlerClass; private final Class<? extends Event> eventClass; public HandlerMethodNotFoundException(Class<? extends EventHandler> handlerClass, Class<? extends Event> eventClass) { this.handlerClass = handlerClass; this.eventClass = eventClass; } @Override public String getMessage() { return "No handler method found for event " + eventClass + " on handler " + handlerClass + ". Make sure the method is annotated with @HandleEvent passing the event class and it takes only one or no arguments"; } }
{ "content_hash": "831899a8b0b467a3b55a5882cd7df452", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 217, "avg_line_length": 41.791666666666664, "alnum_prop": 0.7367896311066799, "repo_name": "abyu/tide", "id": "df6690bc9a06635cbefb55511b35f6b911214d17", "size": "1003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/skk/tide/HandlerMethodNotFoundException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "24983" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:agui="http://schemas.agui.com/apk/res/agui" agui:layout_width="wrap_content" agui:layout_height="wrap_content" agui:background="@drawable/test" > <TextView agui:id="@agui:id/agui_message" agui:layout_width="wrap_content" agui:layout_height="wrap_content" agui:text="message" /> <Button agui:id="@agui:id/agui_yes" agui:layout_width="wrap_content" agui:layout_height="wrap_content" agui:text="yes" agui:layout_below="@+id/agui_message" /> <Button agui:id="@agui:id/agui_no" agui:layout_width="wrap_content" agui:layout_height="wrap_content" agui:text="no" agui:layout_toRightOf="@agui:id/agui_yes" agui:layout_below="@agui:id/agui_message" /> </RelativeLayout>
{ "content_hash": "53ea7912c8b8f2f131dd84af9e62f49a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 51, "avg_line_length": 26.5, "alnum_prop": 0.6729559748427673, "repo_name": "thahn0720/agui_framework", "id": "f237b824e8e0bb11647c2741b018e9be63eb4e44", "size": "795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "agui_framework/src/main/resources/res/layout/agui_dialog.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2231" }, { "name": "Java", "bytes": "4109623" } ], "symlink_target": "" }
<link rel="import" href="../bower_components/polymer/polymer.html"> <dom-module id="pixabay-img"> <template> <style> :host { display: block; line-height: 0px; } img { min-width: 100%; height: auto; } </style> <img src="[[_src]]"> </template> </dom-module> <script> Polymer({ is: 'pixabay-img', properties: { query: { type: String, value: '' }, minWidth: { type: Number, value: 0 }, minHeight: { type: Number, value: 0 }, category: { type: String, value: '' }, imageType: { type: String, value: "photo" }, key: { type: String, value: '2407172-5cbaffba46cc537259d6549e9' }, /* * An object that caches requests from Pixabay for an hour at a time. * Maps URL => {timeout: timestamp when request should be uncached, response: response data} */ _requestCache: { type: Object, value: function() { return {} } } }, observers: [ '_computeSrc(key, query, minWidth, minHeight, category, imageType)' ], _computeSrc: function(key, query, minWidth, minHeight, category, imageType) { console.log('ran'); var queryString = ""; if (key) { queryString += "key=" + key + "&" } if (query) { queryString += "q=" + encodeURIComponent(query) + "&" } if (minWidth) { queryString += "min_width=" + minWidth + "&" } if (minHeight) { queryString += "min_height" + minHeight + "&" } if (category) { queryString += "category=" + category + "&" } if (imageType) { queryString += "image_type=" + imageType + "&" } var self = this; Promise.resolve().then(function() { if (self._requestCache && queryString in self._requestCache) { var fromCache = self._requestCache[queryString]; if (fromCache.timeout > Date.now()) { return fromCache.response; } } else { return fetch("https://pixabay.com/api/?" + queryString) .then(function(response) { if (response.status !== 200) { console.error('Problem finding Pixabay image: '+ response.status); return; } return response.json(); }); } }).then(function(data) { self._requestCache[queryString] = { timeout: Date.now() + 3600000, response: data }; self._src = data.hits[Math.floor((Math.random() * data.hits.length))].webformatURL; }); } }); </script>
{ "content_hash": "e46e019ae1fcd352794b9909bde0010d", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 95, "avg_line_length": 23.169642857142858, "alnum_prop": 0.5302504816955684, "repo_name": "tjsavage/canvas2", "id": "0580cd1538618fa7b28e8ab843416c5e270d47ba", "size": "2595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dashboard/components/pixabay-img.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "46117" }, { "name": "JavaScript", "bytes": "70672" }, { "name": "Shell", "bytes": "2649" } ], "symlink_target": "" }
DISTNAME= ctime-${VERSION} VERSION?= 0.1.0 # PKGREVISION?= 1 CATEGORIES= nanobox MASTER_SITES= github.com/glinton/ctime MAINTAINER= pkgsrc-users@NetBSD.org HOMEPAGE= github.com/glinton/ctime COMMENT= A touch-like utility to trigger filesystem events LICENSE= MIT WRKSRC= ${WRKDIR}/ctime USE_LANGUAGES= # none GIT_REPOSITORIES= ctime GIT_REPO.ctime= git@github.com:glinton/ctime.git GIT_TAG.ctime= v${VERSION} GO_DOMAIN= github.com GO_USER= glinton GO_PROJECT= ctime .include "../../base/git/git-package.mk" .include "../../base/go/go-app.mk" .include "../../mk/bsd.pkg.mk"
{ "content_hash": "15a1d079313a205e3cfab62a8d1b4389", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 59, "avg_line_length": 22.37037037037037, "alnum_prop": 0.706953642384106, "repo_name": "pagodabox/nanobox-pkgsrc-base", "id": "d67cb05e1b41574d2d9536ca1ee5e092fa082e0d", "size": "706", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ctime/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "2111" }, { "name": "C", "bytes": "124108" }, { "name": "C++", "bytes": "88248" }, { "name": "CMake", "bytes": "11030" }, { "name": "D", "bytes": "3770" }, { "name": "GLSL", "bytes": "2755" }, { "name": "Groff", "bytes": "13804" }, { "name": "Java", "bytes": "18226" }, { "name": "JavaScript", "bytes": "3718" }, { "name": "Makefile", "bytes": "1253655" }, { "name": "Objective-C", "bytes": "2017" }, { "name": "PHP", "bytes": "3340" }, { "name": "Python", "bytes": "56426" }, { "name": "Ruby", "bytes": "170987" }, { "name": "Shell", "bytes": "147796" } ], "symlink_target": "" }
<!-- OsmAnd Batch Creation Config Template. Determines where the OBF creation process is staged and configures the export process. --> <batch_process> <process_attributes mapZooms="" renderingTypesFile="" zoomWaySmoothness="" osmDbDialect="sqlite" mapDbDialect="sqlite"/> <!-- zoomWaySmoothness - 1-4, typical mapZooms - 11;12;13-14;15- --> <process directory_for_osm_files="/home/ubuntu/www/hotosm/utils/tests/files" directory_for_index_files="/home/ubuntu/www/hotosm/utils/tests/files" directory_for_generation="/home/ubuntu/www/hotosm/utils/tests/files" skipExistingIndexesAt="/home/ubuntu/www/hotosm/utils/tests/files" indexPOI="true" indexRouting="true" indexMap="true" indexTransport="true" indexAddress="true"> </process> </batch_process>
{ "content_hash": "18a2f66e71df2f85123fd03c9839911a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 377, "avg_line_length": 69.54545454545455, "alnum_prop": 0.7568627450980392, "repo_name": "dodobas/osm-export-tool2", "id": "f7770a98d8c891cb37ae7b5ab6ab29c0554ba15a", "size": "765", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "utils/tests/files/batch.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "119726" }, { "name": "HTML", "bytes": "152701" }, { "name": "JavaScript", "bytes": "4936760" }, { "name": "Python", "bytes": "366592" }, { "name": "Shell", "bytes": "755" } ], "symlink_target": "" }
package com.gemstone.gemfire.internal.cache.execute; import com.gemstone.gemfire.cache.execute.ResultSender; /** * * @author ymahajan * */ public interface InternalResultSender extends ResultSender<Object> { public void enableOrderedResultStreming(boolean enable); public boolean isLocallyExecuted(); public boolean isLastResultReceived(); public void setException(Throwable t); }
{ "content_hash": "2c20ce8612d195c991ab690d1b900413", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 68, "avg_line_length": 20.15, "alnum_prop": 0.7741935483870968, "repo_name": "sshcherbakov/incubator-geode", "id": "4fd50fb9dcd3d87f49824e3d1656f0929bb8b5f0", "size": "1205", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/InternalResultSender.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1741" }, { "name": "CSS", "bytes": "54202" }, { "name": "Groovy", "bytes": "4066" }, { "name": "HTML", "bytes": "124114" }, { "name": "Java", "bytes": "26687060" }, { "name": "JavaScript", "bytes": "315581" }, { "name": "Scala", "bytes": "237708" }, { "name": "Shell", "bytes": "11132" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test delegated mouse events</title> <meta name="viewport" content="width=570"> <style> @import "../../dojo/resources/dojo.css"; @import "../css/skins/claro.css"; .heading { font-weight: bold; padding-bottom: 0.25em; } .dgrid { height: 20em; margin: 10px; } /* add styles to size this grid appropriately */ #grid .field-order { width: 7%; } #grid .field-name { width: 18%; } </style> <script src="../../dojo/dojo.js" data-dojo-config="async: true"></script> <script> var columns = { order: "step", // give column a custom name name: {}, description: {label: "what to do", sortable: false} }; require(["dgrid/Grid", "dgrid/OnDemandGrid", "dgrid/tree", "dgrid/util/mouse", "dojo/on", "dgrid/test/data/base", "dojo/query", "dojo/domReady!"], function(Grid, OnDemandGrid, tree, mouseUtil, on){ var data = [ {order: 1, name:"preheat", description:"Preheat your oven to 350F"}, {order: 2, name:"mix dry", description:"In a medium bowl, combine flour, salt, and baking soda"}, {order: 3, name:"mix butter", description:"In a large bowl, beat butter, then add the brown sugar and white sugar then mix"}, {order: 4, name:"mix together", description:"Slowly add the dry ingredients from the medium bowl to the wet ingredients in the large bowl, mixing until the dry ingredients are totally combined"}, {order: 5, name:"chocolate chips", description:"Add chocolate chips"}, {order: 6, name:"make balls", description:"Scoop up a golf ball size amount of dough with a spoon and drop in onto a cookie sheet"}, {order: 7, name:"bake", description:"Put the cookies in the oven and bake for about 10-14 minutes"}, {order: 8, name:"remove", description:"Using a spatula, lift cookies off onto wax paper or a cooling rack"}, {order: 9, name:"eat", description:"Eat and enjoy!"} ]; var grid = window.grid = new Grid({ columns: columns }, "grid"); grid.renderArray(data); function makeHandler(grid, type, dir){ return function(evt){ var obj = grid[type](evt), str = obj.column ? obj.row.id + " " + obj.column.id : obj.id; console.log(grid.id + " " + type + " " + dir + ": " + str); }; } function makeHeaderCellHandler(grid, dir){ return function(evt){ console.log(grid.id + " header cell " + dir + ": " + grid.cell(evt).column.id); }; } grid.on(mouseUtil.enterRow, makeHandler(grid, "row", "entered")); grid.on(mouseUtil.leaveRow, makeHandler(grid, "row", "left")); grid.on(mouseUtil.enterCell, makeHandler(grid, "cell", "entered")); grid.on(mouseUtil.leaveCell, makeHandler(grid, "cell", "left")); grid.on(mouseUtil.enterHeaderCell, makeHeaderCellHandler(grid, "entered")); grid.on(mouseUtil.leaveHeaderCell, makeHeaderCellHandler(grid, "left")); var treegrid = window.treegrid = new OnDemandGrid({ store: testCountryStore, query: {type: "continent"}, columns: [ tree({label: "Name", field:"name", sortable: false}), {label:"Type", field:"type", sortable: false}, {label:"Population", field:"population"}, {label:"Timezone", field:"timezone"} ] }, "treegrid"); treegrid.on(mouseUtil.enterRow, makeHandler(treegrid, "row", "entered")); treegrid.on(mouseUtil.leaveRow, makeHandler(treegrid, "row", "left")); treegrid.on(mouseUtil.enterCell, makeHandler(treegrid, "cell", "entered")); treegrid.on(mouseUtil.leaveCell, makeHandler(treegrid, "cell", "left")); // specifically only hooking up leaveHeaderCell, to ensure that leave events // work independently (in earlier dev, this wasn't the case) treegrid.on(mouseUtil.leaveHeaderCell, makeHeaderCellHandler(treegrid, "left")); }); </script> </head> <body class="claro"> <h2>A basic grid rendered from an array, with simulated mouseover events</h2> <div id="grid"></div> <h2>A grid with a tree column</h2> <div id="treegrid"></div> </body> </html>
{ "content_hash": "ca00013aa146c423023d4fcd2c6bab4f", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 200, "avg_line_length": 39.70192307692308, "alnum_prop": 0.6386534269798982, "repo_name": "aguadev/aguadev", "id": "1e3b1800a1d773202e60608220367ecccf335541", "size": "4129", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "html/dojo-1.8.3/dgrid/test/Grid_mouseevents.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "63213" }, { "name": "Assembly", "bytes": "2811185" }, { "name": "Awk", "bytes": "1651" }, { "name": "C", "bytes": "17157035" }, { "name": "C++", "bytes": "16652335" }, { "name": "CSS", "bytes": "7295053" }, { "name": "D", "bytes": "38703" }, { "name": "Emacs Lisp", "bytes": "14719" }, { "name": "Java", "bytes": "664579" }, { "name": "JavaScript", "bytes": "74379284" }, { "name": "Lua", "bytes": "37481" }, { "name": "Objective-C", "bytes": "62279" }, { "name": "PHP", "bytes": "1497773" }, { "name": "Perl", "bytes": "13076601" }, { "name": "Puppet", "bytes": "4423" }, { "name": "Python", "bytes": "2466246" }, { "name": "R", "bytes": "2216" }, { "name": "Ruby", "bytes": "11167" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "327744" }, { "name": "TeX", "bytes": "4217" }, { "name": "XQuery", "bytes": "2397" }, { "name": "XSLT", "bytes": "255596" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
/// <reference path="../app/service/router.ts" /> /// <reference path="../app/service/storage.ts" /> /// <reference path="../basecontroller.ts" /> module sap.sbo.ng4c.header { import BaseController = sap.sbo.ng4c.BaseController; import Storage = sap.sbo.ng4c.app.service.Storage; import Router = sap.sbo.ng4c.app.service.Router; export interface SettingScope extends Scope { onThemeChange: Function; settingPress: Function; meta: SettingMeta; select: string; } export interface SettingMeta { setting: boolean; } export class Setting extends BaseController { private scope: SettingScope; private storage: Storage; private router: Router; public constructor($scope: Scope, $element: JQuery, $attrs: ng.IAttributes, storage: Storage, router: Router) { super($scope, $element, $attrs, "sap.sbo.ng4c.header.Setting"); this.scope = <SettingScope>$scope; this.storage = storage; this.router = router; this.scope.onThemeChange = $.proxy(this.onThemeChange, this); this.scope.meta = { setting: false }; this.scope.settingPress = $.proxy(this.settingPress, this); this.scope.$on("bodyClickBroadcast", $.proxy(this.onPressOutside, this)); } public onThemeChange($event: JQueryEventObject): void { this.scope.$emit("switchTheme", this.scope.select); } private settingPress($event: JQueryEventObject): void { this.scope.meta.setting = true; } private onPressOutside(event: ng.IAngularEvent): void { } } }
{ "content_hash": "8c64fdf2e2767139e4b6ba47bd190f84", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 119, "avg_line_length": 33.96, "alnum_prop": 0.6171967020023557, "repo_name": "JackieWei/fiori", "id": "0677e309de387186942053a4d55217210f0a8b54", "size": "1700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/resources/sap/sbo/ng4c/header/Setting.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1622" }, { "name": "CSS", "bytes": "1265192" }, { "name": "HTML", "bytes": "245895" }, { "name": "JavaScript", "bytes": "147527" }, { "name": "TypeScript", "bytes": "114277" } ], "symlink_target": "" }