text
stringlengths
2
1.04M
meta
dict
<?php class Verify extends Eloquent { protected $table = 'verify'; protected $primaryKey = 'code'; public $timestamps = false; protected $fillable = ['id', 'code']; static public function doVerify($code){ $data = self::find($code); if(!$data) return false; $user = User::find($data->id); $user->emailverify = '1'; $user->save(); $data->delete(); return true; } }
{ "content_hash": "a6df7d0e38d72fca6ee9d1c666f26ad6", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 43, "avg_line_length": 25.72222222222222, "alnum_prop": 0.5248380129589633, "repo_name": "newcxs/Taurus", "id": "f9e81b47b002929c709cf40c00ae986072c83aa5", "size": "463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/Verify.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "407" }, { "name": "JavaScript", "bytes": "459108" }, { "name": "PHP", "bytes": "127836" } ], "symlink_target": "" }
#include "libxml++/parsers/saxparser.h" #include "libxml++/nodes/element.h" #include "libxml++/keepblanks.h" #include <libxml/parser.h> #include <libxml/parserInternals.h> // for xmlCreateFileParserCtxt #include <cstdarg> //For va_list. #include <iostream> namespace xmlpp { struct SaxParserCallback { static xmlEntityPtr get_entity(void* context, const xmlChar* name); static void entity_decl(void* context, const xmlChar* name, int type, const xmlChar* publicId, const xmlChar* systemId, xmlChar* content); static void start_document(void* context); static void end_document(void* context); static void start_element(void* context, const xmlChar* name, const xmlChar** p); static void end_element(void* context, const xmlChar* name); static void characters(void* context, const xmlChar* ch, int len); static void comment(void* context, const xmlChar* value); static void warning(void* context, const char* fmt, ...); static void error(void* context, const char* fmt, ...); static void fatal_error(void* context, const char* fmt, ...); static void cdata_block(void* context, const xmlChar* value, int len); static void internal_subset(void* context, const xmlChar* name, const xmlChar*publicId, const xmlChar*systemId); }; SaxParser::SaxParser(bool use_get_entity) : sax_handler_( new _xmlSAXHandler ) { xmlSAXHandler temp = { SaxParserCallback::internal_subset, 0, // isStandalone 0, // hasInternalSubset 0, // hasExternalSubset 0, // resolveEntity use_get_entity ? SaxParserCallback::get_entity : 0, // getEntity SaxParserCallback::entity_decl, // entityDecl 0, // notationDecl 0, // attributeDecl 0, // elementDecl 0, // unparsedEntityDecl 0, // setDocumentLocator SaxParserCallback::start_document, // startDocument SaxParserCallback::end_document, // endDocument SaxParserCallback::start_element, // startElement SaxParserCallback::end_element, // endElement 0, // reference SaxParserCallback::characters, // characters 0, // ignorableWhitespace 0, // processingInstruction SaxParserCallback::comment, // comment SaxParserCallback::warning, // warning SaxParserCallback::error, // error SaxParserCallback::fatal_error, // fatalError 0, // getParameterEntity SaxParserCallback::cdata_block, // cdataBlock 0, // externalSubset 0, // initialized 0, // private 0, // startElementNs 0, // endElementNs 0, // serror }; *sax_handler_ = temp; } SaxParser::~SaxParser() { release_underlying(); } xmlEntityPtr SaxParser::on_get_entity(const Glib::ustring& name) { return entity_resolver_doc_.get_entity(name); } void SaxParser::on_entity_declaration(const Glib::ustring& name, XmlEntityType type, const Glib::ustring& publicId, const Glib::ustring& systemId, const Glib::ustring& content) { entity_resolver_doc_.set_entity_declaration(name, type, publicId, systemId, content); } void SaxParser::on_start_document() { } void SaxParser::on_end_document() { } void SaxParser::on_start_element(const Glib::ustring& /* name */, const AttributeList& /* attributes */) { } void SaxParser::on_end_element(const Glib::ustring& /* name */) { } void SaxParser::on_characters(const Glib::ustring& /* text */) { } void SaxParser::on_comment(const Glib::ustring& /* text */) { } void SaxParser::on_warning(const Glib::ustring& /* text */) { } void SaxParser::on_error(const Glib::ustring& /* text */) { } void SaxParser::on_fatal_error(const Glib::ustring& text) { throw parse_error("Fatal error: " + text); } void SaxParser::on_cdata_block(const Glib::ustring& /* text */) { } void SaxParser::on_internal_subset(const Glib::ustring& name, const Glib::ustring& publicId, const Glib::ustring& systemId) { entity_resolver_doc_.set_internal_subset(name, publicId, systemId); } // implementation of this function is inspired by the SAX documentation by James Henstridge. // (http://www.daa.com.au/~james/gnome/xml-sax/implementing.html) void SaxParser::parse() { //TODO If this is not the first parsing with this SaxParser, the xmlDoc object // in entity_resolver_doc_ should be deleted and replaced by a new one. // Otherwise entity declarations from a previous parsing may erroneously affect // this parsing. This would be much easier if entity_resolver_doc_ were a // std::auto_ptr<Document>, so the xmlpp::Document could be deleted and a new // one created. A good place for such code would be in an overridden // SaxParser::initialize_context(). It would be an ABI break. if(!context_) { throw internal_error("Parser context not created."); } xmlSAXHandlerPtr old_sax = context_->sax; context_->sax = sax_handler_.get(); xmlResetLastError(); initialize_context(); const int parseError = xmlParseDocument(context_); context_->sax = old_sax; Glib::ustring error_str = format_xml_parser_error(context_); if (error_str.empty() && parseError == -1) error_str = "xmlParseDocument() failed."; release_underlying(); // Free context_ check_for_exception(); if(!error_str.empty()) { throw parse_error(error_str); } } void SaxParser::parse_file(const Glib::ustring& filename) { if(context_) { throw parse_error("Attempt to start a second parse while a parse is in progress."); } KeepBlanks k(KeepBlanks::Default); context_ = xmlCreateFileParserCtxt(filename.c_str()); parse(); } void SaxParser::parse_memory_raw(const unsigned char* contents, size_type bytes_count) { if(context_) { throw parse_error("Attempt to start a second parse while a parse is in progress."); } KeepBlanks k(KeepBlanks::Default); context_ = xmlCreateMemoryParserCtxt((const char*)contents, bytes_count); parse(); } void SaxParser::parse_memory(const Glib::ustring& contents) { parse_memory_raw((const unsigned char*)contents.c_str(), contents.bytes()); } void SaxParser::parse_stream(std::istream& in) { if(context_) { throw parse_error("Attempt to start a second parse while a parse is in progress."); } KeepBlanks k(KeepBlanks::Default); xmlResetLastError(); context_ = xmlCreatePushParserCtxt( sax_handler_.get(), 0, // user_data 0, // chunk 0, // size 0); // no filename for fetching external entities if(!context_) { throw internal_error("Could not create parser context\n" + format_xml_error()); } initialize_context(); //TODO: Shouldn't we use a Glib::ustring here, and some alternative to std::getline()? int firstParseError = XML_ERR_OK; std::string line; while( ( ! exception_ ) && std::getline(in, line)) { // since getline does not get the line separator, we have to add it since the parser care // about layout in certain cases. line += '\n'; const int parseError = xmlParseChunk(context_, line.c_str(), line.size() /* This is a std::string, not a ustring, so this is the number of bytes. */, 0 /* don't terminate */); // Save the first error code if any, but read on. // More errors might be reported and then thrown by check_for_exception(). if (parseError != XML_ERR_OK && firstParseError == XML_ERR_OK) firstParseError = parseError; } if( ! exception_ ) { //This is called just to terminate parsing. const int parseError = xmlParseChunk(context_, 0 /* chunk */, 0 /* size */, 1 /* terminate (1 or 0) */); if (parseError != XML_ERR_OK && firstParseError == XML_ERR_OK) firstParseError = parseError; } Glib::ustring error_str = format_xml_parser_error(context_); if (error_str.empty() && firstParseError != XML_ERR_OK) error_str = "Error code from xmlParseChunk(): " + Glib::ustring::format(firstParseError); release_underlying(); // Free context_ check_for_exception(); if(!error_str.empty()) { throw parse_error(error_str); } } void SaxParser::parse_chunk(const Glib::ustring& chunk) { parse_chunk_raw((const unsigned char*)chunk.c_str(), chunk.bytes()); } void SaxParser::parse_chunk_raw(const unsigned char* contents, size_type bytes_count) { KeepBlanks k(KeepBlanks::Default); xmlResetLastError(); if(!context_) { context_ = xmlCreatePushParserCtxt( sax_handler_.get(), 0, // user_data 0, // chunk 0, // size 0); // no filename for fetching external entities if(!context_) { throw internal_error("Could not create parser context\n" + format_xml_error()); } initialize_context(); } else xmlCtxtResetLastError(context_); int parseError = XML_ERR_OK; if(!exception_) parseError = xmlParseChunk(context_, (const char*)contents, bytes_count, 0 /* don't terminate */); check_for_exception(); Glib::ustring error_str = format_xml_parser_error(context_); if (error_str.empty() && parseError != XML_ERR_OK) error_str = "Error code from xmlParseChunk(): " + Glib::ustring::format(parseError); if(!error_str.empty()) { throw parse_error(error_str); } } void SaxParser::release_underlying() { Parser::release_underlying(); } void SaxParser::finish_chunk_parsing() { xmlResetLastError(); if(!context_) { context_ = xmlCreatePushParserCtxt( sax_handler_.get(), 0, // this, // user_data 0, // chunk 0, // size 0); // no filename for fetching external entities if(!context_) { throw internal_error("Could not create parser context\n" + format_xml_error()); } initialize_context(); } else xmlCtxtResetLastError(context_); int parseError = XML_ERR_OK; if(!exception_) //This is called just to terminate parsing. parseError = xmlParseChunk(context_, 0 /* chunk */, 0 /* size */, 1 /* terminate (1 or 0) */); Glib::ustring error_str = format_xml_parser_error(context_); if (error_str.empty() && parseError != XML_ERR_OK) error_str = "Error code from xmlParseChunk(): " + Glib::ustring::format(parseError); release_underlying(); // Free context_ check_for_exception(); if(!error_str.empty()) { throw parse_error(error_str); } } xmlEntityPtr SaxParserCallback::get_entity(void* context, const xmlChar* name) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); xmlEntityPtr result = 0; try { result = parser->on_get_entity((const char*)name); } catch(const exception& e) { parser->handleException(e); } return result; } void SaxParserCallback::entity_decl(void* context, const xmlChar* name, int type, const xmlChar* publicId, const xmlChar* systemId, xmlChar* content) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { parser->on_entity_declaration( ( name ? Glib::ustring((const char*)name) : ""), static_cast<XmlEntityType>(type), ( publicId ? Glib::ustring((const char*)publicId) : ""), ( systemId ? Glib::ustring((const char*)systemId) : ""), ( content ? Glib::ustring((const char*)content) : "") ); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::start_document(void* context) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { parser->on_start_document(); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::end_document(void* context) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); if(parser->exception_) return; try { parser->on_end_document(); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::start_element(void* context, const xmlChar* name, const xmlChar** p) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); SaxParser::AttributeList attributes; if(p) for(const xmlChar** cur = p; cur && *cur; cur += 2) attributes.push_back( SaxParser::Attribute( (char*)*cur, (char*)*(cur + 1) )); try { parser->on_start_element(Glib::ustring((const char*) name), attributes); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::end_element(void* context, const xmlChar* name) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { parser->on_end_element(Glib::ustring((const char*) name)); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::characters(void * context, const xmlChar* ch, int len) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { // Here we force the use of Glib::ustring::ustring( InputIterator begin, InputIterator end ) // instead of Glib::ustring::ustring( const char*, size_type ) because it // expects the length of the string in characters, not in bytes. parser->on_characters( Glib::ustring( reinterpret_cast<const char *>(ch), reinterpret_cast<const char *>(ch + len) ) ); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::comment(void* context, const xmlChar* value) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { parser->on_comment(Glib::ustring((const char*) value)); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::warning(void* context, const char* fmt, ...) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); va_list arg; char buff[1024]; //TODO: Larger/Shared va_start(arg, fmt); vsnprintf(buff, sizeof(buff)/sizeof(buff[0]), fmt, arg); va_end(arg); try { parser->on_warning(Glib::ustring(buff)); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::error(void* context, const char* fmt, ...) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); va_list arg; char buff[1024]; //TODO: Larger/Shared if(parser->exception_) return; va_start(arg, fmt); vsnprintf(buff, sizeof(buff)/sizeof(buff[0]), fmt, arg); va_end(arg); try { parser->on_error(Glib::ustring(buff)); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::fatal_error(void* context, const char* fmt, ...) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); va_list arg; char buff[1024]; //TODO: Larger/Shared va_start(arg, fmt); vsnprintf(buff, sizeof(buff)/sizeof(buff[0]), fmt, arg); va_end(arg); try { parser->on_fatal_error(Glib::ustring(buff)); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::cdata_block(void* context, const xmlChar* value, int len) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { // Here we force the use of Glib::ustring::ustring( InputIterator begin, InputIterator end ) // see comments in SaxParserCallback::characters parser->on_cdata_block( Glib::ustring( reinterpret_cast<const char *>(value), reinterpret_cast<const char *>(value + len) ) ); } catch(const exception& e) { parser->handleException(e); } } void SaxParserCallback::internal_subset(void* context, const xmlChar* name, const xmlChar* publicId, const xmlChar* systemId) { _xmlParserCtxt* the_context = static_cast<_xmlParserCtxt*>(context); SaxParser* parser = static_cast<SaxParser*>(the_context->_private); try { const Glib::ustring pid = publicId ? Glib::ustring((const char*) publicId) : ""; const Glib::ustring sid = systemId ? Glib::ustring((const char*) systemId) : ""; parser->on_internal_subset( Glib::ustring((const char*) name), pid, sid); } catch(const exception& e) { parser->handleException(e); } } } // namespace xmlpp
{ "content_hash": "457659ed1eaccef9ec8a92cd852f05b6", "timestamp": "", "source": "github", "line_count": 620, "max_line_length": 176, "avg_line_length": 27.13225806451613, "alnum_prop": 0.6673998335513018, "repo_name": "alexandrustaetu/natural_editor", "id": "204dd7d461f1b408814ae6efb0f92d6fb1af80d4", "size": "17151", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "external/libxml++-2.37.1/libxml++/parsers/saxparser.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "85830" }, { "name": "C++", "bytes": "341100" }, { "name": "Shell", "bytes": "2362" } ], "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 (1.8.0_242) on Tue Mar 03 01:19:56 NOVT 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.foxlabs.validation.converter.NumberConverter (Validation Framework 1.1.2 API)</title> <meta name="date" content="2020-03-03"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.foxlabs.validation.converter.NumberConverter (Validation Framework 1.1.2 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/foxlabs/validation/converter/NumberConverter.html" title="class in org.foxlabs.validation.converter">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/foxlabs/validation/converter/class-use/NumberConverter.html" target="_top">Frames</a></li> <li><a href="NumberConverter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.foxlabs.validation.converter.NumberConverter" class="title">Uses of Class<br>org.foxlabs.validation.converter.NumberConverter</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/foxlabs/validation/converter/NumberConverter.html" title="class in org.foxlabs.validation.converter">NumberConverter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.foxlabs.validation.converter">org.foxlabs.validation.converter</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.foxlabs.validation.converter"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/foxlabs/validation/converter/NumberConverter.html" title="class in org.foxlabs.validation.converter">NumberConverter</a> in <a href="../../../../../org/foxlabs/validation/converter/package-summary.html">org.foxlabs.validation.converter</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../org/foxlabs/validation/converter/NumberConverter.html" title="class in org.foxlabs.validation.converter">NumberConverter</a> in <a href="../../../../../org/foxlabs/validation/converter/package-summary.html">org.foxlabs.validation.converter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/BigDecimalConverter.html" title="class in org.foxlabs.validation.converter">BigDecimalConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.math.BigDecimal</code> type.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/BigIntegerConverter.html" title="class in org.foxlabs.validation.converter">BigIntegerConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.math.BigInteger</code> type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/ByteConverter.html" title="class in org.foxlabs.validation.converter">ByteConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Byte</code> type.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/DoubleConverter.html" title="class in org.foxlabs.validation.converter">DoubleConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Double</code> type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/FloatConverter.html" title="class in org.foxlabs.validation.converter">FloatConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Float</code> type.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/IntegerConverter.html" title="class in org.foxlabs.validation.converter">IntegerConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Integer</code> type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/LongConverter.html" title="class in org.foxlabs.validation.converter">LongConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Long</code> type.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/NumberConverter.DecimalType.html" title="class in org.foxlabs.validation.converter">NumberConverter.DecimalType</a>&lt;V extends <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html?is-external=true" title="class or interface in java.lang">Number</a>&gt;</span></code> <div class="block">This class provides base <code>NumberConverter</code> implementation for all decimal types.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/NumberConverter.IntegerType.html" title="class in org.foxlabs.validation.converter">NumberConverter.IntegerType</a>&lt;V extends <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html?is-external=true" title="class or interface in java.lang">Number</a>&gt;</span></code> <div class="block">This class provides base <code>NumberConverter</code> implementation for all integer types.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/foxlabs/validation/converter/ShortConverter.html" title="class in org.foxlabs.validation.converter">ShortConverter</a></span></code> <div class="block">This class provides <code>NumberConverter</code> implementation for the <code>java.lang.Short</code> type.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/foxlabs/validation/converter/NumberConverter.html" title="class in org.foxlabs.validation.converter">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/foxlabs/validation/converter/class-use/NumberConverter.html" target="_top">Frames</a></li> <li><a href="NumberConverter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2011&#x2013;2020 <a href="https://foxlabs.org">FoxLabs</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "53381a0872e72c8d730690a92dd365c3", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 400, "avg_line_length": 48.314655172413794, "alnum_prop": 0.6783834418770631, "repo_name": "foxinboxx/foxlabs-validation", "id": "e84fce69f5d72067533eb28dc9c364b25cd5edf9", "size": "11209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/foxlabs/validation/converter/class-use/NumberConverter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "927349" } ], "symlink_target": "" }
namespace blink { namespace cssvalue { String CSSGridIntegerRepeatValue::CustomCSSText() const { StringBuilder result; result.Append("repeat("); result.Append(String::Number(Repetitions())); result.Append(", "); result.Append(CSSValueList::CustomCSSText()); result.Append(')'); return result.ReleaseString(); } bool CSSGridIntegerRepeatValue::Equals( const CSSGridIntegerRepeatValue& other) const { return repetitions_ == other.repetitions_ && CSSValueList::Equals(other); } } // namespace cssvalue } // namespace blink
{ "content_hash": "b82eda8729fcb6749482eb2f4f99e0f0", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 75, "avg_line_length": 27.25, "alnum_prop": 0.7339449541284404, "repo_name": "chromium/chromium", "id": "89088d975c51534b22d74e9b470a1b6714e7246c", "size": "843", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/css/css_grid_integer_repeat_value.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.jy.common.utils.weixin.core; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.nutz.lang.Strings; import org.nutz.log.Log; import org.nutz.log.Logs; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.DefaultHandler2; /** * 采用驱动式处理微信消息 * * @author * @since 2.0 */ public class MessageHandler extends DefaultHandler2 { private static final Log log = Logs.get(); // 节点属性值 private String attrVal; static Map<String, String> _vals = new ConcurrentHashMap<String, String>(); static StringBuffer _sb = new StringBuffer(); public Map<String, String> getValues() { return _vals; } @Override public void startDocument() throws SAXException { _vals.clear(); _sb.setLength(0); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("PicList".equals(qName)) { _sb.append("["); return; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (log.isDebugEnabled()) { if (!Strings.equals("xml", qName) && !Strings.equals("ScanCodeInfo", qName) && !Strings.equals("SendLocationInfo", qName) && !Strings.equals("SendPicsInfo", qName) && !Strings.equals("PicList", qName) && !Strings.equals("item", qName)) { log.debugf("Current node vaule: [%s-%s]", qName, attrVal); } } // 暂存为map集合 if ("ToUserName".equals(qName)) { _vals.put("toUserName", attrVal); return; } if ("FromUserName".equals(qName)) { _vals.put("fromUserName", attrVal); return; } if ("CreateTime".equals(qName)) { _vals.put("createTime", attrVal); return; } if ("MsgType".equals(qName)) { _vals.put("msgType", attrVal); return; } if ("Content".equals(qName)) { _vals.put("content", attrVal); return; } if ("PicUrl".equals(qName)) { _vals.put("picUrl", attrVal); return; } if ("MediaId".equals(qName)) { _vals.put("mediaId", attrVal); return; } if ("Format".equals(qName)) { _vals.put("format", attrVal); return; } if ("Recognition".equals(qName)) { _vals.put("recognition", attrVal); return; } if ("ThumbMediaId".equals(qName)) { _vals.put("thumbMediaId", attrVal); return; } if ("Location_X".equals(qName)) { _vals.put("locationX", attrVal); return; } if ("Location_Y".equals(qName)) { _vals.put("locationY", attrVal); return; } if ("Scale".equals(qName)) { _vals.put("scale", attrVal); return; } if ("Label".equals(qName)) { _vals.put("label", attrVal); return; } if ("Title".equals(qName)) { _vals.put("title", attrVal); return; } if ("Description".equals(qName)) { _vals.put("description", attrVal); return; } if ("Url".equals(qName)) { _vals.put("url", attrVal); return; } if ("MsgId".equals(qName) || "MsgID".equals(qName)) { _vals.put("msgId", attrVal); return; } if ("Event".equals(qName)) { _vals.put("event", attrVal); return; } if ("EventKey".equals(qName)) { _vals.put("eventKey", attrVal); return; } if ("ScanType".equals(qName)) { _vals.put("scanType", attrVal); return; } if ("ScanResult".equals(qName)) { _vals.put("scanResult", attrVal); return; } if ("Poiname".equals(qName)) { _vals.put("poiname", attrVal); return; } if ("Count".equals(qName)) { _vals.put("count", attrVal); return; } if ("PicMd5Sum".equals(qName)) { _sb.append("{\"picMd5Sum\":\"").append(attrVal).append("\"},"); return; } if ("PicList".equals(qName)) { _sb.deleteCharAt(_sb.lastIndexOf(",")); _sb.append("]"); _vals.put("picList", _sb.toString()); return; } if ("Status".equals(qName)) { _vals.put("status", attrVal); return; } if ("TotalCount".equals(qName)) { _vals.put("totalCount", attrVal); return; } if ("FilterCount".equals(qName)) { _vals.put("filterCount", attrVal); return; } if ("SentCount".equals(qName)) { _vals.put("sentCount", attrVal); return; } if ("ErrorCount".equals(qName)) { _vals.put("errorCount", attrVal); return; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { this.attrVal = new String(ch, start, length); } }
{ "content_hash": "651595706040e1473325e146eba0aadf", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 95, "avg_line_length": 28.107142857142858, "alnum_prop": 0.48974405518242875, "repo_name": "futureskywei/whale", "id": "6032c04ac7dbf4b4f26a9173a2cf515f26a89e84", "size": "5551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/jy/common/utils/weixin/core/MessageHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "784148" }, { "name": "ColdFusion", "bytes": "2253" }, { "name": "HTML", "bytes": "2208161" }, { "name": "Java", "bytes": "1987736" }, { "name": "JavaScript", "bytes": "5161683" }, { "name": "PHP", "bytes": "38915" } ], "symlink_target": "" }
SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ZinniaDrupal.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ZinniaDrupal.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/ZinniaDrupal" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ZinniaDrupal" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
{ "content_hash": "0893756ff2749f1bece3b3e79061d8bb", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 141, "avg_line_length": 36.88590604026846, "alnum_prop": 0.7025109170305677, "repo_name": "azaghal/zinnia-drupal", "id": "471457b66250828695ea46ca118605cd2e9619db", "size": "5588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "29961" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Form</title> </head> <body> <form> <select name="prefix"> <option value="Mr">Mr</option> <option value="Mrs">Mrs</option> <option value="Ms">Ms</option> </select><br> First name:<br> <input type="text" name="firstname"><br> Last name:<br> <input type="text" name="lastname"><br> <input type="radio" name="gender" value="male" checked> Male<br> <input type="radio" name="gender" value="female"> Female<br> <input type="radio" name="gender" value="other"> Other<br> <textarea name="message" rows="10" cols="20" maxlength="200"></textarea> <br> <input type="checkbox" name="food" value="Pizza"> I like pizza<br> <input type="checkbox" name="food" value="Pasta" checked> I like pasta<br> <input type="submit" value="Submit"> <button type="button" onclick="reset()">clear</button><br> </form> <br><br> <a href="main.html#label1">Etykieta</a> </body> </html>
{ "content_hash": "eb66b5728f0883f6eca93f65c5be606e", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 76, "avg_line_length": 25.394736842105264, "alnum_prop": 0.6424870466321243, "repo_name": "superdyzio/PWR-Stuff", "id": "3ee829568e8b3dfde45148be785bd2b401ec57e1", "size": "965", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "INF/Programowanie Systemów Webowych/lista1/forms.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "17829" }, { "name": "Batchfile", "bytes": "1042" }, { "name": "C", "bytes": "2403055" }, { "name": "C#", "bytes": "625528" }, { "name": "C++", "bytes": "3066245" }, { "name": "CMake", "bytes": "983251" }, { "name": "CSS", "bytes": "218848" }, { "name": "Common Lisp", "bytes": "378578" }, { "name": "HTML", "bytes": "4999679" }, { "name": "Java", "bytes": "475300" }, { "name": "JavaScript", "bytes": "266296" }, { "name": "M", "bytes": "2385" }, { "name": "M4", "bytes": "3010" }, { "name": "Makefile", "bytes": "3734730" }, { "name": "Matlab", "bytes": "160418" }, { "name": "OCaml", "bytes": "2021" }, { "name": "PHP", "bytes": "10629" }, { "name": "Perl", "bytes": "7551" }, { "name": "PowerShell", "bytes": "31323" }, { "name": "Python", "bytes": "607184" }, { "name": "QMake", "bytes": "1211" }, { "name": "Scala", "bytes": "4781" }, { "name": "Shell", "bytes": "1550640" }, { "name": "Tcl", "bytes": "4143" }, { "name": "q", "bytes": "1050" } ], "symlink_target": "" }
const simctl = require('simctl'), shell = require('shelljs') module.exports = { start: function(device_id) { var result = simctl.extensions.start(device_id); if (result.code === 0) { return true; } return false; }, list: function() { var siminfo = simctl.list({ silent: true }); if (siminfo) { return siminfo.json; } return null; }, install: function(device, path) { var result = simctl.install(device, path); if (result.code === 0) { return true; } return false; }, uninstall: function(device, app_id) { var result = simctl.uninstall(device, app_id); if (result.code === 0) { return true; } return false; }, launch: function(device, app_id) { var result = simctl.launch(false, device, app_id, {}); if (result.code === 0) { return true; } return false; }, container: function(device, app_id) { var command = 'xcrun simctl get_app_container ' + device + ' ' + app_id; var result = shell.exec(command, { silent: true }); if (result.code === 0) { return result.stdout.trim(); } return null; } }
{ "content_hash": "d380172df0643557bf9cc892ac4e8c97", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 80, "avg_line_length": 20.56923076923077, "alnum_prop": 0.4981301421091997, "repo_name": "bookjam/jamkit", "id": "154f4fe888a65ed30781f65ebef1b2ceedb9df92", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "simctl.js", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "93538" } ], "symlink_target": "" }
import template from './album.html'; import controller from './album.controller'; import './album.scss'; let albumComponent = { restrict: 'E', bindings: { id: "=", title: "=", description: "=", image: "=" }, controllerAs: 'vm', template, controller }; export default albumComponent;
{ "content_hash": "994aa64707080eab50d9dd581bc89b15", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 44, "avg_line_length": 17.38888888888889, "alnum_prop": 0.6166134185303515, "repo_name": "smirnoffnew/ANGULAR_TEST", "id": "8f31d33f04295c380fc26915b1534e5796bebb04", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/components/album/album.component.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1382" }, { "name": "HTML", "bytes": "8719" }, { "name": "JavaScript", "bytes": "43937" } ], "symlink_target": "" }
package general; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class ClassSpy { private Class<?> c; public ClassSpy(Class<?> c) { this.c = c; } public List<Field> getFields() { List<Field> fList = new ArrayList<Field>(); // does not get the private members Field[] dummy = c.getFields(); for (Field f : dummy) { fList.add(f); } // get the private members dummy = c.getDeclaredFields(); for (Field f : dummy) { if (fList.contains(f) == false) { fList.add(f); } } return fList; } public List<Method> getMethods() { List<Method> mList = new ArrayList<Method>(); // does not get the private members Method[] dummy = c.getMethods(); for (Method m : dummy) { mList.add(m); } // get the private members dummy = c.getDeclaredMethods(); for (Method m : dummy) { if (mList.contains(m) == false) { mList.add(m); } } return mList; } public List<Constructor<?>> getConstructors() { List<Constructor<?>> cList = new ArrayList<Constructor<?>>(); // gets all Constructor<?>[] dummy = c.getDeclaredConstructors(); for (Constructor<?> c : dummy) { cList.add(c); } return cList; } public Package getPackage() { return c.getPackage(); } }
{ "content_hash": "cc83f54a2a7448f07fbd46904f0f46cb", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 69, "avg_line_length": 22.397260273972602, "alnum_prop": 0.5253822629969419, "repo_name": "VIRTWO/java", "id": "5aa8421a9543c305e9720a7ee17e125849465c27", "size": "1635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/general/ClassSpy.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "379" }, { "name": "Java", "bytes": "68493" } ], "symlink_target": "" }
/*! * Generated using the Bootstrap Customizer (http://v3.bootcss.com/customize/?id=963984441ae57bd17cfe) * Config saved to config.json and https://gist.github.com/963984441ae57bd17cfe */ /*! * Bootstrap v3.3.5 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ .btn-default, .btn-primary, .btn-success, .btn-info, .btn-warning, .btn-danger { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); } .btn-default:active, .btn-primary:active, .btn-success:active, .btn-info:active, .btn-warning:active, .btn-danger:active, .btn-default.active, .btn-primary.active, .btn-success.active, .btn-info.active, .btn-warning.active, .btn-danger.active { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn-default.disabled, .btn-primary.disabled, .btn-success.disabled, .btn-info.disabled, .btn-warning.disabled, .btn-danger.disabled, .btn-default[disabled], .btn-primary[disabled], .btn-success[disabled], .btn-info[disabled], .btn-warning[disabled], .btn-danger[disabled], fieldset[disabled] .btn-default, fieldset[disabled] .btn-primary, fieldset[disabled] .btn-success, fieldset[disabled] .btn-info, fieldset[disabled] .btn-warning, fieldset[disabled] .btn-danger { -webkit-box-shadow: none; box-shadow: none; } .btn-default .badge, .btn-primary .badge, .btn-success .badge, .btn-info .badge, .btn-warning .badge, .btn-danger .badge { text-shadow: none; } .btn:active, .btn.active { background-image: none; } .btn-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); background-image: linear-gradient(to bottom, #ffffff 0%, #e0e0e0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #dbdbdb; text-shadow: 0 1px 0 #fff; border-color: #ccc; } .btn-default:hover, .btn-default:focus { background-color: #e0e0e0; background-position: 0 -15px; } .btn-default:active, .btn-default.active { background-color: #e0e0e0; border-color: #dbdbdb; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: #e0e0e0; background-image: none; } .btn-primary { background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#265a88)); background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #245580; } .btn-primary:hover, .btn-primary:focus { background-color: #265a88; background-position: 0 -15px; } .btn-primary:active, .btn-primary.active { background-color: #265a88; border-color: #245580; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #265a88; background-image: none; } .btn-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#419641)); background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #3e8f3e; } .btn-success:hover, .btn-success:focus { background-color: #419641; background-position: 0 -15px; } .btn-success:active, .btn-success.active { background-color: #419641; border-color: #3e8f3e; } .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, .btn-success.disabled:hover, .btn-success[disabled]:hover, fieldset[disabled] .btn-success:hover, .btn-success.disabled:focus, .btn-success[disabled]:focus, fieldset[disabled] .btn-success:focus, .btn-success.disabled.focus, .btn-success[disabled].focus, fieldset[disabled] .btn-success.focus, .btn-success.disabled:active, .btn-success[disabled]:active, fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { background-color: #419641; background-image: none; } .btn-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#2aabd2)); background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #28a4c9; } .btn-info:hover, .btn-info:focus { background-color: #2aabd2; background-position: 0 -15px; } .btn-info:active, .btn-info.active { background-color: #2aabd2; border-color: #28a4c9; } .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, .btn-info.disabled:hover, .btn-info[disabled]:hover, fieldset[disabled] .btn-info:hover, .btn-info.disabled:focus, .btn-info[disabled]:focus, fieldset[disabled] .btn-info:focus, .btn-info.disabled.focus, .btn-info[disabled].focus, fieldset[disabled] .btn-info.focus, .btn-info.disabled:active, .btn-info[disabled]:active, fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { background-color: #2aabd2; background-image: none; } .btn-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#eb9316)); background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #e38d13; } .btn-warning:hover, .btn-warning:focus { background-color: #eb9316; background-position: 0 -15px; } .btn-warning:active, .btn-warning.active { background-color: #eb9316; border-color: #e38d13; } .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, .btn-warning.disabled:hover, .btn-warning[disabled]:hover, fieldset[disabled] .btn-warning:hover, .btn-warning.disabled:focus, .btn-warning[disabled]:focus, fieldset[disabled] .btn-warning:focus, .btn-warning.disabled.focus, .btn-warning[disabled].focus, fieldset[disabled] .btn-warning.focus, .btn-warning.disabled:active, .btn-warning[disabled]:active, fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { background-color: #eb9316; background-image: none; } .btn-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c12e2a)); background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #b92c28; } .btn-danger:hover, .btn-danger:focus { background-color: #c12e2a; background-position: 0 -15px; } .btn-danger:active, .btn-danger.active { background-color: #c12e2a; border-color: #b92c28; } .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, .btn-danger.disabled:hover, .btn-danger[disabled]:hover, fieldset[disabled] .btn-danger:hover, .btn-danger.disabled:focus, .btn-danger[disabled]:focus, fieldset[disabled] .btn-danger:focus, .btn-danger.disabled.focus, .btn-danger[disabled].focus, fieldset[disabled] .btn-danger.focus, .btn-danger.disabled:active, .btn-danger[disabled]:active, fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { background-color: #c12e2a; background-image: none; } .thumbnail, .img-thumbnail { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); background-color: #e8e8e8; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); background-color: #2e6da4; } .navbar-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f8f8f8)); background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#e2e2e2)); background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); } .navbar-brand, .navbar-nav > li > a { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); } .navbar-inverse { background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: -o-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#3c3c3c), to(#222222)); background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border-radius: 4px; } .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%); background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#080808), to(#0f0f0f)); background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-nav > li > a { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-static-top, .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } @media (max-width: 767px) { .navbar .navbar-nav .open .dropdown-menu > .active > a, .navbar .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar .navbar-nav .open .dropdown-menu > .active > a:focus { color: #fff; background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); } } .alert { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); } .alert-success { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#c8e5bc)); background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0); border-color: #b2dba1; } .alert-info { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#b9def0)); background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0); border-color: #9acfea; } .alert-warning { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#f8efc0)); background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0); border-color: #f5e79e; } .alert-danger { background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#e7c3c3)); background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0); border-color: #dca7a7; } .progress { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#f5f5f5)); background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); } .progress-bar { background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#286090)); background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0); } .progress-bar-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#449d44)); background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); } .progress-bar-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#31b0d5)); background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0); } .progress-bar-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#ec971f)); background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0); } .progress-bar-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c9302c)); background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0); } .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .list-group { border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { text-shadow: 0 -1px 0 #286090; background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2b669a)); background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0); border-color: #2b669a; } .list-group-item.active .badge, .list-group-item.active:hover .badge, .list-group-item.active:focus .badge { text-shadow: none; } .panel { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .panel-default > .panel-heading { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); } .panel-primary > .panel-heading { background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); } .panel-success > .panel-heading { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#d0e9c6)); background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0); } .panel-info > .panel-heading { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#c4e3f3)); background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0); } .panel-warning > .panel-heading { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#faf2cc)); background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0); } .panel-danger > .panel-heading { background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#ebcccc)); background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0); } .well { background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#f5f5f5)); background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0); border-color: #dcdcdc; -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); }
{ "content_hash": "a847f323e0beac0ce5a2d2d43cd46488", "timestamp": "", "source": "github", "line_count": 592, "max_line_length": 208, "avg_line_length": 43.66554054054054, "alnum_prop": 0.7258413926499033, "repo_name": "MRdou325/lvyou", "id": "5924828e5fe608cdc68231f2d2e896753a04180e", "size": "26018", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Public/Home/bootstrap/css/bootstrap-theme.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1085012" }, { "name": "HTML", "bytes": "867887" }, { "name": "JavaScript", "bytes": "3632562" }, { "name": "PHP", "bytes": "1864562" }, { "name": "Smarty", "bytes": "11936" } ], "symlink_target": "" }
// Copyright 2014 Google Inc. All rights reserved. // // 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. /***** stenotype ***** * * stenotype is a mechanism for quickly dumping raw packets to disk. It aims to * have a simple interface (no file rotation: that's left as an exercise for * the reader) while being very powerful. * * stenotype uses a NIC->disk pipeline specifically designed to provide as fast * an output to disk as possible while just using the kernel's built-in * mechanisms. * * 1) NIC -> RAM * stenotype uses MMAP'd AF_PACKET with 1MB blocks and a high timeout to offload * writing packets and deciding their layout to the kernel. The kernel packs * all the packets it can into 1MB, then lets the userspace process know there's * a block available in the MMAP'd ring buffer. Nicely, it guarantees no * overruns (packets crossing the 1MB boundary) and good alignment to memory * pages. * * 2) RAM -> Disk * Since the kernel already gave us a single 1MB block of packets that's nicely * aligned, we can O_DIRECT write it straight to disk. This avoids any * additional copying or kernel buffering. To keep sequential reads going * strong, we do all disk IO asynchronously via io_submit (which works * specifically for O_DIRECT files... joy!). Since the data is being written to * disk asynchronously, we use the time it's writing to disk to do our own * in-memory processing and indexing. * * There are N (flag-specified) async IO operations available... once we've used * up all N, we block on a used one finishing, then reuse it. * The whole pipeline consists of: * - kernel gives userspace a 1MB block of packets * - userspace iterates over packets in block, updates any indexes * - userspace starts async IO operation to write block to disk * - after N async IO operations are submitted, we synchronously wait for the * least recent one to finish. * - when an async IO operation finishes, we release the 1MB block back to the * kernel to write more packets. */ #include <errno.h> // errno #include <fcntl.h> // O_* #include <grp.h> // getgrnam() #include <linux/if_packet.h> // AF_PACKET, sockaddr_ll #include <poll.h> // POLLIN #include <pthread.h> // pthread_sigmask() #include <pwd.h> // getpwnam() #include <sched.h> // sched_setaffinity() #include <seccomp.h> // scmp_filter_ctx, seccomp_*(), SCMP_* #include <signal.h> // sigaction(), SIGINT, SIGTERM #include <string.h> // strerror() #include <sys/prctl.h> // prctl(), PR_SET_* #include <sys/resource.h> // setpriority(), PRIO_PROCESS #include <sys/socket.h> // socket() #include <sys/stat.h> // umask() #include <sys/syscall.h> // syscall(), SYS_gettid #include <unistd.h> // setuid(), setgid() #include <string> #include <sstream> #include <thread> // Due to some weird interactions with <argp.h>, <string>, and --std=c++0x, this // header MUST be included AFTER <string>. #include <argp.h> // argp_parse() #include "aio.h" #include "index.h" #include "packets.h" #include "util.h" namespace { std::string flag_iface = "eth0"; std::string flag_filter = ""; std::string flag_dir = ""; int64_t flag_count = -1; int32_t flag_blocks = 2048; int32_t flag_aiops = 128; int64_t flag_filesize_mb = 4 << 10; int32_t flag_threads = 1; int64_t flag_fileage_sec = 60; uint16_t flag_fanout_type = // Use rollover as the default if it's available. #ifdef PACKET_FANOUT_FLAG_ROLLOVER PACKET_FANOUT_LB | PACKET_FANOUT_FLAG_ROLLOVER; #else PACKET_FANOUT_LB; #endif uint16_t flag_fanout_id = 0; std::string flag_uid; std::string flag_gid; bool flag_index = true; std::string flag_seccomp = "kill"; int flag_index_nicelevel = 0; int flag_preallocate_file_mb = 0; bool flag_watchdogs = true; int ParseOptions(int key, char* arg, struct argp_state* state) { switch (key) { case 'v': st::logging_verbose_level++; break; case 'q': st::logging_verbose_level--; break; case 300: flag_iface = arg; break; case 301: flag_dir = arg; break; case 302: flag_count = atoi(arg); break; case 303: flag_blocks = atoi(arg); break; case 304: flag_aiops = atoi(arg); break; case 305: flag_filesize_mb = atoi(arg); break; case 306: flag_threads = atoi(arg); break; case 307: flag_fileage_sec = atoi(arg); break; case 308: flag_fanout_type = atoi(arg); break; case 309: flag_fanout_id = atoi(arg); break; case 310: flag_uid = arg; break; case 311: flag_gid = arg; break; case 312: flag_index = false; break; case 313: flag_index_nicelevel = atoi(arg); break; case 314: flag_filter = arg; break; case 315: flag_seccomp = arg; break; case 316: flag_preallocate_file_mb = atoi(arg); break; case 317: flag_watchdogs = false; } return 0; } void ParseOptions(int argc, char** argv) { const char* s = "STRING"; const char* n = "NUM"; struct argp_option options[] = { {0, 'v', 0, 0, "Verbose logging, may be given multiple times"}, {0, 'q', 0, 0, "Quiet logging. Each -q counteracts one -v"}, {"iface", 300, s, 0, "Interface to read packets from"}, {"dir", 301, s, 0, "Directory to store packet files in"}, {"count", 302, n, 0, "Total number of packets to read, -1 to read forever"}, {"blocks", 303, n, 0, "Total number of blocks to use, each is 1MB"}, {"aiops", 304, n, 0, "Max number of async IO operations"}, {"filesize_mb", 305, n, 0, "Max file size in MB before file is rotated"}, {"threads", 306, n, 0, "Number of parallel threads to read packets with"}, {"fileage_sec", 307, n, 0, "Files older than this many secs are rotated"}, {"fanout_type", 308, n, 0, "TPACKET_V3 fanout type to fanout packets"}, {"fanout_id", 309, n, 0, "If fanning out across processes, set this"}, {"uid", 310, n, 0, "Drop privileges to this user"}, {"gid", 311, n, 0, "Drop privileges to this group"}, {"no_index", 312, 0, 0, "Do not compute or write indexes"}, {"index_nicelevel", 313, n, 0, "Nice level of indexing threads"}, {"filter", 314, s, 0, "BPF compiled filter used to filter which packets " "will be captured. This has to be a compiled BPF in hexadecimal, which " "can be obtained from a human readable filter expression using the " "provided compile_bpf.sh script."}, {"seccomp", 315, s, 0, "Seccomp style, one of 'none', 'trace', 'kill'."}, {"preallocate_file_mb", 316, n, 0, "When creating new files, preallocate to this many MB"}, {"no_watchdogs", 317, 0, 0, "Don't start any watchdogs"}, {0}, }; struct argp argp = {options, &ParseOptions}; argp_parse(&argp, argc, argv, 0, 0, 0); } } // namespace namespace st { // These two synchronization mechanisms are used to coordinate when to // chroot/chuid so it's after when the threads create their sockets but before // they start writing files. Notification main_complete; void DropPrivileges() { LOG(INFO) << "Dropping privileges"; if (getgid() == 0 || flag_gid != "") { if (flag_gid == "") { flag_gid = "nogroup"; } LOG(INFO) << "Dropping priviledges from " << getgid() << " to GID " << flag_gid; auto group = getgrnam(flag_gid.c_str()); CHECK(group != NULL) << "Unable to get info for group " << flag_gid; CHECK_SUCCESS(Errno(setgid(group->gr_gid))); } else { LOG(V1) << "Staying with GID=" << getgid(); } if (getuid() == 0 || flag_uid != "") { if (flag_uid == "") { flag_uid = "nobody"; } LOG(INFO) << "Dropping priviledges from " << getuid() << " to UID " << flag_uid; auto passwd = getpwnam(flag_uid.c_str()); CHECK(passwd != NULL) << "Unable to get info for user " << flag_uid; flag_uid = passwd->pw_uid; CHECK_SUCCESS(Errno(initgroups(flag_uid.c_str(), getgid()))); CHECK_SUCCESS(Errno(setuid(passwd->pw_uid))); } else { LOG(V1) << "Staying with UID=" << getuid(); } } #define SECCOMP_RULE_ADD(...) \ CHECK_SUCCESS(NegErrno(seccomp_rule_add(__VA_ARGS__))) void CommonPrivileges(scmp_filter_ctx ctx) { // Very common operations, including sleeping, logging, and getting time. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(clock_nanosleep), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(clock_gettime), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(gettimeofday), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0); // Mutex and other synchronization. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(set_robust_list), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(futex), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(restart_syscall), 0); // File operations. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fallocate), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(ftruncate), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fstat), 0); #ifdef __NR_fstat64 SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fstat64), 0); #endif SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0); // Signal handling and propagation to threads. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigaction), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigprocmask), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigreturn), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(tgkill), 0); // Malloc/ringbuffer. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 0); #ifdef __NR_mmap2 SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap2), 0); #endif SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(munmap), 0); // Malloc. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mprotect), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(madvise), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0); // Exiting threads. SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0); #ifdef __NR_sigreturn SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(sigreturn), 0); #endif } scmp_filter_ctx kSkipSeccomp = scmp_filter_ctx(-1); scmp_filter_ctx SeccompCtx() { if (flag_seccomp == "none") return kSkipSeccomp; if (flag_seccomp == "trace") return seccomp_init(SCMP_ACT_TRACE(1)); if (flag_seccomp == "kill") return seccomp_init(SCMP_ACT_KILL); LOG(FATAL) << "invalid --seccomp flag: " << flag_seccomp; return NULL; // unreachable } void DropCommonThreadPrivileges() { scmp_filter_ctx ctx = SeccompCtx(); if (ctx == kSkipSeccomp) return; CHECK(ctx != NULL); CommonPrivileges(ctx); CHECK_SUCCESS(NegErrno(seccomp_load(ctx))); seccomp_release(ctx); } void DropIndexThreadPrivileges() { scmp_filter_ctx ctx = SeccompCtx(); if (ctx == kSkipSeccomp) return; CHECK(ctx != NULL); CommonPrivileges(ctx); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rename), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 1, SCMP_A1(SCMP_CMP_EQ, O_WRONLY | O_CREAT | O_TRUNC)); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 1, SCMP_A1(SCMP_CMP_EQ, O_RDWR | O_CREAT | O_TRUNC)); CHECK_SUCCESS(NegErrno(seccomp_load(ctx))); seccomp_release(ctx); } void DropPacketThreadPrivileges() { scmp_filter_ctx ctx = SeccompCtx(); if (ctx == kSkipSeccomp) return; CHECK(ctx != NULL); CommonPrivileges(ctx); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(io_setup), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(io_submit), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(io_getevents), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(poll), 1, SCMP_A1(SCMP_CMP_EQ, POLLIN)); SECCOMP_RULE_ADD( ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 2, SCMP_A1(SCMP_CMP_EQ, O_WRONLY | O_CREAT | O_DSYNC | O_DIRECT), SCMP_A2(SCMP_CMP_EQ, 0600)); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getsockopt), 0); SECCOMP_RULE_ADD(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rename), 0); CHECK_SUCCESS(NegErrno(seccomp_load(ctx))); seccomp_release(ctx); } #undef SECCOMP_RULE_ADD Error SetAffinity(int cpu) { cpu_set_t cpus; CPU_ZERO(&cpus); CPU_SET(cpu, &cpus); return Errno(sched_setaffinity(0, sizeof(cpus), &cpus)); } void WriteIndexes(int thread, st::ProducerConsumerQueue* write_index) { LOG(V1) << "Starting WriteIndexes thread " << thread; Watchdog dog("WriteIndexes thread " + std::to_string(thread), (flag_watchdogs ? flag_fileage_sec * 3 : -1)); pid_t tid = syscall(SYS_gettid); LOG_IF_ERROR(Errno(setpriority(PRIO_PROCESS, tid, flag_index_nicelevel)), "setpriority"); DropIndexThreadPrivileges(); while (true) { LOG(V1) << "Waiting for index"; Index* i = reinterpret_cast<Index*>(write_index->Get()); LOG(V1) << "Got index " << int64_t(i); if (i == NULL) { break; } LOG_IF_ERROR(i->Flush(), "index flush"); LOG(V1) << "Wrote index " << int64_t(i); delete i; dog.Feed(); } LOG(V1) << "Exiting write index thread"; } bool run_threads = true; void HandleSignals(int sig) { if (run_threads) { LOG(INFO) << "Got signal " << sig << ", stopping threads"; run_threads = false; } } void HandleSignalsThread() { LOG(V1) << "Handling signals"; struct sigaction handler; handler.sa_handler = &HandleSignals; sigemptyset(&handler.sa_mask); handler.sa_flags = 0; sigaction(SIGINT, &handler, NULL); sigaction(SIGTERM, &handler, NULL); DropCommonThreadPrivileges(); main_complete.WaitForNotification(); LOG(V1) << "Signal handling done"; } void RunThread(int thread, st::ProducerConsumerQueue* write_index, PacketsV3* v3) { if (flag_threads > 1) { LOG_IF_ERROR(SetAffinity(thread), "set affinity"); } Watchdog dog("Thread " + std::to_string(thread), (flag_watchdogs ? flag_fileage_sec * 2 : -1)); std::unique_ptr<PacketsV3> cleanup(v3); DropPacketThreadPrivileges(); LOG(INFO) << "Thread " << thread << " starting to process packets"; // Set up file writing, if requested. Output output(flag_aiops); // All dirnames are guaranteed to end with '/'. std::string file_dirname = flag_dir + "PKT" + std::to_string(thread) + "/"; std::string index_dirname = flag_dir + "IDX" + std::to_string(thread) + "/"; Packet p; int64_t micros = GetCurrentTimeMicros(); CHECK_SUCCESS( output.Rotate(file_dirname, micros, flag_preallocate_file_mb << 10)); Index* index = NULL; if (flag_index) { index = new Index(index_dirname, micros); } else { LOG(ERROR) << "Indexing turned off"; } int64_t start = GetCurrentTimeMicros(); int64_t lastlog = 0; int64_t blocks = 0; int64_t block_offset = 0; for (int64_t remaining = flag_count; remaining != 0 && run_threads;) { CHECK_SUCCESS(output.CheckForCompletedOps(false)); int64_t current_micros = GetCurrentTimeMicros(); // Rotate file if necessary. int64_t current_file_age_secs = (current_micros - micros) / kNumMicrosPerSecond; if (block_offset == flag_filesize_mb || current_file_age_secs > flag_fileage_sec) { LOG(V1) << "Rotating file " << micros << " with " << block_offset << " blocks"; // File size got too big, rotate file. micros = current_micros; block_offset = 0; CHECK_SUCCESS( output.Rotate(file_dirname, micros, flag_preallocate_file_mb << 10)); if (flag_index) { write_index->Put(index); index = new Index(index_dirname, micros); } } // Read in a new block from AF_PACKET. Block b; CHECK_SUCCESS(v3->NextBlock(&b, kNumMillisPerSecond)); if (b.Empty()) { continue; } // Index all packets if necessary. if (flag_index) { for (; remaining != 0 && b.Next(&p); remaining--) { index->Process(p, block_offset << 20); } } blocks++; block_offset++; // Log stats every 100MB or at least 1/minute. if (blocks % 100 == 0 || lastlog < current_micros - 60 * kNumMicrosPerSecond) { lastlog = current_micros; double duration = (current_micros - start) * 1.0 / kNumMicrosPerSecond; Stats stats; Error stats_err = v3->GetStats(&stats); if (SUCCEEDED(stats_err)) { LOG(INFO) << "Thread " << thread << " stats: MB=" << blocks << " secs=" << duration << " MBps=" << (blocks / duration) << " " << stats.String(); } else { LOG(ERROR) << "Unable to get stats: " << *stats_err; } } // Start an async write of the current block. Could block // waiting for the write 'aiops' writes ago. CHECK_SUCCESS(output.Write(&b)); dog.Feed(); } LOG(V1) << "Finishing thread " << thread; // Write out the last index. if (flag_index) { write_index->Put(index); } // Close last open file. CHECK_SUCCESS(output.Flush()); LOG(INFO) << "Finished thread " << thread << " successfully"; } int Main(int argc, char** argv) { LOG_IF_ERROR(Errno(prctl(PR_SET_PDEATHSIG, SIGTERM)), "prctl PDEATHSIG"); ParseOptions(argc, argv); LOG(V1) << "Stenotype running with these arguments:"; for (int i = 0; i < argc; i++) { LOG(V1) << i << ":\t\"" << argv[i] << "\""; } LOG(INFO) << "Starting..."; // Sanity check flags and setup options. CHECK(flag_filesize_mb <= 4 << 10); CHECK(flag_filesize_mb > 1); CHECK(flag_filesize_mb > flag_aiops); CHECK(flag_blocks >= 16); // arbitrary lower limit. CHECK(flag_threads >= 1); CHECK(flag_aiops <= flag_blocks); CHECK(flag_dir != ""); if (flag_dir[flag_dir.size() - 1] != '/') { flag_dir += "/"; } // Before we drop any privileges, set up our sniffing sockets. // We have to do this before calling DropPrivileges, which does a // setuid/setgid and could lose us the ability to do this at a later date. LOG(INFO) << "Setting up AF_PACKET sockets for packet reading"; int socktype = SOCK_RAW; struct tpacket_req3 options; memset(&options, 0, sizeof(options)); options.tp_block_size = 1 << 20; // it's very important this be 1MB options.tp_block_nr = flag_blocks; options.tp_frame_size = 16 << 10; // does not matter at all options.tp_frame_nr = 0; // computed for us. options.tp_retire_blk_tov = 10 * kNumMillisPerSecond; std::vector<PacketsV3*> sockets; for (int i = 0; i < flag_threads; i++) { // Set up AF_PACKET packet reading. PacketsV3::Builder builder; CHECK_SUCCESS(builder.SetUp(socktype, options)); int fanout_id = getpid(); if (flag_fanout_id > 0) { fanout_id = flag_fanout_id; } if (flag_fanout_id > 0 || flag_threads > 1) { CHECK_SUCCESS(builder.SetFanout(flag_fanout_type, fanout_id)); } if (!flag_filter.empty()) { CHECK_SUCCESS(builder.SetFilter(flag_filter)); } PacketsV3* v3; CHECK_SUCCESS(builder.Bind(flag_iface, &v3)); sockets.push_back(v3); } // To be safe, also set umask before any threads are created. umask(0077); // Now that we have sockets, drop privileges. // We HAVE to do this before we start any threads, since it's unclear whether // setXid will set the IDs for the all process threads or just the current // one. This should also be done before signal masking, because apparently // sometimes Linux sends a SIGSETXID signal to threads during this, and if // that is ignored setXid will hang forever. DropPrivileges(); // Start a thread whose sole purpose is to handle signals. // Signal handling in a multi-threaded application is HARD. This binary // wants to handle signals very simply: one thread catches SIGINT/SIGTERM and // sets a bool accordingly. However, Linux will deliver the signal to one // (random) thread. How to handle this? First, we create the one single // thread that is going to get signals... std::thread signal_thread(&HandleSignalsThread); signal_thread.detach(); // ... Then, we block those signals from being handled by this thread or any // of its children. All other threads MUST be created after this. sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGINT); sigaddset(&sigset, SIGTERM); CHECK_SUCCESS(Errno(pthread_sigmask(SIG_BLOCK, &sigset, NULL))); // Now, we can finally start the threads that read in packets, index them, and // write them to disk. auto write_indexes = new st::ProducerConsumerQueue[flag_threads]; LOG(V1) << "Starting writing threads"; std::vector<std::thread*> threads; for (int i = 0; i < flag_threads; i++) { LOG(V1) << "Starting thread " << i; threads.push_back( new std::thread(&RunThread, i, &write_indexes[i], sockets[i])); } // To avoid blocking on index writes, each writer thread has a secondary // thread just for creating and writing the indexes. We pass to-write // indexes through to the writing thread via the write_index FIFO queue. // TODO(gconnell): Move index writing thread creation into RunThread. std::vector<std::thread*> index_threads; if (flag_index) { LOG(V1) << "Starting indexing threads"; for (int i = 0; i < flag_threads; i++) { std::thread* t = new std::thread(&WriteIndexes, i, &write_indexes[i]); index_threads.push_back(t); } } // Drop all privileges we need. Note: we because of what we've already done, // we really don't need much anymore. No need to create new threads, to write // files, to open sockets... we basically just hang around waiting for all the // other threads to finish. DropCommonThreadPrivileges(); for (auto thread : threads) { LOG(V1) << "===============Waiting for thread=============="; CHECK(thread->joinable()); thread->join(); LOG(V1) << "Thread finished"; delete thread; } LOG(V1) << "Finished all threads"; if (flag_index) { for (int i = 0; i < flag_threads; i++) { LOG(V1) << "Closing write index queue " << i << ", waiting for thread"; write_indexes[i].Close(); CHECK(index_threads[i]->joinable()); index_threads[i]->join(); LOG(V1) << "Index thread finished"; delete index_threads[i]; } } delete[] write_indexes; LOG(INFO) << "Process exiting successfully"; main_complete.Notify(); return 0; } } // namespace st int main(int argc, char** argv) { return st::Main(argc, argv); }
{ "content_hash": "c8b894a0dfebf791660bb92af4a1f43a", "timestamp": "", "source": "github", "line_count": 642, "max_line_length": 80, "avg_line_length": 36.0202492211838, "alnum_prop": 0.6386594594594595, "repo_name": "nbareil/stenographer", "id": "cc2f80ecb99d3d864d351c6cc1c1df2ce9842fd3", "size": "23125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stenotype/stenotype.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "84110" }, { "name": "Go", "bytes": "103921" }, { "name": "Makefile", "bytes": "2831" }, { "name": "Shell", "bytes": "15862" }, { "name": "Yacc", "bytes": "6222" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0" /> <meta name="format-detection" content="telephone=no"> <title>DynamicApp Test Application.</title> <link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.17.custom.css" type="text/css"> <script type='text/javascript' src='js/jquery-1.7.1.min.js'></script> <script type='text/javascript' src='js/jquery-ui-1.8.17.custom.min.js'></script> <script type="text/javascript" src="js/jquery-ui-timepicker.js"></script> <script type='text/javascript' src='js/iscroll4.js'></script> <script type="text/javascript" src="js/jquery-ui-sliderAccess.js"></script> <script type="text/javascript" src="js/jquery.simplemodal.js"></script> <script type="text/javascript" src="js/DynamicApp.js"></script> <style type="text/css"> html { -webkit-text-size-adjust: none; /* Never autoresize text */ } #img3by3 { float: left; width: 33%; height: 90px; margin: 0; padding-top: 10px; /* border: 1px solid; */ text-align: center; } /* Overlay */ #simplemodal-overlay {background-color:#000; cursor:wait;} /* Container */ #simplemodal-container {height:300px; width:80%; border:2px solid #bbb; padding:12px; background-color: white;} #simplemodal-container .simplemodal-data {padding:8px;} #simplemodal-container a {color:#ddd;} #simplemodal-container a.modalCloseImg {background:url(css/smoothness/images/x.png) no-repeat; width:25px; height:29px; display:inline; z-index:3200; position:absolute; top:-15px; right:-16px; cursor:pointer;} #simplemodal-container h3 {color:#84b8d9;} #wrapper { width:98%; height:310px; margin:0 auto !important; position:relative; z-index:1; overflow:hidden; -webkit-border-radius:10px; border: 1px solid; } #wrapperCache1 { width:98%; height:310px; margin:0 auto !important; position:relative; z-index:1; overflow:hidden; -webkit-border-radius:10px; border: 1px solid; } #wrapperCache2 { width:98%; height:310px; margin:0 auto !important; position:relative; z-index:1; overflow:hidden; -webkit-border-radius:10px; border: 1px solid; } #imgDiv { width:100%; height:310px; float:left; padding:0; } #cacheDiv { width:100%; float:left; padding:0; } .contentDiv { padding: 5px 0px !important; } /* css for timepicker */ .ui-datepicker { width: 275px !important;} .ui-timepicker-div, .ui-datepicker-calendar, .ui-datepicker-header, .ui-datepicker-buttonpane { font-size: 10px !important;} .ui-timepicker-div .ui-widget-header { margin-bottom: 8px; } .ui-timepicker-div dl { text-align: left; } .ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; } .ui-timepicker-div dl dd { margin: 0 10px 10px 65px; } .ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; } #ui-timepicker-div-notificationTime .ui-slider { font-size: 14px; } #btTestPeerList th, #btTestPeerList td { background-color: white; text-align: center; } #btPeerList div:not(#noPeersText) { border-bottom:1px solid; padding:3px; } #bt4LETestPeripheralList th, #bt4LETestPeripheralList td { background-color: white; text-align: center; } #bt4LEPeripheralList div:not(#no4LEPeripheralText) { border-bottom:1px solid; padding:3px; } .btFloatingDiv { background-color: white; border: 2px solid; text-align: center; z-index: 1000; display: none; font-size: 60%; /*position: fixed; top: 50%; left: 50%; min-height: 120px; margin-top: -50px; width: 250px; margin-left: -125px;*/ } .noTitleDialog .ui-dialog-titlebar {display:none} </style> <script language="javascript"> <!-- var isIOS = false; var isWindows = false; var accordion; $(function() { if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) { var msStyle = document.createElement("style"); msStyle.appendChild( document.createTextNode("textarea, select {font-size: 1.5em !important}") ); msStyle.appendChild( document.createTextNode("td, th {width: 160px !important}") ); document.getElementsByTagName("head")[0].appendChild(msStyle); } if (navigator.userAgent.match(/iPod|iPad|iPhone/i)){ $('.felica').remove(); isIOS = true; } else if (navigator.userAgent.match(/Android/)) { $('.bluetoothLE').remove(); $('.pdf').remove(); } else if (navigator.userAgent.match(/Windows Phone/i)) { $('.bluetoothLE').remove(); $('.pdf').remove(); $('.felica').remove(); $('.database').remove(); $('.addressbook').remove(); isWindows = true; } accordion = $('#accordion'); accordion.accordion({ active: accordion.find('h3').length - 1, collapsible: true, changestart: function(event, ui) { var index = $(this).find("h3").index(ui.newHeader[0]); if(index == 0) { appVersionShow(); } else if(index == 4) { // movie getThumbnail(); } if(moviePlaylist[currentMovie]) { if(moviePlaylist[currentMovie].state == Movie.MOVIE_RUNNING || moviePlaylist[currentMovie].state == Movie.MOVIE_PAUSED) { stop.click(); } } if(soundPlaylist[currentSound]) { if(soundPlaylist[currentSound].state == Sound.SOUND_RUNNING || soundPlaylist[currentSound].state == Sound.SOUND_PAUSED) { sStop.click(); } } }, autoHeight: false }); //full height var a = function() { $('section').css({height: '100%'}); }; setTimeout(a, 100); }); /* * App Version * * */ function appVersionShow() { var callback = function(version) { $('#lblAppVersion').html('Version '+ version); }; AppVersion.get(callback); } /* * Camera * * */ var imgScroll, imgDiv, imgCount = 0; function loadIScroll() { imgScroll = new iScroll('wrapper', { hScrollbar: false, vScrollbar: false, checkDOMChanges: false }); } $(function(){ loadIScroll(); imgDiv = $('#imgDiv'); $('#camera').click(function(event) { var successCallback = function(data) { if(false && imgCount < 9) { // for testing only for(var i=0;i<9;i++) { var img = '<div id="img3by3"><img src="'+data+'" style="height:90px;width:90px"/></div>'; imgDiv.append(img); imgCount++; } } var img = '<div id="img3by3"><div style="position:relative;background-image:url('+data+');background-size:100%;height:90px;width:90px;text-align:right;margin:0px auto;"><span style="position:absolute;bottom:0px;left:0px;width:90px;height:90px;background: url(\'css/smoothness/images/cameraPhoto.png\') no-repeat scroll right bottom transparent;">&nbsp;</span></div></div>'; imgDiv.prepend(img); imgCount++; if(imgCount%3 == 1 && imgCount > 9) { var newHeight = parseInt(/(\d+)px/.exec(imgDiv.css('height'))) + 100; imgDiv.css('height', newHeight); imgScroll.refresh(); } }; var errorCallback = function(error) { alert("Error: " + error); }; var options = { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType : Camera.PictureSourceType.CAMERA, encodingType: Math.round(Math.random()) // returns 1 or 0 for PNG or JPEG resp. }; Camera.getPicture(successCallback, errorCallback, options); }); }); /* * Video Recording * */ var vidRecord, vidPlay, vidStop, vidLblDuration, vidLblPosition; var vSlider, vInterval=500, vProcessFlag = true; var videoTitle = ''; var recordedVideo; function getVideoThumbnail(title) { videoTitle = title; var movie = new Movie(videoTitle); var successCallback = function(data) { if(data.indexOf('null') < 0) { var imgDiv = $('#imgDiv'); if (navigator.userAgent.match(/iPod|iPad|iPhone/i)){ var img = '<div id="img3by3" class="movieThumbnail" data-title="'+title+'"><div style="position:relative;background-image:url('+data+');background-size:100%;height:90px;width:90px;text-align:right;margin:0px auto;"><span style="position:absolute;bottom:0px;left:0px;width:90px;height:90px;background: url(\'css/smoothness/images/cameraFilm.png\') no-repeat scroll right bottom transparent;">&nbsp;</span></div></div>'; } else if (navigator.userAgent.match(/Android|Windows/i)) { var img = '<div id="img3by3" class="movieThumbnail" data-title="'+title+'"><div style="position:relative;height:90px;width:90px;text-align:right;margin:0px auto;font-size:80%; text-align:center;"><img src="'+data+'" width="90px" height="90px"/><span style="position:absolute;bottom:0px;left:0px;top:0px;width:90px;height:90px;background: url(\'css/smoothness/images/cameraFilm.png\') no-repeat scroll right bottom transparent;">&nbsp;</span></div></div>'; } imgDiv.prepend(img); imgCount++; if(imgCount%3 == 1 && imgCount > 9) { var newHeight = parseInt(/(\d+)px/.exec(imgDiv.css('height'))) + 100; imgDiv.css('height', newHeight); imgScroll.refresh(); } } }; var errorCallback = function(error) { alert('Error generating thumbnail: ' + error); }; movie.getThumbnail(successCallback, errorCallback, {offset:1}); } function getVideoPosition() { if (vProcessFlag && recordedVideo.state == Movie.MOVIE_RUNNING) { recordedVideo.getCurrentPosition(); vidLblPosition.html(recordedVideo.position); vSlider.slider("value", recordedVideo.position); setTimeout(getVideoPosition, vInterval); } else if (vSlider && recordedVideo.state == Movie.MOVIE_STOPPED) { vSlider.hide(); } } $(function () { vidRecord = $('#record'); vidPlay = $('#playvideo'); vidStop = $('#stopvideo'); vidLblDuration = $('#mainContentVideo #duration'); vidLblPosition = $('#mainContentVideo #position'); vidPlay.click(function (event) { var me = $(this); if (me.val() == 'play') { onclickVideoPlay(); } else { recordedVideo.pause(); } vidStop.removeAttr('disabled'); }); vidStop.click(function (event) { vProcessFlag = false; if(vSlider) vSlider.hide(); vidPlay.val('play'); vidStop.attr('disabled', 'disabled'); recordedVideo.stop(); }); $('#imgDiv').on('click', '.movieThumbnail', function() { videoTitle = $(this).attr('data-title'); recordedVideo = null; vSlider = null; $('#recordMovieDiv').dialog({ modal: true, resizable: false, dialogClass: 'noTitleDialog', autoOpen: false, open: function(event, ui) { vidPlay.val('play'); $('#playvideo').click(); }, close: function(event, ui) { if(vidStop.is(':disabled')) { $('#recordMovieDiv').dialog('close'); $('#recordMovieDiv').dialog('destroy'); } else { $('#stopvideo').click(); } } }); $('#recordMovieDiv').dialog('open'); }); }); function onclickVideoPlay() { if(!recordedVideo) { var mainContentMovie = $('#mainContentVideoFrame'); var offset = mainContentMovie.offset(); var sString; var successCallback = function() { var movie = recordedVideo; if(typeof movie == 'undefined') return; switch(movie.state) { case Movie.MOVIE_RUNNING : if(vidPlay.val() == 'play') { vProcessFlag = true; vidPlay.val('pause'); vidRecord.attr('disabled', 'disabled'); } if(!vSlider) { vSlider = $('#videoSlider') .slider({ min: 0, max: movie.duration, range: "min", value: 1, animate: true, slide: function(event, ui) { vProcessFlag = false; movie.setCurrentPosition(ui.value - 1, function(){vProcessFlag = true;getVideoPosition();}); } }); } if(vSlider.not(':visible')) { vSlider.show(); } vidLblDuration.html(recordedVideo.duration); getVideoPosition(); sString = 'playing'; accordion.accordion('option', {event:''}); break; case Movie.MOVIE_STOPPED : sString = 'stop'; vidPlay.val('play'); vidStop.attr('disabled', 'disabled'); vidRecord.removeAttr('disabled'); if(vSlider) { vidLblDuration.html(0); vidLblPosition.html(0); } else { vidLblDuration.html(''); vidLblPosition.html(''); } $('#recordMovieDiv').dialog('close'); $('#recordMovieDiv').dialog('destroy'); accordion.accordion('option', 'event', 'click'); break; case Movie.MOVIE_PAUSED : sString = 'pause'; if(vidPlay.val() == 'pause') { vProcessFlag = false; vidPlay.val('play'); } vidRecord.removeAttr('disabled'); break; case Movie.MOVIE_NONE : sString = 'none'; break; default : sString = 'default'; break; } }; var errorCallback = function(error) { $('#recordMovieDiv').dialog('close'); $('#recordMovieDiv').dialog('destroy'); alert('Error: ' + error); }; var options = { frame:{posX:offset.left, posY: offset.top, width:mainContentMovie.width(), height:mainContentMovie.height()}, scalingMode:Movie.SCALING_ASPECT_FIT, controlStyle:Movie.CONTROL_NONE }; recordedVideo = new Movie(videoTitle, successCallback, errorCallback, options); } recordedVideo.play(); } function record() { var successCallback = function(data) { videoTitle = data; setTimeout(function(){getVideoThumbnail(videoTitle);}, 200); }; var errorCallback = function(error) { alert("Error: " + error); }; Camera.recordVideo(successCallback, errorCallback); } /* * Sound * * */ //01 Freedom Song.mp3 //rockGuitar.mp3 //http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3 //http://dc340.4shared.com/img/1118481151/f6abdb37/dlink__2Fdownload_2F2uy4DCZ2_3Ftsid_3D00000000-000000-00000000/preview.mp3 var sPrevious, sNext, sPlay, sStop, lblSPosition, lblSDuration; var sSlider, sInterval = 500, sProcessFlag = true; var soundTitles = ["Crash-Boom-Kapow_Traffic-Jam-Jam-320.mp3", "http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3", "djnarcs_Freedom-320.mp3"]; var currentSound = 0; var soundPlaylist = new Array(); function onclickSoundPlay() { if(!soundPlaylist[currentSound]) { var sString; var successCallback = function() { var sound = soundPlaylist[currentSound]; switch(sound.state) { case Sound.SOUND_RUNNING : if(!sSlider) { sSlider = $('#soundSlider') .slider({ min: 0, max: sound.duration, range: "min", value: 1, animate: true, slide: function(event, ui) { sProcessFlag = false; sound.setCurrentPosition(ui.value - 1, function(){sProcessFlag = true;getSoundPosition();}); } }); } if(sSlider.not(':visible')) { sSlider.show(); } lblSDuration.html(soundPlaylist[currentSound].duration); getSoundPosition(); sString = 'playing'; break; case Sound.SOUND_STOPPED : sString = 'stop'; sPlay.val('play'); sStop.attr('disabled', 'disabled'); if(sSlider) { lblSPosition.html(0); } else { lblSPosition.html(''); } break; case Sound.SOUND_PAUSED : sString = 'pause'; break; case Sound.SOUND_NONE : sString = 'none'; break; default : sString = 'default'; break; } //lblSDuration.html(soundPlaylist[currentSound].duration + ' ' + sString); //$('#mainContentSound #position').html(soundPlaylist[currentSound].position + ' ' + soundPlaylist[currentSound].state + ' ' + sString); }; var errorCallback = function(error) { if (sPlay.val() == 'pause') { sPlay.val('play'); } alert('Error: ' + error); }; soundPlaylist[currentSound] = new Sound(soundTitles[currentSound], successCallback, errorCallback); } soundPlaylist[currentSound].play({numberOfLoops:2}); } function getSoundPosition() { if (sProcessFlag && soundPlaylist[currentSound].state == Sound.SOUND_RUNNING) { soundPlaylist[currentSound].getCurrentPosition(); lblSPosition.html(soundPlaylist[currentSound].position); sSlider.slider("value", soundPlaylist[currentSound].position); setTimeout(getSoundPosition, sInterval); } else if (sSlider && soundPlaylist[currentSound].state == Sound.SOUND_STOPPED) { sSlider.hide(); } } function onclickSoundRelease() { soundPlaylist[currentSound].release(); } $(function () { sPrevious = $('#sPrevious'); sNext = $('#sNext'); sPlay = $('#sPlay'); sStop = $('#sStop'); lblSDuration = $('#mainContentSound #duration'); lblSPosition = $('#mainContentSound #position'); if(currentSound < 1){ sPrevious.attr('disabled', 'disabled'); } else if(currentSound == soundTitles.length-1 || soundTitles.length == 0){ sNext.attr('disabled', 'disabled'); } sPrevious.click(function (event) { if(soundPlaylist[currentSound] && (soundPlaylist[currentSound].state == Sound.SOUND_RUNNING || soundPlaylist[currentSound].state == Sound.SOUND_PAUSED || soundPlaylist[currentSound].state == Sound.SOUND_STARTING)) { sStop.click(); } if (currentSound > 0) { currentSound--; sSlider = null; } if (currentSound == 0) { $(this).attr('disabled', 'disabled'); } alert(soundTitles[currentSound]); if (soundTitles.length > 0) { sNext.removeAttr('disabled'); } lblSDuration.html(''); lblSPosition.html(''); sStop.attr('disabled', 'disabled'); }); sPlay.click(function (event) { var me = $(this); if (me.val() == 'play') { sProcessFlag = true; me.val('pause'); onclickSoundPlay(); } else { sProcessFlag = false; me.val('play'); soundPlaylist[currentSound].pause(); } sStop.removeAttr('disabled'); }); sStop.click(function (event) { sProcessFlag = false; if (typeof sSlider != 'undefined' && sSlider != null) sSlider.hide(); sPlay.val('play'); lblSPosition.html(0); sStop.attr('disabled', 'disabled'); soundPlaylist[currentSound].stop(); }); sNext.click(function (event) { if(soundPlaylist[currentSound] && (soundPlaylist[currentSound].state == Sound.SOUND_RUNNING || soundPlaylist[currentSound].state == Sound.SOUND_PAUSED || soundPlaylist[currentSound].state == Sound.SOUND_STARTING)) { sStop.click(); } var max = soundTitles.length - 1; if (currentSound < max) { currentSound++; sSlider = null; } if (currentSound == max) { $(this).attr('disabled', 'disabled'); } alert(soundTitles[currentSound]); if (soundTitles.length > 0) { sPrevious.removeAttr('disabled'); } lblSDuration.html(''); lblSPosition.html(''); sStop.attr('disabled', 'disabled'); }); }); /* * Movie * * */ //http://www.808.dk/pics/video/gizmo.mp4 //big-buck-bunny-clip.m4v //http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8 var previous, next, play, stop, lblDuration, lblPosition; var slider, interval=500, processFlag = true; var movieTitles = ["1.mp4", "http://www.808.dk/pics/video/gizmo.mp4", "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8", "http://devimages.apple.com/iphone/samples/bipbop/gear3/prog_index.m3u8", "5.mp4"]; var currentMovie = 0; var moviePlaylist = new Array(); function getThumbnail() { var movie = new Movie(movieTitles[currentMovie]); var successCallback = function(data) { if(data.indexOf('null') < 0) { $('#mainContentMovieFrame').html('<img src="'+data+'" style="padding:0;margin:0 auto;height:200px;width:100%;"/>'); } else { $('#mainContentMovieFrame').html(''); } }; var errorCallback = function(error) { $('#mainContentMovieFrame').html('<img src="'+null+'" style="padding:0;margin:0 auto;height:200px;width:100%;"/>'); alert('Error generating thumbnail: ' + error); }; var options = {offset:1}; //movie.duration = 25; movie.getThumbnail(successCallback, errorCallback, options); } function onclickMoviePlay() { if(!moviePlaylist[currentMovie]) { var mainContentMovie = $('#mainContentMovieFrame'); var offset = mainContentMovie.offset(); var sString; var successCallback = function() { var movie = moviePlaylist[currentMovie]; if(typeof movie == 'undefined') return; switch(movie.state) { case Movie.MOVIE_RUNNING : if(play.val() == 'play') { processFlag = true; play.val('pause'); } if(!slider) { slider = $('#movieSlider') .slider({ min: 0, max: movie.duration, range: "min", value: 1, animate: true, slide: function(event, ui) { processFlag = false; movie.setCurrentPosition(ui.value - 1, function(){processFlag = true;getPosition();}); } }); } if(slider.not(':visible')) { slider.show(); } lblDuration.html(moviePlaylist[currentMovie].duration); getPosition(); sString = 'playing'; accordion.accordion('option', {event:''}); break; case Movie.MOVIE_STOPPED : sString = 'stop'; play.val('play'); stop.attr('disabled', 'disabled'); if(slider) { lblPosition.html(0); } else { lblPosition.html(''); } accordion.accordion('option', 'event', 'click'); break; case Movie.MOVIE_PAUSED : sString = 'pause'; if(play.val() == 'pause') { processFlag = false; play.val('play'); } break; case Movie.MOVIE_NONE : sString = 'none'; break; default : sString = 'default'; break; } //lblDuration.html(moviePlaylist[currentMovie].duration + ' ' + sString); //$('#mainContentMovie #position').html(moviePlaylist[currentMovie].position + ' ' + moviePlaylist[currentMovie].state + ' ' + sString); }; var errorCallback = function(error) { alert('Error: ' + error); }; var options = { frame:{posX:offset.left, posY: offset.top, width:mainContentMovie.width(), height:mainContentMovie.height()}, scalingMode:Movie.SCALING_ASPECT_FIT, controlStyle:Movie.CONTROL_NONE }; moviePlaylist[currentMovie] = new Movie(movieTitles[currentMovie], successCallback, errorCallback, options); } moviePlaylist[currentMovie].play(); } function getPosition() { if (processFlag && moviePlaylist[currentMovie].state == Movie.MOVIE_RUNNING) { moviePlaylist[currentMovie].getCurrentPosition(); lblPosition.html(moviePlaylist[currentMovie].position); slider.slider("value", moviePlaylist[currentMovie].position); setTimeout(getPosition, interval); } else if (slider && moviePlaylist[currentMovie].state == Movie.MOVIE_STOPPED) { slider.hide(); } } function onclickMovieRelease() { moviePlaylist[currentMovie].release(); } function onclickMovieGetThumbnail() { movie.getThumbnail(function(data){ $('#thumb').attr('src', data); $('#thumb').css({'width' : '300px' , 'height' : '200px'}); $('#image').attr('src', data); }, function(error){ alert('Error generating thumbnail: ' + error); },{ offset: movie.position }); } $(function () { previous = $('#previous'); next = $('#next'); play = $('#play'); stop = $('#stop'); lblDuration = $('#mainContentMovie #duration'); lblPosition = $('#mainContentMovie #position'); if(currentMovie < 1){ previous.attr('disabled', 'disabled'); } else if(currentMovie == movieTitles.length-1 || movieTitles.length == 0){ next.attr('disabled', 'disabled'); } previous.click(function (event) { if(moviePlaylist[currentMovie] && (moviePlaylist[currentMovie].state == Movie.MOVIE_RUNNING || moviePlaylist[currentMovie].state == Movie.MOVIE_PAUSED)) { stop.click(); } if (currentMovie > 0) { currentMovie--; slider = null; } if (currentMovie == 0) { $(this).attr('disabled', 'disabled'); } getThumbnail(); alert(movieTitles[currentMovie]); if (movieTitles.length > 0) { next.removeAttr('disabled'); } lblDuration.html(''); lblPosition.html(''); stop.attr('disabled', 'disabled'); }); play.click(function (event) { var me = $(this); if (me.val() == 'play') { onclickMoviePlay(); } else { moviePlaylist[currentMovie].pause(); } stop.removeAttr('disabled'); }); stop.click(function (event) { processFlag = false; if(slider) slider.hide(); play.val('play'); stop.attr('disabled', 'disabled'); moviePlaylist[currentMovie].stop(); }); next.click(function (event) { if(moviePlaylist[currentMovie] && (moviePlaylist[currentMovie].state == Movie.MOVIE_RUNNING || moviePlaylist[currentMovie].state == Movie.MOVIE_PAUSED)) { stop.click(); } var max = movieTitles.length - 1; if (currentMovie < max) { currentMovie++; slider = null; } if (currentMovie == max) { $(this).attr('disabled', 'disabled'); } getThumbnail(); alert(movieTitles[currentMovie]); if (movieTitles.length > 0) { previous.removeAttr('disabled'); } lblDuration.html(''); lblPosition.html(''); stop.attr('disabled', 'disabled'); }); }); /* * File * * */ // test file = /Users/alliancesoftwareinc/Library/Application Support/iPhone Simulator/5.0/Applications/254C18ED-8816-4646-B62D-880300D4EC0D/Documents/testFile.txt var file; $(function(){$('#fileTest input[type="button"]:not(".initButton")').attr('disabled', 'disabled');}); function initSuccess(result) { fileReader = new FileReader(file); fileWriter = new FileWriter(file); $('#fileTest input[type="button"]:not(".initNotRequired")').removeAttr('disabled'); }; function initError(error) { fileReader = fileWriter = null; $('#fileTest input[type="button"]:not(".initNotRequired")').attr('disabled', 'disabled'); }; function initFile() { file = new File($('#fileDir').val(), $('#filename').val(), initSuccess, initError); $('#fileTest .initNotRequired').removeAttr('disabled'); } function onclickFileCreate() { file.create(function(){alert('create ok @' + file.fullPath);initSuccess();}, function(errCode){alert('create error: ' + errCode);initError(errCode)}); } function onclickFileIsFile() { alert(file.isFile() ? 'Is a file' : 'Not a file'); } function onclickFileIsDirectory() { alert(file.isDirectory() ? 'Is a directory' : 'Not a directory'); } function onclickFileCopy() { file.copy($('#copyMoveDir').val(), $('#newFilename').val(), function(){alert('copy ok');}, function(errCode){alert('Copy error: ' + errCode);}); } function onclickFileMove() { file.move($('#copyMoveDir').val(), $('#newFilename').val(), function(){alert('move ok ' + file.parentPath);}, function(errCode){alert('Move error: ' + errCode);}); } function onclickFileDelete() { file.remove(function(){alert('delete ok' + file.parentPath); $('#fileTest input[type="button"]:not(".initNotRequired")').attr('disabled', 'disabled'); }, function(errCode){alert('Delete error: ' + errCode);}); } var fileReader; function onclickFileReaderRead() { if(!fileReader) { fileReader = new FileReader(file); } fileReader.read(null, function(data){$('#readData').val(decodeURIComponent(data));}, function(errCode){alert('Read error: ' + errCode);}); } //var emptyFile = new File('documents://ztestFolder/', 'empty.txt'); var fileWriter; function onclickFileWriterWrite() { if(!fileWriter) { fileWriter = new FileWriter(file); } fileWriter.write($('#fileInputData').val(), function(data){$('#seekData').val(data.size);}, function(errCode){alert('Write error: ' + errCode);}); } function onclickFileWriterSeek() { fileWriter.seek($('#seekData').val()); } /* * Encryption * * */ var encrypt = function() { var successCallback = function(data) { $('#encOutputData').val(data.encText); }; var errorCallback = function(error) { alert('Error: ' + error.msg); }; var data = $('#encInputData').val(); if(data.length > 0) { Encryptor.encrypt(data, successCallback, errorCallback); } }; var decrypt = function() { var successCallback = function(data) { $('#encOutputData').val(data.decText); }; var errorCallback = function(error) { alert('Error: ' + error.msg); }; var data = $('#encInputData').val(); if(data.length > 0) { Encryptor.decrypt(data, successCallback, errorCallback); } }; var swap = function() { $('#encInputData').val($('#encOutputData').val()); $('#encOutputData').val(''); } /* * Notification * * */ var notificationTime; $(function(){ var dateNow = new Date(); notificationTime = $('#notificationTime'); notificationTime.datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss', beforeShow: function(input, inst) { if(!isWindows) { var offset = notificationTime.offset(); inst.dpDiv.css({marginTop: offset.top-100 + 'px'}); } notificationTime.datepicker('setTime', new Date()); }, hour: dateNow.getHours(), hourGrid: 3, minute: dateNow.getMinutes(), minuteGrid: 10, second: dateNow.getSeconds(), showSecond: true, secondGrid: 10, addSliderAccess: true, sliderAccessArgs: { touchonly: false } }); $('#hasAction').change(function(event) { if(!$('#hasAction').is(':checked')) { $('#action').attr('disabled', 'disabled'); } else { $('#action').removeAttr('disabled'); } }); }); var setNotification = function() { var successCallback = function() { alert('Success: Notification set'); }; var errorCallback = function() { alert('Error: Notification not set'); }; var options = { badge: $('#notificationBadge').val(), hasAction: $('#hasAction').is(':checked'), action: $('#action').val() }; Notification.notify( notificationTime.val(), $('#notificationMsg').val(), successCallback, errorCallback, options ); }; var cancelNotification = function() { Notification.cancelNotification(notificationTime.val(), function() { alert('Notification cancelled'); }, function() { alert('Cancel notification error'); }); }; var showLoadingScreen = function(flag) { if(flag == null || flag) { var label = $('#loadingText').val(); var style = $("#style option:selected").val(); var posX = $('#posX').val(); var posY = $('#posY').val(); var pos = null; if(isNumber(posX) && isNumber(posY)) { pos = {x:posX, y:posY}; } var frame = null; var frameX = $('#frameX').val(); var frameY = $('#frameY').val(); var frameWidth = $('#frameWidth').val(); var frameHeight = $('#frameHeight').val(); if(isNumber(frameX) && isNumber(frameY) && isNumber(frameWidth) && isNumber(frameHeight)) { frame = {x:frameX, y:frameY, width:frameWidth, height:frameHeight}; } LoadingScreen.startLoad( function() { var duration = $('#stopAfter').val()*1000; setTimeout(LoadingScreen.stopLoad, duration);//hideLoadingScreen(); }, function() { alert('error'); }, { label:label, style:style, pos:pos, frame:frame, isBlackBackground:$('#isBlackBackground').is(':checked') }); } else { LoadingScreen.stopLoad(); } }; function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /* * Cache * * */ var cacheScroll; function refreshCacheList() { var cacheList = Cache.getList(); var cacheTable = $('#cacheDiv'); cacheTable.html(''); cacheTable.css('height', cacheList.length * 72 + 'px'); for(var i=0; i<cacheList.length; i++) { var obj = cacheList[i]; cacheTable.append('ID: ' + obj.id + '<br />' + 'Data: ' + obj.data + '<br />' + 'ExpireDate: ' + obj.expireDate + '<br />' + '<a href="#" onclick="removeCacheData(\''+obj.id+'\');return false;">Delete</a>' + '<br /><br />'); /*cacheTable.append('<br/>'+JSON.stringify(obj)+ '<span style="text-decoration:underline" onclick="removeCacheData(\''+obj.id+'\');">Delete</span>');*/ } cacheScroll.refresh(); } function saveCacheData() { Cache.addData( $('#cacheDataInput').val(), $('#expireDate').val(), function(){ refreshCacheList(); $('#cacheDataInput').val(''); $('#expireDate').val(''); }, function(){alert('error');} ); } function removeCacheData(id) { Cache.removeData(id, function() {refreshCacheList();},function() {alert('error');}); return false; } function resetDataCache() { Cache.resetDataCache(function(){refreshCacheList();}, function(){alert('error');}); } $(function(){ cacheScroll = new iScroll('wrapperCache1', { hScrollbar: false, vScrollbar: false, checkDOMChanges: false }); resourceScroll = new iScroll('wrapperCache2', { hScrollbar: false, vScrollbar: false, checkDOMChanges: true }); $('#expireDate').datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss', showSecond: true, hourGrid: 3, minuteGrid: 10, secondGrid: 10 }); $('#resourceExpireDate').datetimepicker({ dateFormat: 'yy-mm-dd', timeFormat: 'hh:mm:ss', showSecond: true, hourGrid: 3, minuteGrid: 10, secondGrid: 10 }); }); function addResource() { LoadingScreen.startLoad(function() { Cache.addResource($('#resourceURL').val(), $('#resourceExpireDate').val(), function(result) { showResourceCache(); LoadingScreen.stopLoad(); }, function() { LoadingScreen.stopLoad(); alert('error'); }); }); } function getResource(id) { LoadingScreen.startLoad(function() { Cache.updateResource(id, $('#resourceExpireDate').val(), function(result) { showResourceCache(); LoadingScreen.stopLoad(); }, function() { LoadingScreen.stopLoad(); alert('error'); }); }); } function showResourceCache() { var cacheList = Cache.getResourceList(); var cacheTable = $('#cacheResourceDiv'); cacheTable.html(''); cacheTable.css('height', cacheList.length * 76 + 'px'); for(var i=0; i<cacheList.length; i++) { var obj = cacheList[i]; cacheTable.append(JSON.stringify(obj) + '<br />' + '<a href="#" onclick="removeResourceData(\''+obj.id+'\');return false;">Delete</a>' + '<br />' + '<a href="#" onclick="getResource(\''+obj.id+'\');return false;">Get Resource</a>' + '<br /><br />'); } resourceScroll.refresh(); } function removeResourceData(id) { Cache.removeResource(id, function() {showResourceCache();},function(errCode) {alert('error: ' + errCode);}); return false; } function resetResourceCache() { Cache.resetResourceCache(function(){showResourceCache()}, function(){alert('error');}); } /* * QR Code Reader * * */ function qrReaderSuccessCallback(data) { $('#qrReaderResult').html(data); } function qrReaderErrorCallback(error) { alert('QR Code Error: '+error); } function qrReaderScan(_source) { QRReader.read(qrReaderSuccessCallback, qrReaderErrorCallback, {source: _source}); } /* * Database * * */ var db; function initDb() { var successCallback = function() { alert('Database init success'); }; var errorCallback = function(error) { alert('Database init error: ' + error); }; db = new Database($('#dbName').val(), successCallback, errorCallback); } function dbExecuteQuery() { if(!db) { return; } var successCallback = function(result) { var res = '[]'; if(result.length > 0) { res = '['; for(var i=0;i<result.length;i++) { var item = '{'; for(var one in result[i]) { item += '"' + one + '":"' + result[i][one] + '",'; } res += item.slice(0, -1) + '},'; } res = res.slice(0, -1) + ']'; } alert('Result: ' + res); }; var errorCallback = function(error) { alert('Database query error: ' + error); }; var sql = $('#dbSQL').val(); db.executeSQL(sql, null, successCallback, errorCallback); } function dbBeginTrans() { if(!db) { return; } var successCallback = function() { alert('Begin Transaction OK'); }; var errorCallback = function(error) { alert('Database query error: ' + error); }; db.begin(successCallback, errorCallback); } function dbCommit() { if(!db) { return; } var successCallback = function() { alert('Commit OK'); }; var errorCallback = function(error) { alert('Database query error: ' + error); }; db.commit(successCallback, errorCallback); } function dbRollback() { if(!db) { return; } var successCallback = function() { alert('Rollback OK'); }; var errorCallback = function(error) { alert('Database query error: ' + error); }; db.rollback(successCallback, errorCallback); } /* * AddressBook * * */ function showAddressBook(isSelect) { if(isSelect) { AddressBook.showForSelection( function(data){ var stringified = JSON.stringify(data); stringified = unescape(stringified.replace(/\\u/g, '%u')); $('#addressBookData').html(stringified); }, function(message){ alert('Error: ' + message); }); } else { AddressBook.show( function(){ alert('Success'); }, function(message){ alert('Error: ' + message); }); } } /* * Contacts * * */ var contactsContact = null var contactsSearchResult = null; function contactsCreate() { contactsContact = Contacts.create(); $('.contactsCreate').prop('disabled', false); } function contactsSearch() { var conditions = new Array(); var sc = $('#contactsSearchConditions .searchCondition'); if(sc.length == 0) { return; } for(var i=0;i<sc.length;i++) { conditions.push($(sc[i]).children('td:first').text()); } var sort = Contacts.SEARCH_ORDER_ASC; var searchSuccess = function(contacts) { contactsSearchResult = contacts; var r = $('#contactsSearchResult'); if(contactsSearchResult.length > 0) { for(var i=0;i<contactsSearchResult.length;i++) { r.append('<tr style="background-color:#FFF" class="contactsSRRow"><td>&nbsp;' + contactsSearchResult[i].id + '</td></tr>'); } } else { r.append('<tr style="background-color:#FFF" class="contactsSRRow"><td>&nbsp;No results.</td></tr>'); } }; var searchError = function(message) { alert('Error: ' + message); }; $('#contactsSearchResult .contactsSRRow').remove(); Contacts.search(conditions, sort, searchSuccess, searchError); } function contactSave() { var sc = $('#contactsCreateData .createOption'); if(sc.length == 0) { return; } //{addresses:[{homeLabel:{country:, city:, street:}}, {workLabel:{country:, city:, street:}}]} for(var i=0;i<sc.length;i++) { var c = $(sc[i]); //tr var key = c.attr('data-key'); var value = {}; var cIsObject = c.attr('data-isobject'); var cIsArray = c.attr('data-isarray'); var cIsMultiVal = c.attr('data-ismultival'); var k = $('[data-key="' +key + '"]'); //all trs with key if(cIsObject || cIsArray) { if(cIsArray) { value = new Array(); } for(var j=0;j<k.length;j++) { var kj = $(k[j]); //tr var kc = kj.children(); //td if(cIsArray) { var temp = {}; if(cIsMultiVal) { var mvLabel = kj.attr('data-mvlabel'); for(var _k in value) { var _kk = null; for(_kk in value[_k]) { }; if(_kk == mvLabel) { temp = value[_k]; value.splice(_k, 1); } } if(!temp[mvLabel]) { temp[mvLabel] = {}; } temp[mvLabel][kj.attr('data-label')] = kc[1].innerHTML; } else if(cIsObject) { temp[kj.attr('data-label')] = kc[1].innerHTML; } else { temp = kc[1].innerHTML; } value.push(temp); } else { value[kj.attr('data-label')] = kc[1].innerHTML; } } } else { var kc = k.children(); //td value = kc[1].innerHTML; } contactsContact[key] = value; } if(contactsContact) { contactsContact.save( function() { contactsContact = null; $('.contactsCreate').prop('disabled', true); $('.contactsCreateAction').click(); alert('Successfully saved contact'); }, function(message){ alert('Error: ' + message); } ); } } function contactRemove() { var removeId = $('#contactsRemoveId').val(); if(removeId.length > 0) { var c = Contacts.create(); c.id = removeId; c.remove( function() { alert('Successfully removed contact'); }, function(message) { alert('Error: ' + message); } ); } } $(function() { var contactProperties; if(isIOS) { contactProperties = [ {key: 'id'}, {key: 'displayName'}, {key: 'name', isObject: true, label: ['firstName', 'firstNamePhonetic', 'lastName', 'lastNamePhonetic', 'middleName', 'middleNamePhonetic', 'nickname', 'prefix', 'suffix']}, {key: 'nickname'}, {key: 'phoneNumbers', isArray: true, isObject: true, label: ['phoneNumbersFax', 'phoneNumbersIPhone', 'phoneNumbersMain', 'phoneNumbersMobile', 'phoneNumbersOtherFax', 'phoneNumbersPager', 'phoneNumbersPhone', 'phoneNumbersWorkFax']}, {key: 'emails', isArray: true, isObject: true, label: ['homeLabel', 'workLabel', 'otherLabel']}, {key: 'addresses', isArray: true, isObject: true, isMultiValue: true, multiValueLabel: ['homeLabel', 'workLabel', 'otherLabel'], label: ['addressesCity', 'addressesCountryCode', 'addressesCountry', 'addressesState', 'addressesStreet', 'addressesZIP'] }, {key: 'ims', isArray: true, isObject: true, label: ['imsAim', 'imsFacebook', 'imsGaduGadu', 'imsGoogleTalk', 'imsICQ', 'imsJabber', 'imsMSN', 'imsQQ', 'imsSkype', 'imsYahoo']}, {key: 'organizations'}, {key: 'birthday'}, {key: 'note'}, {key: 'photo'}, //{key: 'categories'}, {key: 'urls', isArray: true, isObject: true, label: ['homePageLabel', 'homeLabel', 'workLabel', 'otherLabel']}]; } else if(isWindows) { contactProperties = [ {key: 'id'}, {key: 'displayName'}, {key: 'name', isObject: true, label: ['firstName', 'lastName', 'middleName', 'nickname', 'title', 'suffix']}, {key: 'nickname'}, {key: 'phoneNumbers', isArray: true, isObject: true, label: ['home', 'home2', 'homeFax', 'work', 'work2', 'workFax', 'mobile', 'mobile2', 'company']}, {key: 'emails', isArray: true, isObject: true, label: ['personal', 'work', 'other']}, {key: 'addresses', isArray: true, isObject: true, isMultiValue: true, multiValueLabel: ['home', 'work', 'other'], label: ['city', 'country', 'state', 'street', 'zipcode'] }, //{key: 'ims', isArray: true, isObject: true, label: ['imsAim', 'imsFacebook', 'imsGaduGadu', 'imsGoogleTalk', 'imsICQ', 'imsJabber', 'imsMSN', 'imsQQ', 'imsSkype', 'imsYahoo']}, {key: 'organizations', isObject: true, label: ['company', 'jobTitle']}, {key: 'birthday'}, {key: 'note'}, {key: 'photo'}, //{key: 'categories'}, {key: 'urls'}]; } else { contactProperties = [ {key: 'id'}, {key: 'displayName'}, {key: 'name', isObject: true, label: ['givenName', 'familyName', 'middleName', 'prefix', 'suffix']}, {key: 'nickName'}, {key: 'phoneNumbers', isArray: true, isObject: true, label: ['home', 'mobile', 'work', 'workFax', 'homeFax', 'pager', 'other', 'custom', 'callback']}, {key: 'emails', isArray: true, isObject: true, label: ['home', 'mobile', 'work', 'other', 'custom']}, {key: 'addresses', isArray: true, isObject: true, isMultiValue: true, multiValueLabel: ['home', 'other', 'work', 'custom'], label: ['streetAddress', 'locality', 'region', 'postalCode', 'country']}, {key: 'ims', isArray: true, isObject: true, label: ['aim', 'custom', 'googleTalk', 'icq', 'jabber', 'msn', 'netMeeting', 'qq', 'skype', 'yahoo']}, {key: 'organizations', isArray: true, isObject: true, isMultiValue: true, multiValueLabel: ['other', 'work', 'custom'], label: ['department', 'title', 'name']}, {key: 'birthday'}, {key: 'note'}, {key: 'photo'}, //{key: 'categories', isArray: true, isObject: true, label: ['category']}, {key: 'urls', isArray: true, isObject: true, label: ['home', 'custom', 'work', 'blog', 'ftp', 'homepage', 'profile']}]; } var sOptions = $('#contactsSearchOptions'); var sEOptions = $('#contactsSearchExtraOptions'); var cOptions = $('#contactsCreateOptions'); var cEOptions = $('#contactsCreateExtraOptions'); var cMVOptions = $('#contactsCreateMValOptions'); for(var i=0;i<contactProperties.length;i++) { var prop = contactProperties[i]; sOptions.append('<option value="'+prop.key+'" class="sub_'+prop.key+'" ' + ((prop.isObject) ? 'data-isobject="true"' : '') + ((prop.isArray) ? 'data-isarray="true"' : '') + '>' + prop.key + '</option>'); if(prop.key == 'displayName' && isIOS) { continue; } cOptions.append('<option value="'+prop.key+'" class="sub_'+prop.key+'" ' + ((prop.isObject) ? 'data-isobject="true"' : '') + ((prop.isMultiValue) ? 'data-ismultival="true"' : '') + ((prop.isArray) ? 'data-isarray="true"' : '') + '>' + prop.key + '</option>'); if(prop.label) { for(var j=0;j<prop.label.length;j++) { if(!prop.isArray) { sEOptions.append('<option value="'+prop.label[j]+'" class="sub_'+prop.key+'">' +prop.label[j]+ '</option>'); } cEOptions.append('<option value="'+prop.label[j]+'" class="sub_'+prop.key+'">' +prop.label[j]+ '</option>'); } } if(prop.multiValueLabel) { for(var j=0;j<prop.multiValueLabel.length;j++) { cMVOptions.append('<option value="'+prop.multiValueLabel[j]+'" class="sub_'+prop.key+'">' +prop.multiValueLabel[j]+ '</option>'); } } } cascadeSelect(cOptions, cEOptions); cascadeSelect(cOptions, cMVOptions); cascadeSelect(sOptions, sEOptions); cOptions.change(function(e) { var s = $(this).children('option:selected').val(); if(s == 'photo') { $('#contactsCreatePicOpt').show(); } else { $('#contactsCreatePicOpt').hide(); } /*if(s == 'addresses') { $('.mValForm').show(); } else { $('.mValForm').hide(); }*/ }); $('#contactsCreatePicOpt').click(function() { var successCallback = function(imgData) { $('#contactsCreateValue').val(imgData); $('#contactsAddCreateOpt').click(); }; var errorCallback = function() {}; var options = { quality: 50, destinationType: Camera.DestinationType.FILE_URI, //DATA_URL, sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM, encodingType: Math.round(Math.random()) }; Camera.getPicture(successCallback, errorCallback, options); }); // search $('#contactsAddCondition').click(function() { var o = $('#contactsSearchOptions option:selected'); var oe = $('#contactsSearchExtraOptions option:selected'); var c = $('#contactsSearchCond option:selected').val(); var v = $('#contactsSearchValue').val(); var id = 'searchOpt' + o.val() + (oe.length > 0 ? oe.val() : ''); if(o.length > 0 && v.length > 0) { if($('.searchCondition#'+id).length > 0) { if(!o.attr('data-isarray')) { $('.searchCondition#'+id).remove(); } } $('#contactsSearchConditions').append('<tr class="searchCondition" style="background-color:#FFF" id="'+id+'" data-key="'+o.val()+'" ' + ((o.attr('data-isobject')) ? 'data-isobject="true" ' : '') + ((o.attr('data-isarray')) ? 'data-isarray="true" ' : '') + ((oe.val()) ? ('data-label="' + oe.val() + '"') : '') + '>' + '<td>' + ((oe.val()) ? oe.val() : o.val()) + ' ' + c + ' ' + v + '</td>' + '<td style="text-align:center"><input type="button" class="contactsConditionAction" value="-"></td>' + '</tr>'); } }); $('#contactsSearchConditions').on('click', '.contactsConditionAction', function() { var p = $(this).parents('tr'); p.remove(); }); $('#contactsSearchResult').on('click', 'td', function() { var index = $(this).parent().index(); if(index > 0) { alert(JSON.stringify(contactsSearchResult[index-1])); } }); // create $('.contactsCreate').prop('disabled', true); $('#contactsAddCreateOpt').click(function() { var o = $('#contactsCreateOptions option:selected'); var om = $('#contactsCreateMValOptions option:selected'); var oe = $('#contactsCreateExtraOptions option:selected'); var v = $('#contactsCreateValue').val(); var id = 'createOpt' + o.val() + (om.length > 0 ? om.val() : '') + (oe.length > 0 ? oe.val() : ''); if(o.length > 0 && v.length > 0) { if($('.createOption#'+id).length > 0) { if(!o.attr('data-isarray') || o.attr('data-ismultival')) { $('.createOption#'+id).remove(); } } $('#contactsCreateData').append('<tr class="createOption" style="background-color:#FFF" id="'+id+'" data-key="'+o.val()+'" ' + ((o.attr('data-isobject')) ? 'data-isobject="true" ' : '') + ((o.attr('data-isarray')) ? 'data-isarray="true" ' : '') + ((o.attr('data-ismultival')) ? 'data-ismultival="true" ' : '') + ((oe.val()) ? ('data-label="' + oe.val() + '"') : '') + ((om.val()) ? ('data-mvlabel="' + om.val() + '"') : '') + '>' + '<td>'+o.val() + (om.val() ? ('<br />&nbsp&nbsp[' + om.val() + ']'): '') + ((oe.val()) ? ('<br />&nbsp&nbsp' + oe.val()) : '') + '</td>' + '<td style="max-width:100px;overflow:hidden;word-wrap:break-word;">'+v+'</td>' + '<td style="text-align:center"><input type="button" class="contactsCreateAction" value="-"></td>' + '</tr>'); } $('#contactsCreateValue').val(''); }); $('#contactsCreateData').on('click', '.contactsCreateAction', function() { var p = $(this).parents('tr'); p.remove(); }); }); /* * Bluetooth * * */ var disconnectedPeer; function btDiscover() { disconnectedPeer = null ; if (isWindows) { var btPeerList = $('#btPeerList'); btPeerList.html('<div id="noPeersText" style="padding:3px;">Looking for peers...</div>'); } Bluetooth.discover(); btShowModal(); } Bluetooth.onStateChanged = (function(deviceName, id, state) { var orig = Bluetooth.onStateChanged; return function(deviceName, id, state) { orig(deviceName, id, state); var btPeerList = $('#btPeerList'); var btModal = $('#btModal'); var rowId = id.replace(/:/g,""); $('#btPeerList #btPeer' + rowId).remove(); var rowHtml = ''; if(state == Bluetooth.STATE_AVAILABLE) { if(btModal.is(':hidden') && id != disconnectedPeer) { btShowModal(); } rowHtml = '<div id="btPeer'+rowId+'" style="" onclick="Bluetooth.connect({id:\''+id+'\',deviceName:\''+deviceName+'\',state:'+state+'}, btConnectSuccess, btConnectError)">'+deviceName+'('+id+')'+'</div>'; } else if(state == Bluetooth.STATE_CONNECTING) { rowHtml = '<div id="btPeer'+rowId+'" style="background-color:gray;color:lightgray">Attempting connection to '+deviceName+'('+id+')'+'</div>'; } else if(state == Bluetooth.STATE_CONNECTED) { rowHtml = '<div id="btPeer'+rowId+'" style="background-color:gray;">'+deviceName+'('+id+')'+'</div>'; if(btModal.is(':visible')) { btHideModal(); } } else if(state == Bluetooth.STATE_DISCONNECTED) { disconnectedPeer = id; } btPeerList.append(rowHtml); if(Bluetooth.peerList.length == 0 || btPeerList.children(':not(#noPeersText)').length == 0) { btPeerList.html('<div id="noPeersText" style="padding:3px;">Looking for peers...</div>'); } else { $('#noPeersText').remove(); } btUpdatePeerList(); } })(); function btConnectSuccess() { alert('Successfully connected to peer.'); } function btConnectError() { alert('Error connecting to peer.'); } function btUpdatePeerList() { $('#btTestPeerList tr:not(.peerListHeader)').remove(); for(var i=0; i<Bluetooth.peerList.length; i++) { var state = Bluetooth.peerList[i].state; var peerListHtml = '<tr class="peerItem">' + '<td style="word-wrap:break-word">' + Bluetooth.peerList[i].id + '</td>' + '<td style="word-wrap:break-word">' + Bluetooth.peerList[i].deviceName + '</td>' + '<td>' + state + '</td>'; if(state == Bluetooth.STATE_AVAILABLE) { peerListHtml += '<td><input type="button" value="Connect"/></td>'; } else if(state == Bluetooth.STATE_CONNECTED) { peerListHtml += '<td style="text-align:left">' + '<input type="button" value="Disconnect"/><br />' + '<input type="button" value="Send" style="margin-top:5px;"/><br />' + '<input type="button" value="Send Image" style="margin-top:5px;"/></td>'; } else { peerListHtml += '<td>&nbsp;</td>'; } peerListHtml += '</tr>'; if (isWindows) { if (state != Bluetooth.STATE_AVAILABLE && state != Bluetooth.STATE_CONNECTING) { $('#btTestPeerList').append(peerListHtml); } } else { $('#btTestPeerList').append(peerListHtml); } } } var btImage, btText; $(function() { $('#btTestPeerList').on('click', 'input', function(){ var td = $(this).parent().siblings('td'); var inputVal = $(this).val(); var peerData = {id: $(td[0]).html(), deviceName: $(td[1]).html(), state: $(td[2]).html()}; if(inputVal == 'Connect') { Bluetooth.connect( peerData, function() { alert('Successfully connected to peer.'); btUpdatePeerList(); }, function() { alert('Error connecting to peer'); } ); } else if(inputVal == 'Disconnect') { Bluetooth.disconnect( peerData, function() { alert('Successfully disconnected from peer.'); }, function() { alert('Error disconnected from peer'); } ); } else if(inputVal == 'Send') { Bluetooth.send( peerData, $('#btMessage').val(), function() { alert('Successfully sent message.'); }, function() { alert('Error sending message.'); } ); } else if(inputVal == 'Send Image') { var successCallback = function(data) { Bluetooth.send( peerData, data, function() { alert('Successfully sent image data.'); }, function() { alert('Error sending image.'); } ); }; var errorCallback = function(error) { alert(error); }; var options = { quality: 30, destinationType: Camera.DestinationType.DATA_URL, sourceType : Camera.PictureSourceType.CAMERA, encodingType: Camera.EncodingType.JPEG }; Camera.getPicture(successCallback, errorCallback, options); } }); $('#btImage') .load(function() { $(this).show(); }) .error(function(){ $(this).hide(); }); }); function btShowModal() { $('#btModal').dialog({ modal: true, dialogClass: 'noTitleDialog', resizable: false }); } function btHideModal() { $('#btModal').dialog("close"); } Bluetooth.onRecvCallback = function(peerData, receiveData) { $('#btMessage').val('Message from ' + peerData.deviceName + '(' + peerData.id + '):\n' + receiveData); $('#btImage').attr('src', receiveData); } /* * Bluetooth 4 LE * * */ var bt4LEdisconnectedPeer; function bt4LEScanDevices() { bt4LEdisconnectedPeer = null; var selectedServices = $('#serviceMultiList option:selected'); var services = new Array(); for(var i=0; i<selectedServices.length; i++) { services[i] = selectedServices[i].value; } Bluetooth4LE.scanDevices(services); bt4LEShowModal(); } Bluetooth4LE.onStateChanged = (function(deviceName, id, state) { var orig = Bluetooth4LE.onStateChanged; return function(deviceName, id, state) { orig(deviceName, id, state); var bt4LEPeripheralList = $('#bt4LEPeripheralList'); var bt4LEModal = $('#bt4LEModal'); var rowId = id.replace(/:/g,""); $('#bt4LEPeripheralList #bt4LEPeripheral' + rowId).remove(); var rowHtml = ''; if(state == Bluetooth4LE.STATE_AVAILABLE || state == Bluetooth4LE.STATE_CONNECTING) { if(bt4LEModal.is(':hidden') && id != disconnectedPeer) { bt4LEShowModal(); } rowHtml = '<div id="bt4LEPeripheral'+rowId+'" style="" onclick="Bluetooth4LE.connect({id:\''+id+'\',deviceName:\''+deviceName+'\',state:'+state+'}, bt4LEConnectSuccess, bt4LEConnectError)">'+deviceName+'('+id+')'+'</div>'; } else if(state == Bluetooth4LE.STATE_CONNECTED) { rowHtml = '<div id="bt4LEPeripheral'+rowId+'" style="background-color:gray;">'+deviceName+'('+id+')'+'</div>'; if(bt4LEModal.is(':visible')) { bt4LEHideModal(); } } else if(state == Bluetooth4LE.STATE_DISCONNECTED) { bt4LEdisconnectedPeer = id; } bt4LEPeripheralList.append(rowHtml); if(Bluetooth4LE.peripheralList.length == 0 || bt4LEPeripheralList.children(':not(#noPeripheralsText)').length == 0) { bt4LEPeripheralList.html('<div id="noPeripheralsText" style="padding:3px;">Looking for peripherals...</div>'); } else { $('#noPeripheralsText').remove(); } bt4LEUpdatePeripheralList(); } })(); function bt4LEConnectSuccess() { alert('Successfully connected to peripheral.'); } function bt4LEConnectError() { $('#bt4LEPeripheralList [id^="bt4LEPeripheral"]').remove(); bt4LEHideModal(); alert('Error connecting to peripheral.'); } function bt4LEUpdatePeripheralList() { $('#bt4LETestPeripheralList tr:not(.peripheralListHeader)').remove(); for(var i=0; i<Bluetooth4LE.peripheralList.length; i++) { var state = Bluetooth4LE.peripheralList[i].state; var peripheralListHtml = '<tr class="peripheralItem">' + '<td>' + Bluetooth4LE.peripheralList[i].id + '</td>' + '<td>' + Bluetooth4LE.peripheralList[i].deviceName + '</td>' + '<td>' + state + '</td>'; if(state == Bluetooth.STATE_AVAILABLE) { peripheralListHtml += '<td><input type="button" value="Connect"/></td>'; } else if(state == Bluetooth.STATE_CONNECTED) { peripheralListHtml += '<td style="text-align:left">' + 'Characteristic: <br />' + '<input type="button" value="Write" style="margin-top:5px;" class="characteristic"/>' + '<input type="button" value="Read" style="margin-top:5px;" class="characteristic"/><br />' + 'Descriptor: <br />' + '<input type="button" value="Write" style="margin-top:5px;" class="descriptor"/>' + '<input type="button" value="Read" style="margin-top:5px;" class="descriptor"/><br />' + '<input type="button" value="Disconnect" style="margin-top:5px;"/></td>'; } else { peripheralListHtml += '<td>&nbsp;</td>'; } peripheralListHtml += '</tr>'; $('#bt4LETestPeripheralList').append(peripheralListHtml); } } $(function() { $('#bt4LETestPeripheralList').on('click', 'input', function(){ var td = $(this).parent().siblings('td'); var inputVal = $(this).val(); var peipheralData = {id: $(td[0]).html(), deviceName: $(td[1]).html(), state: $(td[2]).html()}; if(inputVal == 'Connect') { Bluetooth4LE.connect( peipheralData, function() { alert('Successfully connected to peer.'); bt4LEUpdatePeripheralList(); }, function() { alert('Error connecting to peer'); } ); } else if(inputVal == 'Disconnect') { Bluetooth4LE.disconnect( peipheralData, function() { alert('Successfully disconnected from peer.'); }, function() { alert('Error disconnected from peer'); } ); } else { var peripheral = new Peripheral(peipheralData.deviceName, peipheralData.id); var inputClass = $(this).attr('class'); if(inputClass == 'characteristic') { if(inputVal == 'Read') { peripheral.readValueForCharacteristic( $('#serviceList option:selected').val(), $('#characteristicList option:selected').val(), $('#characteristicVTypeList option:selected').val(), function(value) { alert('Successfully read characteristic value: ' + value); }, function() { alert('Error reading characteristic value.'); } ); } else if(inputVal == 'Write') { peripheral.writeValueForCharacteristic( $('#characteristicValue').val(), $('#characteristicVTypeList option:selected').val(), $('#serviceList option:selected').val(), $('#characteristicList option:selected').val(), $('#characteristicWriteType input:radio:checked').val(), function() { alert('Successfully written value to characteristic'); }, function() { alert('Error writing value to characteristic'); } ); } } else if(inputClass == 'descriptor') { if(inputVal == 'Read') { peripheral.readValueForDescriptor( $('#serviceList option:selected').val(), $('#characteristicList option:selected').val(), $('#descriptorList option:selected').val(), $('#descriptorVTypeList option:selected').val(), function(value) { alert('Successfully read descriptor value: ' + value); }, function() { alert('Error reading descriptor value.'); } ); } else if(inputVal == 'Write') { peripheral.writeValueForDescriptor( $('#descriptorValue').val(), $('#descriptorVTypeList option:selected').val(), $('#serviceList option:selected').val(), $('#characteristicList option:selected').val(), $('#descriptorList option:selected').val(), function() { alert('Successfully written value to descriptor'); }, function() { alert('Error writing value to descriptor'); } ); } } } }); var services = [ {label: "SERVICE_BATTERY_SERVICE", value: Bluetooth4LE.SERVICE_BATTERY_SERVICE}, {label: "SERVICE_IMMEDIATE_ALERT", value: Bluetooth4LE.SERVICE_IMMEDIATE_ALERT} ]; var characteristics = [ {label: "ALERT_LEVEL", value: Bluetooth4LE.CHARACTERISTICS_ALERT_LEVEL, parent: Bluetooth4LE.SERVICE_IMMEDIATE_ALERT}, {label: "BATTERY_LEVEL", value: Bluetooth4LE.CHARACTERISTICS_BATTERY_LEVEL, parent: Bluetooth4LE.SERVICE_BATTERY_SERVICE} ]; var characteristicValueTypes = [ {label: "VALUE_TYPE_UINT8", value: Bluetooth4LE.VALUE_TYPE_UINT8, parent: Bluetooth4LE.CHARACTERISTICS_ALERT_LEVEL}, {label: "VALUE_TYPE_UINT8", value: Bluetooth4LE.VALUE_TYPE_UINT8, parent: Bluetooth4LE.CHARACTERISTICS_BATTERY_LEVEL} ]; var descriptors = [ {label: "CHARACTERISTIC_PRESENTATION_FORMAT", value: Bluetooth4LE.DESCRIPTORS_CHARACTERISTIC_PRESENTATION_FORMAT, parent: Bluetooth4LE.CHARACTERISTICS_BATTERY_LEVEL}, {label: "CLIENT_CHARACTERISTIC_CONFIGURATION", value: Bluetooth4LE.DESCRIPTORS_CLIENT_CHARACTERISTIC_CONFIGURATION, parent: Bluetooth4LE.CHARACTERISTICS_BATTERY_LEVEL} ]; var descriptorValueTypes = [ {label: "VALUE_TYPE_8BIT", value: Bluetooth4LE.VALUE_TYPE_8BIT, parent: Bluetooth4LE.DESCRIPTORS_CHARACTERISTIC_PRESENTATION_FORMAT}, {label: "VALUE_TYPE_SINT8", value: Bluetooth4LE.VALUE_TYPE_UINT8, parent: Bluetooth4LE.DESCRIPTORS_CHARACTERISTIC_PRESENTATION_FORMAT}, {label: "VALUE_TYPE_UINT16", value: Bluetooth4LE.VALUE_TYPE_UINT16, parent: Bluetooth4LE.DESCRIPTORS_CHARACTERISTIC_PRESENTATION_FORMAT}, {label: "VALUE_TYPE_16BIT", value: Bluetooth4LE.VALUE_TYPE_16BIT, parent: Bluetooth4LE.DESCRIPTORS_CHARACTERISTIC_PRESENTATION_FORMAT}, {label: "VALUE_TYPE_16BIT", value: Bluetooth4LE.VALUE_TYPE_16BIT, parent: Bluetooth4LE.DESCRIPTORS_CLIENT_CHARACTERISTIC_CONFIGURATION} ]; var sMultiList = $('#serviceMultiList'); for(var service in services) { var s = services[service]; sMultiList.append('<option value="'+s.value+'" selected="selected">'+s.label+'</option>'); } var sList = $('#serviceList'); for(var service in services) { var s = services[service]; sList.append('<option value="'+s.value+'" selected="selected" class="sub_'+s.value+'">'+s.label+'</option>'); } var cList = $('#characteristicList'); for(var characteristic in characteristics) { var c = characteristics[characteristic]; cList.append('<option value="'+c.value+'" class="sub_'+c.parent+'">'+c.label+'</option>'); } var cVList = $('#characteristicVTypeList'); for(var characteristicValueType in characteristicValueTypes) { var v = characteristicValueTypes[characteristicValueType]; cVList.append('<option value="'+v.value+'" class="sub_'+v.parent+'">'+v.label+'</option>'); } var dList = $('#descriptorList'); for(var descriptor in descriptors) { var d = descriptors[descriptor]; dList.append('<option value="'+d.value+'" class="sub_'+d.parent+'">'+d.label+'</option>'); } var dVList = $('#descriptorVTypeList'); for(var descriptorValueType in descriptorValueTypes) { var v = descriptorValueTypes[descriptorValueType]; dVList.append('<option value="'+v.value+'" class="sub_'+v.parent+'">'+v.label+'</option>'); } cascadeSelect(sMultiList, sList, true); cascadeSelect(sList, cList); cascadeSelect(cList, cVList); cascadeSelect(cList, dList); cascadeSelect(dList, dVList); sMultiList.change(); }); function cascadeSelect(parent, child, isMulti){ var childOptions = child.find('option:not(.static)'); child.data('options',childOptions); parent.change(function(){ childOptions.remove(); if(isMulti) { parent.children('option:selected').each(function(){ child .append(child.data('options').filter('.sub_' + this.value)) .change(); }); } else { child .append(child.data('options').filter('.sub_' + this.value)) .change(); } }); childOptions.not('.static, .sub_' + parent.val()).remove(); } function bt4LEShowModal() { $('#bt4LEModal').dialog({ modal: true, dialogClass: 'noTitleDialog', resizable: false }); } function bt4LEHideModal() { $('#bt4LEModal').dialog("close"); } /* * Felica * */ function felicaGetIdM() { var successCallback = function(idM) { alert('Manufacturer Id: ' + idM); }; var errorCallback = function() { alert('Error retreiving manufacturer id.'); }; Felica.getIdM(successCallback, errorCallback); } function felicaGetPMm() { var successCallback = function(pMm) { alert('Manufacturer: ' + pMm); }; var errorCallback = function() { alert('Error retreiving manufacturer.'); }; Felica.getPMm(successCallback, errorCallback); } function felicaSystemCode() { var successCallback = function(systemCodes) { alert('System codes: ' + systemCodes); }; var errorCallback = function() { alert('Error retreiving system codes.'); }; Felica.requestSystemCode(successCallback, errorCallback); } function felicaServiceCode() { var successCallback = function(serviceCodes) { alert('Service codes: ' + serviceCodes); var options = ''; for(var i=0; i<serviceCodes.length; i++) { options += '<option>' + serviceCodes[i] + '</option>'; } $('#felicaServiceCodes').html(options); options = ''; for(var i=0; i<10; i++) { options += '<option>' + i + '</option>'; } $('#felicaAddress').html(options); }; var errorCallback = function() { alert('Error retreiving service codes.'); }; Felica.requestServiceCode(successCallback, errorCallback); } function felicaResponse() { var successCallback = function(response) { alert('Response: ' + response); }; var errorCallback = function() { alert('Error retreiving response.'); }; Felica.requestResponse(successCallback, errorCallback); } function felicaRead() { var successCallback = function(blockData) { $('#felicaData').val(blockData); }; var errorCallback = function() { alert('Error retreiving response.'); }; Felica.readWithoutEncryption( $('#felicaServiceCodes').children('option:selected').html(), $('#felicaAddress').children('option:selected').html(), successCallback, errorCallback); } function felicaWrite() { var successCallback = function() { alert('Successfully written data to card.'); }; var errorCallback = function() { alert('Error writing data to card.'); }; Felica.writeWithoutEncryption( $('#felicaServiceCodes').children('option:selected').html(), $('#felicaAddress').children('option:selected').html(), $('#felicaData').val(), successCallback, errorCallback); } /* * PDFViewer * */ function pdfShow() { var path = $('#pdfPath').val(); alert(path + ' ' + path.length + $('.pdfViewerType:checked').val()); if(path.length > 0) { switch(parseInt($('.pdfViewerType:checked').val())) { case 1: // file object var f; var _s = function(s) { alert(f.fullPath); PDFViewer.showWithFileObject(f); }; var _e = function(e) { alert('Error showing pdf file'); }; var _f = path.split('/').reverse()[0]; var _p = path.replace(_f, '').replace(/\/$/,''); //_p = 'media_resources'; //_p = ''; //alert(_p.replace('/', '')); var f = new File(_p, _f, _s, _e); break; case 2: // file path PDFViewer.showWithFilePath(path); break; case 3: // url PDFViewer.showWithURL(path); break; } } } $(function() { $('.pdfViewerType').change(function() { switch(parseInt($('.pdfViewerType:checked').val())) { case 1: $('#pdfPath').val('media_resources/sample.pdf'); break; case 2: $('#pdfPath').val('sample2.pdf'); break; case 3: $('#pdfPath').val('http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf'); break; } }); $('.pdfViewerType:first').prop('checked', true); }); $(document).ready(function(){ $("#secmain").height(screen.height); }); /* * Ads * */ var adButton, adStatus, adStatusLbl; var AD_STATUS_HIDDEN = 0, AD_STATUS_VISIBLE = 1; $(function () { adButton = $('#adButton'); adStatus = -1; adStatusLbl = $('#adStatus'); adStatusLbl.html(); adButton.click(function(event) { var action = $(this).val(); if (action == 'show') { showAd(); } else if(action == 'hide') { hideAd(); } else if(action == 'create') { createAd(); } }); }); function createAd() { var successCallback = function() { if(adStatus == -1) { $("html, body").animate({ scrollTop: $(document).height() }, "slow"); adStatus = AD_STATUS_VISIBLE; adStatusLbl.html('Ad is created.'); adButton.val('hide'); adButton.removeAttr('disabled'); } showAd(); }; var errorCallback = function() { if(adStatus == -1) { adStatusLbl.html('Failed to create and load ad.'); adButton.val('create'); adButton.removeAttr('disabled'); return; } hideAd(); }; var options = {id: "", appId: ""}; adStatusLbl.html('Creating ad banner.'); adButton.attr('disabled', 'disabled'); //Ad.create(Ad.POSITION_TOP, successCallback, errorCallback, options); Ad.create(Ad.POSITION_BOTTOM, successCallback, errorCallback, options); } function showAd() { if(adStatus == AD_STATUS_HIDDEN) { var successCallback = function() { $("html, body").animate({ scrollTop: $(document).height() }, "slow"); adStatus = AD_STATUS_VISIBLE; adStatusLbl.html('Ad is shown.'); adButton.val('hide'); }; var errorCallback = function() { adStatusLbl.html('Failed to show Ad.'); adButton.val('show'); }; Ad.show(successCallback, errorCallback); } } function hideAd() { if(adStatus == AD_STATUS_VISIBLE) { var successCallback = function() { adStatus = AD_STATUS_HIDDEN; adStatusLbl.html('Ad is hidden.'); adButton.val('show'); }; var errorCallback = function() { adStatusLbl.html('Failed to hide Ad.'); adButton.val('hide'); }; Ad.hide(successCallback, errorCallback); } } // --> </script> </head> <body> <section id="secmain" data-role="page"> <header id="mainHeader" data-role="header" data-position="inline"> </header> <textarea id="request" rows="10" cols="46" wrap="soft" style="display:none"></textarea> <div id="accordion" style="font-size:10px !important;"> <h3><a href="#">Application Version</a></h3> <div> <span id="lblAppVersion" style="">Version 1.0</span> <br /><br /> </div> <h3><a href="#">Image Decryption</a></h3> <div> &lt;img src="images/gbb.jpg.pkg"&gt; :<br /> <div style="border: 1px solid;height:80px;width:80px;"> <img src="images/gbb.jpg.pkg" style="height:80px;width:80px;"/> </div><br /> &lt;img src="images/purpurea.jpg.pkg"&gt; :<br /> <div style="border: 1px solid;height:80px;width:80px;"> <img src="images/purpurea.jpg.pkg" style="height:80px;width:80px;"/> </div><br /> &lt;img src="images/avic.jpg.pkg"&gt; :<br /> <div style="border: 1px solid;height:80px;width:80px;"> <img src="images/avic.jpg.pkg" style="height:80px;width:80px;"/> </div><br /><br /> </div> <h3><a href="#">Camera</a></h3> <div class="contentDiv" width="100%" height="100%"> <div id="wrapper"> <div id="imgDiv"></div> </div> <div style="text-align:center;padding-top:5px"> <input type="button" id="camera" value="photo" width="80px"/> <input type="button" id="record" value="video" onclick="record();"/> </div> <div id="recordMovieDiv" style="display:none;font-size:10px !important;font-family: Verdana,Arial,sans-serif;"> <div id="mainContentVideoFrame" data-role="content" style="border: 1px solid #BBB;padding:0;margin:0 auto;height:200px;width:98%;"> </div> <table width="100%" style="text-align:center"> <tr> <td style="height:20px" colspan="2"><div id="videoSlider"></div></td> </tr> <tr> <td width="50%"><input type="button" value="play" id="playvideo"/></td> <td><input type="button" value="stop / close" id="stopvideo" disabled="disabled"/></td> </tr> </table> <div id="mainContentVideo" data-role="content" style="padding:0;margin-top: 5px;"> &nbsp;&nbsp;Position: <span id="position"></span><br /> &nbsp;&nbsp;Duration: <span id="duration"></span> </div> <img id="thumb"/> </div> </div> <h3><a href="#">Sound</a></h3> <div> <table width="100%" height="100"style="padding-top:5px;"> <tr> <td style="padding:5px" colspan="5"><div id="soundSlider"></div></td> </tr> <tr> <td><input type="button" value="|<<" id="sPrevious"/></td> <td><input type="button" value="play" id="sPlay"/></td> <td><input type="button" value="stop" id="sStop" disabled="disabled"/></td> <td><input type="button" value=">>|" id="sNext"/></td> </tr> </table> <div id="mainContentSound" data-role="content" style="padding-bottom:5px;margin:0;"> &nbsp;&nbsp;Position: <span id="position"></span><br /> &nbsp;&nbsp;Duration: <span id="duration"></span> </div> </div> <h3><a href="#">Movie</a></h3> <div class="contentDiv"> <div id="mainContentMovieFrame" data-role="content" style="padding:0;margin:0 auto;height:200px;width:98%;"> </div> <table width="100%" style="text-align:center"> <tr> <td style="height:20px" colspan="5"><div id="movieSlider"></div></td> </tr> <tr> <td><input type="button" value="|<<" id="previous"/></td> <td><input type="button" value="play" id="play"/></td> <td><input type="button" value="stop" id="stop" disabled="disabled"/></td> <td><input type="button" value=">>|" id="next"/></td> </tr> </table> <div id="mainContentMovie" data-role="content" style="padding:0;margin:0;"> &nbsp;&nbsp;Position: <span id="position"></span><br /> &nbsp;&nbsp;Duration: <span id="duration"></span> </div> <img id="thumb" /> </div> <h3><a href="#">File, FileReader, FileWriter</a></h3> <div id="fileTest" style="padding-right:0px !important;"> Directory: <input type="text" value="/this/is/not/an/existing/directory" id="fileDir" size="30"/><br /> Filename: <input type="text" value="testFile.txt" id="filename" size="30"/><br /> <input type="button" value="INIT" onclick="initFile();" class="initButton initNotRequired" /> <input type="button" value="IsFile" onclick="onclickFileIsFile();" /> <input type="button" value="IsDir" onclick="onclickFileIsDirectory();" /><br /> Copy/Move Dir: <input type="text" value="" id="copyMoveDir" size="25"/><br /> New Filename: <input type="text" value="" id="newFilename" size="25"/><br /> <input type="button" value="Copy" onclick="onclickFileCopy();" /> <input type="button" value="Move" onclick="onclickFileMove();" /> <input type="button" value="Delete" onclick="onclickFileDelete();" /> <br /> File data:<br /> <textarea id="readData" rows="3" cols="40" wrap="soft" disabled="disabled"></textarea><br /> FileReader:&nbsp;&nbsp; <input type="button" value="Read" onclick="onclickFileReaderRead();" /> <br /> Input data:<br /> <textarea id="fileInputData" rows="5" cols="40" wrap="soft">熟語</textarea><br /> FileWriter:&nbsp;&nbsp; <input type="button" value="Write" onclick="onclickFileWriterWrite();" /> <input type="button" value="Seek" onclick="onclickFileWriterSeek();" /> <input type="text" value="" id="seekData" size="3"/> </div> <h3><a href="#">Encryption</a></h3> <div> Input data:<br /> <textarea id="encInputData" rows="3" cols="40" wrap="soft">熟語</textarea><br /> <a href="#" onclick="$('#encInputData').val('');" style="align:right;">clear</a><br /><br /> Result data:<br /> <textarea id="encOutputData" rows="3" cols="40" wrap="soft" disabled="disabled"></textarea><br /> <a href="#" onclick="$('#encOutputData').val('');" style="align:right;">clear</a><br /><br /> <input type="button" value="Encrypt" onclick="encrypt();" /> <input type="button" value="Decrypt" onclick="decrypt();" /> <input type="button" value="Swap" onclick="swap();" /> </div> <h3><a href="#">Notifications</a></h3> <div id="notificationTest"> Time: <input type="text" value="" id="notificationTime" readonly="readonly"/><br /> Message:<br /> <textarea id="notificationMsg" rows="3" cols="40" wrap="soft">This is the message shown in the notification.</textarea><br /> Badge#: <input type="text" value="1" id="notificationBadge" size="3"/><br /> Action: <input type="checkbox" checked="yes" id="hasAction" /> &nbsp;<input type="text" value="View" id="action"/><br /><br /> <input type="button" value="Notify" onclick="setNotification();" /> <input type="button" value="Cancel" onclick="cancelNotification();" /> </div> <h3><a href="#">Loading Screen</a></h3> <div> Loading text: <input type="text" id="loadingText" size="25"/><br /><br /> Style: <select id="style"> <option value="0">White Large</option> <option value="1">White</option> <option value="2">Gray</option> </select><br /><br /> Frame: <br /> X: <input type="text" id="frameX" size="3"/> Y: <input type="text" id="frameY" size="3"/> width: <input type="text" id="frameWidth" size="3"/> height: <input type="text" id="frameHeight" size="3"/><br /> Black BGColor: <input type="checkbox" checked="yes" id="isBlackBackground" /> <br /><br /> <input type="text" id="stopAfter" value="5" size="3"/>sec&nbsp;<input type="button" value="Start" onclick="showLoadingScreen();" /> <input type="button" value="Stop" onclick="showLoadingScreen(false);" style="display:none" /> </div> <h3><a href="#">Cache</a></h3> <div> <div id="wrapperCache1" style="-webkit-border-radius:0px;height:145px !important;width:250px !important;float:left !important;"> <div id="cacheDiv"></div> </div> <br style="clear:both" />Data:<br /> <textarea id="cacheDataInput" rows="3" cols="40" wrap="soft"></textarea><br /> Expire Date: <input type="text" id="expireDate" readonly="readonly"/><br /> <!--Seconds: <input type="text" id="expireSeconds" size="5"/--><br /><br /> <input type="button" value="Save" onclick="saveCacheData()" /> <input type="button" value="Reset" onclick="resetDataCache()"/><br /> <a href="#" onclick="refreshCacheList();return false;">Show data cache list</a><br /><br /> Resource Cache:<br /> <div id="wrapperCache2" style="-webkit-border-radius:0px;height:145px !important;width:250px !important;float:left !important;"> <div id="cacheResourceDiv" style="width:1000px !important;"></div> </div> <br style="clear:both" />URL: <input type="text" value="http://www.android.com/images/whatsnew/jb-new-logo.png" id="resourceURL" size="25" style="margin-top:10px"/><br /> Expire Date: <input type="text" id="resourceExpireDate" readonly="readonly"/><br /><br /> <input type="button" value="Save resource" onclick="addResource()" /> <input type="button" value="Reset" onclick="resetResourceCache()" /><br /> <a href="#" onclick="showResourceCache();return false;">Show resource cache list</a> </div> <h3><a href="#">QR Code Reader</a></h3> <div> <textarea id="qrReaderResult" rows="3" cols="40" wrap="soft" disabled="disabled"></textarea><br /> <input type="button" value="Scan QR Code from Camera" onclick="qrReaderScan(0)" /><br /> <input type="button" value="Scan QR Code from Library" onclick="qrReaderScan(1)" style="padding-top:10px"/><br /> </div> <h3 class="database"><a href="#">Database</a></h3> <div class="database"> <input type="text" value="mySqlite" id="dbName" size="30"/> <input type="button" value="Init" onclick="initDb()"/><br /> <textarea id="dbSQL" rows="3" cols="40" wrap="soft"></textarea><br /> <a href="#" onclick="$('#dbSQL').val($('#create').html());return false;" style="align:right;">create table</a>&nbsp; <a href="#" onclick="$('#dbSQL').val($('#insert').html());return false;" style="align:right;">insert query</a>&nbsp; <a href="#" onclick="$('#dbSQL').val($('#select').html());return false;" style="align:right;">select query</a><br /><br /> <input type="button" value="Execute Query" onclick="dbExecuteQuery()"/><br /><br /> <input type="button" value="Begin Transaction" onclick="dbBeginTrans()"/> <input type="button" value="Commit" onclick="dbCommit()"/> <input type="button" value="Rollback" onclick="dbRollback()"/> <span id="create" style="display:none">CREATE TABLE IF NOT EXISTS DynamicApp (ID INTEGER PRIMARY KEY AUTOINCREMENT, DATA TEXT, DATE DATE)</span> <span id="insert" style="display:none">INSERT INTO DynamicApp (DATA, DATE) VALUES ("熟語TESTDATA", "2012-01-01")</span> <span id="select" style="display:none">SELECT * FROM DynamicApp WHERE DATA LIKE "%DATA"</span> </div> <h3 class="addressbook"><a href="#">AddressBook</a></h3> <div class="addressbook"> <input type="button" value="Show" onclick="showAddressBook(false)"/>&nbsp;&nbsp; <input type="button" value="Show (Select)" onclick="showAddressBook(true)"/><br /><br /> Output of Select:<br /> <textarea rows="5" cols="40" id="addressBookData" disabled="disabled"></textarea><br> <a href="#" onclick="$('#addressBookData').val('');" style="align:right;">clear</a><br /> </div> <h3><a href="#">Contacts</a></h3> <div> <input type="button" value="Create" onclick="contactsCreate()" /><br /> <table> <tr> <td>key:</td> <td> <select id="contactsCreateOptions" class="contactsCreate" style="width:90px"></select> <input id="contactsCreatePicOpt" class="contactsCreate" type="button" value="Image" style="display:none"/> </td> </tr> <tr class="mValForm"> <td>label:</td> <td><select id="contactsCreateMValOptions" class="contactsCreate" style="width:90px"></select></td> </tr> <tr> <td>label:</td> <td><select id="contactsCreateExtraOptions" class="contactsCreate" style="width:90px"></select></td> </tr> <tr> <td>value:</td> <td> <input id="contactsCreateValue" class="contactsCreate" type="text" style="width:100px"/> &nbsp; <input id="contactsAddCreateOpt" class="contactsCreate" type="button" value="+" /> </td> </tr> </table> <table id="contactsCreateData" style="background-color: #AAAAAA;margin-top:5px" cellspacing="1"> <tr style="background-color: #FFF;"> <th width="85">option</th> <th width="100">value</th> <th>action</th> </tr> </table><br /> <input type="button" class="contactsCreate" value="Save" onclick="contactSave()" /><br /><br /> Search:<br /> <table> <tr> <td>key:</td> <td><select id="contactsSearchOptions" style="width:90px"></select></td> </tr> <tr> <td>label:</td> <td> <select id="contactsSearchExtraOptions" style="width:90px"></select> <select id="contactsSearchCond" style="width:50px"> <option value="=">=</option> <option value="!=">!=</option> </select> </td> </tr> <tr> <td>value:</td> <td> <input id="contactsSearchValue" type="text" style="width:100px"/> &nbsp; <input id="contactsAddCondition" type="button" value="+"/> </td> </tr> </table> <table id="contactsSearchConditions" style="background-color: #AAAAAA;margin-top:5px" cellspacing="1"> <tr style="background-color: #FFF;"> <th width="185">condition</th> <th>action</th> </tr> </table><br /> <input type="button" value="Search" onclick="contactsSearch()" /><br /> <table id="contactsSearchResult" style="background-color: #AAAAAA;margin-top:5px" cellspacing="1"> <tr style="background-color: #FFF;"> <th width="225">Search Result</th> </tr> </table><br /><br /> Remove id: <input id="contactsRemoveId" type="input" style="width:100px"/>&nbsp; <input type="button" value="Remove" onclick="contactRemove()" /> </div> <h3><a href="#">Bluetooth</a></h3> <div> <input type="button" value="Discover" onclick="btDiscover();"/><br /> Message:<br /> <textarea rows="6" cols="22" id="btMessage" style="float:left;height:95px">熟語</textarea> <div style="margin-left:10px;height:100px;width:100px;float:left;border:1px solid;"> <img id="btImage" width="100" height="100" src="" style="height:100px"/> </div> <div id="btModal" class="btFloatingDiv"> <div style="border-bottom:2px solid;font-weight:bold;padding:5px 0"> Available Devices </div> <div id="btPeerList" style="height:150px;overflow-y:auto;overflow-x:hidden"> <div id="noPeersText">Looking for peers...</div> </div> <div style="padding:5px 0"> <input type="button" onclick="btHideModal();" value="Cancel" /> </div> </div> <div id="btOverlay" style="background-color:black;filter:alpha(opacity=70);opacity:0.7;width:100%;height:100%;z-index:400;position:fixed;top:0;left:0;display:none"> </div> <div style="clear:both;padding-top:10px;padding:bottom:20px"> <table id="btTestPeerList" style="background-color: #AAAAAA;" cellspacing="1"> <tr class="peerListHeader"> <th width="80">id</th> <th width="80">name</th> <th width="50">state</th> <th width="80">action</th> </tr> </table> </div><br /><br /> </div> <h3 class="bluetoothLE"><a href="#">Bluetooth 4 LE</a></h3> <div class="bluetoothLE"> Services:<br /> <select id="serviceMultiList" style="width:245px" multiple="multiple" size="5"> </select><br /> <input type="button" value="Scan Devices" onclick="bt4LEScanDevices();" style="margin:10px 0"/><br /> Services:<br /> <select id="serviceList" style="width:245px"> </select><br /> Characteristic:<br /> <select id="characteristicList" style="width:245px"> </select><br /> Value Type:<br /> <select id="characteristicVTypeList" style="width:245px"> </select><br /> <input id="characteristicValue" type="text" style="width:250px;" value="1"/><br /> <div id="characteristicWriteType"> &nbsp;&nbsp;Write type:<br /> &nbsp;&nbsp;&nbsp;&nbsp;With Response<input type="radio" name="writeType" value="0"/> &nbsp;&nbsp;&nbsp;&nbsp;Without Response<input type="radio" name="writeType" value="1" style="margin-bottom:10px"/><br /> </div> Descriptor:<br /> <select id="descriptorList" style="width:245px"> </select><br /> Value Type:<br /> <select id="descriptorVTypeList" style="width:245px"> </select><br /> <input id="descriptorValue" type="text" style="width:250px" value="1"/><br /> <div id="bt4LEModal" class="btFloatingDiv"> <div style="border-bottom:2px solid;font-weight:bold;padding:5px 0"> Available Bluetooth LE Devices </div> <div id="bt4LEPeripheralList" style="height:150px;overflow-y:auto;overflow-x:hidden"> <div id="noPeripheralsText">Looking for peripherals...</div> </div> <div style="padding:5px 0"> <input type="button" onclick="bt4LEHideModal();" value="Cancel" /> </div> </div> <div id="bt4LEOverlay" style="background-color:black;filter:alpha(opacity=70);opacity:0.7;width:100%;height:100%;z-index:400;position:fixed;top:0;left:0;display:none"> </div> <div style="clear:both;padding-top:10px;padding:bottom:20px"> <table id="bt4LETestPeripheralList" style="background-color: #AAAAAA;" cellspacing="1"> <tr class="peripheralListHeader"> <th width="80">id</th> <th width="80">name</th> <th width="50">state</th> <th width="80">action</th> </tr> </table> </div><br /><br /> </div> <h3 class="felica"><a href="#">Felica</a></h3> <div class="felica"> <input type="button" value="Get Manufacturer Id" onclick="felicaGetIdM();" style="margin:5px 0 5px 0;width: 125px;"/> <input type="button" value="Get Manufacturer" onclick="felicaGetPMm();" style="margin:5px 0;width: 125px;"/><br /> <input type="button" value="Request System Codes" onclick="felicaSystemCode();" style="margin:5px 0 5px 0;width: 125px;"/> <input type="button" value="Request Service Codes" onclick="felicaServiceCode();" style="margin:5px 0;width: 125px;"/><br /> <input type="button" value="Request Response" onclick="felicaResponse();" style="margin:5px 0 5px 0;width: 125px;"/><br /> <table> <tr><td>Service Code:</td><td><select id="felicaServiceCodes"></select></td></tr> <tr><td>Address:</td><td><select id="felicaAddress"></select></td></tr> <tr><td>Data:</td><td><input id="felicaData" type="text" maxlength="32" size="32"/></td></tr> </table> <input type="button" value="Read Without Encryption" onclick="felicaRead();" style="margin:5px 0;width: 140px;"/> <input type="button" value="Write Without Encryption" onclick="felicaWrite();" style="margin:5px 0;width: 140px;"/><br /> </div> <h3 class="pdf"><a href="#">PDF Viewer</a></h3> <div class="pdf"> <input type="radio" class="pdfViewerType" name="pdfViewerType" value="1" checked> File Object<br /> <input type="radio" class="pdfViewerType" name="pdfViewerType" value="2"> File Path<br /> <input type="radio" class="pdfViewerType" name="pdfViewerType" value="3"> URL<br /> <input type="text" id="pdfPath" value="media_resources/sample.pdf"/><br /> <input type="button" value="View PDF" onclick="pdfShow();" style="margin:5px 0 5px 0;"/> </div> <h3><a href="#">Ads</a></h3> <div> <span id="adStatus"></span><br /> <input type="button" value="create" id="adButton" style="margin:5px 0;"/> </div> </div> </section> </body> </html>
{ "content_hash": "36ba0e9726d89d79ce57e71f8b240eb6", "timestamp": "", "source": "github", "line_count": 2986, "max_line_length": 473, "avg_line_length": 40.99263228399196, "alnum_prop": 0.46206006339662103, "repo_name": "dynamicapp/dynamicapp", "id": "b7aba27069ba5f03bcead4078739ae4379b255e2", "size": "122422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Android/DynamicAppTestApp/assets/www/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "175621" }, { "name": "C++", "bytes": "620333" }, { "name": "CSS", "bytes": "19042" }, { "name": "D", "bytes": "80773" }, { "name": "Java", "bytes": "472414" }, { "name": "JavaScript", "bytes": "1369921" }, { "name": "Objective-C", "bytes": "717982" }, { "name": "Objective-C++", "bytes": "34505" }, { "name": "Python", "bytes": "1721313" }, { "name": "Shell", "bytes": "1114" } ], "symlink_target": "" }
FROM balenalib/up-board-ubuntu:cosmic-run ENV GO_VERSION 1.15.6 # gcc for cgo RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ gcc \ libc6-dev \ make \ pkg-config \ git \ && rm -rf /var/lib/apt/lists/* RUN set -x \ && fetchDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-amd64.tar.gz" \ && echo "3918e6cc85e7eaaa6f859f1bdbaac772e7a825b0eb423c63d3ae68b21f84b844 go$GO_VERSION.linux-amd64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-amd64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-amd64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu cosmic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.6 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "a434992295110e4dbac63513da493826", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 687, "avg_line_length": 50.369565217391305, "alnum_prop": 0.7043590850237376, "repo_name": "nghiant2710/base-images", "id": "8f93e470a78ae1a4c95b7c74e72f1fec880a7bce", "size": "2338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/golang/up-board/ubuntu/cosmic/1.15.6/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
import { magenta } from 'chalk'; import { bot, Response, dataSources } from '../../config'; import '../../env'; // eslint-disable-next-line const namespace = 'download'; /* istanbul ignore next */ /** * Test * @param {Object} vorpal - Vorpal instance * @returns {Object} test */ export async function promptDataType(vorpal) { const { response } = new Response(namespace); const prompt = magenta('What data would you like to download?'); vorpal.activeCommand.log(`${bot}${prompt}`); const { dataType } = await vorpal.activeCommand.prompt({ type: 'list', name: 'dataType', message: response, choices: dataSources, }); return dataType; } /** * Test * @param {Object} vorpal - Vorpal instance * @returns {string} dataType */ export async function getDataType(vorpal) { const DATATYPE = process.env.HERITAGEBOTDATATYPE; if (DATATYPE === undefined) { return promptDataType(vorpal); } return DATATYPE; } export { getDataType as default };
{ "content_hash": "e0c01da635b59369dc6d1de362859be9", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 68, "avg_line_length": 25, "alnum_prop": 0.6458536585365854, "repo_name": "domjtalbot/heritagebot", "id": "daad6d2846b06d5d0b6eeff3709a6de3d905d14b", "size": "1025", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/download/prompt/getDataType.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "48207" } ], "symlink_target": "" }
<!-- Stylish portfolio startbootstrap.com --> <html lang="en"> <head> <!--Calendar--> <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" /> <link href="demo/MonthPicker.min.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script src="js/jquery.maskedinput.min.js"></script> <script src="demo/MonthPicker.min.js"></script> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Archeological Society of Maryland, Inc.</title> <link rel="shortcut icon" href="http://marylandarcheology.org/favicon.ico" /> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/stylish-portfolio.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <a id="menu-toggle" href="#" class="btn btn-dark btn-lg toggle"><i class="fa fa-bars"></i></a> <nav id="sidebar-wrapper"> <ul class="sidebar-nav"> <a id="menu-close" href="#" class="btn btn-light btn-lg pull-right toggle"><i class="fa fa-times"></i></a> <li class="sidebar-brand"> <a href="index.html" onclick=$("#menu-close").click();>ASM</a> </li> <li> <a href="index.html" onclick=$("#menu-close").click();>Home</a> </li> <li> <a href="#about" onclick=$("#menu-close").click();>About</a> </li> </ul> </nav> <!-- Header --> <section id="contactus" class="contactus bg-primary"> <div class="container"> <div class="row text-center"> <div class="col-lg-10 col-lg-offset-1"> <h1>ASM's 2012 William B. Marye Award</h1> <h3>Stephen Israel</h3> <hr class="small"> <!-- /.row (nested) --> </div> <!-- /.col-lg-10 --> </div> <!-- /.row --> </div> <!-- /.container --> </section> <!-- About --> <section id="about" class="about"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <div class="container"> <div class="row"> <div class="col-lg-10 col-lg-offset-1 text-center"> <div class="row" > <div class="image123" style="padding-right: 50px"> <div class="imgContainer"> <img src="img/Stephen_Israel.gif" alt="Stephen Israel accepts the William B. Marye Award for 2012" width="400" height="300" hspace="5" vspace="5" border="1" style="margin-left:-60px"> </div> </div><br> <p style="padding-right: 30px">The 2012 recipient of the William B. Marye Award, Stephen Israel has made particularly outstanding and lasting contributions to several areas of Maryland archeology. Stephen is well known for his willingness to take on almost any task that will further the cause of Maryland Archeology and his generosity with his time in assisting and guiding avocational archeologists.</p><br> <p style="padding-right: 30px">The award committee notes his long years of service to this community. Following military service, which included a deployment to Viet Nam,, Stephen completed his Masters Degree in Anthropology at the University of Oklahoma in 1969. From 1976 until his retirement in 2003 he worked as an archeologist for the US Army Corp of Engineers with responsibility for research activity in four states. His work outside of official duties include assisting archeologists in Maryland and surrounding states as well. In 2007, the Archeological Society of Virginia presented him with their Out-Of_State Award for Outstanding Service to the Commonwealth of Virginia archeology.</p><br> <p style="padding-right: 30px">Stephen is a regular and enthusiastic participant in all forms of ASM meetings and related activities. ASM can always count on him to support CAT program activities as well as the Annual Field Sessions. He is a frequent contributor to Maryland Archeology, our official journal. He is also active with the Council for Maryland Archeology, the Eastern States Archaeological Federation, the Middle Atlantic Archaeological Conference, and archeological organizations in several states. </p> </div> <!-- /.row (nested) --> </div> <!-- /.col-lg-10 --> </div> <!-- /.row --> </div> <!-- /.container --> </div> </div> </div> <!-- /.row --> </div> <!-- /.container --> </section> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Custom Theme JavaScript --> <script> // Closes the sidebar menu $("#menu-close").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); // Opens the sidebar menu $("#menu-toggle").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); // Scrolls to the selected menu item on the page $(function() { $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); //#to-top button appears after scrolling var fixed = false; $(document).scroll(function() { if ($(this).scrollTop() > 250) { if (!fixed) { fixed = true; // $('#to-top').css({position:'fixed', display:'block'}); $('#to-top').show("slow", function() { $('#to-top').css({ position: 'fixed', display: 'block' }); }); } } else { if (fixed) { fixed = false; $('#to-top').hide("slow", function() { $('#to-top').css({ display: 'none' }); }); } } }); </script> </body> </html>
{ "content_hash": "4d554057343509beedb5961e6b8e32da", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 196, "avg_line_length": 38.38785046728972, "alnum_prop": 0.5220937309799147, "repo_name": "acesinc/asm-website", "id": "bb56f6869f389acf1d6148528d650d49cdfe1478", "size": "8215", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ExampleAwards.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "479179" }, { "name": "HTML", "bytes": "1205109" }, { "name": "JavaScript", "bytes": "223105" }, { "name": "PHP", "bytes": "138" } ], "symlink_target": "" }
package org.basex.util; import java.util.*; import org.basex.util.list.*; /** * Convenience functions for handling arrays; serves as an extension to Java's {@link Arrays} class. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public final class Array { /** Initial default size for new arrays. */ public static final int CAPACITY = 1 << 3; /** Default factor for resizing dynamic arrays. */ public static final double RESIZE = 1.5; /** Private constructor. */ private Array() { } /** * Copies the specified array. * @param array array to be copied * @param size new array size * @return new array */ public static byte[][] copyOf(final byte[][] array, final int size) { final byte[][] tmp = new byte[size][]; System.arraycopy(array, 0, tmp, 0, Math.min(size, array.length)); return tmp; } /** * Copies the specified array. * @param array array to be copied * @param size new array size * @return new array */ public static int[][] copyOf(final int[][] array, final int size) { final int[][] tmp = new int[size][]; System.arraycopy(array, 0, tmp, 0, Math.min(size, array.length)); return tmp; } /** * Copies the specified array. * @param array array to be copied * @param size new array size * @return new array */ public static String[] copyOf(final String[] array, final int size) { final String[] tmp = new String[size]; System.arraycopy(array, 0, tmp, 0, Math.min(size, array.length)); return tmp; } /** * Adds an entry to the end of an array and returns the new array. * @param array array to be resized * @param entry entry to be added * @param <T> array type * @return array */ public static <T> T[] add(final T[] array, final T entry) { final int s = array.length; final T[] t = Arrays.copyOf(array, s + 1); t[s] = entry; return t; } /** * Adds an entry to the end of an array and returns the specified new array. * @param array array to be resized * @param target target array (must have one more entry than the source array) * @param entry entry to be added * @param <T> array type * @return array */ public static <T> T[] add(final T[] array, final T[] target, final T entry) { copy(array, target); target[array.length] = entry; return target; } /** * Adds an entry to the end of an array and returns the new array. * @param array array to be resized * @param entry entry to be added * @return array */ public static int[] add(final int[] array, final int entry) { final int s = array.length; final int[] t = Arrays.copyOf(array, s + 1); t[s] = entry; return t; } /** * Moves entries inside an array. * @param array array * @param pos position * @param off move offset * @param size number of entries to move */ public static void move(final Object array, final int pos, final int off, final int size) { System.arraycopy(array, pos, array, pos + off, size); } /** * Copies entries from one array to another. * @param <T> object type * @param source source array * @param target target array * @return object */ public static <T> T[] copy(final T[] source, final T[] target) { System.arraycopy(source, 0, target, 0, source.length); return target; } /** * Removes an array entry at the specified position. * @param array array to be resized * @param pos position * @param <T> array type * @return array */ public static <T> T[] delete(final T[] array, final int pos) { final int s = array.length - 1; move(array, pos + 1, -1, s - pos); return Arrays.copyOf(array, s); } /** * Sorts the specified tokens and returns an array with offsets to the sorted array. * @param values values to sort by (will be sorted as well) * @param numeric numeric sort * @param ascending ascending * @return array containing the order */ public static int[] createOrder(final byte[][] values, final boolean numeric, final boolean ascending) { final IntList il = number(values.length); il.sort(values, numeric, ascending); return il.finish(); } /** * Sorts the specified double values and returns an array with offsets to the sorted array. * @param values values to sort by (will be sorted as well) * @param ascending ascending * @return array containing the order */ public static int[] createOrder(final double[] values, final boolean ascending) { final IntList il = number(values.length); il.sort(values, ascending); return il.finish(); } /** * Sorts the specified int values and returns an array with offsets to the sorted array. * @param values values to sort by (will be sorted as well) * @param ascending ascending * @return array containing the order */ public static int[] createOrder(final int[] values, final boolean ascending) { final IntList il = number(values.length); il.sort(values, ascending); return il.finish(); } /** * Sorts the specified long values and returns an array with offsets to the sorted array. * @param values values to sort by (will be sorted as well) * @param ascending ascending * @return array containing the order */ public static int[] createOrder(final long[] values, final boolean ascending) { final IntList il = number(values.length); il.sort(values, ascending); return il.finish(); } /** * Returns an enumerated integer list. * @param size array size * @return number list */ public static IntList number(final int size) { final int[] tmp = new int[size]; for(int i = 0; i < size; ++i) tmp[i] = i; return new IntList(tmp); } /** * Reverses the order of the elements in the given array. * @param array array */ public static void reverse(final byte[] array) { reverse(array, 0, array.length); } /** * Reverses the order of all elements in the given interval. * @param array array * @param pos position of first element of the interval * @param len length of the interval */ private static void reverse(final byte[] array, final int pos, final int len) { for(int l = pos, r = pos + len - 1; l < r; l++, r--) { final byte tmp = array[l]; array[l] = array[r]; array[r] = tmp; } } /** * Reverses the order of all elements in the given interval. * @param array array * @param pos position of first element of the interval * @param len length of the interval */ public static void reverse(final Object[] array, final int pos, final int len) { for(int l = pos, r = pos + len - 1; l < r; l++, r--) { final Object tmp = array[l]; array[l] = array[r]; array[r] = tmp; } } /** * Returns a value for a new array size, which will always be larger than the specified value. * @param old old size * @return resulting size */ public static int newSize(final int old) { return newSize(old, RESIZE); } /** * Returns a value for a new array size, which will always be larger than the specified value. * @param old old size * @param factor resize factor; must be larger than or equal to 1 * @return resulting size */ public static int newSize(final int old, final double factor) { return (int) (old * factor) + 1; } }
{ "content_hash": "890a7f53ce485b076b0305b875a12cdc", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 100, "avg_line_length": 29.839357429718877, "alnum_prop": 0.6407806191117092, "repo_name": "joansmith/basex", "id": "847996623a623f2669583619af4fb0d1fc87ddee", "size": "7430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "basex-core/src/main/java/org/basex/util/Array.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "9372" }, { "name": "Batchfile", "bytes": "2502" }, { "name": "C", "bytes": "17146" }, { "name": "C#", "bytes": "15568" }, { "name": "C++", "bytes": "7796" }, { "name": "CSS", "bytes": "3386" }, { "name": "Common Lisp", "bytes": "3211" }, { "name": "HTML", "bytes": "1057" }, { "name": "Haskell", "bytes": "4065" }, { "name": "Java", "bytes": "6901921" }, { "name": "JavaScript", "bytes": "8001" }, { "name": "Makefile", "bytes": "1234" }, { "name": "PHP", "bytes": "8690" }, { "name": "Perl", "bytes": "7801" }, { "name": "Python", "bytes": "26123" }, { "name": "QMake", "bytes": "377" }, { "name": "Rebol", "bytes": "4731" }, { "name": "Ruby", "bytes": "7359" }, { "name": "Scala", "bytes": "11692" }, { "name": "Shell", "bytes": "3557" }, { "name": "Visual Basic", "bytes": "11957" }, { "name": "XQuery", "bytes": "217459" }, { "name": "XSLT", "bytes": "172" } ], "symlink_target": "" }
import lodash from 'lodash'; // fix for node.js <= 3, it throws TypeError when value type invalid in weak set function hasVisited(ast, visited) { try { return visited.has(ast); } catch (e) { return false; } } function recursive(ast, visited) { if (!ast || hasVisited(ast, visited)) { return []; } if (Array.isArray(ast)) { return lodash(ast) .map((node) => recursive(node, visited)) .flatten() .value(); } if (ast.type) { visited.add(ast); return lodash(ast) .keys() .filter((key) => key !== 'tokens' && key !== 'comments') .map((key) => recursive(ast[key], visited)) .flatten() .concat(ast) .value(); } return []; } export default function getNodes(ast) { const visited = new WeakSet(); return recursive(ast, visited); }
{ "content_hash": "c6d266db0fa09f2d1448929402375e23", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 21.23076923076923, "alnum_prop": 0.5809178743961353, "repo_name": "depcheck/depcheck", "id": "875c32414977a2baf574ecacc8b6ecc472956efc", "size": "828", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/utils/parser.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "59" }, { "name": "JavaScript", "bytes": "215174" }, { "name": "SCSS", "bytes": "486" }, { "name": "Sass", "bytes": "300" }, { "name": "Svelte", "bytes": "74" }, { "name": "TypeScript", "bytes": "995" }, { "name": "Vue", "bytes": "486" } ], "symlink_target": "" }
import cv2 import zbar from math import sqrt import numpy as np # Size of qr class QRCode(object): """ Represents a QR code. Locations are not accurate. Useful properties: self.value: the value of the code. self.points: numpy self.X: X value of center self.Y: Y value of center """ def __init__(self, symbol, size): # Raw object from zbar. self.symbol = symbol self.value = self.symbol.data # Begin Processing symbol self.topLeft, self.bottomLeft, self.bottomRight, self.topRight = [item for item in self.symbol.location] self.points = np.float32(symbol.location) self.set_centroid_location() l = size self.verts = np.float32([[-l/2, -l/2, 0], [-l/2, l/2, 0], [l/2, -l/2, 0], [l/2, l/2, 0]]) self.rvec = [999]*3 self.tvec = [999]*3 self.displacement = [] self.displacement_2d = [] def __str__(self): return "value: %s \n Location: %s \n Verts: %s" % \ (self.value, self.centroid_location, self.points) @property def tvec(self): return self.__tvec @tvec.setter def tvec(self, vec): self.__tvec = vec self.displacement_2d = sqrt(vec[0]**2 + vec[1]**2) self.displacement = sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2) @property def points(self): return self.__points @points.setter def points(self, value): """Numpy array of corners of QR code. """ self.__points = np.float32(value) def set_centroid_location(self): x_sum = 0 y_sum = 0 # calculate center from x and y of points for item in self.symbol.location: x_sum += item[0] y_sum += item[1] X = x_sum / 4 Y = y_sum /4 self.centroid_location = (X, Y)
{ "content_hash": "626aa237a89026e5f2a7f314ae3a078d", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 112, "avg_line_length": 26.945945945945947, "alnum_prop": 0.5155466399197592, "repo_name": "IEEERobotics/bot", "id": "113e284ddbc007aa54664e13f41a5928984be292", "size": "1994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bot/hardware/qr_code.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "2496" }, { "name": "Makefile", "bytes": "340" }, { "name": "OpenEdge ABL", "bytes": "7302" }, { "name": "Python", "bytes": "346823" }, { "name": "Shell", "bytes": "19575" }, { "name": "VimL", "bytes": "1414" } ], "symlink_target": "" }
#pragma once #ifndef GEODE_DATASERIALIZABLEPRIMITIVE_H_ #define GEODE_DATASERIALIZABLEPRIMITIVE_H_ #include "../Serializable.hpp" #include "DSCode.hpp" namespace apache { namespace geode { namespace client { class DataOutput; class DataInput; namespace internal { class APACHE_GEODE_EXPORT DataSerializablePrimitive : public virtual Serializable { public: ~DataSerializablePrimitive() noexcept override = default; virtual void toData(DataOutput& dataOutput) const = 0; virtual void fromData(DataInput& dataInput) = 0; virtual DSCode getDsCode() const = 0; }; } // namespace internal } // namespace client } // namespace geode } // namespace apache #endif // GEODE_DATASERIALIZABLEPRIMITIVE_H_
{ "content_hash": "02c0927ea6f09a2a683e9d6f65778c74", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 59, "avg_line_length": 21.205882352941178, "alnum_prop": 0.7545076282940361, "repo_name": "pivotal-jbarrett/geode-native", "id": "8d6e82dfe50c81936582ebdbeeb17b00172e8183", "size": "1523", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "cppcache/include/geode/internal/DataSerializablePrimitive.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1046" }, { "name": "C", "bytes": "1195" }, { "name": "C#", "bytes": "3558268" }, { "name": "C++", "bytes": "9005412" }, { "name": "CMake", "bytes": "304594" }, { "name": "Dockerfile", "bytes": "2985" }, { "name": "Java", "bytes": "441181" }, { "name": "Perl", "bytes": "2704" }, { "name": "PowerShell", "bytes": "30834" }, { "name": "Python", "bytes": "72929" }, { "name": "Shell", "bytes": "39018" } ], "symlink_target": "" }
package com.google.android.exoplayer2.offline; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import static com.google.common.truth.Truth.assertThat; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.robolectric.shadows.ShadowLooper.shadowMainLooper; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.Renderer; import com.google.android.exoplayer2.RenderersFactory; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.offline.DownloadHelper.Callback; import com.google.android.exoplayer2.source.MediaPeriod; import com.google.android.exoplayer2.source.MediaSourceEventListener.EventDispatcher; import com.google.android.exoplayer2.source.TrackGroup; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.testutil.FakeMediaPeriod; import com.google.android.exoplayer2.testutil.FakeMediaSource; import com.google.android.exoplayer2.testutil.FakeRenderer; import com.google.android.exoplayer2.testutil.FakeTimeline; import com.google.android.exoplayer2.testutil.FakeTimeline.TimelineWindowDefinition; import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.ExoTrackSelection; import com.google.android.exoplayer2.trackselection.MappingTrackSelector.MappedTrackInfo; import com.google.android.exoplayer2.trackselection.TrackSelectionOverride; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters; import com.google.android.exoplayer2.upstream.Allocator; import com.google.android.exoplayer2.util.MimeTypes; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** Unit tests for {@link DownloadHelper}. */ @RunWith(AndroidJUnit4.class) public class DownloadHelperTest { private static final Object TEST_MANIFEST = new Object(); private static final Timeline TEST_TIMELINE = new FakeTimeline( new Object[] {TEST_MANIFEST}, new TimelineWindowDefinition(/* periodCount= */ 2, /* id= */ new Object())); private static TrackGroup trackGroupVideoLow; private static TrackGroup trackGroupVideoLowAndHigh; private static TrackGroup trackGroupAudioUs; private static TrackGroup trackGroupAudioZh; private static TrackGroup trackGroupTextUs; private static TrackGroup trackGroupTextZh; private static TrackGroupArray[] trackGroupArrays; private static MediaItem testMediaItem; private DownloadHelper downloadHelper; @BeforeClass public static void staticSetUp() { Format videoFormatLow = createVideoFormat(/* bitrate= */ 200_000); Format videoFormatHigh = createVideoFormat(/* bitrate= */ 800_000); Format audioFormatEn = createAudioFormat(/* language= */ "en"); Format audioFormatDe = createAudioFormat(/* language= */ "de"); Format textFormatEn = createTextFormat(/* language= */ "en"); Format textFormatDe = createTextFormat(/* language= */ "de"); trackGroupVideoLow = new TrackGroup(videoFormatLow); trackGroupVideoLowAndHigh = new TrackGroup(videoFormatLow, videoFormatHigh); trackGroupAudioUs = new TrackGroup(audioFormatEn); trackGroupAudioZh = new TrackGroup(audioFormatDe); trackGroupTextUs = new TrackGroup(textFormatEn); trackGroupTextZh = new TrackGroup(textFormatDe); TrackGroupArray trackGroupArrayAll = new TrackGroupArray( trackGroupVideoLowAndHigh, trackGroupAudioUs, trackGroupAudioZh, trackGroupTextUs, trackGroupTextZh); TrackGroupArray trackGroupArraySingle = new TrackGroupArray(trackGroupVideoLow, trackGroupAudioUs); trackGroupArrays = new TrackGroupArray[] {trackGroupArrayAll, trackGroupArraySingle}; testMediaItem = new MediaItem.Builder().setUri("http://test.uri").setCustomCacheKey("cacheKey").build(); } @Before public void setUp() { FakeRenderer videoRenderer = new FakeRenderer(C.TRACK_TYPE_VIDEO); FakeRenderer audioRenderer = new FakeRenderer(C.TRACK_TYPE_AUDIO); FakeRenderer textRenderer = new FakeRenderer(C.TRACK_TYPE_TEXT); RenderersFactory renderersFactory = (handler, videoListener, audioListener, metadata, text) -> new Renderer[] {textRenderer, audioRenderer, videoRenderer}; downloadHelper = new DownloadHelper( testMediaItem, new TestMediaSource(), DownloadHelper.DEFAULT_TRACK_SELECTOR_PARAMETERS_WITHOUT_CONTEXT, DownloadHelper.getRendererCapabilities(renderersFactory)); } @Test public void getManifest_returnsManifest() throws Exception { prepareDownloadHelper(downloadHelper); assertThat(downloadHelper.getManifest()).isEqualTo(TEST_MANIFEST); } @Test public void getPeriodCount_returnsPeriodCount() throws Exception { prepareDownloadHelper(downloadHelper); assertThat(downloadHelper.getPeriodCount()).isEqualTo(2); } @Test public void getTrackGroups_returnsTrackGroups() throws Exception { prepareDownloadHelper(downloadHelper); TrackGroupArray trackGroupArrayPeriod0 = downloadHelper.getTrackGroups(/* periodIndex= */ 0); TrackGroupArray trackGroupArrayPeriod1 = downloadHelper.getTrackGroups(/* periodIndex= */ 1); assertThat(trackGroupArrayPeriod0).isEqualTo(trackGroupArrays[0]); assertThat(trackGroupArrayPeriod1).isEqualTo(trackGroupArrays[1]); } @Test public void getMappedTrackInfo_returnsMappedTrackInfo() throws Exception { prepareDownloadHelper(downloadHelper); MappedTrackInfo mappedTracks0 = downloadHelper.getMappedTrackInfo(/* periodIndex= */ 0); MappedTrackInfo mappedTracks1 = downloadHelper.getMappedTrackInfo(/* periodIndex= */ 1); assertThat(mappedTracks0.getRendererCount()).isEqualTo(3); assertThat(mappedTracks0.getRendererType(/* rendererIndex= */ 0)).isEqualTo(C.TRACK_TYPE_TEXT); assertThat(mappedTracks0.getRendererType(/* rendererIndex= */ 1)).isEqualTo(C.TRACK_TYPE_AUDIO); assertThat(mappedTracks0.getRendererType(/* rendererIndex= */ 2)).isEqualTo(C.TRACK_TYPE_VIDEO); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 0).length).isEqualTo(2); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 1).length).isEqualTo(2); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 2).length).isEqualTo(1); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 0).get(/* index= */ 0)) .isEqualTo(trackGroupTextUs); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 0).get(/* index= */ 1)) .isEqualTo(trackGroupTextZh); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 1).get(/* index= */ 0)) .isEqualTo(trackGroupAudioUs); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 1).get(/* index= */ 1)) .isEqualTo(trackGroupAudioZh); assertThat(mappedTracks0.getTrackGroups(/* rendererIndex= */ 2).get(/* index= */ 0)) .isEqualTo(trackGroupVideoLowAndHigh); assertThat(mappedTracks1.getRendererCount()).isEqualTo(3); assertThat(mappedTracks1.getRendererType(/* rendererIndex= */ 0)).isEqualTo(C.TRACK_TYPE_TEXT); assertThat(mappedTracks1.getRendererType(/* rendererIndex= */ 1)).isEqualTo(C.TRACK_TYPE_AUDIO); assertThat(mappedTracks1.getRendererType(/* rendererIndex= */ 2)).isEqualTo(C.TRACK_TYPE_VIDEO); assertThat(mappedTracks1.getTrackGroups(/* rendererIndex= */ 0).length).isEqualTo(0); assertThat(mappedTracks1.getTrackGroups(/* rendererIndex= */ 1).length).isEqualTo(1); assertThat(mappedTracks1.getTrackGroups(/* rendererIndex= */ 2).length).isEqualTo(1); assertThat(mappedTracks1.getTrackGroups(/* rendererIndex= */ 1).get(/* index= */ 0)) .isEqualTo(trackGroupAudioUs); assertThat(mappedTracks1.getTrackGroups(/* rendererIndex= */ 2).get(/* index= */ 0)) .isEqualTo(trackGroupVideoLow); } @Test public void getTrackSelections_returnsInitialSelection() throws Exception { prepareDownloadHelper(downloadHelper); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertSingleTrackSelectionEquals(selectedText0, trackGroupTextUs, 0); assertSingleTrackSelectionEquals(selectedAudio0, trackGroupAudioUs, 0); assertSingleTrackSelectionEquals(selectedVideo0, trackGroupVideoLowAndHigh, 1); assertThat(selectedText1).isEmpty(); assertSingleTrackSelectionEquals(selectedAudio1, trackGroupAudioUs, 0); assertSingleTrackSelectionEquals(selectedVideo1, trackGroupVideoLow, 0); } @Test public void getTrackSelections_afterClearTrackSelections_isEmpty() throws Exception { prepareDownloadHelper(downloadHelper); // Clear only one period selection to verify second period selection is untouched. downloadHelper.clearTrackSelections(/* periodIndex= */ 0); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertThat(selectedText0).isEmpty(); assertThat(selectedAudio0).isEmpty(); assertThat(selectedVideo0).isEmpty(); // Verify assertThat(selectedText1).isEmpty(); assertSingleTrackSelectionEquals(selectedAudio1, trackGroupAudioUs, 0); assertSingleTrackSelectionEquals(selectedVideo1, trackGroupVideoLow, 0); } @Test public void getTrackSelections_afterReplaceTrackSelections_returnsNewSelections() throws Exception { prepareDownloadHelper(downloadHelper); DefaultTrackSelector.Parameters parameters = new DefaultTrackSelector.ParametersBuilder(getApplicationContext()) .setPreferredAudioLanguage("de") .setPreferredTextLanguage("de") .setRendererDisabled(/* rendererIndex= */ 2, true) .build(); // Replace only one period selection to verify second period selection is untouched. downloadHelper.replaceTrackSelections(/* periodIndex= */ 0, parameters); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertSingleTrackSelectionEquals(selectedText0, trackGroupTextZh, 0); assertSingleTrackSelectionEquals(selectedAudio0, trackGroupAudioZh, 0); assertThat(selectedVideo0).isEmpty(); assertThat(selectedText1).isEmpty(); assertSingleTrackSelectionEquals(selectedAudio1, trackGroupAudioUs, 0); assertSingleTrackSelectionEquals(selectedVideo1, trackGroupVideoLow, 0); } @Test public void getTrackSelections_afterAddTrackSelections_returnsCombinedSelections() throws Exception { prepareDownloadHelper(downloadHelper); // Select parameters to require some merging of track groups because the new parameters add // all video tracks to initial video single track selection. TrackSelectionParameters parameters = new TrackSelectionParameters.Builder(getApplicationContext()) .setPreferredAudioLanguage("de") .setPreferredTextLanguage("en") .build(); // Add only to one period selection to verify second period selection is untouched. downloadHelper.addTrackSelection(/* periodIndex= */ 0, parameters); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertSingleTrackSelectionEquals(selectedText0, trackGroupTextUs, 0); assertThat(selectedAudio0).hasSize(2); assertTrackSelectionEquals(selectedAudio0.get(0), trackGroupAudioUs, 0); assertTrackSelectionEquals(selectedAudio0.get(1), trackGroupAudioZh, 0); assertSingleTrackSelectionEquals(selectedVideo0, trackGroupVideoLowAndHigh, 0, 1); assertThat(selectedText1).isEmpty(); assertSingleTrackSelectionEquals(selectedAudio1, trackGroupAudioUs, 0); assertSingleTrackSelectionEquals(selectedVideo1, trackGroupVideoLow, 0); } @Test public void getTrackSelections_afterAddAudioLanguagesToSelection_returnsCombinedSelections() throws Exception { prepareDownloadHelper(downloadHelper); downloadHelper.clearTrackSelections(/* periodIndex= */ 0); downloadHelper.clearTrackSelections(/* periodIndex= */ 1); // Add a non-default language, and a non-existing language (which will select the default). downloadHelper.addAudioLanguagesToSelection("de", "Klingonese"); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertThat(selectedVideo0).isEmpty(); assertThat(selectedText0).isEmpty(); assertThat(selectedAudio0).hasSize(2); assertTrackSelectionEquals(selectedAudio0.get(0), trackGroupAudioZh, 0); assertTrackSelectionEquals(selectedAudio0.get(1), trackGroupAudioUs, 0); assertThat(selectedVideo1).isEmpty(); assertThat(selectedText1).isEmpty(); assertSingleTrackSelectionEquals(selectedAudio1, trackGroupAudioUs, 0); } @Test public void getTrackSelections_afterAddTextLanguagesToSelection_returnsCombinedSelections() throws Exception { prepareDownloadHelper(downloadHelper); downloadHelper.clearTrackSelections(/* periodIndex= */ 0); downloadHelper.clearTrackSelections(/* periodIndex= */ 1); // Add a non-default language, and a non-existing language (which will select the default). downloadHelper.addTextLanguagesToSelection( /* selectUndeterminedTextLanguage= */ true, "de", "Klingonese"); List<ExoTrackSelection> selectedText0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo0 = downloadHelper.getTrackSelections(/* periodIndex= */ 0, /* rendererIndex= */ 2); List<ExoTrackSelection> selectedText1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 0); List<ExoTrackSelection> selectedAudio1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 1); List<ExoTrackSelection> selectedVideo1 = downloadHelper.getTrackSelections(/* periodIndex= */ 1, /* rendererIndex= */ 2); assertThat(selectedVideo0).isEmpty(); assertThat(selectedAudio0).isEmpty(); assertThat(selectedText0).hasSize(2); assertTrackSelectionEquals(selectedText0.get(0), trackGroupTextZh, 0); assertTrackSelectionEquals(selectedText0.get(1), trackGroupTextUs, 0); assertThat(selectedVideo1).isEmpty(); assertThat(selectedAudio1).isEmpty(); assertThat(selectedText1).isEmpty(); } @Test public void getDownloadRequest_createsDownloadRequest_withAllSelectedTracks() throws Exception { prepareDownloadHelper(downloadHelper); // Ensure we have track groups with multiple indices, renderers with multiple track groups and // also renderers without any track groups. TrackSelectionParameters parameters = new TrackSelectionParameters.Builder(getApplicationContext()) .setPreferredAudioLanguage("de") .setPreferredTextLanguage("en") .build(); downloadHelper.addTrackSelection(/* periodIndex= */ 0, parameters); byte[] data = TestUtil.buildTestData(10); DownloadRequest downloadRequest = downloadHelper.getDownloadRequest(data); assertThat(downloadRequest.uri).isEqualTo(testMediaItem.localConfiguration.uri); assertThat(downloadRequest.mimeType).isEqualTo(testMediaItem.localConfiguration.mimeType); assertThat(downloadRequest.customCacheKey) .isEqualTo(testMediaItem.localConfiguration.customCacheKey); assertThat(downloadRequest.data).isEqualTo(data); assertThat(downloadRequest.streamKeys) .containsExactly( new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 0, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 0, /* streamIndex= */ 1), new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 2, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 3, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 1, /* groupIndex= */ 0, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 1, /* groupIndex= */ 1, /* streamIndex= */ 0)); } @Test public void getDownloadRequest_createsDownloadRequest_withMultipleOverridesOfSameType() throws Exception { prepareDownloadHelper(downloadHelper); TrackSelectionParameters parameters = new TrackSelectionParameters.Builder(getApplicationContext()) .addOverride(new TrackSelectionOverride(trackGroupAudioUs, /* trackIndex= */ 0)) .addOverride(new TrackSelectionOverride(trackGroupAudioZh, /* trackIndex= */ 0)) .setTrackTypeDisabled(C.TRACK_TYPE_VIDEO, /* disabled= */ true) .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, /* disabled= */ true) .build(); downloadHelper.replaceTrackSelections(/* periodIndex= */ 0, parameters); downloadHelper.clearTrackSelections(/* periodIndex= */ 1); DownloadRequest downloadRequest = downloadHelper.getDownloadRequest(/* data= */ null); assertThat(downloadRequest.streamKeys) .containsExactly( new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 1, /* streamIndex= */ 0), new StreamKey(/* periodIndex= */ 0, /* groupIndex= */ 2, /* streamIndex= */ 0)); } private static void prepareDownloadHelper(DownloadHelper downloadHelper) throws Exception { AtomicReference<Exception> prepareException = new AtomicReference<>(null); CountDownLatch preparedLatch = new CountDownLatch(1); downloadHelper.prepare( new Callback() { @Override public void onPrepared(DownloadHelper helper) { preparedLatch.countDown(); } @Override public void onPrepareError(DownloadHelper helper, IOException e) { prepareException.set(e); preparedLatch.countDown(); } }); while (!preparedLatch.await(0, MILLISECONDS)) { shadowMainLooper().idleFor(shadowMainLooper().getNextScheduledTaskTime()); } if (prepareException.get() != null) { throw prepareException.get(); } } private static Format createVideoFormat(int bitrate) { return new Format.Builder() .setSampleMimeType(MimeTypes.VIDEO_H264) .setAverageBitrate(bitrate) .build(); } private static Format createAudioFormat(String language) { return new Format.Builder() .setSampleMimeType(MimeTypes.AUDIO_AAC) .setLanguage(language) .build(); } private static Format createTextFormat(String language) { return new Format.Builder() .setSampleMimeType(MimeTypes.TEXT_VTT) .setSelectionFlags(C.SELECTION_FLAG_DEFAULT) .setLanguage(language) .build(); } private static void assertSingleTrackSelectionEquals( List<ExoTrackSelection> trackSelectionList, TrackGroup trackGroup, int... tracks) { assertThat(trackSelectionList).hasSize(1); assertTrackSelectionEquals(trackSelectionList.get(0), trackGroup, tracks); } private static void assertTrackSelectionEquals( ExoTrackSelection trackSelection, TrackGroup trackGroup, int... tracks) { assertThat(trackSelection.getTrackGroup()).isEqualTo(trackGroup); assertThat(trackSelection.length()).isEqualTo(tracks.length); int[] selectedTracksInGroup = new int[trackSelection.length()]; for (int i = 0; i < trackSelection.length(); i++) { selectedTracksInGroup[i] = trackSelection.getIndexInTrackGroup(i); } Arrays.sort(selectedTracksInGroup); Arrays.sort(tracks); assertThat(selectedTracksInGroup).isEqualTo(tracks); } private static final class TestMediaSource extends FakeMediaSource { public TestMediaSource() { super(TEST_TIMELINE); } @Override public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator, long startPositionUs) { int periodIndex = TEST_TIMELINE.getIndexOfPeriod(id.periodUid); return new FakeMediaPeriod( trackGroupArrays[periodIndex], allocator, TEST_TIMELINE.getWindow(0, new Timeline.Window()).positionInFirstPeriodUs, new EventDispatcher() .withParameters(/* windowIndex= */ 0, id, /* mediaTimeOffsetMs= */ 0)) { @Override public List<StreamKey> getStreamKeys(List<ExoTrackSelection> trackSelections) { List<StreamKey> result = new ArrayList<>(); for (ExoTrackSelection trackSelection : trackSelections) { int groupIndex = trackGroupArrays[periodIndex].indexOf(trackSelection.getTrackGroup()); for (int i = 0; i < trackSelection.length(); i++) { result.add( new StreamKey(periodIndex, groupIndex, trackSelection.getIndexInTrackGroup(i))); } } return result; } }; } @Override public void releasePeriod(MediaPeriod mediaPeriod) { // Do nothing. } } }
{ "content_hash": "c7da0b7227c6427d28d4a4659e504a92", "timestamp": "", "source": "github", "line_count": 527, "max_line_length": 100, "avg_line_length": 47.61290322580645, "alnum_prop": 0.7281205164992827, "repo_name": "google/ExoPlayer", "id": "dab7fd1488aed410b0ba0df668fa95e27634bb09", "size": "25711", "binary": false, "copies": "1", "ref": "refs/heads/release-v2", "path": "library/core/src/test/java/com/google/android/exoplayer2/offline/DownloadHelperTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "112860" }, { "name": "CMake", "bytes": "3728" }, { "name": "GLSL", "bytes": "24937" }, { "name": "Java", "bytes": "15604745" }, { "name": "Makefile", "bytes": "11496" }, { "name": "Shell", "bytes": "25523" } ], "symlink_target": "" }
''' Created on Aug 21, 2015 @author: David Zwicker <dzwicker@seas.harvard.edu> ''' from __future__ import division import collections import functools import logging import sys import unittest import warnings from contextlib import contextmanager try: collectionsAbc = collections.abc # python 3 except AttributeError: collectionsAbc = collections # python 2 import numpy as np import six from six.moves import zip_longest from .math import arrays_close class MockLoggingHandler(logging.Handler): """ Mock logging handler to check for expected logs. Messages are available from an instance's ``messages`` dict, in order, indexed by a lowercase log level string (e.g., 'debug', 'info', etc.). Adapted from http://stackoverflow.com/a/20553331/932593 """ def __init__(self, *args, **kwargs): self.messages = {'debug': [], 'info': [], 'warning': [], 'error': [], 'critical': []} super(MockLoggingHandler, self).__init__(*args, **kwargs) def emit(self, record): """ Store a message from ``record`` in the instance's ``messages`` dict. """ self.acquire() try: self.messages[record.levelname.lower()].append(record.getMessage()) finally: self.release() def reset(self): """ reset all messages """ self.acquire() try: for message_list in self.messages.values(): message_list.clear() finally: self.release() class TestBase(unittest.TestCase): """ extends the basic TestCase class with some convenience functions """ def assertAllClose(self, arr1, arr2, rtol=1e-05, atol=1e-08, msg=None): """ compares all the entries of the arrays a and b """ try: # try to convert to numpy arrays arr1 = np.asanyarray(arr1) arr2 = np.asanyarray(arr2) except ValueError: # try iterating explicitly try: for v1, v2 in zip_longest(arr1, arr2): self.assertAllClose(v1, v2, rtol, atol, msg) except TypeError: if msg is None: msg = "" else: msg += "; " raise TypeError(msg + "Don't know how to compare %s and %s" % (arr1, arr2)) else: if msg is None: msg = 'Values are not equal' msg += '\n%s !=\n%s)' % (arr1, arr2) is_close = arrays_close(arr1, arr2, rtol, atol, equal_nan=True) self.assertTrue(is_close, msg) def assertDictAllClose(self, a, b, rtol=1e-05, atol=1e-08, msg=None): """ compares all the entries of the dictionaries a and b """ if msg is None: msg = '' else: msg += '\n' for k, v in a.items(): # create a message if non was given submsg = msg + ('Dictionaries differ for key `%s` (%s != %s)' % (k, v, b[k])) # try comparing as numpy arrays and fall back if that doesn't work try: self.assertAllClose(v, b[k], rtol, atol, submsg) except TypeError: self.assertEqual(v, b[k], submsg) class WarnAssertionsMixin(object): """ Mixing that allows to test for warnings Code inspired by https://blog.ionelmc.ro/2013/06/26/testing-python-warnings/ """ @contextmanager def assertNoWarnings(self): try: warnings.simplefilter("error") yield finally: warnings.resetwarnings() @contextmanager def assertWarnings(self, messages): """ Asserts that the given messages are issued in the given order. """ if not messages: raise RuntimeError("Use assertNoWarnings instead!") with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter("always") for mod in list(sys.modules.values()): if hasattr(mod, '__warningregistry__'): mod.__warningregistry__.clear() yield warning_list = [w.message.args[0] for w in warning_list] for message in messages: if not any(message in warning for warning in warning_list): self.fail('Message `%s` was not contained in warnings' % message) def deep_getsizeof(obj, ids=None): """Find the memory footprint of a Python object This is a recursive function that drills down a Python object graph like a dictionary holding nested dictionaries with lists of lists and tuples and sets. The sys.getsizeof function does a shallow size of only. It counts each object inside a container as pointer only regardless of how big it really is. Function modified from https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609 """ if ids is not None: if id(obj) in ids: return 0 else: ids = set() r = sys.getsizeof(obj) ids.add(id(obj)) if isinstance(obj, six.string_types): # simple string return r if isinstance(obj, collectionsAbc.Mapping): # simple mapping return r + sum(deep_getsizeof(k, ids) + deep_getsizeof(v, ids) for k, v in six.iteritems(obj)) if isinstance(obj, collectionsAbc.Container): # collection that is neither a string nor a mapping return r + sum(deep_getsizeof(x, ids) for x in obj) if hasattr(obj, '__dict__'): # custom object return r + deep_getsizeof(obj.__dict__, ids) # basic object: neither of the above return r def repeat(num): """ decorator for repeating tests several times """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for _ in range(num): f(*args, **kwargs) return wrapper return decorator if __name__ == '__main__': unittest.main()
{ "content_hash": "3f419c09c4969494195cff7bec97bea2", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 101, "avg_line_length": 29.737089201877936, "alnum_prop": 0.5582570255762551, "repo_name": "david-zwicker/py-utils", "id": "72f86ea1953dd510c35d8558f32e38b177003fb1", "size": "6334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/testing.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "510313" }, { "name": "Shell", "bytes": "1174" } ], "symlink_target": "" }
![Build status](https://travis-ci.org/Hnatekmar/GeneticAlgorithm.svg "Build") Program that tries to approximate picture (64x64 only) with various geometric shapes (circles or rectangles). You can download most recent build [here](https://akela.mendelu.cz/~xhnatek/PP/bin.zip) (Windows only). It uses genetic algorithm for finding optimal position, dimension and color of each shape. Results of this process are demonstrated in picture below. ![Mona Lisa approximated with circles](mona.PNG) Another example could be this picture that was obtained with rectangle based approximation. ![Mona Lisa approximated with rectangles](last.png)
{ "content_hash": "74941bc6acdde6814a87df8ec2c752c6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 214, "avg_line_length": 49.38461538461539, "alnum_prop": 0.7928348909657321, "repo_name": "Hnatekmar/GeneticAlgorithm", "id": "d5bf8aff5af1367c4899067e189070b3511a5607", "size": "662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "D", "bytes": "16853" } ], "symlink_target": "" }
#ifndef PLOTTER_H #define PLOTTER_H void hand_up(void); void hand_down(void); void set_xy(double x, double y); void set_home_position(void); void controlled_move(int x, int y); #endif /* PLOTTER_H */
{ "content_hash": "4dfeed8ba0baa46300b852f2e4533162", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 35, "avg_line_length": 18.454545454545453, "alnum_prop": 0.7044334975369458, "repo_name": "gearchange/plotter", "id": "4cfb06982439822705c8785fa8f7a05d53ab5620", "size": "203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plotter.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5004" }, { "name": "Makefile", "bytes": "15601" }, { "name": "Shell", "bytes": "1369" } ], "symlink_target": "" }
package com.flipkart.foxtrot.core.querystore.impl; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.ObjectMapper; import com.flipkart.foxtrot.common.ActionResponse; import com.flipkart.foxtrot.common.group.GroupResponse; import com.flipkart.foxtrot.core.TestUtils; import com.flipkart.foxtrot.core.cache.CacheManager; import com.flipkart.foxtrot.core.cache.impl.DistributedCache; import com.flipkart.foxtrot.core.cache.impl.DistributedCacheFactory; import com.flipkart.foxtrot.core.querystore.QueryStore; import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader; import com.flipkart.foxtrot.core.table.TableMetadataManager; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.test.TestHazelcastInstanceFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Created by rishabh.goyal on 28/04/14. */ public class DistributedCacheTest { private DistributedCache distributedCache; private HazelcastInstance hazelcastInstance; private ObjectMapper mapper; @Before public void setUp() throws Exception { mapper = new ObjectMapper(); mapper = spy(mapper); hazelcastInstance = new TestHazelcastInstanceFactory(1).newHazelcastInstance(); HazelcastConnection hazelcastConnection = Mockito.mock(HazelcastConnection.class); when(hazelcastConnection.getHazelcast()).thenReturn(hazelcastInstance); distributedCache = new DistributedCache(hazelcastConnection, "TEST", mapper); CacheManager cacheManager = new CacheManager(new DistributedCacheFactory(hazelcastConnection, mapper)); TableMetadataManager tableMetadataManager = Mockito.mock(TableMetadataManager.class); when(tableMetadataManager.exists(TestUtils.TEST_TABLE_NAME)).thenReturn(true); QueryStore queryStore = Mockito.mock(QueryStore.class); AnalyticsLoader analyticsLoader = new AnalyticsLoader(tableMetadataManager, null, queryStore, null, cacheManager, mapper); TestUtils.registerActions(analyticsLoader, mapper); } @After public void tearDown() throws Exception { hazelcastInstance.shutdown(); } @Test public void testPut() throws Exception { ActionResponse expectedResponse = new GroupResponse(Collections.<String, Object>singletonMap("Hello", "world")); ActionResponse returnResponse = distributedCache.put("DUMMY_KEY_PUT", expectedResponse); assertEquals(expectedResponse, returnResponse); GroupResponse actualResponse = GroupResponse.class.cast(distributedCache.get("DUMMY_KEY_PUT")); assertEquals(GroupResponse.class.cast(expectedResponse).getResult(), actualResponse.getResult()); } @Test public void testPutCacheException() throws Exception { doThrow(new JsonGenerationException("TEST_EXCEPTION")).when(mapper).writeValueAsString(any()); ActionResponse returnResponse = distributedCache.put("DUMMY_KEY_PUT", null); verify(mapper, times(1)).writeValueAsString(any()); assertNull(returnResponse); assertNull(hazelcastInstance.getMap("TEST").get("DUMMY_KEY_PUT")); } @Test public void testGet() throws Exception { GroupResponse baseRequest = new GroupResponse(); baseRequest.setResult(Collections.<String, Object>singletonMap("Hello", "World")); String requestString = mapper.writeValueAsString(baseRequest); distributedCache.put("DUMMY_KEY_GET", mapper.readValue(requestString, ActionResponse.class)); ActionResponse actionResponse = distributedCache.get("DUMMY_KEY_GET"); String actualResponse = mapper.writeValueAsString(actionResponse); assertEquals(requestString, actualResponse); } @Test public void testGetInvalidKeyValue() throws Exception { assertNull(distributedCache.get("DUMMY_KEY_GET")); } @Test public void testGetNullKey() throws Exception { assertNull(distributedCache.get(null)); } @Test public void testHas() throws Exception { GroupResponse baseRequest = new GroupResponse(); baseRequest.setResult(Collections.<String, Object>singletonMap("Hello", "World")); distributedCache.put("DUMMY_KEY_HAS", baseRequest); boolean response = distributedCache.has("DUMMY_KEY_HAS"); assertTrue(response); response = distributedCache.has("INVALID_KEY"); assertFalse(response); response = distributedCache.has(null); assertFalse(response); } }
{ "content_hash": "6d024e994f4f25951293b5508ca5f635", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 130, "avg_line_length": 42.27927927927928, "alnum_prop": 0.7430215214148732, "repo_name": "santanusinha/foxtrot", "id": "3fc768df99bd6cb2a7f77eff667603433c9d8e1a", "size": "5300", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "foxtrot-core/src/test/java/com/flipkart/foxtrot/core/querystore/impl/DistributedCacheTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7567" }, { "name": "HTML", "bytes": "64819" }, { "name": "Java", "bytes": "681493" }, { "name": "JavaScript", "bytes": "265255" }, { "name": "Python", "bytes": "755" }, { "name": "Shell", "bytes": "3248" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="keyline_first">24dp</dimen> </resources>
{ "content_hash": "64647419d0bb5edef04c122657942203", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 44, "avg_line_length": 18.333333333333332, "alnum_prop": 0.6545454545454545, "repo_name": "MostafaGazar/tensorflow", "id": "2389ad07f5cb40d3aea402d1c8e437db84c5638f", "size": "110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/examples/android/res/values-sw600dp/dimens.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "88155" }, { "name": "C++", "bytes": "12907224" }, { "name": "CMake", "bytes": "65581" }, { "name": "CSS", "bytes": "774" }, { "name": "Go", "bytes": "42531" }, { "name": "HTML", "bytes": "1171692" }, { "name": "Java", "bytes": "143277" }, { "name": "JavaScript", "bytes": "12972" }, { "name": "Jupyter Notebook", "bytes": "1833435" }, { "name": "Makefile", "bytes": "23390" }, { "name": "Objective-C", "bytes": "7056" }, { "name": "Objective-C++", "bytes": "64592" }, { "name": "Protocol Buffer", "bytes": "136850" }, { "name": "Python", "bytes": "11873486" }, { "name": "Shell", "bytes": "267196" }, { "name": "TypeScript", "bytes": "675176" } ], "symlink_target": "" }
<?php namespace SellerLabs\Nucleus\Meditation\Interfaces; use SellerLabs\Nucleus\Meditation\SpecResult; /** * Interface CheckableInterface. * * Describes an object that can be checked against a set of constraints (a * specification) and return a result describing the result of the computation. * * @author Eduardo Trujillo <ed@sellerlabs.com> * @package SellerLabs\Nucleus\Meditation\Interfaces */ interface CheckableInterface { /** * Check that a certain input passes the spec or constraint collection. * * @param mixed $input * * @return SpecResult */ public function check(array $input); }
{ "content_hash": "27678eab40b0d8101ef08c34150571ec", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 79, "avg_line_length": 23.035714285714285, "alnum_prop": 0.7162790697674418, "repo_name": "sellerlabs/nucleus", "id": "6b7e1855e073aeadb1088e7b0ccd411d64e7017c", "size": "865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SellerLabs/Nucleus/Meditation/Interfaces/CheckableInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "441057" }, { "name": "Shell", "bytes": "483" } ], "symlink_target": "" }
// Copyright (C) 1999, 2000 Jaakko Järvi (jaakko.jarvi@cs.utu.fi) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org // ------------------------------------------------ #ifndef BOOST_LAMBDA_LAMBDA_FUNCTORS_HPP #define BOOST_LAMBDA_LAMBDA_FUNCTORS_HPP namespace boost { namespace lambda { // -- lambda_functor -------------------------------------------- // -------------------------------------------------------------- //inline const null_type const_null_type() { return null_type(); } namespace detail { namespace { static const null_type constant_null_type = null_type(); } // unnamed } // detail class unused {}; #define cnull_type() detail::constant_null_type // -- free variables types -------------------------------------------------- // helper to work around the case where the nullary return type deduction // is always performed, even though the functor is not nullary namespace detail { template<int N, class Tuple> struct get_element_or_null_type { typedef typename detail::tuple_element_as_reference<N, Tuple>::type type; }; template<int N> struct get_element_or_null_type<N, null_type> { typedef null_type type; }; } template <int I> struct placeholder; template<> struct placeholder<FIRST> { template<class SigArgs> struct sig { typedef typename detail::get_element_or_null_type<0, SigArgs>::type type; }; template<class RET, CALL_TEMPLATE_ARGS> RET call(CALL_FORMAL_ARGS) const { BOOST_STATIC_ASSERT(boost::is_reference<RET>::value); CALL_USE_ARGS; // does nothing, prevents warnings for unused args return a; } }; template<> struct placeholder<SECOND> { template<class SigArgs> struct sig { typedef typename detail::get_element_or_null_type<1, SigArgs>::type type; }; template<class RET, CALL_TEMPLATE_ARGS> RET call(CALL_FORMAL_ARGS) const { CALL_USE_ARGS; return b; } }; template<> struct placeholder<THIRD> { template<class SigArgs> struct sig { typedef typename detail::get_element_or_null_type<2, SigArgs>::type type; }; template<class RET, CALL_TEMPLATE_ARGS> RET call(CALL_FORMAL_ARGS) const { CALL_USE_ARGS; return c; } }; template<> struct placeholder<EXCEPTION> { template<class SigArgs> struct sig { typedef typename detail::get_element_or_null_type<3, SigArgs>::type type; }; template<class RET, CALL_TEMPLATE_ARGS> RET call(CALL_FORMAL_ARGS) const { CALL_USE_ARGS; return env; } }; typedef const lambda_functor<placeholder<FIRST> > placeholder1_type; typedef const lambda_functor<placeholder<SECOND> > placeholder2_type; typedef const lambda_functor<placeholder<THIRD> > placeholder3_type; /////////////////////////////////////////////////////////////////////////////// // free variables are lambda_functors. This is to allow uniform handling with // other lambda_functors. // ------------------------------------------------------------------- // -- lambda_functor NONE ------------------------------------------------ template <class T> class lambda_functor : public T { BOOST_STATIC_CONSTANT(int, arity_bits = get_arity<T>::value); public: typedef T inherited; lambda_functor() {} lambda_functor(const lambda_functor& l) : inherited(l) {} lambda_functor(const T& t) : inherited(t) {} template <class SigArgs> struct sig { typedef typename inherited::template sig<typename SigArgs::tail_type>::type type; }; // Note that this return type deduction template is instantiated, even // if the nullary // operator() is not called at all. One must make sure that it does not fail. typedef typename inherited::template sig<null_type>::type nullary_return_type; nullary_return_type operator()() const { return inherited::template call<nullary_return_type> (cnull_type(), cnull_type(), cnull_type(), cnull_type()); } template<class A> typename inherited::template sig<tuple<A&> >::type operator()(A& a) const { return inherited::template call< typename inherited::template sig<tuple<A&> >::type >(a, cnull_type(), cnull_type(), cnull_type()); } template<class A> typename inherited::template sig<tuple<A const&> >::type operator()(A const& a) const { return inherited::template call< typename inherited::template sig<tuple<A const&> >::type >(a, cnull_type(), cnull_type(), cnull_type()); } template<class A, class B> typename inherited::template sig<tuple<A&, B&> >::type operator()(A& a, B& b) const { return inherited::template call< typename inherited::template sig<tuple<A&, B&> >::type >(a, b, cnull_type(), cnull_type()); } template<class A, class B> typename inherited::template sig<tuple<A const&, B&> >::type operator()(A const& a, B& b) const { return inherited::template call< typename inherited::template sig<tuple<A const&, B&> >::type >(a, b, cnull_type(), cnull_type()); } template<class A, class B> typename inherited::template sig<tuple<A&, B const&> >::type operator()(A& a, B const& b) const { return inherited::template call< typename inherited::template sig<tuple<A&, B const&> >::type >(a, b, cnull_type(), cnull_type()); } template<class A, class B> typename inherited::template sig<tuple<A const&, B const&> >::type operator()(A const& a, B const& b) const { return inherited::template call< typename inherited::template sig<tuple<A const&, B const&> >::type >(a, b, cnull_type(), cnull_type()); } template<class A, class B, class C> typename inherited::template sig<tuple<A&, B&, C&> >::type operator()(A& a, B& b, C& c) const { return inherited::template call< typename inherited::template sig<tuple<A&, B&, C&> >::type >(a, b, c, cnull_type()); } template<class A, class B, class C> typename inherited::template sig<tuple<A const&, B const&, C const&> >::type operator()(A const& a, B const& b, C const& c) const { return inherited::template call< typename inherited::template sig<tuple<A const&, B const&, C const&> >::type >(a, b, c, cnull_type()); } // for internal calls with env template<CALL_TEMPLATE_ARGS> typename inherited::template sig<tuple<CALL_REFERENCE_TYPES> >::type internal_call(CALL_FORMAL_ARGS) const { return inherited::template call<typename inherited::template sig<tuple<CALL_REFERENCE_TYPES> >::type>(CALL_ACTUAL_ARGS); } template<class A> const lambda_functor<lambda_functor_base< other_action<assignment_action>, boost::tuple<lambda_functor, typename const_copy_argument <const A>::type> > > operator=(const A& a) const { return lambda_functor_base< other_action<assignment_action>, boost::tuple<lambda_functor, typename const_copy_argument <const A>::type> > ( boost::tuple<lambda_functor, typename const_copy_argument <const A>::type>(*this, a) ); } template<class A> const lambda_functor<lambda_functor_base< other_action<subscript_action>, boost::tuple<lambda_functor, typename const_copy_argument <const A>::type> > > operator[](const A& a) const { return lambda_functor_base< other_action<subscript_action>, boost::tuple<lambda_functor, typename const_copy_argument <const A>::type> > ( boost::tuple<lambda_functor, typename const_copy_argument <const A>::type>(*this, a ) ); } }; } // namespace lambda } // namespace boost // is_placeholder #include <boost/is_placeholder.hpp> namespace boost { template<> struct is_placeholder< lambda::lambda_functor< lambda::placeholder<lambda::FIRST> > > { enum _vt { value = 1 }; }; template<> struct is_placeholder< lambda::lambda_functor< lambda::placeholder<lambda::SECOND> > > { enum _vt { value = 2 }; }; template<> struct is_placeholder< lambda::lambda_functor< lambda::placeholder<lambda::THIRD> > > { enum _vt { value = 3 }; }; } // namespace boost #endif
{ "content_hash": "8dc8f0e9728fa5b0032e6dfb8e54e715", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 97, "avg_line_length": 31.419708029197082, "alnum_prop": 0.6028574747357417, "repo_name": "foxostro/CheeseTesseract", "id": "6ec5ec530517d765ad057db50a6d437bc7ac3443", "size": "8689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "external/windows/boost/include/boost/lambda/detail/lambda_functors.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "469274" }, { "name": "Lua", "bytes": "2009" }, { "name": "Shell", "bytes": "176" } ], "symlink_target": "" }
int main (void) { int prog_state = 0, option = 0, N = 5, M = 2, nPower = 1, mPower = 1, numTests = 1, simOption = 0; string outputFile = "output.txt"; while (prog_state > -1) { // loading? if (prog_state == 0) { simOption = display_menu (1, 0, ':', 1, 2, ";", "Programming Assignment 1 - MyJosephus Problem", "Choose Output Method", "Display All Output and Record Partial Output;Only Record Partial Output"); prog_state = 1; } else if (prog_state == 1) { option = display_menu (1, 0, ':', 1, 9, ";", "Programming Assignment 1 - MyJosephus Problem", "Main Menu", "Test List Implementation;Test Vector Implementation;Set Number of People;Set Elimination Jump Interval;Set Number of People Power Increase;Set Elimination Jump Interval Power Increase;Set Number of Test Cycles;Set Output File Name;Quit"); cin.clear(); cin.ignore(500, '\n' ); if (option == 1) { if (simOption == 1) testListOutput (N, M, nPower, mPower, numTests, outputFile); else if (simOption == 2) testListNoOutput (N, M, nPower, mPower, numTests, outputFile); } else if (option == 2) { if (simOption == 1) testVectorOutput (N, M, nPower, mPower, numTests, outputFile); else if (simOption == 2) testVectorNoOutput (N, M, nPower, mPower, numTests, outputFile); } else if (option == 3) { system ("cls"); cout << "Enter Number of People Playing: "; cin >> N; } else if (option == 4) { system ("cls"); cout << "Enter Elimination Jump Interval: "; cin >> M; } else if (option == 5) { system ("cls"); cout << "Enter Number of People Power Increase: "; cin >> nPower; } else if (option == 6) { system ("cls"); cout << "Enter Elimination Jump Interval Power Increase: "; cin >> mPower; } else if (option == 7) { system ("cls"); cout << "Enter Number of Test Cycles: "; cin >> numTests; } else if (option == 8) { system ("cls"); cout << "Enter Output Filename (with file extension): "; cin >> outputFile; } else { prog_state = -1; } } } return 0; }
{ "content_hash": "7fdb6240e5ba1fa87f9a187dd0e72ab5", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 256, "avg_line_length": 27.126582278481013, "alnum_prop": 0.5912272515165655, "repo_name": "vonderborch/CS223", "id": "7f12c29944c57c7344e34686ed596568c4ab82ad", "size": "2458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PP1/ProgrammingProject1/ProgrammingProject1/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "539" }, { "name": "C++", "bytes": "77523" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace DurableTask.Core { using System; /// <summary> /// An active instance / work item of a task activity /// </summary> public class TaskActivityWorkItem { /// <summary> /// The Id of the work work item, likely related to the task message /// </summary> public string Id; /// <summary> /// The datetime this work item is locked until /// </summary> public DateTime LockedUntilUtc; /// <summary> /// The task message associated with this work item /// </summary> public TaskMessage TaskMessage; } }
{ "content_hash": "50848a4bb7e74307091157c64138a5fe", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 87, "avg_line_length": 36.73684210526316, "alnum_prop": 0.5752148997134671, "repo_name": "affandar/durabletask", "id": "70278b18931c2d8ab0b80dd7168669c8dea0da4a", "size": "1398", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/DurableTask.Core/TaskActivityWorkItem.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "731468" } ], "symlink_target": "" }
All you need to build your own (Big) Data &amp; IOT oriented application ``` docker network create --attachable --driver overlay deetazilla ``` ## Docker Compose File * To create your `docker-compose-merge.yml` file thanks to [combine_services.sh](./dz_compose/scripts/combine_services.sh), which makes use of [yamlreader](https://github.com/ImmobilienScout24/yamlreader): ``` > docker_tag="1.5" ``` * Free Properties * When Docker Secrets are provided: ``` > docker run --rm logimethods/int_compose:${docker_tag} combine_services "[single|cluster]" "secrets" root_metrics spark > docker-compose-merge.yml ``` * When Docker Secrets are NOT provided: ``` > docker run --rm logimethods/int_compose:${docker_tag} combine_services "[single|cluster]" "no_secrets" root_metrics spark > docker-compose-merge.yml ``` * Making use of Properties Files * When Docker Secrets are provided: ``` > docker run --rm logimethods/int_compose:${docker_tag} combine_services -e "local" "[single|cluster]" "secrets" root_metrics spark > docker-compose-merge.yml ``` * When Docker Secrets are NOT provided: ``` > docker run --rm logimethods/int_compose:${docker_tag} combine_services -e "local" "[single|cluster]" "no_secrets" root_metrics spark > docker-compose-merge.yml ``` * To enforce Additional Properties (here located in `alt_properties`): ``` > docker run --rm -v `pwd`/alt_properties:/templater/alt_properties logimethods/int_compose:${docker_tag} combine_services -p alt_properties -e "local" "[single|cluster]" "secrets" root_metrics spark ``` * To directly start the services: ``` > docker run --rm -v /var/run/docker.sock:/var/run/docker.sock logimethods/int_compose:${docker_tag} stack-up "stack_name" "local" "[single|cluster]" "no_secrets" root_metrics spark ``` Or with Docker secrets ``` > docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v `pwd`/devsecrets:/templater/devsecrets logimethods/int_compose:${docker_tag} stack-up "stack_name" "local" "[single|cluster]" "secrets" root_metrics spark ``` You might also use a shortcut (`local-single-up`, `local-cluster-up`, `remote-single-up` or `remote-cluster-up`): ``` > docker run --rm -v /var/run/docker.sock:/var/run/docker.sock logimethods/int_compose:${docker_tag} local-single-up "stack_name" "[single|cluster]" "no_secrets" root_metrics spark ``` * Then, to stop the stack: ``` docker run --rm -v /var/run/docker.sock:/var/run/docker.sock logimethods/int_compose:${docker_tag} \ stack-down "stack_name" "local" ``` Or ``` docker run --rm -v /var/run/docker.sock:/var/run/docker.sock logimethods/int_compose:${docker_tag} \ local-down "stack_name" ``` Or ``` docker run --rm -v /var/run/docker.sock:/var/run/docker.sock logimethods/int_compose:${docker_tag} \ remote-down "stack_name" ``` ## "Docker Compose" Script ``` cd scripts ./compose_classic.sh ``` ## Concourse Continuous Build Process See [Concourse Pipeline](concourse/deetazilla-pipeline.yml). ![deetazilla_concourse_main.png](images/deetazilla_concourse_main.png "Concourse Main Build") ![deetazilla_concourse_integration.png](images/deetazilla_concourse_integration.png "Concourse Integration Build")
{ "content_hash": "f5858f8c02d099693981f101f5c94315", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 226, "avg_line_length": 44.46153846153846, "alnum_prop": 0.6600346020761245, "repo_name": "Logimethods/deetazilla", "id": "22f0273a4e0800a46aa8fc25dfa5c4c62ac088a2", "size": "3481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "7715" }, { "name": "Java", "bytes": "1370" }, { "name": "Python", "bytes": "1516" }, { "name": "Scala", "bytes": "10076" }, { "name": "Shell", "bytes": "18007" }, { "name": "Smarty", "bytes": "30224" } ], "symlink_target": "" }
/* * winhelp.h - define Windows Help context names. * Each definition has the form "winhelp-topic:halibut-topic", where: * - "winhelp-topic" matches up with the \cfg{winhelp-topic} directives * in the Halibut source, and is used for WinHelp; * - "halibut-topic" matches up with the Halibut keywords in the source, * and is used for HTML Help. */ /* Maximum length for WINHELP_CTX_foo strings */ #define WINHELP_CTX_MAXLEN 80 /* These are used in the cross-platform configuration dialog code. */ #define HELPCTX(x) P(WINHELP_CTX_ ## x) #define WINHELP_CTX_no_help NULL #define WINHELP_CTX_session_hostname "session.hostname:config-hostname" #define WINHELP_CTX_session_saved "session.saved:config-saving" #define WINHELP_CTX_session_coe "session.coe:config-closeonexit" #define WINHELP_CTX_logging_main "logging.main:config-logging" #define WINHELP_CTX_logging_filename "logging.filename:config-logfilename" #define WINHELP_CTX_logging_exists "logging.exists:config-logfileexists" #define WINHELP_CTX_logging_flush "logging.flush:config-logflush" #define WINHELP_CTX_logging_ssh_omit_password "logging.ssh.omitpassword:config-logssh" #define WINHELP_CTX_logging_ssh_omit_data "logging.ssh.omitdata:config-logssh" #define WINHELP_CTX_keyboard_backspace "keyboard.backspace:config-backspace" #define WINHELP_CTX_keyboard_homeend "keyboard.homeend:config-homeend" #define WINHELP_CTX_keyboard_funkeys "keyboard.funkeys:config-funkeys" #define WINHELP_CTX_keyboard_appkeypad "keyboard.appkeypad:config-appkeypad" #define WINHELP_CTX_keyboard_appcursor "keyboard.appcursor:config-appcursor" #define WINHELP_CTX_keyboard_nethack "keyboard.nethack:config-nethack" #define WINHELP_CTX_keyboard_compose "keyboard.compose:config-compose" #define WINHELP_CTX_keyboard_ctrlalt "keyboard.ctrlalt:config-ctrlalt" #define WINHELP_CTX_features_application "features.application:config-features-application" #define WINHELP_CTX_features_mouse "features.mouse:config-features-mouse" #define WINHELP_CTX_features_resize "features.resize:config-features-resize" #define WINHELP_CTX_features_altscreen "features.altscreen:config-features-altscreen" #define WINHELP_CTX_features_retitle "features.retitle:config-features-retitle" #define WINHELP_CTX_features_qtitle "features.qtitle:config-features-qtitle" #define WINHELP_CTX_features_dbackspace "features.dbackspace:config-features-dbackspace" #define WINHELP_CTX_features_charset "features.charset:config-features-charset" #define WINHELP_CTX_features_arabicshaping "features.arabicshaping:config-features-shaping" #define WINHELP_CTX_features_bidi "features.bidi:config-features-bidi" #define WINHELP_CTX_terminal_autowrap "terminal.autowrap:config-autowrap" #define WINHELP_CTX_terminal_decom "terminal.decom:config-decom" #define WINHELP_CTX_terminal_lfhascr "terminal.lfhascr:config-crlf" #define WINHELP_CTX_terminal_crhaslf "terminal.crhaslf:config-lfcr" #define WINHELP_CTX_terminal_bce "terminal.bce:config-erase" #define WINHELP_CTX_terminal_blink "terminal.blink:config-blink" #define WINHELP_CTX_terminal_answerback "terminal.answerback:config-answerback" #define WINHELP_CTX_terminal_localecho "terminal.localecho:config-localecho" #define WINHELP_CTX_terminal_localedit "terminal.localedit:config-localedit" #define WINHELP_CTX_terminal_printing "terminal.printing:config-printing" #define WINHELP_CTX_bell_style "bell.style:config-bellstyle" #define WINHELP_CTX_bell_taskbar "bell.taskbar:config-belltaskbar" #define WINHELP_CTX_bell_overload "bell.overload:config-bellovl" #define WINHELP_CTX_window_size "window.size:config-winsize" #define WINHELP_CTX_window_resize "window.resize:config-winsizelock" #define WINHELP_CTX_window_scrollback "window.scrollback:config-scrollback" #define WINHELP_CTX_window_erased "window.erased:config-erasetoscrollback" #define WINHELP_CTX_behaviour_closewarn "behaviour.closewarn:config-warnonclose" #define WINHELP_CTX_behaviour_altf4 "behaviour.altf4:config-altf4" /* Hot key enhancement by Kasper */ #define WINHELP_CTX_behaviour_f1 "behaviour.f1:config-f1" #define WINHELP_CTX_behaviour_f2 "behaviour.f2:config-f2" #define WINHELP_CTX_behaviour_f3 "behaviour.f3:config-f3" #define WINHELP_CTX_behaviour_f4 "behaviour.f4:config-f4" /* end */ #define WINHELP_CTX_behaviour_altspace "behaviour.altspace:config-altspace" #define WINHELP_CTX_behaviour_altonly "behaviour.altonly:config-altonly" #define WINHELP_CTX_behaviour_alwaysontop "behaviour.alwaysontop:config-alwaysontop" #define WINHELP_CTX_behaviour_altenter "behaviour.altenter:config-fullscreen" #define WINHELP_CTX_appearance_cursor "appearance.cursor:config-cursor" #define WINHELP_CTX_appearance_font "appearance.font:config-font" #define WINHELP_CTX_appearance_title "appearance.title:config-title" #define WINHELP_CTX_appearance_hidemouse "appearance.hidemouse:config-mouseptr" #define WINHELP_CTX_appearance_border "appearance.border:config-winborder" #define WINHELP_CTX_connection_termtype "connection.termtype:config-termtype" #define WINHELP_CTX_connection_termspeed "connection.termspeed:config-termspeed" #define WINHELP_CTX_connection_username "connection.username:config-username" #define WINHELP_CTX_connection_username_from_env "connection.usernamefromenv:config-username-from-env" #define WINHELP_CTX_connection_keepalive "connection.keepalive:config-keepalive" #define WINHELP_CTX_connection_nodelay "connection.nodelay:config-nodelay" /* brian jiang */ #define WINHELP_CTX_connection_autologin "connection..autologin:config-autologin" #define WINHELP_CTX_connection_autologinusername "connection..autologinusername:config-autologinusername" #define WINHELP_CTX_connection_autologinpasswd "connection..autologinpasswd:config-autologinpasswd" /* End, brian jiang */ #define WINHELP_CTX_connection_ipversion "connection.ipversion:config-address-family" #define WINHELP_CTX_connection_tcpkeepalive "connection.tcpkeepalive:config-tcp-keepalives" #define WINHELP_CTX_connection_loghost "connection.loghost:config-loghost" #define WINHELP_CTX_proxy_type "proxy.type:config-proxy-type" #define WINHELP_CTX_proxy_main "proxy.main:config-proxy" #define WINHELP_CTX_proxy_exclude "proxy.exclude:config-proxy-exclude" #define WINHELP_CTX_proxy_dns "proxy.dns:config-proxy-dns" #define WINHELP_CTX_proxy_auth "proxy.auth:config-proxy-auth" #define WINHELP_CTX_proxy_command "proxy.command:config-proxy-command" #define WINHELP_CTX_telnet_environ "telnet.environ:config-environ" #define WINHELP_CTX_telnet_oldenviron "telnet.oldenviron:config-oldenviron" #define WINHELP_CTX_telnet_passive "telnet.passive:config-ptelnet" #define WINHELP_CTX_telnet_specialkeys "telnet.specialkeys:config-telnetkey" #define WINHELP_CTX_telnet_newline "telnet.newline:config-telnetnl" #define WINHELP_CTX_rlogin_localuser "rlogin.localuser:config-rlogin-localuser" #define WINHELP_CTX_ssh_nopty "ssh.nopty:config-ssh-pty" #define WINHELP_CTX_ssh_ttymodes "ssh.ttymodes:config-ttymodes" #define WINHELP_CTX_ssh_noshell "ssh.noshell:config-ssh-noshell" #define WINHELP_CTX_ssh_ciphers "ssh.ciphers:config-ssh-encryption" #define WINHELP_CTX_ssh_protocol "ssh.protocol:config-ssh-prot" #define WINHELP_CTX_ssh_command "ssh.command:config-command" #define WINHELP_CTX_ssh_compress "ssh.compress:config-ssh-comp" #define WINHELP_CTX_ssh_share "ssh.sharing:config-ssh-sharing" #define WINHELP_CTX_ssh_kexlist "ssh.kex.order:config-ssh-kex-order" #define WINHELP_CTX_ssh_kex_repeat "ssh.kex.repeat:config-ssh-kex-rekey" #define WINHELP_CTX_ssh_kex_manual_hostkeys "ssh.kex.manualhostkeys:config-ssh-kex-manual-hostkeys" #define WINHELP_CTX_ssh_auth_bypass "ssh.auth.bypass:config-ssh-noauth" #define WINHELP_CTX_ssh_auth_banner "ssh.auth.banner:config-ssh-banner" #define WINHELP_CTX_ssh_auth_privkey "ssh.auth.privkey:config-ssh-privkey" #define WINHELP_CTX_ssh_auth_agentfwd "ssh.auth.agentfwd:config-ssh-agentfwd" #define WINHELP_CTX_ssh_auth_changeuser "ssh.auth.changeuser:config-ssh-changeuser" #define WINHELP_CTX_ssh_auth_pageant "ssh.auth.pageant:config-ssh-tryagent" #define WINHELP_CTX_ssh_auth_tis "ssh.auth.tis:config-ssh-tis" #define WINHELP_CTX_ssh_auth_ki "ssh.auth.ki:config-ssh-ki" #define WINHELP_CTX_ssh_gssapi "ssh.auth.gssapi:config-ssh-auth-gssapi" #define WINHELP_CTX_ssh_gssapi_delegation "ssh.auth.gssapi.delegation:config-ssh-auth-gssapi-delegation" #define WINHELP_CTX_ssh_gssapi_libraries "ssh.auth.gssapi.libraries:config-ssh-auth-gssapi-libraries" #define WINHELP_CTX_selection_buttons "selection.buttons:config-mouse" #define WINHELP_CTX_selection_shiftdrag "selection.shiftdrag:config-mouseshift" #define WINHELP_CTX_selection_rect "selection.rect:config-rectselect" #define WINHELP_CTX_selection_charclasses "selection.charclasses:config-charclasses" #define WINHELP_CTX_selection_linedraw "selection.linedraw:config-linedrawpaste" #define WINHELP_CTX_selection_rtf "selection.rtf:config-rtfpaste" #define WINHELP_CTX_colours_ansi "colours.ansi:config-ansicolour" #define WINHELP_CTX_colours_xterm256 "colours.xterm256:config-xtermcolour" #define WINHELP_CTX_colours_bold "colours.bold:config-boldcolour" #define WINHELP_CTX_colours_system "colours.system:config-syscolour" #define WINHELP_CTX_colours_logpal "colours.logpal:config-logpalette" #define WINHELP_CTX_colours_config "colours.config:config-colourcfg" #define WINHELP_CTX_translation_codepage "translation.codepage:config-charset" #define WINHELP_CTX_translation_cjk_ambig_wide "translation.cjkambigwide:config-cjk-ambig-wide" #define WINHELP_CTX_translation_cyrillic "translation.cyrillic:config-cyr" #define WINHELP_CTX_translation_linedraw "translation.linedraw:config-linedraw" #define WINHELP_CTX_ssh_tunnels_x11 "ssh.tunnels.x11:config-ssh-x11" #define WINHELP_CTX_ssh_tunnels_x11auth "ssh.tunnels.x11auth:config-ssh-x11auth" #define WINHELP_CTX_ssh_tunnels_xauthority "ssh.tunnels.xauthority:config-ssh-xauthority" #define WINHELP_CTX_ssh_tunnels_portfwd "ssh.tunnels.portfwd:config-ssh-portfwd" #define WINHELP_CTX_ssh_tunnels_portfwd_localhost "ssh.tunnels.portfwd.localhost:config-ssh-portfwd-localhost" #define WINHELP_CTX_ssh_tunnels_portfwd_ipversion "ssh.tunnels.portfwd.ipversion:config-ssh-portfwd-address-family" #define WINHELP_CTX_ssh_bugs_ignore1 "ssh.bugs.ignore1:config-ssh-bug-ignore1" #define WINHELP_CTX_ssh_bugs_plainpw1 "ssh.bugs.plainpw1:config-ssh-bug-plainpw1" #define WINHELP_CTX_ssh_bugs_rsa1 "ssh.bugs.rsa1:config-ssh-bug-rsa1" #define WINHELP_CTX_ssh_bugs_ignore2 "ssh.bugs.ignore2:config-ssh-bug-ignore2" #define WINHELP_CTX_ssh_bugs_hmac2 "ssh.bugs.hmac2:config-ssh-bug-hmac2" #define WINHELP_CTX_ssh_bugs_derivekey2 "ssh.bugs.derivekey2:config-ssh-bug-derivekey2" #define WINHELP_CTX_ssh_bugs_rsapad2 "ssh.bugs.rsapad2:config-ssh-bug-sig" #define WINHELP_CTX_ssh_bugs_pksessid2 "ssh.bugs.pksessid2:config-ssh-bug-pksessid2" #define WINHELP_CTX_ssh_bugs_rekey2 "ssh.bugs.rekey2:config-ssh-bug-rekey" #define WINHELP_CTX_ssh_bugs_maxpkt2 "ssh.bugs.maxpkt2:config-ssh-bug-maxpkt2" #define WINHELP_CTX_ssh_bugs_winadj "ssh.bugs.winadj:config-ssh-bug-winadj" #define WINHELP_CTX_ssh_bugs_chanreq "ssh.bugs.winadj:config-ssh-bug-chanreq" #define WINHELP_CTX_ssh_bugs_oldgex2 "ssh.bugs.oldgex2:config-ssh-bug-oldgex2" #define WINHELP_CTX_serial_line "serial.line:config-serial-line" #define WINHELP_CTX_serial_speed "serial.speed:config-serial-speed" #define WINHELP_CTX_serial_databits "serial.databits:config-serial-databits" #define WINHELP_CTX_serial_stopbits "serial.stopbits:config-serial-stopbits" #define WINHELP_CTX_serial_parity "serial.parity:config-serial-parity" #define WINHELP_CTX_serial_flow "serial.flow:config-serial-flow" #define WINHELP_CTX_pageant_general "pageant.general:pageant" #define WINHELP_CTX_pageant_keylist "pageant.keylist:pageant-mainwin-keylist" #define WINHELP_CTX_pageant_addkey "pageant.addkey:pageant-mainwin-addkey" #define WINHELP_CTX_pageant_remkey "pageant.remkey:pageant-mainwin-remkey" #define WINHELP_CTX_pgpfingerprints "pgpfingerprints:pgpkeys" #define WINHELP_CTX_puttygen_general "puttygen.general:pubkey-puttygen" #define WINHELP_CTX_puttygen_keytype "puttygen.keytype:puttygen-keytype" #define WINHELP_CTX_puttygen_bits "puttygen.bits:puttygen-strength" #define WINHELP_CTX_puttygen_generate "puttygen.generate:puttygen-generate" #define WINHELP_CTX_puttygen_fingerprint "puttygen.fingerprint:puttygen-fingerprint" #define WINHELP_CTX_puttygen_comment "puttygen.comment:puttygen-comment" #define WINHELP_CTX_puttygen_passphrase "puttygen.passphrase:puttygen-passphrase" #define WINHELP_CTX_puttygen_savepriv "puttygen.savepriv:puttygen-savepriv" #define WINHELP_CTX_puttygen_savepub "puttygen.savepub:puttygen-savepub" #define WINHELP_CTX_puttygen_pastekey "puttygen.pastekey:puttygen-pastekey" #define WINHELP_CTX_puttygen_load "puttygen.load:puttygen-load" #define WINHELP_CTX_puttygen_conversions "puttygen.conversions:puttygen-conversions" /* These are used in Windows-specific bits of the frontend. * We (ab)use "help context identifiers" (dwContextId) to identify them. */ #define HELPCTXID(x) WINHELP_CTXID_ ## x #define WINHELP_CTXID_no_help 0 #define WINHELP_CTX_errors_hostkey_absent "errors.hostkey.absent:errors-hostkey-absent" #define WINHELP_CTXID_errors_hostkey_absent 1 #define WINHELP_CTX_errors_hostkey_changed "errors.hostkey.changed:errors-hostkey-wrong" #define WINHELP_CTXID_errors_hostkey_changed 2 #define WINHELP_CTX_errors_cantloadkey "errors.cantloadkey:errors-cant-load-key" #define WINHELP_CTXID_errors_cantloadkey 3 #define WINHELP_CTX_option_cleanup "options.cleanup:using-cleanup" #define WINHELP_CTXID_option_cleanup 4 #define WINHELP_CTX_pgp_fingerprints "pgpfingerprints:pgpkeys" #define WINHELP_CTXID_pgp_fingerprints 5
{ "content_hash": "2d4eb6302483dc0c6f1b736c2dc1f948", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 115, "avg_line_length": 67.38916256157636, "alnum_prop": 0.8173976608187135, "repo_name": "KasperDeng/putty", "id": "6cbc0aae386ce9c358f89f6042042554417537a0", "size": "13680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "putty-src/windows/winhelp.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3535683" }, { "name": "CSS", "bytes": "254" }, { "name": "Inno Setup", "bytes": "6565" }, { "name": "M4", "bytes": "6491" }, { "name": "Makefile", "bytes": "18145" }, { "name": "Objective-C", "bytes": "109045" }, { "name": "Perl", "bytes": "135083" }, { "name": "Python", "bytes": "53659" }, { "name": "Shell", "bytes": "15112" } ], "symlink_target": "" }
package org.apache.shardingsphere.elasticjob.restful.serializer; import java.text.MessageFormat; /** * {@link ResponseBodySerializer} not found for specific MIME type. */ public final class ResponseBodySerializerNotFoundException extends RuntimeException { private static final long serialVersionUID = 3201288074956273247L; public ResponseBodySerializerNotFoundException(final String mimeType) { super(MessageFormat.format("ResponseBodySerializer not found for [{0}]", mimeType)); } }
{ "content_hash": "0853b8f52f205d24133725fd0e655d1d", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 92, "avg_line_length": 30.647058823529413, "alnum_prop": 0.7735124760076776, "repo_name": "elasticjob/elastic-job", "id": "415c5e23e76abe6f51efd76f47fbf986495f9926", "size": "1322", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "elasticjob-infra/elasticjob-restful/src/main/java/org/apache/shardingsphere/elasticjob/restful/serializer/ResponseBodySerializerNotFoundException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "553" }, { "name": "CSS", "bytes": "102201" }, { "name": "HTML", "bytes": "189227" }, { "name": "Java", "bytes": "1743175" }, { "name": "JavaScript", "bytes": "704805" }, { "name": "Shell", "bytes": "1889" } ], "symlink_target": "" }
import Joi = require('joi'); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let x: any = null; let value: any = null; let num: number = 0; let str: string = ''; let bool: boolean = false; let exp: RegExp = null; let obj: object = null; let date: Date = null; let err: Error = null; let func: Function = null; let anyArr: any[] = []; let numArr: number[] = []; let strArr: string[] = []; let boolArr: boolean[] = []; let expArr: RegExp[] = []; let objArr: object[] = []; let errArr: Error[] = []; let funcArr: Function[] = []; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let schema: Joi.Schema = null; let schemaLike: Joi.SchemaLike = null; let anySchema: Joi.AnySchema = null; let numSchema: Joi.NumberSchema = null; let strSchema: Joi.StringSchema = null; let arrSchema: Joi.ArraySchema = null; let boolSchema: Joi.BooleanSchema = null; let binSchema: Joi.BinarySchema = null; let dateSchema: Joi.DateSchema = null; let funcSchema: Joi.FunctionSchema = null; let objSchema: Joi.ObjectSchema = null; let altSchema: Joi.AlternativesSchema = null; let schemaArr: Joi.Schema[] = []; let ref: Joi.Reference = null; let description: Joi.Description = null; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let validOpts: Joi.ValidationOptions = null; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; validOpts = { allowUnknown: bool }; validOpts = { skipFunctions: bool }; validOpts = { stripUnknown: bool }; validOpts = { stripUnknown: { arrays: bool } }; validOpts = { stripUnknown: { objects: bool } }; validOpts = { stripUnknown: { arrays: bool, objects: bool } }; validOpts = { presence: 'optional' || 'required' || 'forbidden' }; validOpts = { context: obj }; validOpts = { noDefaults: bool }; validOpts = { language: { root: str, key: str, messages: { wrapArrays: bool }, string: { base: str }, number: { base: str }, object: { base: false, children: { childRule: str } }, customType: { customRule: str } } }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let renOpts: Joi.RenameOptions = null; renOpts = { alias: bool }; renOpts = { multiple: bool }; renOpts = { override: bool }; renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let emailOpts: Joi.EmailOptions = null; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; emailOpts = { tldWhitelist: strArr }; emailOpts = { tldWhitelist: obj }; emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; ipOpts = { version: strArr }; ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let uriOpts: Joi.UriOptions = null; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; uriOpts = { scheme: strArr }; uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let base64Opts: Joi.Base64Options = null; base64Opts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let whenOpts: Joi.WhenOptions = null; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; whenOpts = { is: schema, otherwise: schema }; whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let whenSchemaOpts: Joi.WhenSchemaOptions = null; whenSchemaOpts = { then: schema }; whenSchemaOpts = { otherwise: schema }; whenSchemaOpts = { then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let refOpts: Joi.ReferenceOptions = null; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let stringRegexOpts: Joi.StringRegexOptions = null; stringRegexOpts = { name: str }; stringRegexOpts = { invert: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let validErr: Joi.ValidationError = null; let validErrItem: Joi.ValidationErrorItem; let validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, type: str, path: [str] }; validErrItem = { message: str, type: str, path: [str], options: validOpts, context: obj }; validErrFunc = errs => errs; validErrFunc = errs => errs[0]; validErrFunc = errs => 'Some error'; validErrFunc = errs => err; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = anySchema; schema = numSchema; schema = strSchema; schema = arrSchema; schema = boolSchema; schema = binSchema; schema = dateSchema; schema = funcSchema; schema = objSchema; anySchema = anySchema; anySchema = numSchema; anySchema = strSchema; anySchema = arrSchema; anySchema = boolSchema; anySchema = binSchema; anySchema = dateSchema; anySchema = funcSchema; anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- let schemaMap: Joi.SchemaMap = null; schemaMap = { a: numSchema, b: strSchema }; schemaMap = { a: numSchema, b: { b1: strSchema, b2: anySchema } }; schemaMap = { a: numSchema, b: [ { b1: strSchema }, { b2: anySchema } ], c: arrSchema, d: schemaLike }; schemaMap = { a: 1, b: { b1: '1', b2: 2 }, c: [ { c1: true }, { c2: null } ] } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- anySchema = Joi.any(); namespace common { anySchema = anySchema.allow(x); anySchema = anySchema.allow(x, x); anySchema = anySchema.allow([x, x, x]); anySchema = anySchema.valid(x); anySchema = anySchema.valid(x, x); anySchema = anySchema.valid([x, x, x]); anySchema = anySchema.only(x); anySchema = anySchema.only(x, x); anySchema = anySchema.only([x, x, x]); anySchema = anySchema.equal(x); anySchema = anySchema.equal(x, x); anySchema = anySchema.equal([x, x, x]); anySchema = anySchema.invalid(x); anySchema = anySchema.invalid(x, x); anySchema = anySchema.invalid([x, x, x]); anySchema = anySchema.disallow(x); anySchema = anySchema.disallow(x, x); anySchema = anySchema.disallow([x, x, x]); anySchema = anySchema.not(x); anySchema = anySchema.not(x, x); anySchema = anySchema.not([x, x, x]); anySchema = anySchema.default(); anySchema = anySchema.default(x); anySchema = anySchema.default(x, str); anySchema = anySchema.required(); anySchema = anySchema.optional(); anySchema = anySchema.forbidden(); anySchema = anySchema.strip(); anySchema = anySchema.description(str); anySchema = anySchema.notes(str); anySchema = anySchema.notes(strArr); anySchema = anySchema.tags(str); anySchema = anySchema.tags(strArr); anySchema = anySchema.meta(obj); anySchema = anySchema.example(obj); anySchema = anySchema.unit(str); anySchema = anySchema.options(validOpts); anySchema = anySchema.strict(); anySchema = anySchema.strict(bool); anySchema = anySchema.concat(x); altSchema = anySchema.when(str, whenOpts); altSchema = anySchema.when(ref, whenOpts); altSchema = anySchema.when(schema, whenSchemaOpts); anySchema = anySchema.label(str); anySchema = anySchema.raw(); anySchema = anySchema.raw(bool); anySchema = anySchema.empty(); anySchema = anySchema.empty(str); anySchema = anySchema.empty(anySchema); anySchema = anySchema.error(err); anySchema = anySchema.error(validErrFunc); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- arrSchema = Joi.array(); arrSchema = arrSchema.sparse(); arrSchema = arrSchema.sparse(bool); arrSchema = arrSchema.single(); arrSchema = arrSchema.single(bool); arrSchema = arrSchema.ordered(anySchema); arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema, schemaLike); arrSchema = arrSchema.ordered(schemaMap); arrSchema = arrSchema.ordered([schemaMap, schemaMap, schemaLike]); arrSchema = arrSchema.min(num); arrSchema = arrSchema.max(num); arrSchema = arrSchema.length(num); arrSchema = arrSchema.unique(); arrSchema = arrSchema.unique((a, b) => a.test === b.test); arrSchema = arrSchema.unique('customer.id'); arrSchema = arrSchema.items(numSchema); arrSchema = arrSchema.items(numSchema, strSchema, schemaLike); arrSchema = arrSchema.items([numSchema, strSchema, schemaLike]); arrSchema = arrSchema.items(schemaMap); arrSchema = arrSchema.items(schemaMap, schemaMap, schemaLike); arrSchema = arrSchema.items([schemaMap, schemaMap, schemaLike]); // - - - - - - - - namespace common_copy_paste { // use search & replace from any arrSchema = arrSchema.allow(x); arrSchema = arrSchema.allow(x, x); arrSchema = arrSchema.allow([x, x, x]); arrSchema = arrSchema.valid(x); arrSchema = arrSchema.valid(x, x); arrSchema = arrSchema.valid([x, x, x]); arrSchema = arrSchema.only(x); arrSchema = arrSchema.only(x, x); arrSchema = arrSchema.only([x, x, x]); arrSchema = arrSchema.equal(x); arrSchema = arrSchema.equal(x, x); arrSchema = arrSchema.equal([x, x, x]); arrSchema = arrSchema.invalid(x); arrSchema = arrSchema.invalid(x, x); arrSchema = arrSchema.invalid([x, x, x]); arrSchema = arrSchema.disallow(x); arrSchema = arrSchema.disallow(x, x); arrSchema = arrSchema.disallow([x, x, x]); arrSchema = arrSchema.not(x); arrSchema = arrSchema.not(x, x); arrSchema = arrSchema.not([x, x, x]); arrSchema = arrSchema.default(x); arrSchema = arrSchema.required(); arrSchema = arrSchema.optional(); arrSchema = arrSchema.forbidden(); arrSchema = arrSchema.description(str); arrSchema = arrSchema.notes(str); arrSchema = arrSchema.notes(strArr); arrSchema = arrSchema.tags(str); arrSchema = arrSchema.tags(strArr); arrSchema = arrSchema.meta(obj); arrSchema = arrSchema.example(obj); arrSchema = arrSchema.unit(str); arrSchema = arrSchema.options(validOpts); arrSchema = arrSchema.strict(); arrSchema = arrSchema.concat(x); altSchema = arrSchema.when(str, whenOpts); altSchema = arrSchema.when(ref, whenOpts); altSchema = arrSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- boolSchema = Joi.bool(); boolSchema = Joi.boolean(); namespace common_copy_paste { boolSchema = boolSchema.allow(x); boolSchema = boolSchema.allow(x, x); boolSchema = boolSchema.allow([x, x, x]); boolSchema = boolSchema.valid(x); boolSchema = boolSchema.valid(x, x); boolSchema = boolSchema.valid([x, x, x]); boolSchema = boolSchema.only(x); boolSchema = boolSchema.only(x, x); boolSchema = boolSchema.only([x, x, x]); boolSchema = boolSchema.equal(x); boolSchema = boolSchema.equal(x, x); boolSchema = boolSchema.equal([x, x, x]); boolSchema = boolSchema.invalid(x); boolSchema = boolSchema.invalid(x, x); boolSchema = boolSchema.invalid([x, x, x]); boolSchema = boolSchema.disallow(x); boolSchema = boolSchema.disallow(x, x); boolSchema = boolSchema.disallow([x, x, x]); boolSchema = boolSchema.not(x); boolSchema = boolSchema.not(x, x); boolSchema = boolSchema.not([x, x, x]); boolSchema = boolSchema.default(x); boolSchema = boolSchema.required(); boolSchema = boolSchema.optional(); boolSchema = boolSchema.forbidden(); boolSchema = boolSchema.description(str); boolSchema = boolSchema.notes(str); boolSchema = boolSchema.notes(strArr); boolSchema = boolSchema.tags(str); boolSchema = boolSchema.tags(strArr); boolSchema = boolSchema.meta(obj); boolSchema = boolSchema.example(obj); boolSchema = boolSchema.unit(str); boolSchema = boolSchema.options(validOpts); boolSchema = boolSchema.strict(); boolSchema = boolSchema.concat(x); boolSchema = boolSchema.truthy(str); boolSchema = boolSchema.truthy(num); boolSchema = boolSchema.truthy(strArr); boolSchema = boolSchema.truthy(numArr); boolSchema = boolSchema.truthy(str, str); boolSchema = boolSchema.truthy(strArr, str); boolSchema = boolSchema.truthy(str, strArr); boolSchema = boolSchema.truthy(strArr, strArr); boolSchema = boolSchema.falsy(str); boolSchema = boolSchema.falsy(num); boolSchema = boolSchema.falsy(strArr); boolSchema = boolSchema.falsy(numArr); boolSchema = boolSchema.falsy(str, str); boolSchema = boolSchema.falsy(strArr, str); boolSchema = boolSchema.falsy(str, strArr); boolSchema = boolSchema.falsy(strArr, strArr); boolSchema = boolSchema.insensitive(bool); altSchema = boolSchema.when(str, whenOpts); altSchema = boolSchema.when(ref, whenOpts); altSchema = boolSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- binSchema = Joi.binary(); binSchema = binSchema.encoding(str); binSchema = binSchema.min(num); binSchema = binSchema.max(num); binSchema = binSchema.length(num); namespace common { binSchema = binSchema.allow(x); binSchema = binSchema.allow(x, x); binSchema = binSchema.allow([x, x, x]); binSchema = binSchema.valid(x); binSchema = binSchema.valid(x, x); binSchema = binSchema.valid([x, x, x]); binSchema = binSchema.only(x); binSchema = binSchema.only(x, x); binSchema = binSchema.only([x, x, x]); binSchema = binSchema.equal(x); binSchema = binSchema.equal(x, x); binSchema = binSchema.equal([x, x, x]); binSchema = binSchema.invalid(x); binSchema = binSchema.invalid(x, x); binSchema = binSchema.invalid([x, x, x]); binSchema = binSchema.disallow(x); binSchema = binSchema.disallow(x, x); binSchema = binSchema.disallow([x, x, x]); binSchema = binSchema.not(x); binSchema = binSchema.not(x, x); binSchema = binSchema.not([x, x, x]); binSchema = binSchema.default(x); binSchema = binSchema.required(); binSchema = binSchema.optional(); binSchema = binSchema.forbidden(); binSchema = binSchema.description(str); binSchema = binSchema.notes(str); binSchema = binSchema.notes(strArr); binSchema = binSchema.tags(str); binSchema = binSchema.tags(strArr); binSchema = binSchema.meta(obj); binSchema = binSchema.example(obj); binSchema = binSchema.unit(str); binSchema = binSchema.options(validOpts); binSchema = binSchema.strict(); binSchema = binSchema.concat(x); altSchema = binSchema.when(str, whenOpts); altSchema = binSchema.when(ref, whenOpts); altSchema = binSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- dateSchema = Joi.date(); dateSchema = dateSchema.min(date); dateSchema = dateSchema.max(date); dateSchema = dateSchema.min(str); dateSchema = dateSchema.max(str); dateSchema = dateSchema.min(num); dateSchema = dateSchema.max(num); dateSchema = dateSchema.min(ref); dateSchema = dateSchema.max(ref); dateSchema = dateSchema.format(str); dateSchema = dateSchema.format(strArr); dateSchema = dateSchema.iso(); dateSchema = dateSchema.timestamp(); dateSchema = dateSchema.timestamp('javascript'); dateSchema = dateSchema.timestamp('unix'); namespace common { dateSchema = dateSchema.allow(x); dateSchema = dateSchema.allow(x, x); dateSchema = dateSchema.allow([x, x, x]); dateSchema = dateSchema.valid(x); dateSchema = dateSchema.valid(x, x); dateSchema = dateSchema.valid([x, x, x]); dateSchema = dateSchema.only(x); dateSchema = dateSchema.only(x, x); dateSchema = dateSchema.only([x, x, x]); dateSchema = dateSchema.equal(x); dateSchema = dateSchema.equal(x, x); dateSchema = dateSchema.equal([x, x, x]); dateSchema = dateSchema.invalid(x); dateSchema = dateSchema.invalid(x, x); dateSchema = dateSchema.invalid([x, x, x]); dateSchema = dateSchema.disallow(x); dateSchema = dateSchema.disallow(x, x); dateSchema = dateSchema.disallow([x, x, x]); dateSchema = dateSchema.not(x); dateSchema = dateSchema.not(x, x); dateSchema = dateSchema.not([x, x, x]); dateSchema = dateSchema.default(x); dateSchema = dateSchema.required(); dateSchema = dateSchema.optional(); dateSchema = dateSchema.forbidden(); dateSchema = dateSchema.description(str); dateSchema = dateSchema.notes(str); dateSchema = dateSchema.notes(strArr); dateSchema = dateSchema.tags(str); dateSchema = dateSchema.tags(strArr); dateSchema = dateSchema.meta(obj); dateSchema = dateSchema.example(obj); dateSchema = dateSchema.unit(str); dateSchema = dateSchema.options(validOpts); dateSchema = dateSchema.strict(); dateSchema = dateSchema.concat(x); altSchema = dateSchema.when(str, whenOpts); altSchema = dateSchema.when(ref, whenOpts); altSchema = dateSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- funcSchema = Joi.func(); funcSchema = funcSchema.arity(num); funcSchema = funcSchema.minArity(num); funcSchema = funcSchema.maxArity(num); funcSchema = funcSchema.ref(); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- numSchema = Joi.number(); numSchema = numSchema.min(num); numSchema = numSchema.min(ref); numSchema = numSchema.max(num); numSchema = numSchema.max(ref); numSchema = numSchema.greater(num); numSchema = numSchema.greater(ref); numSchema = numSchema.less(num); numSchema = numSchema.less(ref); numSchema = numSchema.integer(); numSchema = numSchema.precision(num); numSchema = numSchema.multiple(num); numSchema = numSchema.positive(); numSchema = numSchema.negative(); namespace common { numSchema = numSchema.allow(x); numSchema = numSchema.allow(x, x); numSchema = numSchema.allow([x, x, x]); numSchema = numSchema.valid(x); numSchema = numSchema.valid(x, x); numSchema = numSchema.valid([x, x, x]); numSchema = numSchema.only(x); numSchema = numSchema.only(x, x); numSchema = numSchema.only([x, x, x]); numSchema = numSchema.equal(x); numSchema = numSchema.equal(x, x); numSchema = numSchema.equal([x, x, x]); numSchema = numSchema.invalid(x); numSchema = numSchema.invalid(x, x); numSchema = numSchema.invalid([x, x, x]); numSchema = numSchema.disallow(x); numSchema = numSchema.disallow(x, x); numSchema = numSchema.disallow([x, x, x]); numSchema = numSchema.not(x); numSchema = numSchema.not(x, x); numSchema = numSchema.not([x, x, x]); numSchema = numSchema.default(x); numSchema = numSchema.required(); numSchema = numSchema.optional(); numSchema = numSchema.forbidden(); numSchema = numSchema.description(str); numSchema = numSchema.notes(str); numSchema = numSchema.notes(strArr); numSchema = numSchema.tags(str); numSchema = numSchema.tags(strArr); numSchema = numSchema.meta(obj); numSchema = numSchema.example(obj); numSchema = numSchema.unit(str); numSchema = numSchema.options(validOpts); numSchema = numSchema.strict(); numSchema = numSchema.concat(x); altSchema = numSchema.when(str, whenOpts); altSchema = numSchema.when(ref, whenOpts); altSchema = numSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- objSchema = Joi.object(); objSchema = Joi.object(schemaMap); objSchema = objSchema.keys(); objSchema = objSchema.keys(schemaMap); objSchema = objSchema.min(num); objSchema = objSchema.max(num); objSchema = objSchema.length(num); objSchema = objSchema.pattern(exp, schema); objSchema = objSchema.pattern(exp, schemaLike); objSchema = objSchema.and(str); objSchema = objSchema.and(str, str); objSchema = objSchema.and(str, str, str); objSchema = objSchema.and(strArr); objSchema = objSchema.nand(str); objSchema = objSchema.nand(str, str); objSchema = objSchema.nand(str, str, str); objSchema = objSchema.nand(strArr); objSchema = objSchema.or(str); objSchema = objSchema.or(str, str); objSchema = objSchema.or(str, str, str); objSchema = objSchema.or(strArr); objSchema = objSchema.xor(str); objSchema = objSchema.xor(str, str); objSchema = objSchema.xor(str, str, str); objSchema = objSchema.xor(strArr); objSchema = objSchema.with(str, str); objSchema = objSchema.with(str, strArr); objSchema = objSchema.without(str, str); objSchema = objSchema.without(str, strArr); objSchema = objSchema.rename(str, str); objSchema = objSchema.rename(str, str, renOpts); objSchema = objSchema.assert(str, schema); objSchema = objSchema.assert(str, schema, str); objSchema = objSchema.assert(ref, schema); objSchema = objSchema.assert(ref, schema, str); objSchema = objSchema.unknown(); objSchema = objSchema.unknown(bool); objSchema = objSchema.type(func); objSchema = objSchema.type(func, str); objSchema = objSchema.requiredKeys(str); objSchema = objSchema.requiredKeys(str, str); objSchema = objSchema.requiredKeys(strArr); objSchema = objSchema.optionalKeys(str); objSchema = objSchema.optionalKeys(str, str); objSchema = objSchema.optionalKeys(strArr); objSchema = objSchema.forbiddenKeys(str); objSchema = objSchema.forbiddenKeys(str, str); objSchema = objSchema.forbiddenKeys(strArr); namespace common { objSchema = objSchema.allow(x); objSchema = objSchema.allow(x, x); objSchema = objSchema.allow([x, x, x]); objSchema = objSchema.valid(x); objSchema = objSchema.valid(x, x); objSchema = objSchema.valid([x, x, x]); objSchema = objSchema.only(x); objSchema = objSchema.only(x, x); objSchema = objSchema.only([x, x, x]); objSchema = objSchema.equal(x); objSchema = objSchema.equal(x, x); objSchema = objSchema.equal([x, x, x]); objSchema = objSchema.invalid(x); objSchema = objSchema.invalid(x, x); objSchema = objSchema.invalid([x, x, x]); objSchema = objSchema.disallow(x); objSchema = objSchema.disallow(x, x); objSchema = objSchema.disallow([x, x, x]); objSchema = objSchema.not(x); objSchema = objSchema.not(x, x); objSchema = objSchema.not([x, x, x]); objSchema = objSchema.default(x); objSchema = objSchema.required(); objSchema = objSchema.optional(); objSchema = objSchema.forbidden(); objSchema = objSchema.description(str); objSchema = objSchema.notes(str); objSchema = objSchema.notes(strArr); objSchema = objSchema.tags(str); objSchema = objSchema.tags(strArr); objSchema = objSchema.meta(obj); objSchema = objSchema.example(obj); objSchema = objSchema.unit(str); objSchema = objSchema.options(validOpts); objSchema = objSchema.strict(); objSchema = objSchema.concat(x); altSchema = objSchema.when(str, whenOpts); altSchema = objSchema.when(ref, whenOpts); altSchema = objSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- strSchema = Joi.string(); strSchema = strSchema.insensitive(); strSchema = strSchema.min(num); strSchema = strSchema.min(num, str); strSchema = strSchema.min(ref); strSchema = strSchema.min(ref, str); strSchema = strSchema.max(num); strSchema = strSchema.max(num, str); strSchema = strSchema.max(ref); strSchema = strSchema.max(ref, str); strSchema = strSchema.creditCard(); strSchema = strSchema.length(num); strSchema = strSchema.length(num, str); strSchema = strSchema.length(ref); strSchema = strSchema.length(ref, str); strSchema = strSchema.regex(exp); strSchema = strSchema.regex(exp, str); strSchema = strSchema.regex(exp, stringRegexOpts); strSchema = strSchema.replace(exp, str); strSchema = strSchema.replace(str, str); strSchema = strSchema.alphanum(); strSchema = strSchema.token(); strSchema = strSchema.email(); strSchema = strSchema.email(emailOpts); strSchema = strSchema.ip(); strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); strSchema = strSchema.uppercase(); strSchema = strSchema.trim(); strSchema = strSchema.truncate(); strSchema = strSchema.truncate(false); strSchema = strSchema.normalize(); strSchema = strSchema.normalize('NFKC'); strSchema = strSchema.base64(); strSchema = strSchema.base64(base64Opts); namespace common { strSchema = strSchema.allow(x); strSchema = strSchema.allow(x, x); strSchema = strSchema.allow([x, x, x]); strSchema = strSchema.valid(x); strSchema = strSchema.valid(x, x); strSchema = strSchema.valid([x, x, x]); strSchema = strSchema.only(x); strSchema = strSchema.only(x, x); strSchema = strSchema.only([x, x, x]); strSchema = strSchema.equal(x); strSchema = strSchema.equal(x, x); strSchema = strSchema.equal([x, x, x]); strSchema = strSchema.invalid(x); strSchema = strSchema.invalid(x, x); strSchema = strSchema.invalid([x, x, x]); strSchema = strSchema.disallow(x); strSchema = strSchema.disallow(x, x); strSchema = strSchema.disallow([x, x, x]); strSchema = strSchema.not(x); strSchema = strSchema.not(x, x); strSchema = strSchema.not([x, x, x]); strSchema = strSchema.default(x); strSchema = strSchema.required(); strSchema = strSchema.optional(); strSchema = strSchema.forbidden(); strSchema = strSchema.description(str); strSchema = strSchema.notes(str); strSchema = strSchema.notes(strArr); strSchema = strSchema.tags(str); strSchema = strSchema.tags(strArr); strSchema = strSchema.meta(obj); strSchema = strSchema.example(obj); strSchema = strSchema.unit(str); strSchema = strSchema.options(validOpts); strSchema = strSchema.strict(); strSchema = strSchema.concat(x); altSchema = strSchema.when(str, whenOpts); altSchema = strSchema.when(ref, whenOpts); altSchema = strSchema.when(schema, whenSchemaOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.alternatives(); schema = Joi.alternatives().try(schemaArr); schema = Joi.alternatives().try(schema, schema); schema = Joi.alternatives(schemaArr); schema = Joi.alternatives(schema, anySchema, boolSchema); schema = Joi.alt(); schema = Joi.alt().try(schemaArr); schema = Joi.alt().try(schema, schema); schema = Joi.alt(schemaArr); schema = Joi.alt(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.lazy(() => schema) // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- namespace validate_tests { { Joi.validate(value, obj); Joi.validate(value, schema); Joi.validate(value, schema, validOpts); Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; str = err.details[0].path[0]; str = err.details[0].message; str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { x = value; str = err.message; str = err.details[0].path.join('.'); str = err.details[0].message; str = err.details[0].type; }); // variant Joi.validate(num, schema, validOpts, (err, value) => { num = value; }); // plain opts Joi.validate(value, {}); } { let value = { username: 'example', password: 'example' }; let schema = Joi.object().keys({ username: Joi.string().max(255).required(), password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), }); let returnValue: Joi.ValidationResult<typeof value>; returnValue = schema.validate(value); value = schema.validate(value, (err, value) => value); returnValue = Joi.validate(value, schema); returnValue = Joi.validate(value, obj); value = Joi.validate(value, obj, (err, value) => value); value = Joi.validate(value, schema, (err, value) => value); returnValue = Joi.validate(value, schema, validOpts); returnValue = Joi.validate(value, obj, validOpts); value = Joi.validate(value, obj, validOpts, (err, value) => value); value = Joi.validate(value, schema, validOpts, (err, value) => value); returnValue = schema.validate(value); returnValue = schema.validate(value, validOpts); value = schema.validate(value, (err, value) => value); value = schema.validate(value, validOpts, (err, value) => value); returnValue .then(val => JSON.stringify(val, null, 2)) .then(val => { throw 'one error'; }) .catch(e => {}); } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.compile(obj); schema = Joi.compile(schemaMap); Joi.assert(obj, schema); Joi.assert(obj, schema, str); Joi.assert(obj, schema, err); Joi.assert(obj, schemaLike); Joi.attempt(obj, schema); Joi.attempt(obj, schema, str); Joi.attempt(obj, schema, err); Joi.attempt(obj, schemaLike); ref = Joi.ref(str, refOpts); ref = Joi.ref(str); Joi.isRef(ref); description = Joi.describe(schema); description = schema.describe(); schema = Joi.reach(objSchema, ''); const Joi2 = Joi.extend({ name: '', base: schema }); const Joi3 = Joi.extend({ base: Joi.string(), name: 'string', language: { asd: 'must be exactly asd(f)', }, pre(value, state, options) { return value; }, describe(description) { return description; }, rules: [ { name: 'asd', params: { allowF: Joi.boolean().default(false), }, setup(params) { const fIsAllowed = params.allowF; }, validate(params, value, state, options) { if (value === 'asd' || params.allowF && value === 'asdf') { return value; } return this.createError('asd', { v: value }, state, options); }, }, ], }); const Joi4 = Joi.extend([{ name: '', base: schema }, { name: '', base: schema }]); const Joi5 = Joi.extend({ name: '', base: schema }, { name: '', base: schema }); const Joi6 = Joi.extend({ name: '', base: schema }, [{ name: '', base: schema }, { name: '', base: schema }]); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- const defaultsJoi = Joi.defaults((schema) => { switch (schema.schemaType) { case 'string': return schema.allow(''); case 'object': return (schema as Joi.ObjectSchema).min(1); default: return schema; } }); schema = Joi.allow(x, x); schema = Joi.allow([x, x, x]); schema = Joi.valid(x); schema = Joi.valid(x, x); schema = Joi.valid([x, x, x]); schema = Joi.only(x); schema = Joi.only(x, x); schema = Joi.only([x, x, x]); schema = Joi.equal(x); schema = Joi.equal(x, x); schema = Joi.equal([x, x, x]); schema = Joi.invalid(x); schema = Joi.invalid(x, x); schema = Joi.invalid([x, x, x]); schema = Joi.disallow(x); schema = Joi.disallow(x, x); schema = Joi.disallow([x, x, x]); schema = Joi.not(x); schema = Joi.not(x, x); schema = Joi.not([x, x, x]); schema = Joi.required(); schema = Joi.optional(); schema = Joi.forbidden(); schema = Joi.strip(); schema = Joi.description(str); schema = Joi.notes(str); schema = Joi.notes(strArr); schema = Joi.tags(str); schema = Joi.tags(strArr); schema = Joi.meta(obj); schema = Joi.example(obj); schema = Joi.unit(str); schema = Joi.options(validOpts); schema = Joi.strict(); schema = Joi.strict(bool); schema = Joi.concat(x); schema = Joi.when(str, whenOpts); schema = Joi.when(ref, whenOpts); schema = Joi.when(schema, whenSchemaOpts); schema = Joi.label(str); schema = Joi.raw(); schema = Joi.raw(bool); schema = Joi.empty(); schema = Joi.empty(str); schema = Joi.empty(anySchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.allow(x, x); schema = Joi.allow([x, x, x]); schema = Joi.valid(x); schema = Joi.valid(x, x); schema = Joi.valid([x, x, x]); schema = Joi.only(x); schema = Joi.only(x, x); schema = Joi.only([x, x, x]); schema = Joi.equal(x); schema = Joi.equal(x, x); schema = Joi.equal([x, x, x]); schema = Joi.invalid(x); schema = Joi.invalid(x, x); schema = Joi.invalid([x, x, x]); schema = Joi.disallow(x); schema = Joi.disallow(x, x); schema = Joi.disallow([x, x, x]); schema = Joi.not(x); schema = Joi.not(x, x); schema = Joi.not([x, x, x]); schema = Joi.required(); schema = Joi.optional(); schema = Joi.forbidden(); schema = Joi.strip(); schema = Joi.description(str); schema = Joi.notes(str); schema = Joi.notes(strArr); schema = Joi.tags(str); schema = Joi.tags(strArr); schema = Joi.meta(obj); schema = Joi.example(obj); schema = Joi.unit(str); schema = Joi.options(validOpts); schema = Joi.strict(); schema = Joi.strict(bool); schema = Joi.concat(x); schema = Joi.when(str, whenOpts); schema = Joi.when(ref, whenOpts); schema = Joi.when(schema, whenSchemaOpts); schema = Joi.label(str); schema = Joi.raw(); schema = Joi.raw(bool); schema = Joi.empty(); schema = Joi.empty(str); schema = Joi.empty(anySchema);
{ "content_hash": "2f60b2a3d1eef8ce25f3e579298e18c4", "timestamp": "", "source": "github", "line_count": 1129, "max_line_length": 144, "avg_line_length": 30.891939769707704, "alnum_prop": 0.6038650113255154, "repo_name": "rolandzwaga/DefinitelyTyped", "id": "5ea9088a74eb24e9d56dbef179a800eae473c700", "size": "34877", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "types/joi/joi-tests.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "HTML", "bytes": "308" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "18811251" } ], "symlink_target": "" }
#region Apache License Version 2.0 #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2022 Senparc 文件名:TenPay.cs 文件功能描述:微信支付接口 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20160720 修改描述:增加其接口的异步方法 ----------------------------------------------------------------*/ /* 官方API:https://mp.weixin.qq.com/paymch/readtemplate?t=mp/business/course2_tmpl&lang=zh_CN&token=25857919#4 */ using System.Threading.Tasks; using Senparc.Weixin.CommonAPIs; using Senparc.Weixin.Entities; namespace Senparc.Weixin.TenPay.V2 { /// <summary> /// 微信支付接口,官方API:https://mp.weixin.qq.com/paymch/readtemplate?t=mp/business/course2_tmpl&lang=zh_CN&token=25857919#4 /// </summary> public static class TenPay { #region 同步方法 /*此接口不提供异步方法*/ /// <summary> /// Native /// </summary> /// <param name="sign">签名</param> /// <param name="appId">开放平台账户的唯一标识</param> /// <param name="timesTamp">时间戳</param> /// <param name="nonceStr">32 位内的随机串,防重发</param> /// <param name="productId">商品唯一id</param> public static string NativePay(string sign, string appId, string timesTamp, string nonceStr, string productId) { var urlFormat = "weixin://wxpay/bizpayurl?sign={0}&appid={1}&productid={2}&timestamp={3}&noncestr={4}"; var url = string.Format(urlFormat, sign, appId, productId, timesTamp, nonceStr); return url; } /// <summary> /// 发货通知 /// </summary> /// <param name="appId">公众平台账户的AppId</param> /// <param name="accessToken">公众平台AccessToken</param> /// <param name="openId">购买用户的OpenId</param> /// <param name="transId">交易单号</param> /// <param name="out_Trade_No">第三方订单号</param> /// <param name="deliver_TimesTamp">发货时间戳</param> /// <param name="deliver_Status">发货状态,1 表明成功,0 表明失败,失败时需要在deliver_msg 填上失败原因</param> /// <param name="deliver_Msg">发货状态信息,失败时可以填上UTF8 编码的错误提示信息,比如“该商品已退款</param> /// <param name="app_Signature">签名</param> /// <param name="sign_Method">签名方法</param> public static WxJsonResult Delivernotify(string appId,string accessToken, string openId, string transId, string out_Trade_No, string deliver_TimesTamp, string deliver_Status, string deliver_Msg, string app_Signature, string sign_Method = "sha1") { var urlFormat = Config.ApiMpHost + "/pay/delivernotify?access_token={0}"; //组装发送消息 var data = new { appid = appId, openid = openId, transid = transId, out_trade_no = out_Trade_No, deliver_timestamp = deliver_TimesTamp, deliver_status = deliver_Status, deliver_msg = deliver_Msg, app_signature = app_Signature, sign_method = sign_Method }; return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data); } /// <summary> /// 订单查询 /// </summary> /// <param name="appId">公众平台账户的AppId</param> /// <param name="accessToken">公众平台AccessToken</param> /// <param name="package">查询订单的关键信息数据</param> /// <param name="timesTamp">linux 时间戳</param> /// <param name="app_Signature">签名</param> /// <param name="sign_Method">签名方法</param> public static OrderqueryResult Orderquery(string appId, string accessToken,string package, string timesTamp, string app_Signature, string sign_Method) { var urlFormat = Config.ApiMpHost + "/pay/orderquery?access_token={0}"; //组装发送消息 var data = new { appid = appId, package = package, timestamp = timesTamp, app_signature = app_Signature, sign_method = sign_Method }; return CommonJsonSend.Send<OrderqueryResult>(accessToken, urlFormat, data); } #endregion #region 异步方法 /// <summary> /// 【异步方法】发货通知 /// </summary> /// <param name="appId">公众平台账户的AppId</param> /// <param name="accessToken">公众平台AccessToken</param> /// <param name="openId">购买用户的OpenId</param> /// <param name="transId">交易单号</param> /// <param name="out_Trade_No">第三方订单号</param> /// <param name="deliver_TimesTamp">发货时间戳</param> /// <param name="deliver_Status">发货状态,1 表明成功,0 表明失败,失败时需要在deliver_msg 填上失败原因</param> /// <param name="deliver_Msg">发货状态信息,失败时可以填上UTF8 编码的错误提示信息,比如“该商品已退款</param> /// <param name="app_Signature">签名</param> /// <param name="sign_Method">签名方法</param> public static async Task<WxJsonResult> DelivernotifyAsync(string appId, string accessToken,string openId, string transId, string out_Trade_No, string deliver_TimesTamp, string deliver_Status, string deliver_Msg, string app_Signature, string sign_Method = "sha1") { var urlFormat = Config.ApiMpHost + "/pay/delivernotify?access_token={0}"; //组装发送消息 var data = new { appid = appId, openid = openId, transid = transId, out_trade_no = out_Trade_No, deliver_timestamp = deliver_TimesTamp, deliver_status = deliver_Status, deliver_msg = deliver_Msg, app_signature = app_Signature, sign_method = sign_Method }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<WxJsonResult>(accessToken, urlFormat, data); } /// <summary> /// 【异步方法】订单查询 /// </summary> /// <param name="appId">公众平台账户的AppId</param> /// <param name="accessToken">公众平台AccessToken</param> /// <param name="package">查询订单的关键信息数据</param> /// <param name="timesTamp">linux 时间戳</param> /// <param name="app_Signature">签名</param> /// <param name="sign_Method">签名方法</param> public static async Task<OrderqueryResult> OrderqueryAsync(string appId, string accessToken, string package, string timesTamp, string app_Signature, string sign_Method) { var urlFormat = Config.ApiMpHost + "/pay/orderquery?access_token={0}"; //组装发送消息 var data = new { appid = appId, package = package, timestamp = timesTamp, app_signature = app_Signature, sign_method = sign_Method }; return await Senparc.Weixin.CommonAPIs.CommonJsonSend.SendAsync<OrderqueryResult>(accessToken, urlFormat, data); } #endregion } }
{ "content_hash": "987b10ab8455e27f6f5238e0d63cbace", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 270, "avg_line_length": 38.48618784530387, "alnum_prop": 0.5668963537180591, "repo_name": "mc7246/WeiXinMPSDK", "id": "20d26a17822817839bcee485a57aea80c02e40f0", "size": "8618", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPay/V2/TenPay/TenPay.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "7955626" }, { "name": "HTML", "bytes": "560" }, { "name": "JavaScript", "bytes": "214247" } ], "symlink_target": "" }
<html lang="en"> <head> <title>GDB/MI Command Description Format - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="GDB_002fMI.html#GDB_002fMI" title="GDB/MI"> <link rel="prev" href="GDB_002fMI-Simple-Examples.html#GDB_002fMI-Simple-Examples" title="GDB/MI Simple Examples"> <link rel="next" href="GDB_002fMI-Breakpoint-Commands.html#GDB_002fMI-Breakpoint-Commands" title="GDB/MI Breakpoint Commands"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2013 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.''--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="GDB%2fMI-Command-Description-Format"></a> <a name="GDB_002fMI-Command-Description-Format"></a> Next:&nbsp;<a rel="next" accesskey="n" href="GDB_002fMI-Breakpoint-Commands.html#GDB_002fMI-Breakpoint-Commands">GDB/MI Breakpoint Commands</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="GDB_002fMI-Simple-Examples.html#GDB_002fMI-Simple-Examples">GDB/MI Simple Examples</a>, Up:&nbsp;<a rel="up" accesskey="u" href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a> <hr> </div> <h3 class="section">27.7 <span class="sc">gdb/mi</span> Command Description Format</h3> <p>The remaining sections describe blocks of commands. Each block of commands is laid out in a fashion similar to this section. <h4 class="subheading">Motivation</h4> <p>The motivation for this collection of commands. <h4 class="subheading">Introduction</h4> <p>A brief introduction to this collection of commands as a whole. <h4 class="subheading">Commands</h4> <p>For each command in the block, the following is described: <h5 class="subsubheading">Synopsis</h5> <pre class="smallexample"> -command <var>args</var>... </pre> <h5 class="subsubheading">Result</h5> <h5 class="subsubheading"><span class="sc">gdb</span> Command</h5> <p>The corresponding <span class="sc">gdb</span> CLI command(s), if any. <h5 class="subsubheading">Example</h5> <p>Example(s) formatted for readability. Some of the described commands have not been implemented yet and these are labeled N.A. (not available). <!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%% SECTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% --> </body></html>
{ "content_hash": "120d9b6280773b0266cbec8f20a0dfa0", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 144, "avg_line_length": 42.40963855421687, "alnum_prop": 0.7196022727272727, "repo_name": "marduino/stm32Proj", "id": "f693863e4a32ae3fe64aa2c942002f6298daf0c8", "size": "3520", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/armgcc/share/doc/gcc-arm-none-eabi/html/gdb/GDB_002fMI-Command-Description-Format.html", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "23333" }, { "name": "C", "bytes": "4470437" }, { "name": "C++", "bytes": "655791" }, { "name": "HTML", "bytes": "109" }, { "name": "Makefile", "bytes": "10291" } ], "symlink_target": "" }
{- (c) The University of Glasgow 2006 (c) The GRASP Project, Glasgow University, 1992-2000 Defines basic functions for printing error messages. It's hard to put these functions anywhere else without causing some unnecessary loops in the module dependency graph. -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} module Panic ( GhcException(..), showGhcException, throwGhcException, throwGhcExceptionIO, handleGhcException, progName, pgmError, panic, sorry, assertPanic, trace, panicDoc, sorryDoc, pgmErrorDoc, Exception.Exception(..), showException, safeShowException, try, tryMost, throwTo, installSignalHandlers, ) where #include "HsVersions.h" import {-# SOURCE #-} Outputable (SDoc, showSDocUnsafe) import Config import Exception import Control.Concurrent import Data.Dynamic import Debug.Trace ( trace ) import System.IO.Unsafe import System.Environment #ifndef mingw32_HOST_OS import System.Posix.Signals #endif #if defined(mingw32_HOST_OS) import GHC.ConsoleHandler #endif import GHC.Stack import System.Mem.Weak ( deRefWeak ) -- | GHC's own exception type -- error messages all take the form: -- -- @ -- <location>: <error> -- @ -- -- If the location is on the command line, or in GHC itself, then -- <location>="ghc". All of the error types below correspond to -- a <location> of "ghc", except for ProgramError (where the string is -- assumed to contain a location already, so we don't print one). data GhcException -- | Some other fatal signal (SIGHUP,SIGTERM) = Signal Int -- | Prints the short usage msg after the error | UsageError String -- | A problem with the command line arguments, but don't print usage. | CmdLineError String -- | The 'impossible' happened. | Panic String | PprPanic String SDoc -- | The user tickled something that's known not to work yet, -- but we're not counting it as a bug. | Sorry String | PprSorry String SDoc -- | An installation problem. | InstallationError String -- | An error in the user's code, probably. | ProgramError String | PprProgramError String SDoc deriving (Typeable) instance Exception GhcException instance Show GhcException where showsPrec _ e@(ProgramError _) = showGhcException e showsPrec _ e@(CmdLineError _) = showString "<command line>: " . showGhcException e showsPrec _ e = showString progName . showString ": " . showGhcException e -- | The name of this GHC. progName :: String progName = unsafePerformIO (getProgName) {-# NOINLINE progName #-} -- | Short usage information to display when we are given the wrong cmd line arguments. short_usage :: String short_usage = "Usage: For basic information, try the `--help' option." -- | Show an exception as a string. showException :: Exception e => e -> String showException = show -- | Show an exception which can possibly throw other exceptions. -- Used when displaying exception thrown within TH code. safeShowException :: Exception e => e -> IO String safeShowException e = do -- ensure the whole error message is evaluated inside try r <- try (return $! forceList (showException e)) case r of Right msg -> return msg Left e' -> safeShowException (e' :: SomeException) where forceList [] = [] forceList xs@(x : xt) = x `seq` forceList xt `seq` xs -- | Append a description of the given exception to this string. -- -- Note that this uses 'DynFlags.unsafeGlobalDynFlags', which may have some -- uninitialized fields if invoked before 'GHC.initGhcMonad' has been called. -- If the error message to be printed includes a pretty-printer document -- which forces one of these fields this call may bottom. showGhcException :: GhcException -> ShowS showGhcException exception = case exception of UsageError str -> showString str . showChar '\n' . showString short_usage CmdLineError str -> showString str PprProgramError str sdoc -> showString str . showString "\n\n" . showString (showSDocUnsafe sdoc) ProgramError str -> showString str InstallationError str -> showString str Signal n -> showString "signal: " . shows n PprPanic s sdoc -> panicMsg $ showString s . showString "\n\n" . showString (showSDocUnsafe sdoc) Panic s -> panicMsg (showString s) PprSorry s sdoc -> sorryMsg $ showString s . showString "\n\n" . showString (showSDocUnsafe sdoc) Sorry s -> sorryMsg (showString s) where sorryMsg :: ShowS -> ShowS sorryMsg s = showString "sorry! (unimplemented feature or known bug)\n" . showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t") . s . showString "\n" panicMsg :: ShowS -> ShowS panicMsg s = showString "panic! (the 'impossible' happened)\n" . showString (" (GHC version " ++ cProjectVersion ++ " for " ++ TargetPlatform_NAME ++ "):\n\t") . s . showString "\n\n" . showString "Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug\n" throwGhcException :: GhcException -> a throwGhcException = Exception.throw throwGhcExceptionIO :: GhcException -> IO a throwGhcExceptionIO = Exception.throwIO handleGhcException :: ExceptionMonad m => (GhcException -> m a) -> m a -> m a handleGhcException = ghandle -- | Panics and asserts. panic, sorry, pgmError :: String -> a panic x = unsafeDupablePerformIO $ do stack <- ccsToStrings =<< getCurrentCCS x if null stack then throwGhcException (Panic x) else throwGhcException (Panic (x ++ '\n' : renderStack stack)) sorry x = throwGhcException (Sorry x) pgmError x = throwGhcException (ProgramError x) panicDoc, sorryDoc, pgmErrorDoc :: String -> SDoc -> a panicDoc x doc = throwGhcException (PprPanic x doc) sorryDoc x doc = throwGhcException (PprSorry x doc) pgmErrorDoc x doc = throwGhcException (PprProgramError x doc) -- | Throw an failed assertion exception for a given filename and line number. assertPanic :: String -> Int -> a assertPanic file line = Exception.throw (Exception.AssertionFailed ("ASSERT failed! file " ++ file ++ ", line " ++ show line)) -- | Like try, but pass through UserInterrupt and Panic exceptions. -- Used when we want soft failures when reading interface files, for example. -- TODO: I'm not entirely sure if this is catching what we really want to catch tryMost :: IO a -> IO (Either SomeException a) tryMost action = do r <- try action case r of Left se -> case fromException se of -- Some GhcException's we rethrow, Just (Signal _) -> throwIO se Just (Panic _) -> throwIO se -- others we return Just _ -> return (Left se) Nothing -> case fromException se of -- All IOExceptions are returned Just (_ :: IOException) -> return (Left se) -- Anything else is rethrown Nothing -> throwIO se Right v -> return (Right v) -- | Install standard signal handlers for catching ^C, which just throw an -- exception in the target thread. The current target thread is the -- thread at the head of the list in the MVar passed to -- installSignalHandlers. installSignalHandlers :: IO () installSignalHandlers = do main_thread <- myThreadId wtid <- mkWeakThreadId main_thread let interrupt = do r <- deRefWeak wtid case r of Nothing -> return () Just t -> throwTo t UserInterrupt #if !defined(mingw32_HOST_OS) _ <- installHandler sigQUIT (Catch interrupt) Nothing _ <- installHandler sigINT (Catch interrupt) Nothing -- see #3656; in the future we should install these automatically for -- all Haskell programs in the same way that we install a ^C handler. let fatal_signal n = throwTo main_thread (Signal (fromIntegral n)) _ <- installHandler sigHUP (Catch (fatal_signal sigHUP)) Nothing _ <- installHandler sigTERM (Catch (fatal_signal sigTERM)) Nothing return () #else -- GHC 6.3+ has support for console events on Windows -- NOTE: running GHCi under a bash shell for some reason requires -- you to press Ctrl-Break rather than Ctrl-C to provoke -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know -- why --SDM 17/12/2004 let sig_handler ControlC = interrupt sig_handler Break = interrupt sig_handler _ = return () _ <- installHandler (Catch sig_handler) return () #endif
{ "content_hash": "bff4050825c3b03beac10109123ee344", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 103, "avg_line_length": 34.343396226415095, "alnum_prop": 0.6419074826942094, "repo_name": "tjakway/ghcjvm", "id": "b19c770718be0fc5f338b9e0f8de59f9181192b5", "size": "9101", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "compiler/utils/Panic.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "8740" }, { "name": "C", "bytes": "2628872" }, { "name": "C++", "bytes": "35938" }, { "name": "CSS", "bytes": "984" }, { "name": "DTrace", "bytes": "3887" }, { "name": "Emacs Lisp", "bytes": "734" }, { "name": "Game Maker Language", "bytes": "14164" }, { "name": "Gnuplot", "bytes": "103851" }, { "name": "Groff", "bytes": "3840" }, { "name": "HTML", "bytes": "6144" }, { "name": "Haskell", "bytes": "19940711" }, { "name": "Haxe", "bytes": "218" }, { "name": "Logos", "bytes": "126216" }, { "name": "Lua", "bytes": "408853" }, { "name": "M4", "bytes": "50627" }, { "name": "Makefile", "bytes": "546004" }, { "name": "Objective-C", "bytes": "20017" }, { "name": "Objective-C++", "bytes": "535" }, { "name": "Pascal", "bytes": "113830" }, { "name": "Perl", "bytes": "23120" }, { "name": "Perl6", "bytes": "41951" }, { "name": "PostScript", "bytes": "63" }, { "name": "Python", "bytes": "106011" }, { "name": "Shell", "bytes": "76831" }, { "name": "TeX", "bytes": "667" }, { "name": "Yacc", "bytes": "62684" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Validator\Mapping; use Symfony\Component\Validator\MetadataFactoryInterface; use Symfony\Component\Validator\Exception\NoSuchMetadataException; use Symfony\Component\Validator\Mapping\Loader\LoaderInterface; use Symfony\Component\Validator\Mapping\Cache\CacheInterface; /** * A factory for creating metadata for PHP classes. * * @author Bernhard Schussek <bschussek@gmail.com> */ class ClassMetadataFactory implements ClassMetadataFactoryInterface, MetadataFactoryInterface { /** * The loader for loading the class metadata * @var LoaderInterface */ protected $loader; /** * The cache for caching class metadata * @var CacheInterface */ protected $cache; protected $loadedClasses = array(); public function __construct(LoaderInterface $loader = null, CacheInterface $cache = null) { $this->loader = $loader; $this->cache = $cache; } /** * {@inheritdoc} */ public function getMetadataFor($value) { if (!is_object($value) && !is_string($value)) { throw new NoSuchMetadataException('Cannot create metadata for non-objects. Got: ' . gettype($value)); } $class = ltrim(is_object($value) ? get_class($value) : $value, '\\'); if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if (null !== $this->cache && false !== ($this->loadedClasses[$class] = $this->cache->read($class))) { return $this->loadedClasses[$class]; } if (!class_exists($class) && !interface_exists($class)) { throw new NoSuchMetadataException('The class or interface "' . $class . '" does not exist.'); } $metadata = new ClassMetadata($class); // Include constraints from the parent class if ($parent = $metadata->getReflectionClass()->getParentClass()) { $metadata->mergeConstraints($this->getClassMetadata($parent->name)); } // Include constraints from all implemented interfaces foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) { if ('Symfony\Component\Validator\GroupSequenceProviderInterface' === $interface->name) { continue; } $metadata->mergeConstraints($this->getClassMetadata($interface->name)); } if (null !== $this->loader) { $this->loader->loadClassMetadata($metadata); } if (null !== $this->cache) { $this->cache->write($metadata); } return $this->loadedClasses[$class] = $metadata; } /** * {@inheritdoc} */ public function hasMetadataFor($value) { if (!is_object($value) && !is_string($value)) { return false; } $class = ltrim(is_object($value) ? get_class($value) : $value, '\\'); if (class_exists($class) || interface_exists($class)) { return true; } return false; } /** * {@inheritdoc} * * @deprecated Deprecated since version 2.2, to be removed in 2.3. Use * {@link getMetadataFor} instead. */ public function getClassMetadata($class) { return $this->getMetadataFor($class); } }
{ "content_hash": "bb8c30a98b419af35cbe8ae86e35f4f4", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 113, "avg_line_length": 28.810344827586206, "alnum_prop": 0.5966487133453022, "repo_name": "stloyd/symfony", "id": "279d8334555bce5273815e5a88fe4cbbcda4a4a9", "size": "3571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Symfony/Component/Validator/Mapping/ClassMetadataFactory.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10543" }, { "name": "Graphviz (DOT)", "bytes": "3215" }, { "name": "PHP", "bytes": "7422590" }, { "name": "Shell", "bytes": "268" }, { "name": "TypeScript", "bytes": "195" } ], "symlink_target": "" }
/** * Localization strings for the UI Multiselect widget * * @locale fr, fr-FR, fr-CA */ $.extend($.ui.multiselect.locale, { addAll:'Ajouter tout', removeAll:'Supprimer tout', itemsCount:'#{count} items sélectionnés', itemsTotal:'#{count} items total', busy:'veuillez patienter...', errorDataFormat:"Les données n'ont pas pu être ajoutés, format inconnu.", errorInsertNode:"Un problème est survenu en tentant d'ajouter l'item:\n\n\t[#{key}] => #{value}\n\nL'opération a été annulée.", errorReadonly:"L'option #{option} est en lecture seule.", errorRequest:"Désolé! Il semble que la requête ne se soit pas terminé correctement. (Type: #{status})" });
{ "content_hash": "6200b52afd48cb4e3561e232d4aed55e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 128, "avg_line_length": 39.05882352941177, "alnum_prop": 0.7108433734939759, "repo_name": "kamarulismail/yii-multiselect", "id": "cd11a8a9379eb110d75d8b501e27a921e9dd42ff", "size": "678", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resources/js/locale/ui.multiselect-fr.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "63884" }, { "name": "PHP", "bytes": "4953" } ], "symlink_target": "" }
package io.druid.segment.realtime.plumber; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.MoreExecutors; import com.metamx.common.Granularity; import com.metamx.common.ISE; import com.metamx.common.Pair; import com.metamx.common.concurrent.ScheduledExecutors; import com.metamx.common.guava.CloseQuietly; import com.metamx.common.guava.FunctionalIterable; import com.metamx.emitter.EmittingLogger; import com.metamx.emitter.service.ServiceEmitter; import com.metamx.emitter.service.ServiceMetricEvent; import io.druid.client.CachingQueryRunner; import io.druid.client.cache.Cache; import io.druid.client.cache.CacheConfig; import io.druid.common.guava.ThreadRenamingCallable; import io.druid.common.guava.ThreadRenamingRunnable; import io.druid.common.utils.VMUtils; import io.druid.concurrent.Execs; import io.druid.data.input.Committer; import io.druid.concurrent.TaskThreadPriority; import io.druid.data.input.InputRow; import io.druid.query.MetricsEmittingQueryRunner; import io.druid.query.NoopQueryRunner; import io.druid.query.Query; import io.druid.query.QueryRunner; import io.druid.query.QueryRunnerFactory; import io.druid.query.QueryRunnerFactoryConglomerate; import io.druid.query.QueryRunnerHelper; import io.druid.query.QueryToolChest; import io.druid.query.ReportTimelineMissingSegmentQueryRunner; import io.druid.query.SegmentDescriptor; import io.druid.query.spec.SpecificSegmentQueryRunner; import io.druid.query.spec.SpecificSegmentSpec; import io.druid.segment.IndexIO; import io.druid.segment.IndexMerger; import io.druid.segment.IndexSpec; import io.druid.segment.Metadata; import io.druid.segment.QueryableIndex; import io.druid.segment.QueryableIndexSegment; import io.druid.segment.ReferenceCountingSegment; import io.druid.segment.Segment; import io.druid.segment.incremental.IndexSizeExceededException; import io.druid.segment.indexing.DataSchema; import io.druid.segment.indexing.RealtimeTuningConfig; import io.druid.segment.loading.DataSegmentPusher; import io.druid.segment.realtime.FireDepartmentMetrics; import io.druid.segment.realtime.FireHydrant; import io.druid.segment.realtime.SegmentPublisher; import io.druid.server.coordination.DataSegmentAnnouncer; import io.druid.timeline.DataSegment; import io.druid.timeline.TimelineObjectHolder; import io.druid.timeline.VersionedIntervalTimeline; import io.druid.timeline.partition.SingleElementPartitionChunk; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.Interval; import org.joda.time.Period; import javax.annotation.Nullable; import javax.ws.rs.HEAD; import java.io.Closeable; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** */ public class RealtimePlumber implements Plumber { private static final EmittingLogger log = new EmittingLogger(RealtimePlumber.class); private static final int WARN_DELAY = 1000; private final DataSchema schema; private final RealtimeTuningConfig config; private final RejectionPolicy rejectionPolicy; private final FireDepartmentMetrics metrics; private final ServiceEmitter emitter; private final QueryRunnerFactoryConglomerate conglomerate; private final DataSegmentAnnouncer segmentAnnouncer; private final ExecutorService queryExecutorService; private final DataSegmentPusher dataSegmentPusher; private final SegmentPublisher segmentPublisher; private final SegmentHandoffNotifier handoffNotifier; private final Object handoffCondition = new Object(); private final Map<Long, Sink> sinks = Maps.newConcurrentMap(); private final VersionedIntervalTimeline<String, Sink> sinkTimeline = new VersionedIntervalTimeline<String, Sink>( String.CASE_INSENSITIVE_ORDER ); private final Cache cache; private final CacheConfig cacheConfig; private final ObjectMapper objectMapper; private volatile long nextFlush = 0; private volatile boolean shuttingDown = false; private volatile boolean stopped = false; private volatile boolean cleanShutdown = true; private volatile ExecutorService persistExecutor = null; private volatile ExecutorService mergeExecutor = null; private volatile ScheduledExecutorService scheduledExecutor = null; private volatile IndexMerger indexMerger; private volatile IndexIO indexIO; private static final String COMMIT_METADATA_KEY = "%commitMetadata%"; private static final String COMMIT_METADATA_TIMESTAMP_KEY = "%commitMetadataTimestamp%"; private static final String SKIP_INCREMENTAL_SEGMENT = "skipIncrementalSegment"; public RealtimePlumber( DataSchema schema, RealtimeTuningConfig config, FireDepartmentMetrics metrics, ServiceEmitter emitter, QueryRunnerFactoryConglomerate conglomerate, DataSegmentAnnouncer segmentAnnouncer, ExecutorService queryExecutorService, DataSegmentPusher dataSegmentPusher, SegmentPublisher segmentPublisher, SegmentHandoffNotifier handoffNotifier, IndexMerger indexMerger, IndexIO indexIO, Cache cache, CacheConfig cacheConfig, ObjectMapper objectMapper ) { this.schema = schema; this.config = config; this.rejectionPolicy = config.getRejectionPolicyFactory().create(config.getWindowPeriod()); this.metrics = metrics; this.emitter = emitter; this.conglomerate = conglomerate; this.segmentAnnouncer = segmentAnnouncer; this.queryExecutorService = queryExecutorService; this.dataSegmentPusher = dataSegmentPusher; this.segmentPublisher = segmentPublisher; this.handoffNotifier = handoffNotifier; this.indexMerger = Preconditions.checkNotNull(indexMerger, "Null IndexMerger"); this.indexIO = Preconditions.checkNotNull(indexIO, "Null IndexIO"); this.cache = cache; this.cacheConfig = cacheConfig; this.objectMapper = objectMapper; if (!cache.isLocal()) { log.error("Configured cache is not local, caching will not be enabled"); } log.info("Creating plumber using rejectionPolicy[%s]", getRejectionPolicy()); } public DataSchema getSchema() { return schema; } public RealtimeTuningConfig getConfig() { return config; } public RejectionPolicy getRejectionPolicy() { return rejectionPolicy; } public Map<Long, Sink> getSinks() { return sinks; } @Override public Object startJob() { computeBaseDir(schema).mkdirs(); initializeExecutors(); handoffNotifier.start(); Object retVal = bootstrapSinksFromDisk(); startPersistThread(); // Push pending sinks bootstrapped from previous run mergeAndPush(); resetNextFlush(); return retVal; } @Override public int add(InputRow row, Supplier<Committer> committerSupplier) throws IndexSizeExceededException { final Sink sink = getSink(row.getTimestampFromEpoch()); if (sink == null) { return -1; } final int numRows = sink.add(row); if (!sink.canAppendRow() || System.currentTimeMillis() > nextFlush) { persist(committerSupplier.get()); } return numRows; } private Sink getSink(long timestamp) { if (!rejectionPolicy.accept(timestamp)) { return null; } final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity(); final VersioningPolicy versioningPolicy = config.getVersioningPolicy(); final long truncatedTime = segmentGranularity.truncate(new DateTime(timestamp)).getMillis(); Sink retVal = sinks.get(truncatedTime); if (retVal == null) { final Interval sinkInterval = new Interval( new DateTime(truncatedTime), segmentGranularity.increment(new DateTime(truncatedTime)) ); retVal = new Sink(sinkInterval, schema, config, versioningPolicy.getVersion(sinkInterval)); addSink(retVal); } return retVal; } @Override public <T> QueryRunner<T> getQueryRunner(final Query<T> query) { final boolean skipIncrementalSegment = query.getContextValue(SKIP_INCREMENTAL_SEGMENT, false); final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); final QueryToolChest<T, Query<T>> toolchest = factory.getToolchest(); final Function<Query<T>, ServiceMetricEvent.Builder> builderFn = new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override public ServiceMetricEvent.Builder apply(@Nullable Query<T> input) { return toolchest.makeMetricBuilder(query); } }; List<TimelineObjectHolder<String, Sink>> querySinks = Lists.newArrayList(); for (Interval interval : query.getIntervals()) { querySinks.addAll(sinkTimeline.lookup(interval)); } return toolchest.mergeResults( factory.mergeRunners( queryExecutorService, FunctionalIterable .create(querySinks) .transform( new Function<TimelineObjectHolder<String, Sink>, QueryRunner<T>>() { @Override public QueryRunner<T> apply(TimelineObjectHolder<String, Sink> holder) { if (holder == null) { throw new ISE("No timeline entry at all!"); } // The realtime plumber always uses SingleElementPartitionChunk final Sink theSink = holder.getObject().getChunk(0).getObject(); if (theSink == null) { throw new ISE("Missing sink for timeline entry[%s]!", holder); } final SegmentDescriptor descriptor = new SegmentDescriptor( holder.getInterval(), theSink.getSegment().getVersion(), theSink.getSegment().getShardSpec().getPartitionNum() ); return new SpecificSegmentQueryRunner<T>( new MetricsEmittingQueryRunner<T>( emitter, builderFn, factory.mergeRunners( MoreExecutors.sameThreadExecutor(), Iterables.transform( theSink, new Function<FireHydrant, QueryRunner<T>>() { @Override public QueryRunner<T> apply(FireHydrant input) { if (skipIncrementalSegment && !input.hasSwapped()) { return new NoopQueryRunner<T>(); } // Prevent the underlying segment from swapping when its being iterated final Pair<Segment, Closeable> segment = input.getAndIncrementSegment(); try { QueryRunner<T> baseRunner = QueryRunnerHelper.makeClosingQueryRunner( factory.createRunner(segment.lhs), segment.rhs ); if (input.hasSwapped() // only use caching if data is immutable && cache.isLocal() // hydrants may not be in sync between replicas, make sure cache is local ) { return new CachingQueryRunner<>( makeHydrantIdentifier(input, segment.lhs), descriptor, objectMapper, cache, toolchest, baseRunner, MoreExecutors.sameThreadExecutor(), cacheConfig ); } else { return baseRunner; } } catch (RuntimeException e) { CloseQuietly.close(segment.rhs); throw e; } } } ) ) ).withWaitMeasuredFromNow(), new SpecificSegmentSpec( descriptor ) ); } } ) ) ); } protected static String makeHydrantIdentifier(FireHydrant input, Segment segment) { return segment.getIdentifier() + "_" + input.getCount(); } @Override public void persist(final Committer committer) { final List<Pair<FireHydrant, Interval>> indexesToPersist = Lists.newArrayList(); for (Sink sink : sinks.values()) { if (sink.swappable()) { indexesToPersist.add(Pair.of(sink.swap(), sink.getInterval())); } } log.info("Submitting persist runnable for dataSource[%s]", schema.getDataSource()); final Stopwatch runExecStopwatch = Stopwatch.createStarted(); final Stopwatch persistStopwatch = Stopwatch.createStarted(); final Map<String, Object> metadataElems = committer.getMetadata() == null ? null : ImmutableMap.of( COMMIT_METADATA_KEY, committer.getMetadata(), COMMIT_METADATA_TIMESTAMP_KEY, System.currentTimeMillis() ); persistExecutor.execute( new ThreadRenamingRunnable(String.format("%s-incremental-persist", schema.getDataSource())) { @Override public void doRun() { /* Note: If plumber crashes after storing a subset of all the hydrants then we will lose data and next time we will start with the commitMetadata stored in those hydrants. option#1: maybe it makes sense to store the metadata outside the segments in a separate file. This is because the commit metadata isn't really associated with an individual segment-- it's associated with a set of segments that are persisted at the same time or maybe whole datasource. So storing it in the segments is asking for problems. Sort of like this: { "metadata" : {"foo": "bar"}, "segments": [ {"id": "datasource_2000_2001_2000_1", "hydrant": 10}, {"id": "datasource_2001_2002_2001_1", "hydrant": 12}, ] } When a realtime node crashes and starts back up, it would delete any hydrants numbered higher than the ones in the commit file. option#2 We could also just include the set of segments for the same chunk of metadata in more metadata on each of the segments. we might also have to think about the hand-off in terms of the full set of segments being handed off instead of individual segments being handed off (that is, if one of the set succeeds in handing off and the others fail, the real-time would believe that it needs to re-ingest the data). */ long persistThreadCpuTime = VMUtils.safeGetThreadCpuTime(); try { for (Pair<FireHydrant, Interval> pair : indexesToPersist) { metrics.incrementRowOutputCount( persistHydrant( pair.lhs, schema, pair.rhs, metadataElems ) ); } committer.run(); } catch (Exception e) { metrics.incrementFailedPersists(); throw e; } finally { metrics.incrementPersistCpuTime(VMUtils.safeGetThreadCpuTime() - persistThreadCpuTime); metrics.incrementNumPersists(); metrics.incrementPersistTimeMillis(persistStopwatch.elapsed(TimeUnit.MILLISECONDS)); persistStopwatch.stop(); } } } ); final long startDelay = runExecStopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.incrementPersistBackPressureMillis(startDelay); if (startDelay > WARN_DELAY) { log.warn("Ingestion was throttled for [%,d] millis because persists were pending.", startDelay); } runExecStopwatch.stop(); resetNextFlush(); } // Submits persist-n-merge task for a Sink to the mergeExecutor private void persistAndMerge(final long truncatedTime, final Sink sink) { final String threadName = String.format( "%s-%s-persist-n-merge", schema.getDataSource(), new DateTime(truncatedTime) ); mergeExecutor.execute( new ThreadRenamingRunnable(threadName) { @Override public void doRun() { final Interval interval = sink.getInterval(); // Bail out if this sink has been abandoned by a previously-executed task. if (sinks.get(truncatedTime) != sink) { log.info("Sink[%s] was abandoned, bailing out of persist-n-merge.", sink); return; } // Use a file to indicate that pushing has completed. final File persistDir = computePersistDir(schema, interval); final File mergedTarget = new File(persistDir, "merged"); final File isPushedMarker = new File(persistDir, "isPushedMarker"); if (!isPushedMarker.exists()) { removeSegment(sink, mergedTarget); if (mergedTarget.exists()) { log.wtf("Merged target[%s] exists?!", mergedTarget); return; } } else { log.info("Already pushed sink[%s]", sink); return; } /* Note: it the plumber crashes after persisting a subset of hydrants then might duplicate data as these hydrants will be read but older commitMetadata will be used. fixing this possibly needs structural changes to plumber. */ for (FireHydrant hydrant : sink) { synchronized (hydrant) { if (!hydrant.hasSwapped()) { log.info("Hydrant[%s] hasn't swapped yet, swapping. Sink[%s]", hydrant, sink); final int rowCount = persistHydrant(hydrant, schema, interval, null); metrics.incrementRowOutputCount(rowCount); } } } final long mergeThreadCpuTime = VMUtils.safeGetThreadCpuTime(); final Stopwatch mergeStopwatch = Stopwatch.createStarted(); try { List<QueryableIndex> indexes = Lists.newArrayList(); for (FireHydrant fireHydrant : sink) { Segment segment = fireHydrant.getSegment(); final QueryableIndex queryableIndex = segment.asQueryableIndex(); log.info("Adding hydrant[%s]", fireHydrant); indexes.add(queryableIndex); } final File mergedFile = indexMerger.mergeQueryableIndex( indexes, schema.getAggregators(), mergedTarget, config.getIndexSpec() ); // emit merge metrics before publishing segment metrics.incrementMergeCpuTime(VMUtils.safeGetThreadCpuTime() - mergeThreadCpuTime); metrics.incrementMergeTimeMillis(mergeStopwatch.elapsed(TimeUnit.MILLISECONDS)); QueryableIndex index = indexIO.loadIndex(mergedFile); log.info("Pushing [%s] to deep storage", sink.getSegment().getIdentifier()); DataSegment segment = dataSegmentPusher.push( mergedFile, sink.getSegment().withDimensions(Lists.newArrayList(index.getAvailableDimensions())) ); log.info("Inserting [%s] to the metadata store", sink.getSegment().getIdentifier()); segmentPublisher.publishSegment(segment); if (!isPushedMarker.createNewFile()) { log.makeAlert("Failed to create marker file for [%s]", schema.getDataSource()) .addData("interval", sink.getInterval()) .addData("partitionNum", segment.getShardSpec().getPartitionNum()) .addData("marker", isPushedMarker) .emit(); } } catch (Exception e) { metrics.incrementFailedHandoffs(); log.makeAlert(e, "Failed to persist merged index[%s]", schema.getDataSource()) .addData("interval", interval) .emit(); if (shuttingDown) { // We're trying to shut down, and this segment failed to push. Let's just get rid of it. // This call will also delete possibly-partially-written files, so we don't need to do it explicitly. cleanShutdown = false; abandonSegment(truncatedTime, sink); } } finally { mergeStopwatch.stop(); } } } ); handoffNotifier.registerSegmentHandoffCallback( new SegmentDescriptor(sink.getInterval(), sink.getVersion(), config.getShardSpec().getPartitionNum()), mergeExecutor, new Runnable() { @Override public void run() { abandonSegment(sink.getInterval().getStartMillis(), sink); metrics.incrementHandOffCount(); } } ); } @Override public void finishJob() { log.info("Shutting down..."); shuttingDown = true; for (final Map.Entry<Long, Sink> entry : sinks.entrySet()) { persistAndMerge(entry.getKey(), entry.getValue()); } while (!sinks.isEmpty()) { try { log.info( "Cannot shut down yet! Sinks remaining: %s", Joiner.on(", ").join( Iterables.transform( sinks.values(), new Function<Sink, String>() { @Override public String apply(Sink input) { return input.getSegment().getIdentifier(); } } ) ) ); synchronized (handoffCondition) { while (!sinks.isEmpty()) { handoffCondition.wait(); } } } catch (InterruptedException e) { throw Throwables.propagate(e); } } handoffNotifier.stop(); shutdownExecutors(); stopped = true; if (!cleanShutdown) { throw new ISE("Exception occurred during persist and merge."); } } private void resetNextFlush() { nextFlush = new DateTime().plus(config.getIntermediatePersistPeriod()).getMillis(); } protected void initializeExecutors() { final int maxPendingPersists = config.getMaxPendingPersists(); if (persistExecutor == null) { // use a blocking single threaded executor to throttle the firehose when write to disk is slow persistExecutor = Execs.newBlockingSingleThreaded( "plumber_persist_%d", maxPendingPersists, TaskThreadPriority.getThreadPriorityFromTaskPriority(config.getPersistThreadPriority()) ); } if (mergeExecutor == null) { // use a blocking single threaded executor to throttle the firehose when write to disk is slow mergeExecutor = Execs.newBlockingSingleThreaded( "plumber_merge_%d", 1, TaskThreadPriority.getThreadPriorityFromTaskPriority(config.getMergeThreadPriority()) ); } if (scheduledExecutor == null) { scheduledExecutor = Execs.scheduledSingleThreaded("plumber_scheduled_%d"); } } protected void shutdownExecutors() { // scheduledExecutor is shutdown here if (scheduledExecutor != null) { scheduledExecutor.shutdown(); persistExecutor.shutdown(); mergeExecutor.shutdown(); } } protected Object bootstrapSinksFromDisk() { final VersioningPolicy versioningPolicy = config.getVersioningPolicy(); File baseDir = computeBaseDir(schema); if (baseDir == null || !baseDir.exists()) { return null; } File[] files = baseDir.listFiles(); if (files == null) { return null; } Object metadata = null; long latestCommitTime = 0; for (File sinkDir : files) { final Interval sinkInterval = new Interval(sinkDir.getName().replace("_", "/")); //final File[] sinkFiles = sinkDir.listFiles(); // To avoid reading and listing of "merged" dir final File[] sinkFiles = sinkDir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String fileName) { return !(Ints.tryParse(fileName) == null); } } ); Arrays.sort( sinkFiles, new Comparator<File>() { @Override public int compare(File o1, File o2) { try { return Ints.compare(Integer.parseInt(o1.getName()), Integer.parseInt(o2.getName())); } catch (NumberFormatException e) { log.error(e, "Couldn't compare as numbers? [%s][%s]", o1, o2); return o1.compareTo(o2); } } } ); boolean isCorrupted = false; List<FireHydrant> hydrants = Lists.newArrayList(); for (File segmentDir : sinkFiles) { log.info("Loading previously persisted segment at [%s]", segmentDir); // Although this has been tackled at start of this method. // Just a doubly-check added to skip "merged" dir. from being added to hydrants // If 100% sure that this is not needed, this check can be removed. if (Ints.tryParse(segmentDir.getName()) == null) { continue; } QueryableIndex queryableIndex = null; try { queryableIndex = indexIO.loadIndex(segmentDir); } catch (IOException e) { log.error(e, "Problem loading segmentDir from disk."); isCorrupted = true; } if (isCorrupted) { try { File corruptSegmentDir = computeCorruptedFileDumpDir(segmentDir, schema); log.info("Renaming %s to %s", segmentDir.getAbsolutePath(), corruptSegmentDir.getAbsolutePath()); FileUtils.copyDirectory(segmentDir, corruptSegmentDir); FileUtils.deleteDirectory(segmentDir); } catch (Exception e1) { log.error(e1, "Failed to rename %s", segmentDir.getAbsolutePath()); } //Note: skipping corrupted segment might lead to dropping some data. This strategy should be changed //at some point. continue; } Metadata segmentMetadata = queryableIndex.getMetadata(); if (segmentMetadata != null) { Object timestampObj = segmentMetadata.get(COMMIT_METADATA_TIMESTAMP_KEY); if (timestampObj != null) { long timestamp = ((Long) timestampObj).longValue(); if (timestamp > latestCommitTime) { log.info( "Found metaData [%s] with latestCommitTime [%s] greater than previous recorded [%s]", queryableIndex.getMetadata(), timestamp, latestCommitTime ); latestCommitTime = timestamp; metadata = queryableIndex.getMetadata().get(COMMIT_METADATA_KEY); } } } hydrants.add( new FireHydrant( new QueryableIndexSegment( DataSegment.makeDataSegmentIdentifier( schema.getDataSource(), sinkInterval.getStart(), sinkInterval.getEnd(), versioningPolicy.getVersion(sinkInterval), config.getShardSpec() ), queryableIndex ), Integer.parseInt(segmentDir.getName()) ) ); } if (hydrants.isEmpty()) { // Probably encountered a corrupt sink directory log.warn( "Found persisted segment directory with no intermediate segments present at %s, skipping sink creation.", sinkDir.getAbsolutePath() ); continue; } final Sink currSink = new Sink(sinkInterval, schema, config, versioningPolicy.getVersion(sinkInterval), hydrants); addSink(currSink); } return metadata; } private void addSink(final Sink sink) { sinks.put(sink.getInterval().getStartMillis(), sink); sinkTimeline.add( sink.getInterval(), sink.getVersion(), new SingleElementPartitionChunk<Sink>(sink) ); try { segmentAnnouncer.announceSegment(sink.getSegment()); } catch (IOException e) { log.makeAlert(e, "Failed to announce new segment[%s]", schema.getDataSource()) .addData("interval", sink.getInterval()) .emit(); } } protected void startPersistThread() { final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity(); final Period windowPeriod = config.getWindowPeriod(); final DateTime truncatedNow = segmentGranularity.truncate(new DateTime()); final long windowMillis = windowPeriod.toStandardDuration().getMillis(); log.info( "Expect to run at [%s]", new DateTime().plus( new Duration( System.currentTimeMillis(), segmentGranularity.increment(truncatedNow).getMillis() + windowMillis ) ) ); ScheduledExecutors .scheduleAtFixedRate( scheduledExecutor, new Duration( System.currentTimeMillis(), segmentGranularity.increment(truncatedNow).getMillis() + windowMillis ), new Duration(truncatedNow, segmentGranularity.increment(truncatedNow)), new ThreadRenamingCallable<ScheduledExecutors.Signal>( String.format( "%s-overseer-%d", schema.getDataSource(), config.getShardSpec().getPartitionNum() ) ) { @Override public ScheduledExecutors.Signal doCall() { if (stopped) { log.info("Stopping merge-n-push overseer thread"); return ScheduledExecutors.Signal.STOP; } mergeAndPush(); if (stopped) { log.info("Stopping merge-n-push overseer thread"); return ScheduledExecutors.Signal.STOP; } else { return ScheduledExecutors.Signal.REPEAT; } } } ); } private void mergeAndPush() { final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity(); final Period windowPeriod = config.getWindowPeriod(); final long windowMillis = windowPeriod.toStandardDuration().getMillis(); log.info("Starting merge and push."); DateTime minTimestampAsDate = segmentGranularity.truncate( new DateTime( Math.max( windowMillis, rejectionPolicy.getCurrMaxTime() .getMillis() ) - windowMillis ) ); long minTimestamp = minTimestampAsDate.getMillis(); log.info( "Found [%,d] segments. Attempting to hand off segments that start before [%s].", sinks.size(), minTimestampAsDate ); List<Map.Entry<Long, Sink>> sinksToPush = Lists.newArrayList(); for (Map.Entry<Long, Sink> entry : sinks.entrySet()) { final Long intervalStart = entry.getKey(); if (intervalStart < minTimestamp) { log.info("Adding entry [%s] for merge and push.", entry); sinksToPush.add(entry); } else { log.info( "Skipping persist and merge for entry [%s] : Start time [%s] >= [%s] min timestamp required in this run. Segment will be picked up in a future run.", entry, new DateTime(intervalStart), minTimestampAsDate ); } } log.info("Found [%,d] sinks to persist and merge", sinksToPush.size()); for (final Map.Entry<Long, Sink> entry : sinksToPush) { persistAndMerge(entry.getKey(), entry.getValue()); } } /** * Unannounces a given sink and removes all local references to it. It is important that this is only called * from the single-threaded mergeExecutor, since otherwise chaos may ensue if merged segments are deleted while * being created. * * @param truncatedTime sink key * @param sink sink to unannounce */ protected void abandonSegment(final long truncatedTime, final Sink sink) { if (sinks.containsKey(truncatedTime)) { try { segmentAnnouncer.unannounceSegment(sink.getSegment()); removeSegment(sink, computePersistDir(schema, sink.getInterval())); log.info("Removing sinkKey %d for segment %s", truncatedTime, sink.getSegment().getIdentifier()); sinks.remove(truncatedTime); sinkTimeline.remove( sink.getInterval(), sink.getVersion(), new SingleElementPartitionChunk<>(sink) ); for (FireHydrant hydrant : sink) { cache.close(makeHydrantIdentifier(hydrant, hydrant.getSegment())); } synchronized (handoffCondition) { handoffCondition.notifyAll(); } } catch (Exception e) { log.makeAlert(e, "Unable to abandon old segment for dataSource[%s]", schema.getDataSource()) .addData("interval", sink.getInterval()) .emit(); } } } protected File computeBaseDir(DataSchema schema) { return new File(config.getBasePersistDirectory(), schema.getDataSource()); } protected File computeCorruptedFileDumpDir(File persistDir, DataSchema schema) { return new File( persistDir.getAbsolutePath() .replace(schema.getDataSource(), "corrupted" + File.pathSeparator + schema.getDataSource()) ); } protected File computePersistDir(DataSchema schema, Interval interval) { return new File(computeBaseDir(schema), interval.toString().replace("/", "_")); } /** * Persists the given hydrant and returns the number of rows persisted * * @param indexToPersist hydrant to persist * @param schema datasource schema * @param interval interval to persist * * @return the number of rows persisted */ protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already swapped. Ignoring request to persist.", schema.getDataSource(), interval, indexToPersist ); return 0; } log.info( "DataSource[%s], Interval[%s], Metadata [%s] persisting Hydrant[%s]", schema.getDataSource(), interval, metadataElems, indexToPersist ); try { int numRows = indexToPersist.getIndex().size(); final IndexSpec indexSpec = config.getIndexSpec(); indexToPersist.getIndex().getMetadata().putAll(metadataElems); final File persistedFile = indexMerger.persist( indexToPersist.getIndex(), interval, new File(computePersistDir(schema, interval), String.valueOf(indexToPersist.getCount())), indexSpec ); indexToPersist.swapSegment( new QueryableIndexSegment( indexToPersist.getSegment().getIdentifier(), indexIO.loadIndex(persistedFile) ) ); return numRows; } catch (IOException e) { log.makeAlert("dataSource[%s] -- incremental persist failed", schema.getDataSource()) .addData("interval", interval) .addData("count", indexToPersist.getCount()) .emit(); throw Throwables.propagate(e); } } } private void removeSegment(final Sink sink, final File target) { if (target.exists()) { try { log.info("Deleting Index File[%s]", target); FileUtils.deleteDirectory(target); } catch (Exception e) { log.makeAlert(e, "Unable to remove file for dataSource[%s]", schema.getDataSource()) .addData("file", target) .addData("interval", sink.getInterval()) .emit(); } } } }
{ "content_hash": "442bd8598d820484a2c3a5c7a22d8b54", "timestamp": "", "source": "github", "line_count": 1052, "max_line_length": 161, "avg_line_length": 37.17585551330799, "alnum_prop": 0.5935206729908716, "repo_name": "se7entyse7en/druid", "id": "b9d49396682f864ed5fd0691d4becb65d8c28a7b", "size": "39914", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/src/main/java/io/druid/segment/realtime/plumber/RealtimePlumber.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11781" }, { "name": "CSS", "bytes": "11623" }, { "name": "Groff", "bytes": "3617" }, { "name": "HTML", "bytes": "18353" }, { "name": "Java", "bytes": "8573189" }, { "name": "JavaScript", "bytes": "292689" }, { "name": "Makefile", "bytes": "659" }, { "name": "PostScript", "bytes": "5" }, { "name": "Protocol Buffer", "bytes": "552" }, { "name": "R", "bytes": "17002" }, { "name": "Shell", "bytes": "3571" }, { "name": "TeX", "bytes": "410327" } ], "symlink_target": "" }
UP = 1 DOWN = 2 RIGHT = 3 LEFT = 4 def look(direction) if direction == UP puts "looking up" elsif direction == DOWN puts "looking down" elsif direction == RIGHT or direction == LEFT puts "looking sideways" else puts "Hey! what are you doing? LOOK AT ME!" end end look(UP) look(DOWN) look(LEFT) look("somewhere else")
{ "content_hash": "3e2ed247d349f351c5a409c2c05b4eb5", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 47, "avg_line_length": 16.428571428571427, "alnum_prop": 0.6550724637681159, "repo_name": "xarisd/ruby-basics", "id": "f7ae590b74816e08094277dd6b571f9393925f76", "size": "345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/01_taste/08a_no_symbols.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17573" } ], "symlink_target": "" }
IMPLEMENT_CONOBJECT( GuiEditCtrl ); ConsoleDocClass( GuiEditCtrl, "@brief Native side of the GUI editor.\n\n" "Editor use only.\n\n" "@internal" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onHierarchyChanged, void, (), (), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onDelete, void, (), (), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onPreEdit, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onPostEdit, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onClearSelected, void, (), (), "" ) IMPLEMENT_CALLBACK( GuiEditCtrl, onSelect, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onAddSelected, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onRemoveSelected, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onPreSelectionNudged, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onPostSelectionNudged, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onSelectionMoved, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onSelectionCloned, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onTrashSelection, void, ( SimSet* selection ), ( selection ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onAddNewCtrl, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onAddNewCtrlSet, void, ( SimSet* set ), ( set ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onSelectionResized, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onFitIntoParent, void, ( bool width, bool height ), ( width, height ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onMouseModeChange, void, (), (), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onControlInspectPreApply, void, ( GuiControl* control ), ( control ), "" ); IMPLEMENT_CALLBACK( GuiEditCtrl, onControlInspectPostApply, void, ( GuiControl* control ), ( control ), "" ); StringTableEntry GuiEditCtrl::smGuidesPropertyName[ 2 ]; //----------------------------------------------------------------------------- GuiEditCtrl::GuiEditCtrl() : mCurrentAddSet( NULL ), mContentControl( NULL ), mGridSnap( 0, 0 ), mDragBeginPoint( -1, -1 ), mSnapToControls( true ), mSnapToEdges( true ), mSnapToCenters( true ), mSnapToGuides( true ), mSnapToCanvas( true ), mSnapSensitivity( 2 ), mFullBoxSelection( false ), mDrawBorderLines( true ), mDrawGuides( true ) { VECTOR_SET_ASSOCIATION( mSelectedControls ); VECTOR_SET_ASSOCIATION( mDragBeginPoints ); VECTOR_SET_ASSOCIATION( mSnapHits[ 0 ] ); VECTOR_SET_ASSOCIATION( mSnapHits[ 1 ] ); mActive = true; mDotSB = NULL; mSnapped[ SnapVertical ] = false; mSnapped[ SnapHorizontal ] = false; mDragGuide[ GuideVertical ] = false; mDragGuide[ GuideHorizontal ] = false; if( !smGuidesPropertyName[ GuideVertical ] ) smGuidesPropertyName[ GuideVertical ] = StringTable->insert( "guidesVertical" ); if( !smGuidesPropertyName[ GuideHorizontal ] ) smGuidesPropertyName[ GuideHorizontal ] = StringTable->insert( "guidesHorizontal" ); } //----------------------------------------------------------------------------- void GuiEditCtrl::initPersistFields() { addGroup( "Snapping" ); addField( "snapToControls", TypeBool, Offset( mSnapToControls, GuiEditCtrl ), "If true, edge and center snapping will work against controls." ); addField( "snapToGuides", TypeBool, Offset( mSnapToGuides, GuiEditCtrl ), "If true, edge and center snapping will work against guides." ); addField( "snapToCanvas", TypeBool, Offset( mSnapToCanvas, GuiEditCtrl ), "If true, edge and center snapping will work against canvas (toplevel control)." ); addField( "snapToEdges", TypeBool, Offset( mSnapToEdges, GuiEditCtrl ), "If true, selection edges will snap into alignment when moved or resized." ); addField( "snapToCenters", TypeBool, Offset( mSnapToCenters, GuiEditCtrl ), "If true, selection centers will snap into alignment when moved or resized." ); addField( "snapSensitivity", TypeS32, Offset( mSnapSensitivity, GuiEditCtrl ), "Distance in pixels that edge and center snapping will work across." ); endGroup( "Snapping" ); addGroup( "Selection" ); addField( "fullBoxSelection", TypeBool, Offset( mFullBoxSelection, GuiEditCtrl ), "If true, rectangle selection will only select controls fully inside the drag rectangle." ); endGroup( "Selection" ); addGroup( "Rendering" ); addField( "drawBorderLines", TypeBool, Offset( mDrawBorderLines, GuiEditCtrl ), "If true, lines will be drawn extending along the edges of selected objects." ); addField( "drawGuides", TypeBool, Offset( mDrawGuides, GuiEditCtrl ), "If true, guides will be included in rendering." ); endGroup( "Rendering" ); Parent::initPersistFields(); } //============================================================================= // Events. //============================================================================= // MARK: ---- Events ---- //----------------------------------------------------------------------------- bool GuiEditCtrl::onAdd() { if( !Parent::onAdd() ) return false; mTrash = new SimGroup(); mSelectedSet = new SimSet(); if( !mTrash->registerObject() ) return false; if( !mSelectedSet->registerObject() ) return false; return true; } //----------------------------------------------------------------------------- void GuiEditCtrl::onRemove() { Parent::onRemove(); mDotSB = NULL; mTrash->deleteObject(); mSelectedSet->deleteObject(); mTrash = NULL; mSelectedSet = NULL; } //----------------------------------------------------------------------------- bool GuiEditCtrl::onWake() { if (! Parent::onWake()) return false; // Set GUI Controls to DesignTime mode GuiControl::smDesignTime = true; GuiControl::smEditorHandle = this; setEditMode(true); return true; } //----------------------------------------------------------------------------- void GuiEditCtrl::onSleep() { // Set GUI Controls to run time mode GuiControl::smDesignTime = false; GuiControl::smEditorHandle = NULL; Parent::onSleep(); } //----------------------------------------------------------------------------- bool GuiEditCtrl::onKeyDown(const GuiEvent &event) { if (! mActive) return Parent::onKeyDown(event); if (!(event.modifier & SI_PRIMARY_CTRL)) { switch(event.keyCode) { case KEY_BACKSPACE: case KEY_DELETE: deleteSelection(); onDelete_callback(); return true; default: break; } } return false; } //----------------------------------------------------------------------------- void GuiEditCtrl::onMouseDown(const GuiEvent &event) { if (! mActive) { Parent::onMouseDown(event); return; } if(!mContentControl) return; setFirstResponder(); mouseLock(); mLastMousePos = globalToLocalCoord( event.mousePoint ); // Check whether we've hit a guide. If so, start a guide drag. // Don't do this if SHIFT is down. if( !( event.modifier & SI_SHIFT ) ) { for( U32 axis = 0; axis < 2; ++ axis ) { const S32 guide = findGuide( ( guideAxis ) axis, event.mousePoint, 1 ); if( guide != -1 ) { setMouseMode( DragGuide ); mDragGuide[ axis ] = true; mDragGuideIndex[ axis ] = guide; } } if( mMouseDownMode == DragGuide ) return; } // Check whether we have hit a sizing knob on any of the currently selected // controls. for( U32 i = 0, num = mSelectedControls.size(); i < num; ++ i ) { GuiControl* ctrl = mSelectedControls[ i ]; Point2I cext = ctrl->getExtent(); Point2I ctOffset = globalToLocalCoord( ctrl->localToGlobalCoord( Point2I( 0, 0 ) ) ); RectI box( ctOffset.x, ctOffset.y, cext.x, cext.y ); if( ( mSizingMode = ( GuiEditCtrl::sizingModes ) getSizingHitKnobs( mLastMousePos, box ) ) != 0 ) { setMouseMode( SizingSelection ); mLastDragPos = event.mousePoint; // undo onPreEdit_callback( getSelectedSet() ); return; } } // Find the control we have hit. GuiControl* ctrl = mContentControl->findHitControl( mLastMousePos, getCurrentAddSet()->mLayer ); // Give the control itself the opportunity to handle the event // to implement custom editing logic. bool handledEvent = ctrl->onMouseDownEditor( event, localToGlobalCoord( Point2I(0,0) ) ); if( handledEvent == true ) { // The Control handled the event and requested the edit ctrl // *NOT* act on it. return; } else if( event.modifier & SI_SHIFT ) { // Shift is down. Start rectangle selection in add mode // no matter what we have hit. startDragRectangle( event.mousePoint ); mDragAddSelection = true; } else if( selectionContains( ctrl ) ) { // We hit a selected control. If the multiselect key is pressed, // deselect the control. Otherwise start a drag move. if( event.modifier & SI_MULTISELECT ) { removeSelection( ctrl ); //set the mode setMouseMode( Selecting ); } else if( event.modifier & SI_PRIMARY_ALT ) { // Alt is down. Start a drag clone. startDragClone( event.mousePoint ); } else { startDragMove( event.mousePoint ); } } else { // We clicked an unselected control. if( ctrl == getContentControl() ) { // Clicked in toplevel control. Start a rectangle selection. startDragRectangle( event.mousePoint ); mDragAddSelection = false; } else if( event.modifier & SI_PRIMARY_ALT && ctrl != getContentControl() ) { // Alt is down. Start a drag clone. clearSelection(); addSelection( ctrl ); startDragClone( event.mousePoint ); } else if( event.modifier & SI_MULTISELECT ) addSelection( ctrl ); else { // Clicked on child control. Start move. clearSelection(); addSelection( ctrl ); startDragMove( event.mousePoint ); } } } //----------------------------------------------------------------------------- void GuiEditCtrl::onMouseUp(const GuiEvent &event) { if (! mActive || !mContentControl || !getCurrentAddSet() ) { Parent::onMouseUp(event); return; } //find the control we clicked GuiControl *ctrl = mContentControl->findHitControl(mLastMousePos, getCurrentAddSet()->mLayer); bool handledEvent = ctrl->onMouseUpEditor( event, localToGlobalCoord( Point2I(0,0) ) ); if( handledEvent == true ) { // The Control handled the event and requested the edit ctrl // *NOT* act on it. The dude abides. return; } //unlock the mouse mouseUnlock(); // Reset Drag Axis Alignment Information mDragBeginPoint.set(-1,-1); mDragBeginPoints.clear(); mLastMousePos = globalToLocalCoord(event.mousePoint); if( mMouseDownMode == DragGuide ) { // Check to see if the mouse has moved off the canvas. If so, // remove the guides being dragged. for( U32 axis = 0; axis < 2; ++ axis ) if( mDragGuide[ axis ] && !getContentControl()->getGlobalBounds().pointInRect( event.mousePoint ) ) mGuides[ axis ].erase( mDragGuideIndex[ axis ] ); } else if( mMouseDownMode == DragSelecting ) { // If not multiselecting, clear the current selection. if( !( event.modifier & SI_MULTISELECT ) && !mDragAddSelection ) clearSelection(); RectI rect; getDragRect( rect ); // If the region is somewhere less than at least 2x2, count this as a // normal, non-rectangular selection. if( rect.extent.x <= 2 && rect.extent.y <= 2 ) addSelectControlAt( rect.point ); else { // Use HIT_AddParentHits by default except if ALT is pressed. // Use HIT_ParentPreventsChildHit if ALT+CTRL is pressed. U32 hitFlags = 0; if( !( event.modifier & SI_PRIMARY_ALT ) ) hitFlags |= HIT_AddParentHits; if( event.modifier & SI_PRIMARY_ALT && event.modifier & SI_CTRL ) hitFlags |= HIT_ParentPreventsChildHit; addSelectControlsInRegion( rect, hitFlags ); } } else if( ctrl == getContentControl() && mMouseDownMode == Selecting ) setCurrentAddSet( NULL, true ); // deliver post edit event if we've been editing // note: paxorr: this may need to be moved earlier, if the selection has changed. // undo if( mMouseDownMode == SizingSelection || ( mMouseDownMode == MovingSelection && mDragMoveUndo ) ) onPostEdit_callback( getSelectedSet() ); //reset the mouse mode setFirstResponder(); setMouseMode( Selecting ); mSizingMode = sizingNone; // Clear snapping state. mSnapped[ SnapVertical ] = false; mSnapped[ SnapHorizontal ] = false; mSnapTargets[ SnapVertical ] = NULL; mSnapTargets[ SnapHorizontal ] = NULL; // Clear guide drag state. mDragGuide[ GuideVertical ] = false; mDragGuide[ GuideHorizontal ] = false; } //----------------------------------------------------------------------------- void GuiEditCtrl::onMouseDragged( const GuiEvent &event ) { if( !mActive || !mContentControl || !getCurrentAddSet() ) { Parent::onMouseDragged(event); return; } Point2I mousePoint = globalToLocalCoord( event.mousePoint ); //find the control we clicked GuiControl *ctrl = mContentControl->findHitControl( mousePoint, getCurrentAddSet()->mLayer ); bool handledEvent = ctrl->onMouseDraggedEditor( event, localToGlobalCoord( Point2I(0,0) ) ); if( handledEvent == true ) { // The Control handled the event and requested the edit ctrl // *NOT* act on it. The dude abides. return; } // If we're doing a drag clone, see if we have crossed the move threshold. If so, // clone the selection and switch to move mode. if( mMouseDownMode == DragClone ) { // If we haven't yet crossed the mouse delta to actually start the // clone, check if we have now. S32 delta = mAbs( ( mousePoint - mDragBeginPoint ).len() ); if( delta >= 4 ) { cloneSelection(); mLastMousePos = mDragBeginPoint; mDragMoveUndo = false; setMouseMode( MovingSelection ); } } if( mMouseDownMode == DragGuide ) { for( U32 axis = 0; axis < 2; ++ axis ) if( mDragGuide[ axis ] ) { // Set the guide to the coordinate of the mouse cursor // on the guide's axis. Point2I point = event.mousePoint; point -= localToGlobalCoord( Point2I( 0, 0 ) ); point[ axis ] = mClamp( point[ axis ], 0, getExtent()[ axis ] - 1 ); mGuides[ axis ][ mDragGuideIndex[ axis ] ] = point[ axis ]; } } else if( mMouseDownMode == SizingSelection ) { // Snap the mouse cursor to grid if active. Do this on the mouse cursor so that we handle // incremental drags correctly. Point2I mousePoint = event.mousePoint; snapToGrid( mousePoint ); Point2I delta = mousePoint - mLastDragPos; // If CTRL is down, apply smart snapping. if( event.modifier & SI_CTRL ) { RectI selectionBounds = getSelectionBounds(); doSnapping( event, selectionBounds, delta ); } else { mSnapped[ SnapVertical ] = false; mSnapped[ SnapHorizontal ] = false; } // If ALT is down, do a move instead of a resize on the control // knob's axis. Otherwise resize. if( event.modifier & SI_PRIMARY_ALT ) { if( !( mSizingMode & sizingLeft ) && !( mSizingMode & sizingRight ) ) { mSnapped[ SnapVertical ] = false; delta.x = 0; } if( !( mSizingMode & sizingTop ) && !( mSizingMode & sizingBottom ) ) { mSnapped[ SnapHorizontal ] = false; delta.y = 0; } moveSelection( delta ); } else resizeControlsInSelectionBy( delta, mSizingMode ); // Remember drag point. mLastDragPos = mousePoint; } else if (mMouseDownMode == MovingSelection && mSelectedControls.size()) { Point2I delta = mousePoint - mLastMousePos; RectI selectionBounds = getSelectionBounds(); // Apply snaps. doSnapping( event, selectionBounds, delta ); //RDTODO: to me seems to be in need of revision // Do we want to align this drag to the X and Y axes within a certain threshold? if( event.modifier & SI_SHIFT && !( event.modifier & SI_PRIMARY_ALT ) ) { Point2I dragTotalDelta = event.mousePoint - localToGlobalCoord( mDragBeginPoint ); if( dragTotalDelta.y < 10 && dragTotalDelta.y > -10 ) { for(S32 i = 0; i < mSelectedControls.size(); i++) { Point2I selCtrlPos = mSelectedControls[i]->getPosition(); Point2I snapBackPoint( selCtrlPos.x, mDragBeginPoints[i].y); // This is kind of nasty but we need to snap back if we're not at origin point with selection - JDD if( selCtrlPos.y != mDragBeginPoints[i].y ) mSelectedControls[i]->setPosition( snapBackPoint ); } delta.y = 0; } if( dragTotalDelta.x < 10 && dragTotalDelta.x > -10 ) { for(S32 i = 0; i < mSelectedControls.size(); i++) { Point2I selCtrlPos = mSelectedControls[i]->getPosition(); Point2I snapBackPoint( mDragBeginPoints[i].x, selCtrlPos.y); // This is kind of nasty but we need to snap back if we're not at origin point with selection - JDD if( selCtrlPos.x != mDragBeginPoints[i].x ) mSelectedControls[i]->setPosition( snapBackPoint ); } delta.x = 0; } } if( delta.x || delta.y ) moveSelection( delta, mDragMoveUndo ); // find the current control under the mouse canHitSelectedControls( false ); GuiControl *inCtrl = mContentControl->findHitControl(mousePoint, getCurrentAddSet()->mLayer); canHitSelectedControls( true ); // find the nearest control up the heirarchy from the control the mouse is in // that is flagged as a container. while( !inCtrl->mIsContainer ) inCtrl = inCtrl->getParent(); // if the control under the mouse is not our parent, move the selected controls // into the new parent. if(mSelectedControls[0]->getParent() != inCtrl && inCtrl->mIsContainer) { moveSelectionToCtrl( inCtrl, mDragMoveUndo ); setCurrentAddSet( inCtrl, false ); } mLastMousePos += delta; } else mLastMousePos = mousePoint; } //----------------------------------------------------------------------------- void GuiEditCtrl::onRightMouseDown(const GuiEvent &event) { if (! mActive || !mContentControl) { Parent::onRightMouseDown(event); return; } setFirstResponder(); //search for the control hit in any layer below the edit layer GuiControl *hitCtrl = mContentControl->findHitControl(globalToLocalCoord(event.mousePoint), mLayer - 1); if (hitCtrl != getCurrentAddSet()) { setCurrentAddSet( hitCtrl ); } // select the parent if we right-click on the current add set else if( getCurrentAddSet() != mContentControl) { setCurrentAddSet( hitCtrl->getParent() ); select(hitCtrl); } //Design time mouse events GuiEvent designEvent = event; designEvent.mousePoint = mLastMousePos; hitCtrl->onRightMouseDownEditor( designEvent, localToGlobalCoord( Point2I(0,0) ) ); } //============================================================================= // Rendering. //============================================================================= // MARK: ---- Rendering ---- //----------------------------------------------------------------------------- void GuiEditCtrl::onPreRender() { setUpdate(); } //----------------------------------------------------------------------------- void GuiEditCtrl::onRender(Point2I offset, const RectI &updateRect) { Point2I ctOffset; Point2I cext; bool keyFocused = isFirstResponder(); GFXDrawUtil *drawer = GFX->getDrawUtil(); if (mActive) { if( getCurrentAddSet() != getContentControl() ) { // draw a white frame inset around the current add set. cext = getCurrentAddSet()->getExtent(); ctOffset = getCurrentAddSet()->localToGlobalCoord(Point2I(0,0)); RectI box(ctOffset.x, ctOffset.y, cext.x, cext.y); box.inset( -5, -5 ); drawer->drawRect( box, ColorI( 50, 101, 152, 128 ) ); box.inset( 1, 1 ); drawer->drawRect( box, ColorI( 50, 101, 152, 128 ) ); box.inset( 1, 1 ); drawer->drawRect( box, ColorI( 50, 101, 152, 128 ) ); box.inset( 1, 1 ); drawer->drawRect( box, ColorI( 50, 101, 152, 128 ) ); box.inset( 1, 1 ); drawer->drawRect( box, ColorI( 50, 101, 152, 128 ) ); } Vector<GuiControl *>::iterator i; bool multisel = mSelectedControls.size() > 1; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { GuiControl *ctrl = (*i); cext = ctrl->getExtent(); ctOffset = ctrl->localToGlobalCoord(Point2I(0,0)); RectI box(ctOffset.x,ctOffset.y, cext.x, cext.y); ColorI nutColor = multisel ? ColorI( 255, 255, 255, 100 ) : ColorI( 0, 0, 0, 100 ); ColorI outlineColor = multisel ? ColorI( 0, 0, 0, 100 ) : ColorI( 255, 255, 255, 100 ); if(!keyFocused) nutColor.set( 128, 128, 128, 100 ); drawNuts(box, outlineColor, nutColor); } } renderChildControls(offset, updateRect); // Draw selection rectangle. if( mActive && mMouseDownMode == DragSelecting ) { RectI b; getDragRect(b); b.point += offset; // Draw outline. drawer->drawRect( b, ColorI( 100, 100, 100, 128 ) ); // Draw fill. b.inset( 1, 1 ); drawer->drawRectFill( b, ColorI( 150, 150, 150, 128 ) ); } // Draw grid. if( mActive && ( mMouseDownMode == MovingSelection || mMouseDownMode == SizingSelection ) && ( mGridSnap.x || mGridSnap.y ) ) { Point2I cext = getContentControl()->getExtent(); Point2I coff = getContentControl()->localToGlobalCoord(Point2I(0,0)); // create point-dots const Point2I& snap = mGridSnap; U32 maxdot = (U32)(mCeil(cext.x / (F32)snap.x) - 1) * (U32)(mCeil(cext.y / (F32)snap.y) - 1); if( mDots.isNull() || maxdot != mDots->mNumVerts) { mDots.set(GFX, maxdot, GFXBufferTypeStatic); U32 ndot = 0; mDots.lock(); for(U32 ix = snap.x; ix < cext.x; ix += snap.x) { for(U32 iy = snap.y; ndot < maxdot && iy < cext.y; iy += snap.y) { mDots[ndot].color.set( 50, 50, 254, 100 ); mDots[ndot].point.x = F32(ix + coff.x); mDots[ndot].point.y = F32(iy + coff.y); mDots[ndot].point.z = 0.0f; ndot++; } } mDots.unlock(); AssertFatal(ndot <= maxdot, "dot overflow"); AssertFatal(ndot == maxdot, "dot underflow"); } if (!mDotSB) { GFXStateBlockDesc dotdesc; dotdesc.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha); dotdesc.setCullMode( GFXCullNone ); mDotSB = GFX->createStateBlock( dotdesc ); } GFX->setStateBlock(mDotSB); // draw the points. GFX->setVertexBuffer( mDots ); GFX->drawPrimitive( GFXPointList, 0, mDots->mNumVerts ); } // Draw snapping lines. if( mActive && getContentControl() ) { RectI bounds = getContentControl()->getGlobalBounds(); // Draw guide lines. if( mDrawGuides ) { for( U32 axis = 0; axis < 2; ++ axis ) { for( U32 i = 0, num = mGuides[ axis ].size(); i < num; ++ i ) drawCrossSection( axis, mGuides[ axis ][ i ] + bounds.point[ axis ], bounds, ColorI( 0, 255, 0, 100 ), drawer ); } } // Draw smart snap lines. for( U32 axis = 0; axis < 2; ++ axis ) { if( mSnapped[ axis ] ) { // Draw the snap line. drawCrossSection( axis, mSnapOffset[ axis ], bounds, ColorI( 0, 0, 255, 100 ), drawer ); // Draw a border around the snap target control. if( mSnapTargets[ axis ] ) { RectI bounds = mSnapTargets[ axis ]->getGlobalBounds(); drawer->drawRect( bounds, ColorF( .5, .5, .5, .5 ) ); } } } } } //----------------------------------------------------------------------------- void GuiEditCtrl::drawNuts(RectI &box, ColorI &outlineColor, ColorI &nutColor) { GFXDrawUtil *drawer = GFX->getDrawUtil(); S32 lx = box.point.x, rx = box.point.x + box.extent.x - 1; S32 cx = (lx + rx) >> 1; S32 ty = box.point.y, by = box.point.y + box.extent.y - 1; S32 cy = (ty + by) >> 1; if( mDrawBorderLines ) { ColorF lineColor( 0.7f, 0.7f, 0.7f, 0.25f ); ColorF lightLineColor( 0.5f, 0.5f, 0.5f, 0.1f ); if(lx > 0 && ty > 0) { drawer->drawLine(0, ty, lx, ty, lineColor); // Left edge to top-left corner. drawer->drawLine(lx, 0, lx, ty, lineColor); // Top edge to top-left corner. } if(lx > 0 && by > 0) drawer->drawLine(0, by, lx, by, lineColor); // Left edge to bottom-left corner. if(rx > 0 && ty > 0) drawer->drawLine(rx, 0, rx, ty, lineColor); // Top edge to top-right corner. Point2I extent = localToGlobalCoord(getExtent()); if(lx < extent.x && by < extent.y) drawer->drawLine(lx, by, lx, extent.y, lightLineColor); // Bottom-left corner to bottom edge. if(rx < extent.x && by < extent.y) { drawer->drawLine(rx, by, rx, extent.y, lightLineColor); // Bottom-right corner to bottom edge. drawer->drawLine(rx, by, extent.x, by, lightLineColor); // Bottom-right corner to right edge. } if(rx < extent.x && ty < extent.y) drawer->drawLine(rx, ty, extent.x, ty, lightLineColor); // Top-right corner to right edge. } // Adjust nuts, so they dont straddle the controls. lx -= NUT_SIZE + 1; ty -= NUT_SIZE + 1; rx += 1; by += 1; // Draw nuts. drawNut( Point2I( lx - NUT_SIZE, ty - NUT_SIZE ), outlineColor, nutColor ); // Top left drawNut( Point2I( lx - NUT_SIZE, cy - NUT_SIZE / 2 ), outlineColor, nutColor ); // Mid left drawNut( Point2I( lx - NUT_SIZE, by ), outlineColor, nutColor ); // Bottom left drawNut( Point2I( rx, ty - NUT_SIZE ), outlineColor, nutColor ); // Top right drawNut( Point2I( rx, cy - NUT_SIZE / 2 ), outlineColor, nutColor ); // Mid right drawNut( Point2I( rx, by ), outlineColor, nutColor ); // Bottom right drawNut( Point2I( cx - NUT_SIZE / 2, ty - NUT_SIZE ), outlineColor, nutColor ); // Mid top drawNut( Point2I( cx - NUT_SIZE / 2, by ), outlineColor, nutColor ); // Mid bottom } //----------------------------------------------------------------------------- void GuiEditCtrl::drawNut(const Point2I &nut, ColorI &outlineColor, ColorI &nutColor) { RectI r( nut.x, nut.y, NUT_SIZE * 2, NUT_SIZE * 2 ); GFX->getDrawUtil()->drawRect( r, outlineColor ); r.inset( 1, 1 ); GFX->getDrawUtil()->drawRectFill( r, nutColor ); } //============================================================================= // Selections. //============================================================================= // MARK: ---- Selections ---- //----------------------------------------------------------------------------- void GuiEditCtrl::clearSelection(void) { mSelectedControls.clear(); onClearSelected_callback(); } //----------------------------------------------------------------------------- void GuiEditCtrl::setSelection(GuiControl *ctrl, bool inclusive) { //sanity check if( !ctrl ) return; if( mSelectedControls.size() == 1 && mSelectedControls[ 0 ] == ctrl ) return; if( !inclusive ) clearSelection(); if( mContentControl == ctrl ) setCurrentAddSet( ctrl, false ); else addSelection( ctrl ); } //----------------------------------------------------------------------------- void GuiEditCtrl::addSelection(S32 id) { GuiControl * ctrl; if( Sim::findObject( id, ctrl ) ) addSelection( ctrl ); } //----------------------------------------------------------------------------- void GuiEditCtrl::addSelection( GuiControl* ctrl ) { // Only add if this isn't the content control and the // control isn't yet in the selection. if( ctrl != getContentControl() && !selectionContains( ctrl ) ) { mSelectedControls.push_back( ctrl ); if( mSelectedControls.size() == 1 ) { // Update the add set. if( ctrl->mIsContainer ) setCurrentAddSet( ctrl, false ); else setCurrentAddSet( ctrl->getParent(), false ); // Notify script. onSelect_callback( ctrl ); } else { // Notify script. onAddSelected_callback( ctrl ); } } } //----------------------------------------------------------------------------- void GuiEditCtrl::removeSelection( S32 id ) { GuiControl * ctrl; if ( Sim::findObject( id, ctrl ) ) removeSelection( ctrl ); } //----------------------------------------------------------------------------- void GuiEditCtrl::removeSelection( GuiControl* ctrl ) { if( selectionContains( ctrl ) ) { Vector< GuiControl* >::iterator i = ::find( mSelectedControls.begin(), mSelectedControls.end(), ctrl ); if ( i != mSelectedControls.end() ) mSelectedControls.erase( i ); onRemoveSelected_callback( ctrl ); } } //----------------------------------------------------------------------------- void GuiEditCtrl::canHitSelectedControls( bool state ) { for( U32 i = 0, num = mSelectedControls.size(); i < num; ++ i ) mSelectedControls[ i ]->setCanHit( state ); } //----------------------------------------------------------------------------- void GuiEditCtrl::moveSelectionToCtrl( GuiControl *newParent, bool callback ) { for( U32 i = 0; i < mSelectedControls.size(); ++ i ) { GuiControl* ctrl = mSelectedControls[i]; if( ctrl->getParent() == newParent || ctrl->isLocked() || selectionContainsParentOf( ctrl ) ) continue; Point2I globalpos = ctrl->localToGlobalCoord(Point2I(0,0)); newParent->addObject(ctrl); Point2I newpos = ctrl->globalToLocalCoord(globalpos) + ctrl->getPosition(); ctrl->setPosition(newpos); } onHierarchyChanged_callback(); //TODO: undo } //----------------------------------------------------------------------------- static Point2I snapPoint(Point2I point, Point2I delta, Point2I gridSnap) { S32 snap; if(gridSnap.x && delta.x) { snap = point.x % gridSnap.x; point.x -= snap; if(delta.x > 0 && snap != 0) point.x += gridSnap.x; } if(gridSnap.y && delta.y) { snap = point.y % gridSnap.y; point.y -= snap; if(delta.y > 0 && snap != 0) point.y += gridSnap.y; } return point; } void GuiEditCtrl::moveAndSnapSelection( const Point2I &delta, bool callback ) { // move / nudge gets a special callback so that multiple small moves can be // coalesced into one large undo action. // undo if( callback ) onPreSelectionNudged_callback( getSelectedSet() ); Vector<GuiControl *>::iterator i; Point2I newPos; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { GuiControl* ctrl = *i; if( !ctrl->isLocked() && !selectionContainsParentOf( ctrl ) ) { newPos = ctrl->getPosition() + delta; newPos = snapPoint( newPos, delta, mGridSnap ); ctrl->setPosition( newPos ); } } // undo if( callback ) onPostSelectionNudged_callback( getSelectedSet() ); // allow script to update the inspector if( callback && mSelectedControls.size() > 0 ) onSelectionMoved_callback( mSelectedControls[ 0 ] ); } //----------------------------------------------------------------------------- void GuiEditCtrl::moveSelection( const Point2I &delta, bool callback ) { Vector<GuiControl *>::iterator i; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { GuiControl* ctrl = *i; if( !ctrl->isLocked() && !selectionContainsParentOf( ctrl ) ) ctrl->setPosition( ctrl->getPosition() + delta ); } // allow script to update the inspector if( callback ) onSelectionMoved_callback( mSelectedControls[ 0 ] ); } //----------------------------------------------------------------------------- void GuiEditCtrl::justifySelection( Justification j ) { S32 minX, maxX; S32 minY, maxY; S32 extentX, extentY; if (mSelectedControls.size() < 2) return; Vector<GuiControl *>::iterator i = mSelectedControls.begin(); minX = (*i)->getLeft(); maxX = minX + (*i)->getWidth(); minY = (*i)->getTop(); maxY = minY + (*i)->getHeight(); extentX = (*i)->getWidth(); extentY = (*i)->getHeight(); i++; for(;i != mSelectedControls.end(); i++) { minX = getMin(minX, (*i)->getLeft()); maxX = getMax(maxX, (*i)->getLeft() + (*i)->getWidth()); minY = getMin(minY, (*i)->getTop()); maxY = getMax(maxY, (*i)->getTop() + (*i)->getHeight()); extentX += (*i)->getWidth(); extentY += (*i)->getHeight(); } S32 deltaX = maxX - minX; S32 deltaY = maxY - minY; switch(j) { case JUSTIFY_LEFT: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setLeft( minX ); break; case JUSTIFY_TOP: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setTop( minY ); break; case JUSTIFY_RIGHT: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setLeft( maxX - (*i)->getWidth() + 1 ); break; case JUSTIFY_BOTTOM: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setTop( maxY - (*i)->getHeight() + 1 ); break; case JUSTIFY_CENTER_VERTICAL: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setLeft( minX + ((deltaX - (*i)->getWidth()) >> 1 )); break; case JUSTIFY_CENTER_HORIZONTAL: for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if( !( *i )->isLocked() ) (*i)->setTop( minY + ((deltaY - (*i)->getHeight()) >> 1 )); break; case SPACING_VERTICAL: { Vector<GuiControl *> sortedList; Vector<GuiControl *>::iterator k; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { for(k = sortedList.begin(); k != sortedList.end(); k++) { if ((*i)->getTop() < (*k)->getTop()) break; } sortedList.insert(k, *i); } S32 space = (deltaY - extentY) / (mSelectedControls.size() - 1); S32 curY = minY; for(k = sortedList.begin(); k != sortedList.end(); k++) { if( !( *k )->isLocked() ) (*k)->setTop( curY ); curY += (*k)->getHeight() + space; } } break; case SPACING_HORIZONTAL: { Vector<GuiControl *> sortedList; Vector<GuiControl *>::iterator k; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { for(k = sortedList.begin(); k != sortedList.end(); k++) { if ((*i)->getLeft() < (*k)->getLeft()) break; } sortedList.insert(k, *i); } S32 space = (deltaX - extentX) / (mSelectedControls.size() - 1); S32 curX = minX; for(k = sortedList.begin(); k != sortedList.end(); k++) { if( !( *k )->isLocked() ) (*k)->setLeft( curX ); curX += (*k)->getWidth() + space; } } break; } } //----------------------------------------------------------------------------- void GuiEditCtrl::cloneSelection() { Vector< GuiControl* > newSelection; // Clone the controls in the current selection. const U32 numOldControls = mSelectedControls.size(); for( U32 i = 0; i < numOldControls; ++ i ) { GuiControl* ctrl = mSelectedControls[ i ]; // If parent is in selection, too, skip to prevent multiple clones. if( ctrl->getParent() && selectionContains( ctrl->getParent() ) ) continue; // Clone and add to set. GuiControl* clone = dynamic_cast< GuiControl* >( ctrl->deepClone() ); if( clone ) newSelection.push_back( clone ); } // Exchange the selection set. clearSelection(); const U32 numNewControls = newSelection.size(); for( U32 i = 0; i < numNewControls; ++ i ) addSelection( newSelection[ i ] ); // Callback for undo. onSelectionCloned_callback( getSelectedSet() ); } //----------------------------------------------------------------------------- void GuiEditCtrl::deleteSelection() { // Notify script for undo. onTrashSelection_callback( getSelectedSet() ); // Move all objects in selection to trash. Vector< GuiControl* >::iterator i; for( i = mSelectedControls.begin(); i != mSelectedControls.end(); i ++ ) { if( ( *i ) == getCurrentAddSet() ) setCurrentAddSet( getContentControl(), false ); mTrash->addObject( *i ); } clearSelection(); // Notify script it needs to update its views. onHierarchyChanged_callback(); } //----------------------------------------------------------------------------- void GuiEditCtrl::loadSelection( const char* filename ) { // Set redefine behavior to rename. const char* oldRedefineBehavior = Con::getVariable( "$Con::redefineBehavior" ); Con::setVariable( "$Con::redefineBehavior", "renameNew" ); // Exec the file or clipboard contents with the saved selection set. if( filename ) Con::executef( "exec", filename ); else Con::evaluate( Platform::getClipboard() ); SimSet* set; if( !Sim::findObject( "guiClipboard", set ) ) { if( filename ) Con::errorf( "GuiEditCtrl::loadSelection() - could not find 'guiClipboard' in '%s'", filename ); else Con::errorf( "GuiEditCtrl::loadSelection() - could not find 'guiClipboard'" ); return; } // Restore redefine behavior. Con::setVariable( "$Con::redefineBehavior", oldRedefineBehavior ); // Add the objects in the set. if( set->size() ) { clearSelection(); GuiControlVector ctrls; for( U32 i = 0, num = set->size(); i < num; ++ i ) { GuiControl *ctrl = dynamic_cast< GuiControl* >( ( *set )[ i ] ); if( ctrl ) { getCurrentAddSet()->addObject( ctrl ); ctrls.push_back( ctrl ); } } // Select all controls. We need to perform this here rather than in the // loop above as addSelection() will modify the current add set. for( U32 i = 0; i < ctrls.size(); ++ i ) { addSelection( ctrls[i] ); } // Undo onAddNewCtrlSet_callback( getSelectedSet() ); // Notify the script it needs to update its treeview. onHierarchyChanged_callback(); } set->deleteObject(); } //----------------------------------------------------------------------------- void GuiEditCtrl::saveSelection( const char* filename ) { // If there are no selected objects, then don't save. if( mSelectedControls.size() == 0 ) return; // Open the stream. Stream* stream; if( filename ) { stream = FileStream::createAndOpen( filename, Torque::FS::File::Write ); if( !stream ) { Con::errorf( "GuiEditCtrl::saveSelection - could not open '%s' for writing", filename ); return; } } else stream = new MemStream( 4096 ); // Create a temporary SimSet. SimSet* clipboardSet = new SimSet; clipboardSet->registerObject(); Sim::getRootGroup()->addObject( clipboardSet, "guiClipboard" ); // Add the selected controls to the set. for( Vector< GuiControl* >::iterator i = mSelectedControls.begin(); i != mSelectedControls.end(); ++ i ) { GuiControl* ctrl = *i; if( !selectionContainsParentOf( ctrl ) ) clipboardSet->addObject( ctrl ); } // Write the SimSet. Use the IgnoreCanSave to ensure the controls // get actually written out (also disables the default parent inheritance // behavior for the flag). clipboardSet->write( *stream, 0, IgnoreCanSave ); clipboardSet->deleteObject(); // If we were writing to a memory stream, copy to clipboard // now. if( !filename ) { MemStream* memStream = static_cast< MemStream* >( stream ); memStream->write( U8( 0 ) ); Platform::setClipboard( ( const char* ) memStream->getBuffer() ); } delete stream; } //----------------------------------------------------------------------------- void GuiEditCtrl::selectAll() { GuiControl::iterator i; clearSelection(); for(i = getCurrentAddSet()->begin(); i != getCurrentAddSet()->end(); i++) { GuiControl *ctrl = dynamic_cast<GuiControl *>(*i); addSelection( ctrl ); } } //----------------------------------------------------------------------------- void GuiEditCtrl::bringToFront() { if( getNumSelected() != 1 ) return; GuiControl* ctrl = mSelectedControls.first(); ctrl->getParent()->pushObjectToBack( ctrl ); } //----------------------------------------------------------------------------- void GuiEditCtrl::pushToBack() { if( getNumSelected() != 1 ) return; GuiControl* ctrl = mSelectedControls.first(); ctrl->getParent()->bringObjectToFront( ctrl ); } //----------------------------------------------------------------------------- RectI GuiEditCtrl::getSelectionBounds() const { Vector<GuiControl *>::const_iterator i = mSelectedControls.begin(); Point2I minPos = (*i)->localToGlobalCoord( Point2I( 0, 0 ) ); Point2I maxPos = minPos; for(; i != mSelectedControls.end(); i++) { Point2I iPos = (**i).localToGlobalCoord( Point2I( 0 , 0 ) ); minPos.x = getMin( iPos.x, minPos.x ); minPos.y = getMin( iPos.y, minPos.y ); Point2I iExt = ( **i ).getExtent(); iPos.x += iExt.x; iPos.y += iExt.y; maxPos.x = getMax( iPos.x, maxPos.x ); maxPos.y = getMax( iPos.y, maxPos.y ); } minPos = getContentControl()->globalToLocalCoord( minPos ); maxPos = getContentControl()->globalToLocalCoord( maxPos ); return RectI( minPos.x, minPos.y, ( maxPos.x - minPos.x ), ( maxPos.y - minPos.y ) ); } //----------------------------------------------------------------------------- RectI GuiEditCtrl::getSelectionGlobalBounds() const { Point2I minb( S32_MAX, S32_MAX ); Point2I maxb( S32_MIN, S32_MIN ); for( U32 i = 0, num = mSelectedControls.size(); i < num; ++ i ) { // Min. Point2I pos = mSelectedControls[ i ]->localToGlobalCoord( Point2I( 0, 0 ) ); minb.x = getMin( minb.x, pos.x ); minb.y = getMin( minb.y, pos.y ); // Max. const Point2I extent = mSelectedControls[ i ]->getExtent(); maxb.x = getMax( maxb.x, pos.x + extent.x ); maxb.y = getMax( maxb.y, pos.y + extent.y ); } RectI bounds( minb.x, minb.y, maxb.x - minb.x, maxb.y - minb.y ); return bounds; } //----------------------------------------------------------------------------- bool GuiEditCtrl::selectionContains( GuiControl *ctrl ) { Vector<GuiControl *>::iterator i; for (i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) if (ctrl == *i) return true; return false; } //----------------------------------------------------------------------------- bool GuiEditCtrl::selectionContainsParentOf( GuiControl* ctrl ) { GuiControl* parent = ctrl->getParent(); while( parent && parent != getContentControl() ) { if( selectionContains( parent ) ) return true; parent = parent->getParent(); } return false; } //----------------------------------------------------------------------------- void GuiEditCtrl::select( GuiControl* ctrl ) { clearSelection(); addSelection( ctrl ); } //----------------------------------------------------------------------------- void GuiEditCtrl::updateSelectedSet() { mSelectedSet->clear(); Vector<GuiControl*>::iterator i; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) { mSelectedSet->addObject(*i); } } //----------------------------------------------------------------------------- void GuiEditCtrl::addSelectControlsInRegion( const RectI& rect, U32 flags ) { // Do a hit test on the content control. canHitSelectedControls( false ); Vector< GuiControl* > hits; if( mFullBoxSelection ) flags |= GuiControl::HIT_FullBoxOnly; getContentControl()->findHitControls( rect, hits, flags ); canHitSelectedControls( true ); // Add all controls that got hit. for( U32 i = 0, num = hits.size(); i < num; ++ i ) addSelection( hits[ i ] ); } //----------------------------------------------------------------------------- void GuiEditCtrl::addSelectControlAt( const Point2I& pos ) { // Run a hit test. canHitSelectedControls( false ); GuiControl* hit = getContentControl()->findHitControl( pos ); canHitSelectedControls( true ); // Add to selection. if( hit ) addSelection( hit ); } //----------------------------------------------------------------------------- void GuiEditCtrl::resizeControlsInSelectionBy( const Point2I& delta, U32 mode ) { for( U32 i = 0, num = mSelectedControls.size(); i < num; ++ i ) { GuiControl *ctrl = mSelectedControls[ i ]; if( ctrl->isLocked() ) continue; Point2I minExtent = ctrl->getMinExtent(); Point2I newPosition = ctrl->getPosition(); Point2I newExtent = ctrl->getExtent(); if( mSizingMode & sizingLeft ) { newPosition.x += delta.x; newExtent.x -= delta.x; if( newExtent.x < minExtent.x ) { newPosition.x -= minExtent.x - newExtent.x; newExtent.x = minExtent.x; } } else if( mSizingMode & sizingRight ) { newExtent.x += delta.x; if( newExtent.x < minExtent.x ) newExtent.x = minExtent.x; } if( mSizingMode & sizingTop ) { newPosition.y += delta.y; newExtent.y -= delta.y; if( newExtent.y < minExtent.y ) { newPosition.y -= minExtent.y - newExtent.y; newExtent.y = minExtent.y; } } else if( mSizingMode & sizingBottom ) { newExtent.y += delta.y; if( newExtent.y < minExtent.y ) newExtent.y = minExtent.y; } ctrl->resize( newPosition, newExtent ); } if( mSelectedControls.size() == 1 ) onSelectionResized_callback( mSelectedControls[ 0 ] ); } //----------------------------------------------------------------------------- void GuiEditCtrl::fitIntoParents( bool width, bool height ) { // Record undo. onFitIntoParent_callback( width, height ); // Fit. for( U32 i = 0; i < mSelectedControls.size(); ++ i ) { GuiControl* ctrl = mSelectedControls[ i ]; GuiControl* parent = ctrl->getParent(); Point2I position = ctrl->getPosition(); if( width ) position.x = 0; if( height ) position.y = 0; Point2I extents = ctrl->getExtent(); if( width ) extents.x = parent->getWidth(); if( height ) extents.y = parent->getHeight(); ctrl->resize( position, extents ); } } //----------------------------------------------------------------------------- void GuiEditCtrl::selectParents( bool addToSelection ) { Vector< GuiControl* > parents; // Collect all parents. for( U32 i = 0; i < mSelectedControls.size(); ++ i ) { GuiControl* ctrl = mSelectedControls[ i ]; if( ctrl != mContentControl && ctrl->getParent() != mContentControl ) parents.push_back( mSelectedControls[ i ]->getParent() ); } // If there's no parents to select, don't // change the selection. if( parents.empty() ) return; // Blast selection if need be. if( !addToSelection ) clearSelection(); // Add the parents. for( U32 i = 0; i < parents.size(); ++ i ) addSelection( parents[ i ] ); } //----------------------------------------------------------------------------- void GuiEditCtrl::selectChildren( bool addToSelection ) { Vector< GuiControl* > children; // Collect all children. for( U32 i = 0; i < mSelectedControls.size(); ++ i ) { GuiControl* parent = mSelectedControls[ i ]; for( GuiControl::iterator iter = parent->begin(); iter != parent->end(); ++ iter ) { GuiControl* child = dynamic_cast< GuiControl* >( *iter ); if( child ) children.push_back( child ); } } // If there's no children to select, don't // change the selection. if( children.empty() ) return; // Blast selection if need be. if( !addToSelection ) clearSelection(); // Add the children. for( U32 i = 0; i < children.size(); ++ i ) addSelection( children[ i ] ); } //============================================================================= // Guides. //============================================================================= // MARK: ---- Guides ---- //----------------------------------------------------------------------------- void GuiEditCtrl::readGuides( guideAxis axis, GuiControl* ctrl ) { // Read the guide indices from the vector stored on the respective dynamic // property of the control. const char* guideIndices = ctrl->getDataField( smGuidesPropertyName[ axis ], NULL ); if( guideIndices && guideIndices[ 0 ] ) { U32 index = 0; while( true ) { const char* posStr = StringUnit::getUnit( guideIndices, index, " \t" ); if( !posStr[ 0 ] ) break; mGuides[ axis ].push_back( dAtoi( posStr ) ); index ++; } } } //----------------------------------------------------------------------------- void GuiEditCtrl::writeGuides( guideAxis axis, GuiControl* ctrl ) { // Store the guide indices of the given axis in a vector on the respective // dynamic property of the control. StringBuilder str; bool isFirst = true; for( U32 i = 0, num = mGuides[ axis ].size(); i < num; ++ i ) { if( !isFirst ) str.append( ' ' ); char buffer[ 32 ]; dSprintf( buffer, sizeof( buffer ), "%i", mGuides[ axis ][ i ] ); str.append( buffer ); isFirst = false; } String value = str.end(); ctrl->setDataField( smGuidesPropertyName[ axis ], NULL, value ); } //----------------------------------------------------------------------------- S32 GuiEditCtrl::findGuide( guideAxis axis, const Point2I& point, U32 tolerance ) { const S32 p = ( point - localToGlobalCoord( Point2I( 0, 0 ) ) )[ axis ]; for( U32 i = 0, num = mGuides[ axis ].size(); i < num; ++ i ) { const S32 g = mGuides[ axis ][ i ]; if( p >= ( g - tolerance ) && p <= ( g + tolerance ) ) return i; } return -1; } //============================================================================= // Snapping. //============================================================================= // MARK: ---- Snapping ---- //----------------------------------------------------------------------------- RectI GuiEditCtrl::getSnapRegion( snappingAxis axis, const Point2I& center ) const { RectI rootBounds = getContentControl()->getBounds(); RectI rect; if( axis == SnapHorizontal ) rect = RectI( rootBounds.point.x, center.y - mSnapSensitivity, rootBounds.extent.x, mSnapSensitivity * 2 ); else // SnapVertical rect = RectI( center.x - mSnapSensitivity, rootBounds.point.y, mSnapSensitivity * 2, rootBounds.extent.y ); // Clip against root bounds. rect.intersect( rootBounds ); return rect; } //----------------------------------------------------------------------------- void GuiEditCtrl::registerSnap( snappingAxis axis, const Point2I& mousePoint, const Point2I& point, snappingEdges edge, GuiControl* ctrl ) { bool takeNewSnap = false; const Point2I globalPoint = getContentControl()->localToGlobalCoord( point ); // If we have no snap yet, just take this one. if( !mSnapped[ axis ] ) takeNewSnap = true; // Otherwise see if this snap is the better one. else { // Compare deltas to pointer. S32 deltaCurrent = mAbs( mSnapOffset[ axis ] - mousePoint[ axis ] ); S32 deltaNew = mAbs( globalPoint[ axis ] - mousePoint[ axis ] ); if( deltaCurrent > deltaNew ) takeNewSnap = true; } if( takeNewSnap ) { mSnapped[ axis ] = true; mSnapOffset[ axis ] = globalPoint[ axis ]; mSnapEdge[ axis ] = edge; mSnapTargets[ axis ] = ctrl; } } //----------------------------------------------------------------------------- void GuiEditCtrl::findSnaps( snappingAxis axis, const Point2I& mousePoint, const RectI& minRegion, const RectI& midRegion, const RectI& maxRegion ) { // Find controls with edge in either minRegion, midRegion, or maxRegion // (depending on snap settings). for( U32 i = 0, num = mSnapHits[ axis ].size(); i < num; ++ i ) { GuiControl* ctrl = mSnapHits[ axis ][ i ]; if( ctrl == getContentControl() && !mSnapToCanvas ) continue; RectI bounds = ctrl->getGlobalBounds(); bounds.point = getContentControl()->globalToLocalCoord( bounds.point ); // Compute points on min, mid, and max lines of control. Point2I min = bounds.point; Point2I max = min + bounds.extent - Point2I( 1, 1 ); Point2I mid = min; mid.x += bounds.extent.x / 2; mid.y += bounds.extent.y / 2; // Test edge snap cases. if( mSnapToEdges ) { // Min to min. if( minRegion.pointInRect( min ) ) registerSnap( axis, mousePoint, min, SnapEdgeMin, ctrl ); // Max to max. if( maxRegion.pointInRect( max ) ) registerSnap( axis, mousePoint, max, SnapEdgeMax, ctrl ); // Min to max. if( minRegion.pointInRect( max ) ) registerSnap( axis, mousePoint, max, SnapEdgeMin, ctrl ); // Max to min. if( maxRegion.pointInRect( min ) ) registerSnap( axis, mousePoint, min, SnapEdgeMax, ctrl ); } // Test center snap cases. if( mSnapToCenters ) { // Mid to mid. if( midRegion.pointInRect( mid ) ) registerSnap( axis, mousePoint, mid, SnapEdgeMid, ctrl ); } // Test combined center+edge snap cases. if( mSnapToEdges && mSnapToCenters ) { // Min to mid. if( minRegion.pointInRect( mid ) ) registerSnap( axis, mousePoint, mid, SnapEdgeMin, ctrl ); // Max to mid. if( maxRegion.pointInRect( mid ) ) registerSnap( axis, mousePoint, mid, SnapEdgeMax, ctrl ); // Mid to min. if( midRegion.pointInRect( min ) ) registerSnap( axis, mousePoint, min, SnapEdgeMid, ctrl ); // Mid to max. if( midRegion.pointInRect( max ) ) registerSnap( axis, mousePoint, max, SnapEdgeMid, ctrl ); } } } //----------------------------------------------------------------------------- void GuiEditCtrl::doControlSnap( const GuiEvent& event, const RectI& selectionBounds, const RectI& selectionBoundsGlobal, Point2I& delta ) { if( !mSnapToControls || ( !mSnapToEdges && !mSnapToCenters ) ) return; // Allow restricting to just vertical (ALT+SHIFT) or just horizontal (ALT+CTRL) // snaps. bool snapAxisEnabled[ 2 ]; if( event.modifier & SI_PRIMARY_ALT && event.modifier & SI_SHIFT ) snapAxisEnabled[ SnapHorizontal ] = false; else snapAxisEnabled[ SnapHorizontal ] = true; if( event.modifier & SI_PRIMARY_ALT && event.modifier & SI_CTRL ) snapAxisEnabled[ SnapVertical ] = false; else snapAxisEnabled[ SnapVertical ] = true; // Compute snap regions. There is one region centered on and aligned with // each of the selection bounds edges plus two regions aligned on the selection // bounds center. For the selection bounds origin, we use the point that the // selection would be at, if we had already done the mouse drag. RectI snapRegions[ 2 ][ 3 ]; Point2I projectedOrigin( selectionBounds.point + delta ); dMemset( snapRegions, 0, sizeof( snapRegions ) ); for( U32 axis = 0; axis < 2; ++ axis ) { if( !snapAxisEnabled[ axis ] ) continue; if( mSizingMode == sizingNone || ( axis == 0 && mSizingMode & sizingLeft ) || ( axis == 1 && mSizingMode & sizingTop ) ) snapRegions[ axis ][ 0 ] = getSnapRegion( ( snappingAxis ) axis, projectedOrigin ); if( mSizingMode == sizingNone ) snapRegions[ axis ][ 1 ] = getSnapRegion( ( snappingAxis ) axis, projectedOrigin + Point2I( selectionBounds.extent.x / 2, selectionBounds.extent.y / 2 ) ); if( mSizingMode == sizingNone || ( axis == 0 && mSizingMode & sizingRight ) || ( axis == 1 && mSizingMode & sizingBottom ) ) snapRegions[ axis ][ 2 ] = getSnapRegion( ( snappingAxis ) axis, projectedOrigin + selectionBounds.extent - Point2I( 1, 1 ) ); } // Find hit controls. canHitSelectedControls( false ); if( mSnapToEdges ) { for( U32 axis = 0; axis < 2; ++ axis ) if( snapAxisEnabled[ axis ] ) { getContentControl()->findHitControls( snapRegions[ axis ][ 0 ], mSnapHits[ axis ], HIT_NoCanHitNoRecurse ); getContentControl()->findHitControls( snapRegions[ axis ][ 2 ], mSnapHits[ axis ], HIT_NoCanHitNoRecurse ); } } if( mSnapToCenters && mSizingMode == sizingNone ) { for( U32 axis = 0; axis < 2; ++ axis ) if( snapAxisEnabled[ axis ] ) getContentControl()->findHitControls( snapRegions[ axis ][ 1 ], mSnapHits[ axis ], HIT_NoCanHitNoRecurse ); } canHitSelectedControls( true ); // Add the content control itself to the hit controls // so we can always get a snap on it. if( mSnapToCanvas ) { mSnapHits[ 0 ].push_back( mContentControl ); mSnapHits[ 1 ].push_back( mContentControl ); } // Find snaps. for( U32 i = 0; i < 2; ++ i ) if( snapAxisEnabled[ i ] ) findSnaps( ( snappingAxis ) i, event.mousePoint, snapRegions[ i ][ 0 ], snapRegions[ i ][ 1 ], snapRegions[ i ][ 2 ] ); // Clean up. mSnapHits[ 0 ].clear(); mSnapHits[ 1 ].clear(); } //----------------------------------------------------------------------------- void GuiEditCtrl::doGridSnap( const GuiEvent& event, const RectI& selectionBounds, const RectI& selectionBoundsGlobal, Point2I& delta ) { delta += selectionBounds.point; if( mGridSnap.x ) delta.x -= delta.x % mGridSnap.x; if( mGridSnap.y ) delta.y -= delta.y % mGridSnap.y; delta -= selectionBounds.point; } //----------------------------------------------------------------------------- void GuiEditCtrl::doGuideSnap( const GuiEvent& event, const RectI& selectionBounds, const RectI& selectionBoundsGlobal, Point2I& delta ) { if( !mSnapToGuides ) return; Point2I min = getContentControl()->localToGlobalCoord( selectionBounds.point + delta ); Point2I mid = min + selectionBounds.extent / 2; Point2I max = min + selectionBounds.extent - Point2I( 1, 1 ); for( U32 axis = 0; axis < 2; ++ axis ) { if( mSnapToEdges ) { S32 guideMin = -1; S32 guideMax = -1; if( mSizingMode == sizingNone || ( axis == 0 && mSizingMode & sizingLeft ) || ( axis == 1 && mSizingMode & sizingTop ) ) guideMin = findGuide( ( guideAxis ) axis, min, mSnapSensitivity ); if( mSizingMode == sizingNone || ( axis == 0 && mSizingMode & sizingRight ) || ( axis == 1 && mSizingMode & sizingBottom ) ) guideMax = findGuide( ( guideAxis ) axis, max, mSnapSensitivity ); Point2I pos( 0, 0 ); if( guideMin != -1 ) { pos[ axis ] = mGuides[ axis ][ guideMin ]; registerSnap( ( snappingAxis ) axis, event.mousePoint, pos, SnapEdgeMin ); } if( guideMax != -1 ) { pos[ axis ] = mGuides[ axis ][ guideMax ]; registerSnap( ( snappingAxis ) axis, event.mousePoint, pos, SnapEdgeMax ); } } if( mSnapToCenters && mSizingMode == sizingNone ) { const S32 guideMid = findGuide( ( guideAxis ) axis, mid, mSnapSensitivity ); if( guideMid != -1 ) { Point2I pos( 0, 0 ); pos[ axis ] = mGuides[ axis ][ guideMid ]; registerSnap( ( snappingAxis ) axis, event.mousePoint, pos, SnapEdgeMid ); } } } } //----------------------------------------------------------------------------- void GuiEditCtrl::doSnapping( const GuiEvent& event, const RectI& selectionBounds, Point2I& delta ) { // Clear snapping. If we have snapping on, we want to find a new best snap. mSnapped[ SnapVertical ] = false; mSnapped[ SnapHorizontal ] = false; // Compute global bounds. RectI selectionBoundsGlobal = selectionBounds; selectionBoundsGlobal.point = getContentControl()->localToGlobalCoord( selectionBoundsGlobal.point ); // Apply the snaps. doGridSnap( event, selectionBounds, selectionBoundsGlobal, delta ); doGuideSnap( event, selectionBounds, selectionBoundsGlobal, delta ); doControlSnap( event, selectionBounds, selectionBoundsGlobal, delta ); // If we have a horizontal snap, compute a delta. if( mSnapped[ SnapVertical ] ) snapDelta( SnapVertical, mSnapEdge[ SnapVertical ], mSnapOffset[ SnapVertical ], selectionBoundsGlobal, delta ); // If we have a vertical snap, compute a delta. if( mSnapped[ SnapHorizontal ] ) snapDelta( SnapHorizontal, mSnapEdge[ SnapHorizontal ], mSnapOffset[ SnapHorizontal ], selectionBoundsGlobal, delta ); } //----------------------------------------------------------------------------- void GuiEditCtrl::snapToGrid( Point2I& point ) { if( mGridSnap.x ) point.x -= point.x % mGridSnap.x; if( mGridSnap.y ) point.y -= point.y % mGridSnap.y; } //============================================================================= // Misc. //============================================================================= // MARK: ---- Misc ---- //----------------------------------------------------------------------------- void GuiEditCtrl::setContentControl(GuiControl *root) { mContentControl = root; if( root != NULL ) root->mIsContainer = true; setCurrentAddSet( root ); } //----------------------------------------------------------------------------- void GuiEditCtrl::setEditMode(bool value) { mActive = value; clearSelection(); if( mActive && mAwake ) mCurrentAddSet = NULL; } //----------------------------------------------------------------------------- void GuiEditCtrl::setMouseMode( mouseModes mode ) { if( mMouseDownMode != mode ) { mMouseDownMode = mode; onMouseModeChange_callback(); } } //----------------------------------------------------------------------------- void GuiEditCtrl::setCurrentAddSet(GuiControl *ctrl, bool doclearSelection) { if (ctrl != mCurrentAddSet) { if(doclearSelection) clearSelection(); mCurrentAddSet = ctrl; } } //----------------------------------------------------------------------------- GuiControl* GuiEditCtrl::getCurrentAddSet() { if( !mCurrentAddSet ) setCurrentAddSet( mContentControl, false ); return mCurrentAddSet; } //----------------------------------------------------------------------------- void GuiEditCtrl::addNewControl(GuiControl *ctrl) { getCurrentAddSet()->addObject(ctrl); select( ctrl ); // undo onAddNewCtrl_callback( ctrl ); } //----------------------------------------------------------------------------- S32 GuiEditCtrl::getSizingHitKnobs(const Point2I &pt, const RectI &box) { S32 lx = box.point.x, rx = box.point.x + box.extent.x - 1; S32 cx = (lx + rx) >> 1; S32 ty = box.point.y, by = box.point.y + box.extent.y - 1; S32 cy = (ty + by) >> 1; // adjust nuts, so they dont straddle the controls lx -= NUT_SIZE; ty -= NUT_SIZE; rx += NUT_SIZE; by += NUT_SIZE; if (inNut(pt, lx, ty)) return sizingLeft | sizingTop; if (inNut(pt, cx, ty)) return sizingTop; if (inNut(pt, rx, ty)) return sizingRight | sizingTop; if (inNut(pt, lx, by)) return sizingLeft | sizingBottom; if (inNut(pt, cx, by)) return sizingBottom; if (inNut(pt, rx, by)) return sizingRight | sizingBottom; if (inNut(pt, lx, cy)) return sizingLeft; if (inNut(pt, rx, cy)) return sizingRight; return sizingNone; } //----------------------------------------------------------------------------- void GuiEditCtrl::getDragRect(RectI &box) { box.point.x = getMin(mLastMousePos.x, mSelectionAnchor.x); box.extent.x = getMax(mLastMousePos.x, mSelectionAnchor.x) - box.point.x + 1; box.point.y = getMin(mLastMousePos.y, mSelectionAnchor.y); box.extent.y = getMax(mLastMousePos.y, mSelectionAnchor.y) - box.point.y + 1; } //----------------------------------------------------------------------------- void GuiEditCtrl::getCursor(GuiCursor *&cursor, bool &showCursor, const GuiEvent &lastGuiEvent) { GuiCanvas *pRoot = getRoot(); if( !pRoot ) return; showCursor = false; cursor = NULL; Point2I ctOffset; Point2I cext; GuiControl *ctrl; Point2I mousePos = globalToLocalCoord(lastGuiEvent.mousePoint); PlatformWindow *pWindow = static_cast<GuiCanvas*>(getRoot())->getPlatformWindow(); AssertFatal(pWindow != NULL,"GuiControl without owning platform window! This should not be possible."); PlatformCursorController *pController = pWindow->getCursorController(); AssertFatal(pController != NULL,"PlatformWindow without an owned CursorController!"); S32 desiredCursor = PlatformCursorController::curArrow; // first see if we hit a sizing knob on the currently selected control... if (mSelectedControls.size() == 1 ) { ctrl = mSelectedControls.first(); cext = ctrl->getExtent(); ctOffset = globalToLocalCoord(ctrl->localToGlobalCoord(Point2I(0,0))); RectI box(ctOffset.x,ctOffset.y,cext.x, cext.y); GuiEditCtrl::sizingModes sizeMode = (GuiEditCtrl::sizingModes)getSizingHitKnobs(mousePos, box); if( mMouseDownMode == SizingSelection ) { if ( ( mSizingMode == ( sizingBottom | sizingRight ) ) || ( mSizingMode == ( sizingTop | sizingLeft ) ) ) desiredCursor = PlatformCursorController::curResizeNWSE; else if ( ( mSizingMode == ( sizingBottom | sizingLeft ) ) || ( mSizingMode == ( sizingTop | sizingRight ) ) ) desiredCursor = PlatformCursorController::curResizeNESW; else if ( mSizingMode == sizingLeft || mSizingMode == sizingRight ) desiredCursor = PlatformCursorController::curResizeVert; else if (mSizingMode == sizingTop || mSizingMode == sizingBottom ) desiredCursor = PlatformCursorController::curResizeHorz; } else { // Check for current mouse position after checking for actual sizing mode if ( ( sizeMode == ( sizingBottom | sizingRight ) ) || ( sizeMode == ( sizingTop | sizingLeft ) ) ) desiredCursor = PlatformCursorController::curResizeNWSE; else if ( ( sizeMode == ( sizingBottom | sizingLeft ) ) || ( sizeMode == ( sizingTop | sizingRight ) ) ) desiredCursor = PlatformCursorController::curResizeNESW; else if (sizeMode == sizingLeft || sizeMode == sizingRight ) desiredCursor = PlatformCursorController::curResizeVert; else if (sizeMode == sizingTop || sizeMode == sizingBottom ) desiredCursor = PlatformCursorController::curResizeHorz; } } if( mMouseDownMode == MovingSelection && cursor == NULL ) desiredCursor = PlatformCursorController::curResizeAll; if( pRoot->mCursorChanged != desiredCursor ) { // We've already changed the cursor, // so set it back before we change it again. if(pRoot->mCursorChanged != -1) pController->popCursor(); // Now change the cursor shape pController->pushCursor(desiredCursor); pRoot->mCursorChanged = desiredCursor; } } //----------------------------------------------------------------------------- void GuiEditCtrl::setSnapToGrid(U32 gridsize) { if( gridsize != 0 ) gridsize = getMax( gridsize, ( U32 ) MIN_GRID_SIZE ); mGridSnap.set( gridsize, gridsize ); } //----------------------------------------------------------------------------- void GuiEditCtrl::controlInspectPreApply(GuiControl* object) { // undo onControlInspectPreApply_callback( object ); } //----------------------------------------------------------------------------- void GuiEditCtrl::controlInspectPostApply(GuiControl* object) { // undo onControlInspectPostApply_callback( object ); } //----------------------------------------------------------------------------- void GuiEditCtrl::startDragMove( const Point2I& startPoint ) { mDragMoveUndo = true; // For calculating mouse delta mDragBeginPoint = globalToLocalCoord( startPoint ); // Allocate enough space for our selected controls mDragBeginPoints.reserve( mSelectedControls.size() ); // For snapping to origin Vector<GuiControl *>::iterator i; for(i = mSelectedControls.begin(); i != mSelectedControls.end(); i++) mDragBeginPoints.push_back( (*i)->getPosition() ); // Set Mouse Mode setMouseMode( MovingSelection ); // undo onPreEdit_callback( getSelectedSet() ); } //----------------------------------------------------------------------------- void GuiEditCtrl::startDragRectangle( const Point2I& startPoint ) { mSelectionAnchor = globalToLocalCoord( startPoint ); setMouseMode( DragSelecting ); } //----------------------------------------------------------------------------- void GuiEditCtrl::startDragClone( const Point2I& startPoint ) { mDragBeginPoint = globalToLocalCoord( startPoint ); setMouseMode( DragClone ); } //----------------------------------------------------------------------------- void GuiEditCtrl::startMouseGuideDrag( guideAxis axis, U32 guideIndex, bool lockMouse ) { mDragGuideIndex[ axis ] = guideIndex; mDragGuide[ axis ] = true; setMouseMode( DragGuide ); // Grab the mouse. if( lockMouse ) mouseLock(); } //============================================================================= // Console Methods. //============================================================================= // MARK: ---- Console Methods ---- //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, getContentControl, S32, 2, 2, "() - Return the toplevel control edited inside the GUI editor." ) { GuiControl* ctrl = object->getContentControl(); if( ctrl ) return ctrl->getId(); else return 0; } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, setContentControl, void, 3, 3, "( GuiControl ctrl ) - Set the toplevel control to edit in the GUI editor." ) { GuiControl *ctrl; if(!Sim::findObject(argv[2], ctrl)) return; object->setContentControl(ctrl); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, addNewCtrl, void, 3, 3, "(GuiControl ctrl)") { GuiControl *ctrl; if(!Sim::findObject(argv[2], ctrl)) return; object->addNewControl(ctrl); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, addSelection, void, 3, 3, "selects a control.") { S32 id = dAtoi(argv[2]); object->addSelection(id); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, removeSelection, void, 3, 3, "deselects a control.") { S32 id = dAtoi(argv[2]); object->removeSelection(id); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, clearSelection, void, 2, 2, "Clear selected controls list.") { object->clearSelection(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, select, void, 3, 3, "(GuiControl ctrl)") { GuiControl *ctrl; if(!Sim::findObject(argv[2], ctrl)) return; object->setSelection(ctrl, false); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, setCurrentAddSet, void, 3, 3, "(GuiControl ctrl)") { GuiControl *addSet; if (!Sim::findObject(argv[2], addSet)) { Con::printf("%s(): Invalid control: %s", argv[0], argv[2]); return; } object->setCurrentAddSet(addSet); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, getCurrentAddSet, S32, 2, 2, "Returns the set to which new controls will be added") { const GuiControl* add = object->getCurrentAddSet(); return add ? add->getId() : 0; } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, toggle, void, 2, 2, "Toggle activation.") { object->setEditMode( !object->isActive() ); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, justify, void, 3, 3, "(int mode)" ) { object->justifySelection((GuiEditCtrl::Justification)dAtoi(argv[2])); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, bringToFront, void, 2, 2, "") { object->bringToFront(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, pushToBack, void, 2, 2, "") { object->pushToBack(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, deleteSelection, void, 2, 2, "() - Delete the selected controls.") { object->deleteSelection(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, moveSelection, void, 4, 4, "(int dx, int dy) - Move all controls in the selection by (dx,dy) pixels.") { object->moveAndSnapSelection(Point2I(dAtoi(argv[2]), dAtoi(argv[3]))); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, saveSelection, void, 2, 3, "( string fileName=null ) - Save selection to file or clipboard.") { const char* filename = NULL; if( argc > 2 ) filename = argv[ 2 ]; object->saveSelection( filename ); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, loadSelection, void, 2, 3, "( string fileName=null ) - Load selection from file or clipboard.") { const char* filename = NULL; if( argc > 2 ) filename = argv[ 2 ]; object->loadSelection( filename ); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, selectAll, void, 2, 2, "()") { object->selectAll(); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiEditCtrl, getSelection, SimSet*, (),, "Gets the set of GUI controls currently selected in the editor." ) { return object->getSelectedSet(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, getNumSelected, S32, 2, 2, "() - Return the number of controls currently selected." ) { return object->getNumSelected(); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, getSelectionGlobalBounds, const char*, 2, 2, "() - Returns global bounds of current selection as vector 'x y width height'." ) { RectI bounds = object->getSelectionGlobalBounds(); String str = String::ToString( "%i %i %i %i", bounds.point.x, bounds.point.y, bounds.extent.x, bounds.extent.y ); char* buffer = Con::getReturnBuffer( str.length() ); dStrcpy( buffer, str.c_str() ); return buffer; } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, selectParents, void, 2, 3, "( bool addToSelection=false ) - Select parents of currently selected controls." ) { bool addToSelection = false; if( argc > 2 ) addToSelection = dAtob( argv[ 2 ] ); object->selectParents( addToSelection ); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, selectChildren, void, 2, 3, "( bool addToSelection=false ) - Select children of currently selected controls." ) { bool addToSelection = false; if( argc > 2 ) addToSelection = dAtob( argv[ 2 ] ); object->selectChildren( addToSelection ); } //----------------------------------------------------------------------------- DefineEngineMethod( GuiEditCtrl, getTrash, SimGroup*, (),, "Gets the GUI controls(s) that are currently in the trash.") { return object->getTrash(); } //----------------------------------------------------------------------------- ConsoleMethod(GuiEditCtrl, setSnapToGrid, void, 3, 3, "GuiEditCtrl.setSnapToGrid(gridsize)") { U32 gridsize = dAtoi(argv[2]); object->setSnapToGrid(gridsize); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, readGuides, void, 3, 4, "( GuiControl ctrl [, int axis ] ) - Read the guides from the given control." ) { // Find the control. GuiControl* ctrl; if( !Sim::findObject( argv[ 2 ], ctrl ) ) { Con::errorf( "GuiEditCtrl::readGuides - no control '%s'", argv[ 2 ] ); return; } // Read the guides. if( argc > 3 ) { S32 axis = dAtoi( argv[ 3 ] ); if( axis < 0 || axis > 1 ) { Con::errorf( "GuiEditCtrl::readGuides - invalid axis '%s'", argv[ 3 ] ); return; } object->readGuides( ( GuiEditCtrl::guideAxis ) axis, ctrl ); } else { object->readGuides( GuiEditCtrl::GuideHorizontal, ctrl ); object->readGuides( GuiEditCtrl::GuideVertical, ctrl ); } } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, writeGuides, void, 3, 4, "( GuiControl ctrl [, int axis ] ) - Write the guides to the given control." ) { // Find the control. GuiControl* ctrl; if( !Sim::findObject( argv[ 2 ], ctrl ) ) { Con::errorf( "GuiEditCtrl::writeGuides - no control '%i'", argv[ 2 ] ); return; } // Write the guides. if( argc > 3 ) { S32 axis = dAtoi( argv[ 3 ] ); if( axis < 0 || axis > 1 ) { Con::errorf( "GuiEditCtrl::writeGuides - invalid axis '%s'", argv[ 3 ] ); return; } object->writeGuides( ( GuiEditCtrl::guideAxis ) axis, ctrl ); } else { object->writeGuides( GuiEditCtrl::GuideHorizontal, ctrl ); object->writeGuides( GuiEditCtrl::GuideVertical, ctrl ); } } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, clearGuides, void, 2, 3, "( [ int axis ] ) - Clear all currently set guide lines." ) { if( argc > 2 ) { S32 axis = dAtoi( argv[ 2 ] ); if( axis < 0 || axis > 1 ) { Con::errorf( "GuiEditCtrl::clearGuides - invalid axis '%i'", axis ); return; } object->clearGuides( ( GuiEditCtrl::guideAxis ) axis ); } else { object->clearGuides( GuiEditCtrl::GuideHorizontal ); object->clearGuides( GuiEditCtrl::GuideVertical ); } } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, fitIntoParents, void, 2, 4, "( bool width=true, bool height=true ) - Fit selected controls into their parents." ) { bool width = true; bool height = true; if( argc > 2 ) width = dAtob( argv[ 2 ] ); if( argc > 3 ) height = dAtob( argv[ 3 ] ); object->fitIntoParents( width, height ); } //----------------------------------------------------------------------------- ConsoleMethod( GuiEditCtrl, getMouseMode, const char*, 2, 2, "() - Return the current mouse mode." ) { switch( object->getMouseMode() ) { case GuiEditCtrl::Selecting: return "Selecting"; case GuiEditCtrl::DragSelecting: return "DragSelecting"; case GuiEditCtrl::MovingSelection: return "MovingSelection"; case GuiEditCtrl::SizingSelection: return "SizingSelection"; case GuiEditCtrl::DragGuide: return "DragGuide"; case GuiEditCtrl::DragClone: return "DragClone"; default: return ""; } } //============================================================================= // GuiEditorRuler. //============================================================================= class GuiEditorRuler : public GuiControl { public: typedef GuiControl Parent; protected: String mRefCtrlName; String mEditCtrlName; GuiScrollCtrl* mRefCtrl; GuiEditCtrl* mEditCtrl; public: enum EOrientation { ORIENTATION_Horizontal, ORIENTATION_Vertical }; GuiEditorRuler() : mRefCtrl( 0 ), mEditCtrl( 0 ) { } EOrientation getOrientation() const { if( getWidth() > getHeight() ) return ORIENTATION_Horizontal; else return ORIENTATION_Vertical; } bool onWake() { if( !Parent::onWake() ) return false; if( !mEditCtrlName.isEmpty() && !Sim::findObject( mEditCtrlName, mEditCtrl ) ) Con::errorf( "GuiEditorRuler::onWake() - no GuiEditCtrl '%s'", mEditCtrlName.c_str() ); if( !mRefCtrlName.isEmpty() && !Sim::findObject( mRefCtrlName, mRefCtrl ) ) Con::errorf( "GuiEditorRuler::onWake() - no GuiScrollCtrl '%s'", mRefCtrlName.c_str() ); return true; } void onPreRender() { setUpdate(); } void onMouseDown( const GuiEvent& event ) { if( !mEditCtrl ) return; // Determine the guide axis. GuiEditCtrl::guideAxis axis; if( getOrientation() == ORIENTATION_Horizontal ) axis = GuiEditCtrl::GuideHorizontal; else axis = GuiEditCtrl::GuideVertical; // Start dragging a new guide out in the editor. U32 guideIndex = mEditCtrl->addGuide( axis, 0 ); mEditCtrl->startMouseGuideDrag( axis, guideIndex ); } void onRender(Point2I offset, const RectI &updateRect) { GFX->getDrawUtil()->drawRectFill(updateRect, ColorF(1,1,1,1)); Point2I choffset(0,0); if( mRefCtrl != NULL ) choffset = mRefCtrl->getChildPos(); if( getOrientation() == ORIENTATION_Horizontal ) { // it's horizontal. for(U32 i = 0; i < getWidth(); i++) { S32 x = offset.x + i; S32 pos = i - choffset.x; if(!(pos % 10)) { S32 start = 6; if(!(pos %20)) start = 4; if(!(pos % 100)) start = 1; GFX->getDrawUtil()->drawLine(x, offset.y + start, x, offset.y + 10, ColorF(0,0,0,1)); } } } else { // it's vertical. for(U32 i = 0; i < getHeight(); i++) { S32 y = offset.y + i; S32 pos = i - choffset.y; if(!(pos % 10)) { S32 start = 6; if(!(pos %20)) start = 4; if(!(pos % 100)) start = 1; GFX->getDrawUtil()->drawLine(offset.x + start, y, offset.x + 10, y, ColorF(0,0,0,1)); } } } } static void initPersistFields() { addField( "refCtrl", TypeRealString, Offset( mRefCtrlName, GuiEditorRuler ) ); addField( "editCtrl", TypeRealString, Offset( mEditCtrlName, GuiEditorRuler ) ); Parent::initPersistFields(); } DECLARE_CONOBJECT(GuiEditorRuler); DECLARE_CATEGORY( "Gui Editor" ); }; IMPLEMENT_CONOBJECT(GuiEditorRuler); ConsoleDocClass( GuiEditorRuler, "@brief Visual representation of markers on top and left sides of GUI Editor\n\n" "Editor use only.\n\n" "@internal" );
{ "content_hash": "e01d1b1b81908255975a505a3c0a33cc", "timestamp": "", "source": "github", "line_count": 2932, "max_line_length": 164, "avg_line_length": 30.453274215552526, "alnum_prop": 0.5249694811230947, "repo_name": "mattparizeau/Marble-Blast-Clone", "id": "584c9b9e27a30494977d8855f9b0684362c11fdf", "size": "90914", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Engine/source/gui/editor/guiEditCtrl.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "29271" }, { "name": "C", "bytes": "13939158" }, { "name": "C#", "bytes": "1945508" }, { "name": "C++", "bytes": "28623346" }, { "name": "CSS", "bytes": "29749" }, { "name": "Objective-C", "bytes": "245368" }, { "name": "Objective-C++", "bytes": "133442" }, { "name": "PHP", "bytes": "502329" }, { "name": "Pascal", "bytes": "258402" }, { "name": "SAS", "bytes": "13756" }, { "name": "Shell", "bytes": "90939" }, { "name": "Smalltalk", "bytes": "6990" } ], "symlink_target": "" }
var config = require("./../../").config; var pathSyntax = require("falcor-path-syntax"); var ModelResponse = require("./../ModelResponse"); var gets = require("./../../get"); var getWithPathsAsJSONGraph = gets.getWithPathsAsJSONGraph; var getWithPathsAsPathMap = gets.getWithPathsAsPathMap; var GET_VALID_INPUT = require("./validInput"); var validateInput = require("./../../support/validate-input"); var GetResponse = require("./../GetResponse"); /** * Performs a get on the cache and if there are missing paths * then the request will be forwarded to the get request cycle. */ module.exports = function get() { // Validates the input. If the input is not paths or strings then we // will onError. if (config.DEBUG) { var out = validateInput(arguments, GET_VALID_INPUT, "get"); if (out !== true) { return new ModelResponse(function(o) { o.onError(out); }); } } var paths; // If get with paths only mode is on, then we can just // clone the array. if (config.GET_WITH_PATHS_ONLY) { paths = []; for (var i = 0, len = arguments.length; i < len; ++i) { paths[i] = arguments[i]; } } // Else clone and test all of the paths for strings. else { paths = pathSyntax.fromPathsOrPathValues(arguments); } var model = this; // Does a greedy cache lookup before setting up the // request observable. return new ModelResponse(function(observer) { var results; var seed = [{}]; var isJSONG = observer.outputFormat === "AsJSONG"; // Gets either as jsonGraph or as pathMaps if (isJSONG) { results = getWithPathsAsJSONGraph(model, paths, seed); } else { results = getWithPathsAsPathMap(model, paths, seed); } // We can complete without going to the server and without performinc // any cache clean up. if (!results.requestedMissingPaths) { // There has to be at least one value to report an onNext. if (results.hasValue) { observer.onNext(seed[0]); } if (results.errors) { observer.onError(results.errors); } else { observer.onCompleted(); } return null; } // Else go into the legacy get request cycle using full Rx. // The request has to be copied onto the inner request. // TODO: Obvious performance win here if the request cycle was // done without observable copying. var getResponse = GetResponse. create(model, paths); if (isJSONG) { getResponse = getResponse._toJSONG(); } if (observer.isProgressive) { getResponse = getResponse.progressively(); } return getResponse.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); };
{ "content_hash": "7d226e6ca1acd411f0fd8254708ff46b", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 77, "avg_line_length": 33.5, "alnum_prop": 0.5827384815055159, "repo_name": "bigmeech/falcor", "id": "36d7efd80d08ab3fece30c6fccdbd920f9f37f99", "size": "3082", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/response/get/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "3560888" }, { "name": "Shell", "bytes": "1138" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/tknerr/vagrant-managed-servers.png?branch=master)](https://travis-ci.org/tknerr/vagrant-managed-servers) This is a [Vagrant](http://www.vagrantup.com) 1.6+ plugin that adds a provider for "managed servers" to Vagrant, i.e. servers for which you have SSH access but no control over their lifecycle. Since you don't control the lifecycle: * `up` and `destroy` are re-interpreted as "linking" / "unlinking" vagrant with a managed server * once "linked", the `ssh` and `provision` commands work as expected and `status` shows the managed server as either "running" or "not reachable" * `reload` will issue a reboot command on the managed server (cross your fingers ;-)) * `halt`, `suspend` and `resume` are no-ops in this provider Credits: this provider was initially based on the [vagrant-aws](https://github.com/mitchellh/vagrant-aws) provider with the AWS-specific functionality stripped out. ## Features * SSH into managed servers. * Provision managed servers with any built-in Vagrant provisioner. * Reboot a managed server. * Synced folder support. ## Usage Install using the standard Vagrant plugin installation method: ``` $ vagrant plugin install vagrant-managed-servers ``` In the Vagrantfile you can now use the `managed` provider and specify the managed server's hostname and credentials: ```ruby Vagrant.configure("2") do |config| config.vm.box = "tknerr/managed-server-dummy" config.vm.provider :managed do |managed, override| managed.server = "foo.acme.com" override.ssh.username = "bob" override.ssh.private_key_path = "/path/to/bobs_private_key" end end ``` Next run `vagrant up --provider=managed` in order to "link" the vagrant VM with the managed server: ``` $ vagrant up --provider=managed Bringing machine 'default' up with 'managed' provider... ==> default: Box 'tknerr/managed-server-dummy' could not be found. Attempting to find and install... default: Box Provider: managed default: Box Version: >= 0 ==> default: Loading metadata for box 'tknerr/managed-server-dummy' default: URL: https://vagrantcloud.com/tknerr/managed-server-dummy ==> default: Adding box 'tknerr/managed-server-dummy' (v1.0.0) for provider: managed default: Downloading: https://vagrantcloud.com/tknerr/managed-server-dummy/version/1/provider/managed.box default: Progress: 100% (Rate: 122k/s, Estimated time remaining: --:--:--) ==> default: Successfully added box 'tknerr/managed-server-dummy' (v1.0.0) for 'managed'! ==> default: Linking vagrant with managed server foo.acme.com ==> default: -- Server: foo.acme.com ``` Once linked, you can run `vagrant ssh` to ssh into the managed server or `vagrant provision` to provision that server with any of the available vagrant provisioners: ``` $ vagrant provision ... $ vagrant ssh ... ``` In some cases you might need to reboot the managed server via `vagrant reload`: ``` $ vagrant reload ==> default: Rebooting managed server foo.acme.com ==> default: -- Server: foo.acme.com ==> default: Waiting for foo.acme.com to reboot ==> default: Waiting for foo.acme.com to reboot ==> default: Waiting for foo.acme.com to reboot ==> default: foo.acme.com rebooted and ready. ``` If you are done, you can "unlink" vagrant from the managed server by running `vagrant destroy`: ``` $ vagrant destroy -f ==> default: Unlinking vagrant from managed server foo.acme.com ==> default: -- Server: foo.acme.com ``` If you try any of the other VM lifecycle commands like `halt`, `suspend`, `resume`, etc... you will get a warning that these commands are not supported with the vagrant-managed-servers provider. ## Box Format Every provider in Vagrant must introduce a custom box format. This provider introduces a "dummy box" for the `managed` provider which is really nothing more than the required `metadata.json` with the provider name set to "managed". You can use the [tknerr/managed-server-dummy](https://atlas.hashicorp.com/tknerr/boxes/managed-server-dummy) box like that: ```ruby Vagrant.configure("2") do |config| config.vm.box = "tknerr/managed-server-dummy" ... end ``` ## Configuration This provider currently exposes only a single provider-specific configuration option: * `server` - The IP address or hostname of the existing managed server It can be set like typical provider-specific configuration: ```ruby Vagrant.configure("2") do |config| # ... other stuff config.vm.provider :managed do |managed| managed.server = "myserver.mydomain.com" end end ``` ## Networks Networking features in the form of `config.vm.network` are not supported with `vagrant-managed-servers`. If any of these are specified, Vagrant will emit a warning and just ignore it. ## Synced Folders There is minimal synced folders support for provisioning linux guests via rsync, and for windows guests via either smb, winrm or rsync ([see below](https://github.com/tknerr/vagrant-managed-servers#synced-folders-windows)). This is good enough for all built-in Vagrant provisioners (shell, chef, and puppet) to work! ## Windows support It is possible to use this plugin to control pre-existing windows servers using WinRM instead of rsync, with a few prerequisites: * WinRM installed and running on the target machine * The account used to connect is a local account and also a local administrator (domain accounts don't work over basic auth) * WinRM basic authentication is enabled * WinRM unencrypted traffic is enabled For more information, see the WinRM Gem [Troubleshooting Guide](https://github.com/WinRb/WinRM#troubleshooting) Your vagrantfile will look something like this: ```ruby config.vm.define 'my-windows-server' do |windows| windows.vm.communicator = :winrm windows.winrm.username = 'vagrant' windows.winrm.password = 'vagrant' windows.vm.provider :managed do |managed, override| managed.server = 'myserver.mydomain.com' end end ``` ### Synced Folders (Windows) Vagrant Managed Servers will try several different mechanisms to sync folders for Windows guests. In order of priority: 1. [SMB](http://docs.vagrantup.com/v2/synced-folders/smb.html) - requires running from a Windows host, an Administrative console, and Powershell 3 or greater. Note that there is a known [bug](https://github.com/mitchellh/vagrant/issues/3139) which causes the Powershell version check to hang for Powershell 2 2. [WinRM](https://github.com/cimpress-mcp/vagrant-winrm-syncedfolders) - uses the WinRM communicator and is reliable, but can be slow for large numbers of files. 3. [RSync](http://docs.vagrantup.com/v2/synced-folders/rsync.html) - requires `rsync.exe` installed and on your path. Vagrant will try to use the best folder synchronization mechanism given your host and guest capabilities, but you can force a different type of folder sync with the `type` parameter of the `synced_folder` property in your Vagrantfile. ```ruby windows.vm.synced_folder '.', '/vagrant', type: "winrm" ``` ## Development To work on the `vagrant-managed-servers` plugin, clone this repository out, and use [Bundler](http://gembundler.com) to get the dependencies: ``` $ bundle ``` Once you have the dependencies, verify the unit tests pass with `rake`: ``` $ bundle exec rake ``` If those pass, you're ready to start developing the plugin. You can test the plugin without installing it into your Vagrant environment by using the `Vagrantfile` in the top level of this directory and use bundler to execute Vagrant. First, let's pretend we have a managed server by bringing up the `local_linux` vagrant VM with the default virtualbox provider: ``` $ bundle exec vagrant up local_linux ``` Now you can use the managed provider (defined in a separate VM named `managed_linux`) to ssh into or provision the actual managed server: ``` $ # link vagrant with the server $ bundle exec vagrant up managed_linux --provider=managed $ # ssh / provision $ bundle exec vagrant ssh managed_linux $ bundle exec vagrant provision managed_linux $ # unlink $ bundle exec vagrant destroy managed_linux ```
{ "content_hash": "858df1c78eaa128f27cfb794f6064b39", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 308, "avg_line_length": 39.99004975124378, "alnum_prop": 0.7516795222692212, "repo_name": "ekaynar/Bigdata-deployment", "id": "adb39bc4723e36d8132757f02563d0008662075b", "size": "8073", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "readmeold.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "28355" }, { "name": "Shell", "bytes": "4054" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IEMobile 7 ]> <html class="no-js iem7"> <![endif]--> <!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="cleartype" content="on"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/touch/apple-touch-icon-144x144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/touch/apple-touch-icon-114x114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/touch/apple-touch-icon-72x72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="img/touch/apple-touch-icon-57x57-precomposed.png"> <link rel="shortcut icon" href="img/touch/apple-touch-icon.png"> <!-- Tile icon for Win8 (144x144 + tile color) --> <meta name="msapplication-TileImage" content="img/touch/apple-touch-icon-144x144-precomposed.png"> <meta name="msapplication-TileColor" content="#222222"> <!-- For iOS web apps. Delete if not needed. https://github.com/h5bp/mobile-boilerplate/issues/94 --> <!-- <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content=""> --> <!-- This script prevents links from opening in Mobile Safari. https://gist.github.com/1042026 --> <!-- <script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script> --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> </head> <body> <!-- Add your site or application content here --> <script src="js/vendor/zepto.min.js"></script> <script src="js/helper.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1; g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js"; s.parentNode.insertBefore(g,s)}(document,"script")); </script> <img src="http://static.comicvine.com/uploads/original/11/114513/2437125-sheldon_blue.jpg"></img> </body> </html>
{ "content_hash": "5ee830c7de000278c76d136079d053ea", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 330, "avg_line_length": 51.45762711864407, "alnum_prop": 0.6159420289855072, "repo_name": "stw66/HTML5APP_1", "id": "abdbefe17490c81ea969b9260d1304159de720a8", "size": "3036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11076" }, { "name": "JavaScript", "bytes": "14938" } ], "symlink_target": "" }
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { var TopRowHTML = require('hbs!./menu/top-row'); var ProvisionTopRowHTML = require('hbs!./menu/provision-top-row'); var Config = require('sunstone-config'); return { 'insert': _insert, 'insertProvision': _insertProvision, 'setup': _setup, 'hide': _hide, 'show': _show, 'entryClick': _entryClick, }; function _insert(){ $('#top-row').html(TopRowHTML({ logo: Config.logo, link: Config.link_logo, link_text: Config.text_link_logo })); _setup(); } function _insertProvision(){ $('#top-row').html(ProvisionTopRowHTML({logo: Config.provision.logo})); $("#menu-wrapper").remove(); } function _setup(){ $('#menu-toggle').on('click', function(){ var hiding = $('.sunstone-content').hasClass("large-10"); if(!hiding){ $('.sunstone-content').toggleClass('large-10'); $('.sunstone-content').toggleClass('large-12'); } $('#menu-wrapper').toggle(200, function(){ if(hiding){ $('.sunstone-content').toggleClass('large-10'); $('.sunstone-content').toggleClass('large-12'); } }); }); var prevWindowLarge = Foundation.MediaQuery.atLeast('large'); $(window).resize(function() { if(Foundation.MediaQuery.atLeast('large')){ $('#menu-wrapper').removeClass("menu-small"); if(!prevWindowLarge){ // resizing from small to large, show menu _show(); } prevWindowLarge = true; } else { $('#menu-wrapper').addClass("menu-small"); if(prevWindowLarge){ // resizing from large to small, hide menu _hide(); } prevWindowLarge = false; } }); $(window).resize(); } function _hide(){ if($('#menu-wrapper').is(':visible')){ $('#menu-toggle').click(); } } function _show(){ if(!$('#menu-wrapper').is(':visible')){ $('#menu-toggle').click(); } } function _entryClick(){ if(!Foundation.MediaQuery.atLeast('large')){ _hide(); } } });
{ "content_hash": "5ce55c1a645d720b9a800e1a53137951", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 80, "avg_line_length": 31.4, "alnum_prop": 0.49014255383682137, "repo_name": "goberle/one", "id": "41c8495fc6853348b212cd92146c5d053b891f78", "size": "3297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sunstone/public/app/utils/menu.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "178636" }, { "name": "C++", "bytes": "3709612" }, { "name": "CSS", "bytes": "55088" }, { "name": "HTML", "bytes": "690393" }, { "name": "Java", "bytes": "537021" }, { "name": "JavaScript", "bytes": "2331508" }, { "name": "Lex", "bytes": "10531" }, { "name": "Python", "bytes": "135130" }, { "name": "Roff", "bytes": "140261" }, { "name": "Ruby", "bytes": "2921066" }, { "name": "Shell", "bytes": "706083" }, { "name": "Yacc", "bytes": "35797" } ], "symlink_target": "" }
package me.rexim class Mixer { def whatItSays(): String = "waka-waka" }
{ "content_hash": "07d43fce48f46cafcf0cad3b0805d730", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 40, "avg_line_length": 15, "alnum_prop": 0.68, "repo_name": "tsoding/Issuestant", "id": "47a18eab17d9df8e89a8f3f3796034a35efc6c75", "size": "75", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/me/rexim/Mixer.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "20785" } ], "symlink_target": "" }
package net.sf.jsqlparser.statement; import net.sf.jsqlparser.statement.create.table.CreateTable; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.drop.Drop; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.replace.Replace; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.truncate.Truncate; import net.sf.jsqlparser.statement.update.Update; public abstract class StatementVisitorBase implements StatementVisitor { java.io.PrintStream verboseFailure; public StatementVisitorBase() { this(null); } public StatementVisitorBase(java.io.PrintStream verboseFailure) { this.verboseFailure = verboseFailure; } private void unhandledStatement(String f) { if(verboseFailure != null){ verboseFailure.println("Unhandled: Statement-" + f); } } public void visit(Select select) { unhandledStatement("SELECT"); } public void visit(Delete delete) { unhandledStatement("DELETE"); } public void visit(Update update) { unhandledStatement("UPDATE"); } public void visit(Insert insert) { unhandledStatement("INSERT"); } public void visit(Replace replace) { unhandledStatement("REPLACE"); } public void visit(Drop drop) { unhandledStatement("DROP"); } public void visit(Truncate truncate) { unhandledStatement("TRUNCATE"); } public void visit(CreateTable createTable) { unhandledStatement("CREATETABLE"); } }
{ "content_hash": "1472a8fe0a4381b5f75c48db6dc62a21", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 82, "avg_line_length": 38.67567567567568, "alnum_prop": 0.782669461914745, "repo_name": "UBOdin/jsqlparser", "id": "2cd7ecc3bd0a43a12459db0ededa651a868b955f", "size": "2508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/net/sf/jsqlparser/statement/StatementVisitorBase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "484846" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <Context cachingAllowed="false"> <Environment name="PRODUCTION" type="java.lang.Boolean" value="false" /> <!-- Database --> <Environment name="dari/defaultDatabase" type="java.lang.String" value="handlebarsTest.local" /> <Environment name="dari/database/handlebarsTest.local/class" type="java.lang.String" value="com.psddev.dari.db.AggregateDatabase" /> <Environment name="dari/database/handlebarsTest.local/defaultDelegate" type="java.lang.String" value="sql" /> <!-- SQL via H2 --> <Environment name="dari/database/handlebarsTest.local/delegate/sql/class" type="java.lang.String" value="com.psddev.dari.db.SqlDatabase" /> <Environment name="dari/database/handlebarsTest.local/delegate/sql/jdbcUrl" type="java.lang.String" value="jdbc:h2:file:../../../../data/h2/default" /> <Environment name="dari/database/handlebarsTest.local/delegate/sql/jdbcUser" type="java.lang.String" value="root" /> <Environment name="dari/database/handlebarsTest.local/delegate/sql/jdbcPassword" type="java.lang.String" value="" /> <!-- Solr --> <Environment name="dari/database/handlebarsTest.local/delegate/solr/class" type="java.lang.String" value="com.psddev.dari.db.SolrDatabase" /> <Environment name="dari/database/handlebarsTest.local/delegate/solr/groups" type="java.lang.String" value="-* +cms.content.searchable" /> <Environment name="dari/database/handlebarsTest.local/delegate/solr/serverUrl" type="java.lang.String" value="http://localhost:8080/solr" /> <Environment name="dari/database/handlebarsTest.local/delegate/solr/readServerUrl" type="java.lang.String" value="http://localhost:8080/solr" /> <!-- Storage --> <Environment name="dari/defaultStorage" type="java.lang.String" value="handlebarsTest.local" /> <Environment name="dari/storage/handlebarsTest.local/class" type="java.lang.String" value="com.psddev.dari.util.LocalStorageItem" /> <Environment name="dari/storage/handlebarsTest.local/baseUrl" type="java.lang.String" value="http://localhost:8080/storage" /> <Environment name="dari/storage/handlebarsTest.local/rootPath" type="java.lang.String" value="../../../../data/storage" /> </Context>
{ "content_hash": "e7264b970d23f9db23b4abec91367a85", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 155, "avg_line_length": 82.22222222222223, "alnum_prop": 0.7319819819819819, "repo_name": "wearefriday/brightspot-handlebars", "id": "8539a4f95ffe7ef8d22fa503837f17a10f7e2b23", "size": "2220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "etc/tomcat-context.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "4649" } ], "symlink_target": "" }
game.TitleScreen = me.ScreenObject.extend({ // constructor init: function () { this.parent(true); // title screen image this.title = null; this.font = null; this.scrollerfont = null; this.scrollertween = null; this.scroller = "A SMALL STEP BY STEP TUTORIAL FOR GAME CREATION WITH MELONJS "; this.scrollerpos = 600; }, // reset function onResetEvent: function () { if (this.title == null) { // init stuff if not yet done this.title = me.loader.getImage("splash"); // font to display the menu items this.font = new me.BitmapFont("32x32_font", 32); // set the scroller this.scrollerfont = new me.BitmapFont("32x32_font", 32); } // reset to default value this.scrollerpos = 640; // a tween to animate the arrow this.scrollertween = new me.Tween(this).to({ scrollerpos: -2200 }, 10000).onComplete(this.scrollover.bind(this)).start(); // enable the keyboard me.input.bindKey(me.input.KEY.ENTER, "enter", true); // play something // me.audio.play("cling"); }, // some callback for the tween objects scrollover: function () { // reset to default value this.scrollerpos = 640; this.scrollertween.to({ scrollerpos: -2200 }, 10000).onComplete(this.scrollover.bind(this)).start(); }, // update function update: function () { var titleScreen = this; if (window.FB && !titleScreen.fbConnected && !titleScreen.waitingForResponse) { titleScreen.waitingForResponse = true; FB.getLoginStatus(function(response) { if (response.status == "connected") { titleScreen.fbConnected = true; me.input.registerPointerEvent( 'mousedown', me.game.viewport, titleScreen.onClick.bind(titleScreen) ); } titleScreen.waitingForResponse = false; }); } return true; }, onClick: function () { if (me.state.current() !== this) { // We're still in title screen, ignore click return; } $('#selectedFriendsPane').hide(); me.state.change(me.state.PLAY); }, // draw function draw: function (context) { context.drawImage(this.title, 0, 0); this.font.draw(context, "SAVE YOUR FRIENDS", 150, 100); if (this.fbConnected) { this.font.draw(context, "CLICK TO PLAY", 120, 380); } else { $('#fbLogin').show(); } // this.scrollerfont.draw(context, this.scroller, this.scrollerpos, 440); }, // destroy function onDestroyEvent: function () { me.input.unbindKey(me.input.KEY.ENTER); //just in case this.scrollertween.stop(); } });
{ "content_hash": "13a7762c5b526b26b22a435e6e57f43c", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 94, "avg_line_length": 28.5, "alnum_prop": 0.5418735518040384, "repo_name": "romansky/FreindsVsZombies", "id": "004ddabf815ff260820d2a53fc1f3f08adf932b7", "size": "3021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/screens/title.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3290" }, { "name": "JavaScript", "bytes": "438902" } ], "symlink_target": "" }
<a href='https://github.com/angular/angular.js/edit/master/docs/content/error/$injector/nomod.ngdoc' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this doc</a> <h1>Error: error:nomod <div><span class='hint'>Module Unavailable</span></div> </h1> <div> <pre class="minerr-errmsg" error-display="Module '{0}' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.">Module '{0}' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.</pre> </div> <h2>Description</h2> <div class="description"> <p>This error occurs when you declare a dependency on a module that isn&#39;t defined anywhere or hasn&#39;t been loaded in the current browser context.</p> <p>When you receive this error, check that the name of the module in question is correct and that the file in which this module is defined has been loaded (either via <code>&lt;script&gt;</code> tag, loader like require.js, or testing harness like karma).</p> <p>A less common reason for this error is trying to &quot;re-open&quot; a module that has not yet been defined.</p> <p>To define a new module, call <a href="api/ng/function/angular.module">angular.module</a> with a name and an array of dependent modules, like so:</p> <pre><code class="lang-js">// When defining a module with no module dependencies, // the array of dependencies should be defined and empty. var myApp = angular.module(&#39;myApp&#39;, []); </code></pre> <p>To retrieve a reference to the same module for further configuration, call <code>angular.module</code> without the array argument.</p> <pre><code class="lang-js">var myApp = angular.module(&#39;myApp&#39;); </code></pre> <p>Calling <code>angular.module</code> without the array of dependencies when the module has not yet been defined causes this error to be thrown. To fix it, define your module with a name and an empty array, as in the first example above.</p> </div>
{ "content_hash": "055c242851b55bfac40340acead5df02", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 412, "avg_line_length": 59.333333333333336, "alnum_prop": 0.7443820224719101, "repo_name": "amscher/Lendeavor", "id": "957112880c1c1a8ba988564038923cb6d91a2c71", "size": "2136", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "app/angular-1.3.0-rc.2/docs/partials/error/$injector/nomod.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "62530" }, { "name": "JavaScript", "bytes": "1420327" }, { "name": "Perl", "bytes": "10763" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "1026" } ], "symlink_target": "" }
require 'singleton' require 'active_support/core_ext/array/wrap' require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/module/remove_method' require 'active_support/core_ext/string/inflections' module ActiveModel module Observing extend ActiveSupport::Concern module ClassMethods # == Active Model Observers Activation # # Activates the observers assigned. Examples: # # # Calls PersonObserver.instance # ActiveRecord::Base.observers = :person_observer # # # Calls Cacher.instance and GarbageCollector.instance # ActiveRecord::Base.observers = :cacher, :garbage_collector # # # Same as above, just using explicit class references # ActiveRecord::Base.observers = Cacher, GarbageCollector # # Note: Setting this does not instantiate the observers yet. # +instantiate_observers+ is called during startup, and before # each development request. def observers=(*values) @observers = values.flatten end # Gets the current observers. def observers @observers ||= [] end # Instantiate the global Active Record observers. def instantiate_observers observers.each { |o| instantiate_observer(o) } end def add_observer(observer) unless observer.respond_to? :update raise ArgumentError, "observer needs to respond to `update'" end @observer_instances ||= [] @observer_instances << observer end def notify_observers(*arg) if defined? @observer_instances for observer in @observer_instances observer.update(*arg) end end end def count_observers @observer_instances.size end protected def instantiate_observer(observer) #:nodoc: # string/symbol if observer.respond_to?(:to_sym) observer = observer.to_s.camelize.constantize.instance elsif observer.respond_to?(:instance) observer.instance else raise ArgumentError, "#{observer} must be a lowercase, underscored class name (or an instance of the class itself) responding to the instance method. Example: Person.observers = :big_brother # calls BigBrother.instance" end end # Notify observers when the observed class is subclassed. def inherited(subclass) super notify_observers :observed_class_inherited, subclass end end private # Fires notifications to model's observers # # def save # notify_observers(:before_save) # ... # notify_observers(:after_save) # end def notify_observers(method) self.class.notify_observers(method, self) end end # == Active Model Observers # # Observer classes respond to lifecycle callbacks to implement trigger-like # behavior outside the original class. This is a great way to reduce the # clutter that normally comes when the model class is burdened with # functionality that doesn't pertain to the core responsibility of the # class. Example: # # class CommentObserver < ActiveModel::Observer # def after_save(comment) # Notifications.deliver_comment("admin@do.com", "New comment was posted", comment) # end # end # # This Observer sends an email when a Comment#save is finished. # # class ContactObserver < ActiveModel::Observer # def after_create(contact) # contact.logger.info('New contact added!') # end # # def after_destroy(contact) # contact.logger.warn("Contact with an id of #{contact.id} was destroyed!") # end # end # # This Observer uses logger to log when specific callbacks are triggered. # # == Observing a class that can't be inferred # # Observers will by default be mapped to the class with which they share a # name. So CommentObserver will be tied to observing Comment, ProductManagerObserver # to ProductManager, and so on. If you want to name your observer differently than # the class you're interested in observing, you can use the Observer.observe class # method which takes either the concrete class (Product) or a symbol for that # class (:product): # # class AuditObserver < ActiveModel::Observer # observe :account # # def after_update(account) # AuditTrail.new(account, "UPDATED") # end # end # # If the audit observer needs to watch more than one kind of object, this can be # specified with multiple arguments: # # class AuditObserver < ActiveModel::Observer # observe :account, :balance # # def after_update(record) # AuditTrail.new(record, "UPDATED") # end # end # # The AuditObserver will now act on both updates to Account and Balance by treating # them both as records. # class Observer include Singleton class << self # Attaches the observer to the supplied model classes. def observe(*models) models.flatten! models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model } remove_possible_method(:observed_classes) define_method(:observed_classes) { models } end # Returns an array of Classes to observe. # # You can override this instead of using the +observe+ helper. # # class AuditObserver < ActiveModel::Observer # def self.observed_classes # [Account, Balance] # end # end def observed_classes Array.wrap(observed_class) end # The class observed by default is inferred from the observer's class name: # assert_equal Person, PersonObserver.observed_class def observed_class if observed_class_name = name[/(.*)Observer/, 1] observed_class_name.constantize else nil end end end # Start observing the declared classes and their subclasses. def initialize observed_classes.each { |klass| add_observer!(klass) } end def observed_classes #:nodoc: self.class.observed_classes end # Send observed_method(object) if the method exists. def update(observed_method, object) #:nodoc: send(observed_method, object) if respond_to?(observed_method) end # Special method sent by the observed class when it is inherited. # Passes the new subclass. def observed_class_inherited(subclass) #:nodoc: self.class.observe(observed_classes + [subclass]) add_observer!(subclass) end protected def add_observer!(klass) #:nodoc: klass.add_observer(self) end end end
{ "content_hash": "4bb8e6dd26ab092302f30a0db3a88cc3", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 231, "avg_line_length": 31.753488372093024, "alnum_prop": 0.6481617108539622, "repo_name": "hallelujah/db_sower", "id": "62d2694da5e1fb16ffafd6d8737a8b7dd3d2106b", "size": "6827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/vendor/activemodel/lib/active_model/observing.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "33592" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2015 The CyanogenMod Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48"> <path android:fillColor="#FFFFFF" android:pathData="M40 10H8c-2.21 0-3.98 1.79-3.98 4L4 34c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4V14c0-2.21-1.79-4-4-4zm-18 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-6h4v4h-4v-4zm0 6h4v4h-4v-4zm-2 4h-4v-4h4v4zm0-6h-4v-4h4v4zm18 14H16v-4h16v4zm0-8h-4v-4h4v4zm0-6h-4v-4h4v4zm6 6h-4v-4h4v4zm0-6h-4v-4h4v4z" /> </vector>
{ "content_hash": "f13bae4f140ac0effadbb6bdb54a9c4f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 99, "avg_line_length": 41.10344827586207, "alnum_prop": 0.7172818791946308, "repo_name": "DSttr/SystemUI", "id": "07ee10a2012f048f4ddd1fdc064dba3caa954dd1", "size": "1192", "binary": false, "copies": "1", "ref": "refs/heads/cm-13.0-ZNH0E", "path": "SystemUI/res/drawable/ic_dynamic_qs_ime_selector.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7808129" }, { "name": "Makefile", "bytes": "7411" }, { "name": "Python", "bytes": "4884" }, { "name": "Shell", "bytes": "415" } ], "symlink_target": "" }
A Redis cluster proxy. Build === Requirements: * `make` and `cmake` * UNIX-like system with `SO_REUSEPORT | SO_REUSEADDR` support * `epoll` support * pthread * C++ compiler & lib with C++11 features, like g++ 4.8 or clang++ 3.2 (NOTE: install clang++ 3.2 on CentOS 6.5 won't compile because clang uses header files from gcc, which is version 4.4 without C++11 support) * Google Test (for test) To build, just make turn on all debug logs make MODE=debug or compile with g艹 make COMPILER=g++ To link libstdc++ statically, use make STATIC_LINK=1 to run test (just cover message parsing parts) make runtest run test with valgrind checking make runtest CHECK_MEM=1 Run === cerberus CONFIG_FILE [ARGS] The first argument is path of a configuration file, then optional arguments. Those specifies * bind / `-b` : (integer) local port to listen; could also specified * node / `-n` : (address, optional) one of active node in a cluster; format should be *host:port*; could also set after cerberus launched, via the `SETREMOTES` command, see it below * thread / `-t` : (integer) number of threads * read-slave / `-r` : (optional, default off) set to "yes" to turn on read slave mode. A proxy in read-slave mode won't support writing commands like `SET`, `INCR`, `PUBLISH`, and it would select slave nodes for reading commands if possible. For more information please read [here (CN)](https://github.com/HunanTV/redis-cerberus/wiki/%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB). * read-slave-filter / `-R` : (optional, need read-slave set to "yes") if multiple slaves replicating one master, use the one whose host starts with this option value; for example, you have `10.0.0.1:7000` as a master, with 2 slave `10.0.1.1:8000` and `10.0.2.1:9000`, and read-slave-filter set to `10.0.1`, then `10.0.1.1:8000` is preferred. Note this option is no more than a string matching, so `10.0.1.1` and `10.0.10.1` won't be different on option value `10.0.1` * cluster-require-full-coverage : (optional, default on) set to "no" to turn off full coverage mode, so proxy would keep serving when not all slots covered in a cluster. The option set via ARGS would override it in the configuration file. For example cerberus example.conf -t 8 set the program to 8 threads. Commands in Particular === Restricted Commands Bypass --- * `MGET` : execute multiple `GET`s * `MSET` : execute multiple `SET`s * `DEL` : execute multiple `DEL`s * `RENAME` : if source and destination are not in the same slot, execute a `GET`-`SET`-`DEL` sequence without atomicity * `BLPOP` / `BRPOP` : one list limited; might return nil value before timeout [See detail (CN)](https://github.com/HunanTV/redis-cerberus/wiki/BLPOP-And-BRPOP) * `EVAL` : one key limited; if any key which is not in the same slot with the argument key is in the lua script, a cross slot error would return Extra Commands --- * `PROXY` / `INFO`: show proxy information, including threads count, clients counts, commands statistics, and remote redis servers * `KEYSINSLOT slot count`: list keys in a specified slot, same as `CLUSTER GETKEYSINSLOT slot count` * `UPDATESLOTMAP`: notify each thread to update slot map after the next operation * `SETREMOTES host port host port ...`: reset redis server addresses to arguments, and update slot map after that Not Implemented --- * keys: `KEYS`, `MIGRATE`, `MOVE`, `OBJECT`, `RANDOMKEY`, `RENAMENX`, `SCAN`, `BITOP`, * list: `BRPOPLPUSH`, `RPOPLPUSH`, * set: `SINTERSTORE`, `SDIFFSTORE`, `SINTER`, `SMOVE`, `SUNIONSTORE`, * sorted set: `ZINTERSTORE`, `ZUNIONSTORE`, * pub/sub: `PUBSUB`, `PUNSUBSCRIBE`, `UNSUBSCRIBE`, others: `PFADD`, `PFCOUNT`, `PFMERGE`, `EVALSHA`, `SCRIPT`, `WATCH`, `UNWATCH`, `EXEC`, `DISCARD`, `MULTI`, `SELECT`, `QUIT`, `ECHO`, `AUTH`, `CLUSTER`, `BGREWRITEAOF`, `BGSAVE`, `CLIENT`, `COMMAND`, `CONFIG`, `DBSIZE`, `DEBUG`, `FLUSHALL`, `FLUSHDB`, `LASTSAVE`, `MONITOR`, `ROLE`, `SAVE`, `SHUTDOWN`, `SLAVEOF`, `SLOWLOG`, `SYNC`, `TIME`, For more information please read [here (CN)](https://github.com/HunanTV/redis-cerberus/wiki/Redis-%E9%9B%86%E7%BE%A4%E4%BB%A3%E7%90%86%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E4%B8%8E%E4%BD%BF%E7%94%A8).
{ "content_hash": "73795f39072f39af88407c0ac888ba01", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 467, "avg_line_length": 43.103092783505154, "alnum_prop": 0.7086821334608945, "repo_name": "TigerZhang/redis-cerberus", "id": "fcffff42d47395920a6d91337a3afff3b0fd0014", "size": "4183", "binary": false, "copies": "1", "ref": "refs/heads/yunba", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "765655" }, { "name": "CMake", "bytes": "7513" }, { "name": "Makefile", "bytes": "7140" }, { "name": "Python", "bytes": "6057" } ], "symlink_target": "" }
'use strict'; angular.module('spedycjacentralaApp') .provider('AlertService', function () { this.toast = false; this.$get = ['$timeout', '$sce', '$translate', function($timeout, $sce,$translate) { var exports = { factory: factory, isToast: isToast, add: addAlert, closeAlert: closeAlert, closeAlertByIndex: closeAlertByIndex, clear: clear, get: get, success: success, error: error, info: info, warning : warning }, toast = this.toast, alertId = 0, // unique id for each alert. Starts from 0. alerts = [], timeout = 5000; // default timeout function isToast() { return toast; } function clear() { alerts = []; } function get() { return alerts; } function success(msg, params, position) { return this.add({ type: "success", msg: msg, params: params, timeout: timeout, toast: toast, position: position }); } function error(msg, params, position) { return this.add({ type: "danger", msg: msg, params: params, timeout: timeout, toast: toast, position: position }); } function warning(msg, params, position) { return this.add({ type: "warning", msg: msg, params: params, timeout: timeout, toast: toast, position: position }); } function info(msg, params, position) { return this.add({ type: "info", msg: msg, params: params, timeout: timeout, toast: toast, position: position }); } function factory(alertOptions) { var alert = { type: alertOptions.type, msg: $sce.trustAsHtml(alertOptions.msg), id: alertOptions.alertId, timeout: alertOptions.timeout, toast: alertOptions.toast, position: alertOptions.position ? alertOptions.position : 'top right', scoped: alertOptions.scoped, close: function (alerts) { return exports.closeAlert(this.id, alerts); } } if(!alert.scoped) { alerts.push(alert); } return alert; } function addAlert(alertOptions, extAlerts) { alertOptions.alertId = alertId++; alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params); var that = this; var alert = this.factory(alertOptions); if (alertOptions.timeout && alertOptions.timeout > 0) { $timeout(function () { that.closeAlert(alertOptions.alertId, extAlerts); }, alertOptions.timeout); } return alert; } function closeAlert(id, extAlerts) { var thisAlerts = extAlerts ? extAlerts : alerts; return this.closeAlertByIndex(thisAlerts.map(function(e) { return e.id; }).indexOf(id), thisAlerts); } function closeAlertByIndex(index, thisAlerts) { return thisAlerts.splice(index, 1); } return exports; }]; this.showAsToast = function(isToast) { this.toast = isToast; }; });
{ "content_hash": "1026dfb35c647ca5af6c4a0f34317ead", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 116, "avg_line_length": 32.22727272727273, "alnum_prop": 0.4221908791725435, "repo_name": "wyzellak/sandbox-internet-apps-design", "id": "ce834d58c954a0888363d96d213c0742f9f9809d", "size": "4254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "centrala/src/main/webapp/scripts/components/alert/alert.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "48278" }, { "name": "Batchfile", "bytes": "10012" }, { "name": "CSS", "bytes": "8840" }, { "name": "HTML", "bytes": "308660" }, { "name": "Java", "bytes": "558512" }, { "name": "JavaScript", "bytes": "398525" }, { "name": "Shell", "bytes": "14116" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Support &mdash; sql2gee 0.0.6 documentation</title> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="index" title="Index" href="genindex.html"/> <link rel="search" title="Search" href="search.html"/> <link rel="top" title="sql2gee 0.0.6 documentation" href="index.html"/> <link rel="prev" title="Installation" href="install.html"/> <script src="_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="index.html" class="icon icon-home"> sql2gee </a> <div class="version"> 0.0.6 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">Contents:</span></p> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="install.html">Installation</a></li> <li class="toctree-l1 current"><a class="current reference internal" href="#">Support</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="index.html">sql2gee</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="index.html">Docs</a> &raquo;</li> <li>Support</li> <li class="wy-breadcrumbs-aside"> <a href="_sources/support.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="support"> <h1>Support<a class="headerlink" href="#support" title="Permalink to this headline">¶</a></h1> <p>The easiest way to get help with the project is to open an issue on Github.</p> <p>More info soon.</p> </div> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="install.html" class="btn btn-neutral" title="Installation" accesskey="p"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2017, Raul Requero. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'./', VERSION:'0.0.6', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
{ "content_hash": "06050b9760b3a640e2126711b496097c", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 192, "avg_line_length": 23.507317073170732, "alnum_prop": 0.5490765719028844, "repo_name": "benlaken/sql2gee", "id": "52e013056fe967421af559d4cd8e5deae7670f0c", "size": "4822", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "docs/_build/html/support.html", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "480" }, { "name": "Python", "bytes": "46609" } ], "symlink_target": "" }
import React from 'react'; import Ul from './Ul'; import Wrapper from './Wrapper'; function List(props) { const ComponentToRender = props.component; let content = (<div></div>); // If we have items, render them if (props.items) { content = props.items.map((item, index) => ( <ComponentToRender key={`item-${index}`} item={item} {...props.componentProps}/> )); } else { // Otherwise render a single component content = (<ComponentToRender {...props.componentProps}/>); } return ( <Wrapper> <Ul> {content} </Ul> </Wrapper> ); } List.propTypes = { component: React.PropTypes.func.isRequired, componentProps: React.PropTypes.object, items: React.PropTypes.array, }; export default List;
{ "content_hash": "f20740df4091d1e537bb003d0f7837bd", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 86, "avg_line_length": 21.742857142857144, "alnum_prop": 0.6320630749014454, "repo_name": "kenzanboo/tumbler-blog-api", "id": "e5da9d8f29ee755ce6080cf902af93bc04a7d5e2", "size": "761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/List/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1526" }, { "name": "HTML", "bytes": "11152" }, { "name": "JavaScript", "bytes": "184773" } ], "symlink_target": "" }
module Kohawk class Binding attr_reader :context, :exchange def initialize(context, exchange) @context = context @exchange = exchange end def bind(queue) # logger.info("Binding queue #{queue_name} to #{binding} ...") bindings.each do |binding| x = exchange.create q = queue.create q.bind(x, :routing_key => binding) end end def bindings queue_definition[:bindings] end def queue_definition context.queue_definition end end end
{ "content_hash": "84247a3d9edf6b0de240778ae7c3f444", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 68, "avg_line_length": 18, "alnum_prop": 0.6018518518518519, "repo_name": "jcarley/kohawk", "id": "1b0afa513263d60743ec4e3bb4e9d0b10a09f9b5", "size": "540", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/kohawk/binding.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "37236" }, { "name": "Shell", "bytes": "1064" } ], "symlink_target": "" }
ml.module('three.extras.core.Gyroscope') .requires('three.Three', 'three.core.Object3D', 'three.core.Quaternion', 'three.core.Vector3') .defines(function(){ /** * @author alteredq / http://alteredqualia.com/ */ THREE.Gyroscope = function () { THREE.Object3D.call( this ); }; THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype ); THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) { this.matrixAutoUpdate && this.updateMatrix(); // update matrixWorld if ( this.matrixWorldNeedsUpdate || force ) { if ( this.parent ) { this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix ); this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld ); this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject ); this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld ); } else { this.matrixWorld.copy( this.matrix ); } this.matrixWorldNeedsUpdate = false; force = true; } // update children for ( var i = 0, l = this.children.length; i < l; i ++ ) { this.children[ i ].updateMatrixWorld( force ); } }; THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3(); THREE.Gyroscope.prototype.translationObject = new THREE.Vector3(); THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion(); THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion(); THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3(); THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3(); });
{ "content_hash": "d76e88eabc94032c4e8f9bef1e8d1b3e", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 92, "avg_line_length": 23.728571428571428, "alnum_prop": 0.6893437688139675, "repo_name": "zfedoran/modulite-three.js", "id": "5fbb21b6dadcaf37e35e8fa295dd5e16e9b6121a", "size": "1661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/js/threejs/src/extras/core/Gyroscope.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "898391" } ], "symlink_target": "" }
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace SIT.Web.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
{ "content_hash": "b73a264af258a1cfc26749fef2d88758", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 140, "avg_line_length": 39.888888888888886, "alnum_prop": 0.6344011142061281, "repo_name": "llalov/Issue-Tracking-System", "id": "bf76afeea242e65f478e23e2dea397e60230db2a", "size": "1436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/SoftUniIssueTracker.Web/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "871" }, { "name": "HTML", "bytes": "13342" }, { "name": "JavaScript", "bytes": "83058" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5bd1cea375d9c076f3d1cfbc41053831", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "89bcbea18c2416a83f8fd93758d9f1dbb2823a65", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Protozoa/Euglenozoa/Euglenida/Euglenales/Astasiaceae/Petalomonas/Petalomonas messikommeri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<button class="btn btn-success" (click)="startGame()">Start Game</button> <button class="btn btn-danger" (click)="stopGame()">Stop Game</button>
{ "content_hash": "7c31d10b96c0ee7dd3bda9a8c8512a84", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 73, "avg_line_length": 72, "alnum_prop": 0.7152777777777778, "repo_name": "piemasters/Angular-4-Training", "id": "0ce317c6db1db672eebd7e5a36047a2b656652aa", "size": "144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/assignment4/game-control/game-control.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "839" }, { "name": "HTML", "bytes": "36369" }, { "name": "JavaScript", "bytes": "2607" }, { "name": "TypeScript", "bytes": "109857" } ], "symlink_target": "" }
import unittest from citest.base import ( ExecutionContext, JsonSnapshotHelper) import citest.json_contract as jc import citest.json_predicate as jp _called_verifiers = [] _TEST_FOUND_ERROR_COMMENT='Found error.' class TestObsoleteObservationFailureVerifier(jc.ObservationFailureVerifier): def __init__(self, title, expect): super(TestObsoleteObservationFailureVerifier, self).__init__(title) self.__expect = expect def _error_comment_or_none(self, error): if error.args[0] == self.__expect: return _TEST_FOUND_ERROR_COMMENT return None def _makeObservationVerifyResult( valid, observation=None, good_results=None, bad_results=None, failed_constraints=None): default_result = jp.PredicateResult(valid=valid) good_results = good_results or ([default_result] if valid else []) bad_results = bad_results or ([] if valid else [default_result]) failed_constraints = failed_constraints or [] observation = observation or jc.Observation() good_attempt_results = [jp.ObjectResultMapAttempt(observation, result) for result in good_results] bad_attempt_results = [jp.ObjectResultMapAttempt(observation, result) for result in bad_results] return jc.ObservationVerifyResult( valid=valid, observation=observation, good_results=good_attempt_results, bad_results=bad_attempt_results, failed_constraints=failed_constraints) class FakeObservationVerifier(jc.ObservationVerifier): def __init__(self, title, dnf_verifier, result): super(FakeObservationVerifier, self).__init__( title=title, dnf_verifiers=dnf_verifier) self.__result = result def __call__(self, context, observation): _called_verifiers.append(self) return self.__result class ObservationVerifierTest(unittest.TestCase): def assertEqual(self, expect, have, msg=''): if not msg: msg = 'EXPECTED\n{0!r}\nGOT\n{1!r}'.format(expect, have) JsonSnapshotHelper.AssertExpectedValue(expect, have, msg) def test_result_builder_add_good_result(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('A') pred = jp.PathPredicate(None, jp.STR_EQ('A')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(True) self.assertTrue(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual([], verify_results.bad_results) self.assertEqual([], verify_results.failed_constraints) self.assertEqual(map_result.good_object_result_mappings, verify_results.good_results) def test_result_builder_add_bad_result(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('A') pred = jp.PathPredicate(None, jp.STR_EQ('B')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(False) self.assertFalse(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual([], verify_results.good_results) self.assertEqual([pred], verify_results.failed_constraints) self.assertEqual(map_result.bad_object_result_mappings, verify_results.bad_results) def test_result_builder_add_mixed_results(self): context = ExecutionContext() observation = jc.Observation() observation.add_object('GOOD') observation.add_object('BAD') pred = jp.PathPredicate(None, jp.STR_EQ('GOOD')) builder = jc.ObservationVerifyResultBuilder(observation) map_pred = jp.MapPredicate(pred) map_result = map_pred(context, observation.objects) builder.add_map_result(map_result) verify_results = builder.build(False) self.assertFalse(verify_results) self.assertEqual(observation, verify_results.observation) self.assertEqual(map_result.good_object_result_mappings, verify_results.good_results) self.assertEqual([], verify_results.failed_constraints) self.assertEqual(map_result.bad_object_result_mappings, verify_results.bad_results) def test_result_observation_verifier_conjunction_ok(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] pred_results = [] for i in range(3): this_result = jp.PredicateResult(True, comment='Pred {0}'.format(i)) pred_results.append(this_result) result = _makeObservationVerifyResult( valid=True, good_results=[this_result]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) builder.AND(fake_verifier) # verify build can work multiple times self.assertEqual(builder.build(), builder.build()) verifier = builder.build() self.assertEqual([verifiers], verifier.dnf_verifiers) expect = _makeObservationVerifyResult(True, good_results=pred_results) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers, _called_verifiers) def test_result_observation_verifier_conjunction_failure_aborts_early(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(3)] for i in range(3): result = _makeObservationVerifyResult( valid=False, bad_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.AND(fake_verifier) # verify build can work multiple times self.assertEqual(builder.build(), builder.build()) verifier = builder.build() self.assertEqual([verifiers], verifier.dnf_verifiers) expect = _makeObservationVerifyResult( False, bad_results=[pred_results[0]]) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers[:1], _called_verifiers) def test_result_observation_verifier_disjunction_success_aborts_early(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(2)] for i in range(2): result = _makeObservationVerifyResult( valid=True, good_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.OR(fake_verifier) verifier = builder.build() self.assertEqual([verifiers[0:1], verifiers[1:2]], verifier.dnf_verifiers) expect = _makeObservationVerifyResult(True, good_results=[pred_results[0]]) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers[:1], _called_verifiers) def test_result_observation_verifier_disjunction_failure(self): context = ExecutionContext() observation = jc.Observation() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(2)] for i in range(2): result = _makeObservationVerifyResult(observation=observation, valid=False, bad_results=[pred_results[i]]) fake_verifier = FakeObservationVerifier( title=i, dnf_verifier=[], result=result) verifiers.append(fake_verifier) results.append(result) builder.OR(fake_verifier) verifier = builder.build() self.assertEqual([verifiers[0:1], verifiers[1:2]], verifier.dnf_verifiers) expect = _makeObservationVerifyResult( False, observation=observation, bad_results=pred_results) global _called_verifiers _called_verifiers = [] got = verifier(context, observation) self.assertEqual(expect, got) self.assertEqual(verifiers, _called_verifiers) def test_obsolete_observation_failure_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError(error_text) observation.add_error(error) failure_verifier = TestObsoleteObservationFailureVerifier( 'Test', error_text) failure_pred_result = jc.ObservationFailedError([error], valid=True) expect_failure = jc.ObservationVerifyResult( valid=True, observation=observation, good_results=[jp.ObjectResultMapAttempt(observation, failure_pred_result)], bad_results=[], failed_constraints=[], comment=_TEST_FOUND_ERROR_COMMENT) got = failure_verifier(context, observation) self.assertEqual(expect_failure, got) builder = jc.ObservationVerifierBuilder(title='Test') builder.EXPECT(failure_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=True, observation=observation, good_results=expect_failure.good_results, bad_results=[], failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) def test_observation_failure_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError(error_text) observation.add_error(error) exception_pred = jp.ExceptionMatchesPredicate( ValueError, regex=error_text) builder = jc.ObservationVerifierBuilder(title='Test') builder.EXPECT(jc.ObservationErrorPredicate(jp.LIST_MATCHES([exception_pred]))) failure_verifier = builder.build() observation_predicate_result = jc.ObservationPredicateResult( True, observation, jp.LIST_MATCHES([exception_pred]), jp.LIST_MATCHES([exception_pred])(context, [error])) expect_failure = jc.ObservationVerifyResult( True, observation, good_results=[observation_predicate_result], bad_results=[], failed_constraints=[]) got = failure_verifier(context, observation) self.assertEqual(expect_failure, got) def test_obsolete_observation_failure_not_ok(self): error_text = 'the error' context = ExecutionContext() observation = jc.Observation() error = ValueError('not the error') observation.add_error(error) failure_verifier = TestObsoleteObservationFailureVerifier( 'Test', error_text) comment = failure_verifier._error_not_found_comment(observation) failure_pred_result = jp.PredicateResult(valid=False, comment=comment) expect_failure = jc.ObservationVerifyResult( valid=False, observation=observation, bad_results=[jp.ObjectResultMapAttempt(observation, failure_pred_result)], good_results=[], failed_constraints=[], comment=comment) self.assertEqual(expect_failure, failure_verifier(context, observation)) builder = jc.ObservationVerifierBuilder(title='Test Verifier') builder.EXPECT(failure_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=False, observation=observation, bad_results=expect_failure.bad_results, good_results=[], failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) def test_obsolete_observation_failure_or_found(self): context = ExecutionContext() observation = jc.Observation() observation.add_error(ValueError('not the error')) failure_verifier = TestObsoleteObservationFailureVerifier( 'Verify', 'NotFound') comment = failure_verifier._error_not_found_comment(observation) failure_result = jp.PredicateResult(valid=False, comment=comment) # We've already established this result is what we expect bad_observation_result = failure_verifier(context, observation) success_pred_result = jp.PredicateResult(valid=True) good_observation_result = _makeObservationVerifyResult( valid=True, good_results=[success_pred_result], observation=observation) success_verifier = FakeObservationVerifier( 'Found', dnf_verifier=[], result=good_observation_result) builder = jc.ObservationVerifierBuilder(title='Observation Verifier') builder.EXPECT(failure_verifier).OR(success_verifier) verifier = builder.build() expect = jc.ObservationVerifyResult( valid=True, observation=observation, bad_results=bad_observation_result.bad_results, good_results=good_observation_result.good_results, failed_constraints=[]) got = verifier(context, observation) self.assertEqual(expect, got) if __name__ == '__main__': unittest.main()
{ "content_hash": "4b8f070597335d8a99aafd8eb72b59a5", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 83, "avg_line_length": 36.394594594594594, "alnum_prop": 0.6927075597801872, "repo_name": "google/citest", "id": "e9dc4e5ea94b132440049357463add9e36221921", "size": "14132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/json_contract/observation_verifier_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "993608" } ], "symlink_target": "" }
layout: page title: Virginia Jones's 94th Birthday date: 2016-05-24 author: Walter Galvan tags: weekly links, java status: published summary: Sed sit amet blandit diam, vitae hendrerit nibh. Mauris accumsan. banner: images/banner/meeting-01.jpg booking: startDate: 11/21/2016 endDate: 11/26/2016 ctyhocn: MCOSWHX groupCode: VJ9B published: true --- Sed mattis urna ac libero dapibus, non fermentum est condimentum. Nunc facilisis, erat ut cursus dignissim, mauris quam maximus diam, quis feugiat lorem urna at neque. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In a sapien a dui volutpat eleifend. Nam rhoncus tellus sit amet enim faucibus aliquam. Nullam a venenatis ex. Quisque porttitor quam non urna aliquet, aliquet placerat tortor luctus. Quisque quis vehicula nisl. Quisque imperdiet est eget sapien feugiat, et dapibus est convallis. Sed maximus elit ligula, vel tempus sem faucibus nec. Pellentesque maximus lacus vel metus auctor porta. Nullam faucibus eu augue ut elementum. Ut ultrices faucibus ex, eget cursus tortor vehicula nec. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam quis dapibus justo. Cras id facilisis purus. * Integer in libero lobortis, luctus nisi in, pharetra nisi * Suspendisse eget neque pharetra, consectetur lacus posuere, malesuada augue * Nam tempus leo et ligula maximus pretium * Ut volutpat turpis ac elit lacinia convallis * Maecenas a velit eget magna tincidunt sagittis. Donec a dolor eleifend elit scelerisque porttitor. Pellentesque pulvinar varius urna. Ut consectetur aliquam diam. Proin vehicula placerat pretium. Sed eget molestie purus, vitae interdum risus. Aliquam erat volutpat. Sed ultricies rutrum libero ac dapibus. Morbi eget feugiat erat. Ut in lacus at urna laoreet condimentum. Cras nec ultrices dolor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean volutpat, mi quis ullamcorper sodales, nisi enim rhoncus sem, sed semper mi felis at nibh. Phasellus lectus velit, pulvinar in leo quis, tincidunt hendrerit mi. Vivamus pulvinar tortor sed nibh dignissim, id aliquam nisl malesuada. Etiam porttitor est elementum mi venenatis aliquam. Mauris ultrices eros ante, id tincidunt justo euismod quis. Suspendisse vitae dapibus ex.
{ "content_hash": "1874a46ad867c20b1f126419eb6509c4", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 881, "avg_line_length": 93.4, "alnum_prop": 0.811134903640257, "repo_name": "KlishGroup/prose-pogs", "id": "875c9d530abe7d5ec52fcfab287c6e37fa292a38", "size": "2339", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/M/MCOSWHX/VJ9B/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using UIKit; using RottenApi; using CoreGraphics; using Foundation; using RottenTomatoes.TableCells; using System; namespace RottenTomatoes { public class MovieTableSource : UITableViewSource { private Movie _movie; private MovieInfoView _mInfoView; private MovieCast _cast; private ReviewList _reviews; public bool IsSourceLoaded { get { if (_movie != null && _mInfoView != null && _cast != null && _reviews != null) return true; return false; } } public MovieTableSource(Movie movie) { _movie = movie; } public void UpdateMovieInfo(MovieInfo mInfo) { if (mInfo == null) return; _mInfoView = new MovieInfoView(_movie, mInfo); _mInfoView.SizeToFit(); } public void UpdateMovieCast(MovieCast cast) { _cast = cast; } public void UpdateMovieReviews(ReviewList reviews) { _reviews = reviews; } public override nint NumberOfSections(UITableView tableView) { return 4; } public override nint RowsInSection(UITableView tableview, nint section) { switch (section) { case 0: return 1; case 1: return 1; case 2: return _cast.Cast.Count; case 3: return _reviews.Reviews.Count; default: return 5; } } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { case 0: return 90.5f; case 1: return _mInfoView.Height; default: return 50; } } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { case 0: MovieTableCell movieCell = (MovieTableCell)tableView.DequeueReusableCell(MovieTableCell.CellId); movieCell.UpdateCell(_movie); return movieCell; case 1: MovieInfoTableCell infoCell = (MovieInfoTableCell)tableView.DequeueReusableCell(MovieInfoTableCell.CellId); infoCell.UpdateCell(_mInfoView); return infoCell; case 2: ActorTableCell actorCell = (ActorTableCell)tableView.DequeueReusableCell(ActorTableCell.CellId); actorCell.UpdateActor(_cast.Cast[indexPath.Row]); return actorCell; case 3: ReviewTableCell reviewCell = (ReviewTableCell)tableView.DequeueReusableCell(ReviewTableCell.CellId); reviewCell.UpdateReview(_reviews.Reviews[indexPath.Row]); return reviewCell; default: return new UITableViewCell(); } } public override nfloat GetHeightForHeader(UITableView tableView, nint section) { return section == 0 ? 0.0001f : 40; } public override UIView GetViewForHeader(UITableView tableView, nint section) { if (section == 0) return new UIView(); var header = new UIView(new CGRect(0, 0, 320, 40)); header.BackgroundColor = UIColor.Black; var headerLabel = new UILabel(new CGRect(10, 0, 320, 40)) { Font = UIFont.FromName("HelveticaNeue-Bold", 15), TextColor = UIColor.White }; switch (section) { case 1: headerLabel.Text = "Movie info"; break; case 2: headerLabel.Text = "Cast"; break; case 3: headerLabel.Text = "Critic reviews"; break; default: headerLabel.Text = ""; break; } header.Add(headerLabel); return header; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { case 3: UIApplication.SharedApplication.OpenUrl(((ReviewTableCell)tableView.CellAt(indexPath)).ReviewUrl); break; } } } }
{ "content_hash": "8c0e4b4350e0766fb335adf77a3c897f", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 127, "avg_line_length": 30.696202531645568, "alnum_prop": 0.4931958762886598, "repo_name": "alekseevpg/RottenTomatoes", "id": "1b0051f4ee989e1b7a51408ae6f53c2bd4508d44", "size": "4850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RottenTomatoes/TableSources/MovieTableSource.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "208311" }, { "name": "Ruby", "bytes": "1854" } ], "symlink_target": "" }
var _ = require('underscore'); var events = require('events'); var mobs = require('../config/mobs'); var Util = require('./util'); var config = require('../config/game'); module.exports = (function() { var resolveBehaviors; // Sequential static ID for uniqueness var _id = 1; var Enemy = function Enemy(type, wave) { var base, hp; this._id = _id++; this._base = base = mobs[type]; this._emitter = new events.EventEmitter(); this._wave = wave; this._panic = false; this.type = type; this.hp = this.maxHp = hp = Util.randomRange.apply(Util, this._base.health); this.diminishingDamage = Math.max(1, Math.floor(hp * 0.20)); this.position = _.sample(base.startPositions); this.behaviors = resolveBehaviors(base.behaviors); }; /** * Performs an attack on the player object. * * @param Player player * @return Number|Boolean */ Enemy.prototype.attack = function(player) { var damage = false, position; if (this.canAttack()){ damage = Util.randomRange.apply(Util, this._base.damage); if (this.is('ranged')){ damage = damage * config.rangeDamageMod; } if (this.is('ranged-boost')){ position = this.position; while(position !== 0) { damage *= config.rangedBoostMod; position--; } } if(this.is('diminishing')){ damage = damage * this.hp / this.maxHp; } damage = Math.ceil(damage * player.getDefenseMod()); player.damage(damage); } return damage; }; Enemy.prototype.canAttack = function(){ var isRanged = this.is('ranged'); var position = this.position; return position === 0 || (position !== 0 && isRanged); }; Enemy.prototype.damage = function(amount, type) { var evasive = this.is('evasive'); if(!evasive || (evasive && Math.random() > config.evasiveThreshold)){ if(this.is('heavy')) { amount = 1; } if(this.is('diminishing')){ amount = this.diminishingDamage; if (type === 'CollateralDamage'){ amount = amount * 4; } } if (this.is('armored') && type !== 'PowerAttack'){ amount = Math.ceil(amount / 2); } amount = Math.max(1, amount); this.hp -= amount; if(amount && this.is('squeamish')){ this._panic = true; } if (this.hp <= 0) { this._emitter.emit('death', this); } } }; Enemy.prototype.describe = function() { return { id: this._id, type: this.type, hitpoints: this.hp, wave: this._wave, position: this.position }; }; Enemy.prototype.getPosition = function(){ return this.position; }; Enemy.prototype.is = function(thing){ var things = this.behaviors.slice(0); things.push(this.type); return _.contains(things, thing); }; /** * Perform move logic * * @return Object|Boolean */ Enemy.prototype.move = function(){ var result = false; var position = this.position; if(this._panic || (this.is('ranged-boost') && position < 5) ) { this._panic = false; this.position++; } else if (this.is('melee') && position > 0){ this.position--; } this.position = Math.min(this.position, 5); if (position !== this.position){ result = { id : this._id, type : 'move', position : this.position }; } return result; }; Enemy.prototype.on = function(e, callback) { this._emitter.on(e, callback); }; /** * Move and/or attack the player. * * * @return Array */ Enemy.prototype.processLogic = function(player){ var actions = [], move, damage; move = this.move(); if (move){ actions.push(move); } damage = this.attack(player); if (damage !== false){ // might be int 0, so using strict check actions.push({ id : this._id, type : 'attack', damage : damage }); } return actions; }; resolveBehaviors = function(template){ var behaviors = []; _.each(template, function(behavior){ behaviors.push(behavior instanceof Array ? _.sample(behavior) : behavior); }); return behaviors; }; return Enemy; }());
{ "content_hash": "911ddcd405def39ddce1e3a9ea6ced04", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 78, "avg_line_length": 22.203389830508474, "alnum_prop": 0.6157760814249363, "repo_name": "zumba/node-defender-game", "id": "0dc008ff971a19a7fcf288f5d519d7b09f413f2a", "size": "3930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/enemy.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5646" }, { "name": "JavaScript", "bytes": "53554" } ], "symlink_target": "" }
namespace clover { namespace gui { util::PtrTable<Element> Element::elementTable; Cursor *Element::guiCursor= 0; audio::AudioSourceHandle Element::audioSource; Element::Element(const util::Coord& offset_, const util::Coord& rad): triggered(false), errorVisuals(false), elementType(None), active(true), visible(true), enabled(true), firstFrame(true), touchable(true), applySuperActivation(true), draggingType(DraggingType::Left), stretchable(false), autoResize(false), depthOffset(0), superElement(nullptr), curBbState(Bb_None), prevBbState(Bb_None){ radius.setRelative(); minRadius.setRelative(); maxRadius.setRelative(); radius.setType(util::Coord::View_Stretch); minRadius.setType(util::Coord::View_Stretch); maxRadius.setType(util::Coord::View_Stretch); offset.setType(util::Coord::View_Stretch); setRadius(rad); setMinRadius(rad); setMaxRadius(rad); setOffset(offset_); tableIndex= elementTable.insert(*this); } Element::Element(Element&& e): OnTrigger(std::move(e.OnTrigger)), OnSecondaryTrigger(std::move(e.OnSecondaryTrigger)), OnDraggingStart(std::move(e.OnDraggingStart)), OnDragging(std::move(e.OnDragging)), OnDraggingStop(std::move(e.OnDraggingStop)), triggered(e.triggered), errorVisuals(e.errorVisuals), elementType(e.elementType), active(e.active), visible(e.visible), enabled(e.enabled), firstFrame(e.firstFrame), touchable(e.touchable), applySuperActivation(e.applySuperActivation), draggingType(e.draggingType), stretchable(e.stretchable), autoResize(e.autoResize), depthOffset(0), position(e.position), offset(e.offset), radius(e.radius), minRadius(e.minRadius), maxRadius(e.maxRadius), superElement(0), curBbState(e.curBbState), prevBbState(e.prevBbState), tableIndex(e.tableIndex){ elementTable[tableIndex]= this; e.tableIndex= -1; while(!e.visualEntities.empty()){ e.visualEntities.front()->changeContainer(&visualEntities); } // Transfer subElements auto sub_elements= e.subElements; for (auto& m : sub_elements){ e.removeSubElementImpl(*m); } for (auto& m : sub_elements){ addSubElementImpl(*m); } // Switch this to superElement's subElement in the place of e if (e.superElement){ e.superElement->onSubSwap(e, *this); } } Element& Element::operator=(Element&& e){ OnTrigger= std::move(e.OnTrigger); OnSecondaryTrigger= std::move(e.OnSecondaryTrigger); OnDraggingStart= std::move(e.OnDraggingStart); OnDragging= std::move(e.OnDragging); OnDraggingStop= std::move(e.OnDraggingStop); triggered= e.triggered; errorVisuals= e.errorVisuals; elementType= e.elementType; active= e.active; visible= e.visible; enabled= e.enabled; firstFrame= e.firstFrame; touchable= e.touchable; applySuperActivation= e.applySuperActivation; stretchable= e.stretchable; autoResize= e.autoResize; depthOffset= e.depthOffset; draggingType= e.draggingType; position= e.position; offset= e.offset; radius= e.radius; minRadius= e.minRadius; maxRadius= e.maxRadius; curBbState= e.curBbState; prevBbState= e.prevBbState; destroyVisuals(); if (superElement){ superElement->removeSubElementImpl(*this); } elementTable.remove(tableIndex); elementTable[e.tableIndex]= this; tableIndex= e.tableIndex; e.tableIndex= -1; while(!e.visualEntities.empty()){ e.visualEntities.front()->changeContainer(&visualEntities); } // Transfer subElements auto sub_elements= e.subElements; for (auto& m : sub_elements){ e.removeSubElementImpl(*m); } for (auto& m : sub_elements){ addSubElementImpl(*m); } if (e.superElement){ e.superElement->onSubSwap(e, *this); } return *this; } Element::~Element(){ destroyVisuals(); for (auto m : subElements){ m->setSuperElement(0); } if (superElement) superElement->onSubDestroy(*this); if (tableIndex >= 0) elementTable.remove(tableIndex); if (guiCursor->getDraggedElement() == this) guiCursor->stopDragging(); if (guiCursor->getTouchedElement() == this) guiCursor->stopTouching(); global::g_env.guiMgr->onDestroy(*this); } void Element::setOffset(const util::Coord& p){ position.setType(p.getType()); offset.setType(p.getType()); offset= p; offset.setRelative(); if (superElement) position= superElement->getPosition() + offset; else position= offset; //recursiveOnSpatialChange(); } void Element::setPosition(const util::Coord& p){ if (superElement){ setOffset(p - superElement->getPosition()); } else { setOffset(p); } } void Element::setRadius(const util::Coord& r){ minRadius.convertTo(r.getType()); maxRadius.convertTo(r.getType()); radius= r; radius.setRelative(); if (maxRadius.x < r.x) maxRadius.x= r.x; if (maxRadius.y < r.y) maxRadius.y= r.y; if (minRadius.x > r.x) minRadius.x= r.x; if (minRadius.y > r.y) minRadius.y= r.y; ensure_msg(radius.x >= -util::epsilon && radius.y >= -util::epsilon, "%f, %f", radius.x, radius.y); } void Element::setMinRadius(const util::Coord& r){ minRadius= r.converted(radius.getType()); minRadius.setRelative(); ensure_msg(minRadius.x >= -util::epsilon && minRadius.y >= -util::epsilon, "%f, %f", minRadius.x, minRadius.y); //ensure_msg(maxRadius.x >= minRadius.x && maxRadius.y >= minRadius.y, "min: %f, %f max: %f, %f", minRadius.x, minRadius.y, maxRadius.x, maxRadius.y); } void Element::setMaxRadius(const util::Coord& r){ maxRadius= r.converted(radius.getType()); maxRadius.setRelative(); ensure_msg(maxRadius.x >= -util::epsilon && maxRadius.y >= -util::epsilon, "%f, %f", maxRadius.x, maxRadius.y); //ensure_msg(maxRadius.x >= minRadius.x && maxRadius.y >= minRadius.y, "min: %f, %f max: %f, %f", minRadius.x, minRadius.y, maxRadius.x, maxRadius.y); } void Element::minimizeRadius(){ util::Coord min_radius(0.0, minRadius.getType()); for (auto &m : subElements){ const Element& e= *m; util::Coord cur_rad= m->getOffset().abs() + m->getRadius().abs(); cur_rad= cur_rad.converted(min_radius.getType()); if (cur_rad.x > min_radius.x) min_radius.x= cur_rad.x; if (cur_rad.y > min_radius.y) min_radius.y= cur_rad.y; } if (min_radius.x < minRadius.x) min_radius.x= minRadius.x; if (min_radius.y < minRadius.y) min_radius.y= minRadius.y; if (min_radius.x > maxRadius.x) min_radius.x= maxRadius.x; if (min_radius.y > maxRadius.y) min_radius.y= maxRadius.y; if (!stretchable){ /// @todo Invariant ratio } radius= min_radius; radius.setRelative(); } void Element::addSubElement(Element& element){ addSubElementImpl(element); } void Element::removeSubElement(Element& element){ removeSubElementImpl(element); } void Element::onSubSwap(Element& existing, Element& replacing){ onSubDestroy(existing); addSubElement(replacing); } void Element::setActive(bool b){ if (!b) { curBbState= Bb_None; } active= b; for (auto &m : visualEntities){ m->setActiveTarget(active && visible); } for (auto m : subElements){ if (m->applySuperActivation) m->setActive(b); } } void Element::onStopDragging(){ OnDraggingStop(*this); } void Element::setVisible(bool b){ visible= b; for (auto& m : visualEntities){ m->setActiveTarget(active && visible); } for (auto& m : subElements){ m->setVisible(visible); } } void Element::setEnabled(bool b){ enabled= b; for (auto& m : visualEntities){ m->setEnabledTarget(enabled); } for (auto& m : subElements){ m->setEnabled(enabled); } } bool Element::recursiveIsTouched() const { for (auto& m : getSubElements()){ if (m->recursiveIsTouched()) return true; } return isTouched(); } void Element::setSuperElement(Element* s){ ensure(!superElement || !s); superElement= s; } void Element::onSubDestroy(Element& e){ for (auto it= subElements.begin(); it!= subElements.end(); ++it){ if (*it == &e){ subElements.erase(it); break; } } } void Element::preUpdate(){ firstFrame= false; if (isActive()){ util::Color c= {0.0,0.0,1.0,0.8}; if (elementType == LinearLayout) c= util::Color{0.0,0.0,0.0,0.8}; global::g_env.debugDraw->addRect(position, radius, c); } else { curBbState= Bb_None; } for (auto m : subElements) m->preUpdate(); } void Element::postUpdate(){ triggered= false; if (!isActive()) return; // Last is on top for (int i= subElements.size() - 1; i >= 0; --i) subElements[i]->postUpdate(); prevBbState= curBbState; if (touchable && isPointInside(guiCursor->getPosition())){ if (guiCursor->canTouchElement(*this)){ curBbState= Bb_Touch; guiCursor->touch(*this); if (enabled){ if (gUserInput->isTriggered(UserInput::GuiCause)){ triggered= true; OnTrigger(*this); } if (gUserInput->isTriggered(UserInput::GuiSecondaryCause)){ OnSecondaryTrigger(*this); } if (( (gUserInput->isTriggered(UserInput::GuiStartLeftDragging) && draggingType == DraggingType::Left) || (gUserInput->isTriggered(UserInput::GuiStartMiddleDragging) && draggingType == DraggingType::Middle) || (gUserInput->isTriggered(UserInput::GuiStartRightDragging) && draggingType == DraggingType::Right)) && guiCursor->canStartDraggingElement(*this)){ guiCursor->startDragging(*this); OnDraggingStart(*this); } } } else { curBbState= Bb_None; } if (guiCursor->canSetUnderElement(*this)){ guiCursor->setUnderElement(*this); } } else { curBbState= Bb_None; } if (guiCursor->getDraggedElement() == this) OnDragging(*this); } void Element::depthOrderUpdate(int32& depth_index){ depth_index += depthOffset; // Elements under subElements for (auto& m : visualEntities){ if (!m->isOnTopOfElement()) m->setDepth(depth_index); ++depth_index; } for (auto& m : subElements){ m->depthOrderUpdate(depth_index); } // Elements on top of subElements for (auto& m : visualEntities){ if (m->isOnTopOfElement()) m->setDepth(depth_index); ++depth_index; } depth_index -= depthOffset; } bool Element::isPointInside(util::Coord p){ p.convertTo(position.getType()); util::Coord rad; rad.setRelative(); rad= radius.converted(position.getType()); if (p.x >= (position-rad).x && p.y >= (position-rad).y && p.x < (position+rad).x && p.y < (position+rad).y ) return true; return false; } bool Element::hasSubElement(const gui::Element& e) const { for (auto& m : subElements){ if (m == &e) return true; } return false; } bool Element::recursiveHasSubElement(const gui::Element& e) const { if (hasSubElement(e)) return true; for (auto& m : subElements){ if (m->recursiveHasSubElement(e)) return true; } return false; } void Element::bringTop(){ if (superElement){ superElement->bringTop(*this); } else { ensure_msg(0, "Not implemented"); } } void Element::setErrorVisuals(bool b){ errorVisuals= b; for (auto& m : visualEntities){ m->setError(b); } } ElementVisualEntity* Element::createVisualEntity(ElementVisualEntity::Type t){ return newVisualEntityConfig(new ElementVisualEntity(t, visualEntities)); } TextElementVisualEntity* Element::createTextVisualEntity(TextElementVisualEntity::Type t){ return newVisualEntityConfig(new TextElementVisualEntity(t, visualEntities)); } CustomElementVisualEntity* Element::createCustomVisualEntity(){ return newVisualEntityConfig(new CustomElementVisualEntity(visualEntities)); } BaseElementVisualEntity* Element::newVisualEntityConfigImpl(BaseElementVisualEntity* e){ e->setError(errorVisuals); return e; } void Element::destroyVisualEntity(BaseElementVisualEntity* entity){ if (!entity) return; entity->changeContainer(nullptr); } void Element::destroyVisuals(){ while(!visualEntities.empty()){ destroyVisualEntity(visualEntities.back()); } } void Element::bringTop(Element& sub_element){ auto it= subElements.find(&sub_element); ensure(it != subElements.end()); subElements.erase(it); subElements.pushBack(&sub_element); } void Element::spatialUpdate(){ if (superElement) position= superElement->getPosition() + offset; else position= offset; if (radius.x < minRadius.x){ radius.x= minRadius.x; } if (radius.y < minRadius.y){ radius.y= minRadius.y; } if (radius.x > maxRadius.x){ radius.x= maxRadius.x; } if (radius.y > maxRadius.y){ radius.y= maxRadius.y; } if (autoResize){ minimizeRadius(); } } void Element::recursiveSpatialUpdate(){ if (!isActive()) return; spatialUpdate(); // Update subElement radius' for (auto& m : subElements){ m->recursiveSpatialUpdate(); } } void Element::addSubElementImpl(Element& element){ for (auto m : subElements){ ensure(m != &element); } if (!isActive()) element.setActive(false); subElements.pushBack(&element); element.setSuperElement(this); } void Element::removeSubElementImpl(Element& element){ auto it= subElements.find(&element); if (it!= subElements.end()){ subElements.erase(it); element.setSuperElement(0); } } } // gui } // clover
{ "content_hash": "7e262ed9b0c7c4d53da571c3d496701b", "timestamp": "", "source": "github", "line_count": 595, "max_line_length": 151, "avg_line_length": 21.833613445378152, "alnum_prop": 0.6887075667769995, "repo_name": "crafn/clover", "id": "936d833ee0f0980e6863f5f81d08d5e3addc34be", "size": "13157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/source/gui/element.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16329136" }, { "name": "C++", "bytes": "3005254" }, { "name": "Objective-C", "bytes": "52894" }, { "name": "Perl", "bytes": "3982" }, { "name": "Python", "bytes": "16716" }, { "name": "Shell", "bytes": "32" } ], "symlink_target": "" }
use shared::lmcons::{LMSTR, NET_API_STATUS}; use shared::minwindef::{DWORD, LPBYTE, LPDWORD, PBYTE, ULONG}; use um::winnt::LPWSTR; extern "system" { pub fn NetUseAdd( servername: LPWSTR, level: DWORD, buf: LPBYTE, parm_err: LPDWORD, ) -> NET_API_STATUS; pub fn NetUseDel( UncServerName: LMSTR, UseName: LMSTR, ForceCond: DWORD, ) -> NET_API_STATUS; pub fn NetUseEnum( UncServerName: LMSTR, Level: DWORD, BufPtr: *mut LPBYTE, PreferedMaximumSize: DWORD, EntriesRead: LPDWORD, TotalEntries: LPDWORD, ResumeHandle: LPDWORD, ) -> NET_API_STATUS; pub fn NetUseGetInfo( UncServerName: LMSTR, UseName: LMSTR, level: DWORD, bufptr: *mut LPBYTE, ) -> NET_API_STATUS; } STRUCT!{struct USE_INFO_0 { ui0_local: LMSTR, ui0_remote: LMSTR, }} pub type PUSE_INFO_0 = *mut USE_INFO_0; pub type LPUSE_INFO_0 = *mut USE_INFO_0; STRUCT!{struct USE_INFO_1 { ui1_local: LMSTR, ui1_remote: LMSTR, ui1_password: LMSTR, ui1_status: DWORD, ui1_asg_type: DWORD, ui1_refcount: DWORD, ui1_usecount: DWORD, }} pub type PUSE_INFO_1 = *mut USE_INFO_1; pub type LPUSE_INFO_1 = *mut USE_INFO_1; STRUCT!{struct USE_INFO_2 { ui2_local: LMSTR, ui2_remote: LMSTR, ui2_password: LMSTR, ui2_status: DWORD, ui2_asg_type: DWORD, ui2_refcount: DWORD, ui2_usecount: DWORD, ui2_username: LMSTR, ui2_domainname: LMSTR, }} pub type PUSE_INFO_2 = *mut USE_INFO_2; pub type LPUSE_INFO_2 = *mut USE_INFO_2; STRUCT!{struct USE_INFO_3 { ui3_ui2: USE_INFO_2, ui3_flags: ULONG, }} pub type PUSE_INFO_3 = *mut USE_INFO_3; STRUCT!{struct USE_INFO_4 { ui4_ui3: USE_INFO_3, ui4_auth_identity_length: DWORD, ui4_auth_identity: PBYTE, }} pub type PUSE_INFO_4 = *mut USE_INFO_4; pub type LPUSE_INFO_4 = *mut USE_INFO_4; pub const USE_LOCAL_PARMNUM: DWORD = 1; pub const USE_REMOTE_PARMNUM: DWORD = 2; pub const USE_PASSWORD_PARMNUM: DWORD = 3; pub const USE_ASGTYPE_PARMNUM: DWORD = 4; pub const USE_USERNAME_PARMNUM: DWORD = 5; pub const USE_DOMAINNAME_PARMNUM: DWORD = 6; pub const USE_OK: DWORD = 0; pub const USE_PAUSED: DWORD = 1; pub const USE_SESSLOST: DWORD = 2; pub const USE_DISCONN: DWORD = 2; pub const USE_NETERR: DWORD = 3; pub const USE_CONN: DWORD = 4; pub const USE_RECONN: DWORD = 5; pub const USE_WILDCARD: DWORD = -1i32 as u32; pub const USE_DISKDEV: DWORD = 0; pub const USE_SPOOLDEV: DWORD = 1; pub const USE_CHARDEV: DWORD = 2; pub const USE_IPC: DWORD = 3; pub const CREATE_NO_CONNECT: ULONG = 0x1; pub const CREATE_BYPASS_CSC: ULONG = 0x2; pub const CREATE_CRED_RESET: ULONG = 0x4; pub const USE_DEFAULT_CREDENTIALS: ULONG = 0x4;
{ "content_hash": "941eb82d153307cdacfd47de57445477", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 62, "avg_line_length": 29.073684210526316, "alnum_prop": 0.6484431571325127, "repo_name": "Osspial/winapi-rs", "id": "98e56aac5a3e72914bda99992ae089c5d4b72ac0", "size": "3235", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/um/lmuse.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "4277905" } ], "symlink_target": "" }
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>piwik/device-detector<br /><small>/Tests/fixtures/tablet.yml</small></td><td>Android Browser </td><td>Android 4.0.4</td><td>WebKit </td><td style="border-left: 1px solid #555">Gemini</td><td>GEM7008</td><td>tablet</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [os] => Array ( [name] => Android [short_name] => AND [version] => 4.0.4 [platform] => ) [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [device] => Array ( [type] => tablet [brand] => GD [model] => GEM7008 ) [os_family] => Android [browser_family] => Android Browser ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.016</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.0* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.0 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Generic</td><td>Android 4.0</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.26003</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => Android 4.0 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.0.4 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.0.x Ice Cream Sandwich [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555">Gemini</td><td>GEM7008</td><td>tablet</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.0 [platform] => ) [device] => Array ( [brand] => GD [brandName] => Gemini [model] => GEM7008 [device] => 2 [deviceName] => tablet ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => 1 [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.0.4 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 4.0.4</td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"></td><td>GEM7008</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.003</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 0 [patch] => 4 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 0 [patch] => 4 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Generic_Android [model] => GEM7008 [family] => GEM7008 ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.08201</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.0.4 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => Spanish - Spain [agent_languageTag] => es-es ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.0.4</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.42604</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Ice Cream Sandwich) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => IMM76D ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Ice Cream Sandwich [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Ice Cream Sandwich) [operating_system_version_full] => 4.0.4 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.4; es-es; GEM7008 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.0.4</td><td style="border-left: 1px solid #555">Gemini</td><td>JoyTab GEM7008</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.012</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.0.4 ) [device] => Array ( [type] => tablet [manufacturer] => Gemini [model] => JoyTab GEM7008 ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.0.4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.092</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.0 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.0 [complete_device_name] => Generic Android 4 Tablet [form_factor] => Tablet [is_phone] => false [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 4 Tablet [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.0 [pointing_method] => touchscreen [release_date] => 2012_january [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => false [is_tablet] => true [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 480 [resolution_height] => 800 [columns] => 60 [max_image_width] => 480 [max_image_height] => 800 [rows] => 40 [physical_screen_width] => 92 [physical_screen_height] => 153 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:39:42</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "bf260e888fc35abd68a35858deb6ca22", "timestamp": "", "source": "github", "line_count": 1144, "max_line_length": 766, "avg_line_length": 40.99650349650349, "alnum_prop": 0.5364605543710022, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "a2f85323758248dd8e3d45e147c2b2869489453b", "size": "46901", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v4/user-agent-detail/cc/01/cc01adc8-4b96-4c3e-b493-28444c9bc994.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
'use strict'; module.exports = function (Logger, $rootScope, $state, $auth, $anchorScroll, UserService) { $rootScope.$on("$stateChangeError", console.log.bind(console)); $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { Logger.info("Change state from '" + fromState.name + "' (" + fromParams + ") to '" + toState.name + "' (" + toParams + ")"); Logger.info('From state: ' + JSON.stringify(fromState)); Logger.info('To state: ' + JSON.stringify(toState)); if ($auth.isAuthenticated()) { Logger.log("User is authenticated"); // if user is already logged in, go to dashboard if (toState.name === "main.auth.login") { // Preventing the default behavior allows us to use $state.go // to change states event.preventDefault(); Logger.info("Redirect to home"); $state.go('main.home'); } // get user data of currently authenticated user UserService.get('', true).then(function (data) { $rootScope.authenticated = true; $rootScope.currentUser = data; Logger.info('Current user: ' + JSON.stringify($rootScope.currentUser)); // check if user has permissions for required route if (toState.data && toState.data.rank) { Logger.log("Check route permissions"); if (!$auth.isAuthenticated() || !$rootScope.currentUser || $rootScope.currentUser.rank < toState.data.rank) { Logger.log("Insufficient permissions"); event.preventDefault(); if (fromState.abstract === true) { $state.go('main.home'); } } } }, function (data) { Logger.info('Could not load details for current user, go home'); event.preventDefault(); $state.go('main.home'); }); } else { Logger.log("Not authenticated"); $rootScope.authenticated = false; $rootScope.currentUser = null; } }); // (re-)load user data on state changes $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { Logger.info("State change success!"); $rootScope.currentState = toState.name; $anchorScroll(); }); };
{ "content_hash": "4cc62f6c5b10222d20f2f59d1c1ce646", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 132, "avg_line_length": 30.790697674418606, "alnum_prop": 0.5185045317220544, "repo_name": "e1528532/libelektra", "id": "cfc0edb0dfada964d21af9e0197233778ccd79bb", "size": "2648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tools/rest-frontend/resources/assets/js/run/states.js", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "582" }, { "name": "Awk", "bytes": "451" }, { "name": "C", "bytes": "3525961" }, { "name": "C++", "bytes": "1771879" }, { "name": "CMake", "bytes": "375850" }, { "name": "CSS", "bytes": "20625" }, { "name": "Dockerfile", "bytes": "23009" }, { "name": "Groovy", "bytes": "46018" }, { "name": "HTML", "bytes": "100232" }, { "name": "Haskell", "bytes": "83287" }, { "name": "Inform 7", "bytes": "394" }, { "name": "Java", "bytes": "70850" }, { "name": "JavaScript", "bytes": "332870" }, { "name": "Lua", "bytes": "27792" }, { "name": "Makefile", "bytes": "7943" }, { "name": "Objective-C", "bytes": "6429" }, { "name": "Python", "bytes": "76393" }, { "name": "QML", "bytes": "87034" }, { "name": "QMake", "bytes": "4256" }, { "name": "Roff", "bytes": "791" }, { "name": "Ruby", "bytes": "87106" }, { "name": "Shell", "bytes": "198133" }, { "name": "Smarty", "bytes": "1196" }, { "name": "Tcl", "bytes": "330" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03.UnicodeCharcters")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03.UnicodeCharcters")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bb66117b-3b28-43ff-8375-e7b4109477ce")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "96cfd72016f560f46c132f0a2f2a3ec0", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.19444444444444, "alnum_prop": 0.7462792345854005, "repo_name": "yangra/SoftUni", "id": "d79970f973ae0069a0ab59b6a88dacb442bfb445", "size": "1414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TechModule/Programming Fundamentals/09.StringsAndTextProcessing - Exercises/03.UnicodeCharcters/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "301" }, { "name": "Batchfile", "bytes": "64953" }, { "name": "C#", "bytes": "1237474" }, { "name": "CSS", "bytes": "474654" }, { "name": "HTML", "bytes": "187923" }, { "name": "Java", "bytes": "2815020" }, { "name": "JavaScript", "bytes": "636500" }, { "name": "PHP", "bytes": "72489" }, { "name": "SQLPL", "bytes": "27954" }, { "name": "Shell", "bytes": "84674" } ], "symlink_target": "" }
/** * @fileOverview Frontpage tests */ var chai = require('chai'); var expect = chai.expect; var req = require('request'); const test = require('ava'); test('Frontpage 200', t => { var app = require('../back/app'); app.listen(3000); return req.get('http://localhost:3000/', (err, res) => { expect(res.statusCode).to.equal(200); t.pass(); }); });
{ "content_hash": "f9d27e1ede32cab0e4382d6cb94983f8", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 58, "avg_line_length": 20.38888888888889, "alnum_prop": 0.6021798365122616, "repo_name": "sirodoht/muddles", "id": "86569b00c89021e05647dbffc69209ec8bb9b800", "size": "367", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4470" }, { "name": "HTML", "bytes": "6050" }, { "name": "JavaScript", "bytes": "11068" } ], "symlink_target": "" }
package android.support.v17.leanback.supportleanbackshowcase.app.room.db.repo; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Room; import android.os.AsyncTask; import android.support.annotation.WorkerThread; import android.support.v17.leanback.supportleanbackshowcase.R; import android.support.v17.leanback.supportleanbackshowcase.app.room.controller.app.SampleApplication; import android.support.v17.leanback.supportleanbackshowcase.app.room.api.VideoDownloadingService; import android.support.v17.leanback.supportleanbackshowcase.app.room.api.VideosWithGoogleTag; import android.support.v17.leanback.supportleanbackshowcase.app.room.config.AppConfiguration; import android.support.v17.leanback.supportleanbackshowcase.app.room.db.AppDatabase; import android.support.v17.leanback.supportleanbackshowcase.app.room.db.dao.CategoryDao; import android.support.v17.leanback.supportleanbackshowcase.app.room.db.dao.VideoDao; import android.support.v17.leanback.supportleanbackshowcase.app.room.db.entity.CategoryEntity; import android.support.v17.leanback.supportleanbackshowcase.app.room.db.entity.VideoEntity; import android.support.v17.leanback.supportleanbackshowcase.utils.Utils; import android.util.Log; import com.google.gson.Gson; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @Singleton public class VideosRepository { // For debugging purpose private static final boolean DEBUG = false; private static final String TAG = "VideosRepository"; // meta data type constant private static final String RENTED = "rented"; private static final String STATUS = "status"; private static final String CARD = "card"; private static final String BACKGROUND = "background"; private static final String VIDEO = "video"; private static VideosRepository sVideosRepository; private AppDatabase mDb; private VideoDao mVideoDao; private CategoryDao mCategoryDao; // maintain the local cache so the live data can be shared among different components private Map<String, LiveData<List<VideoEntity>>> mVideoEntitiesCache; private LiveData<List<CategoryEntity>> mCategories; public static VideosRepository getVideosRepositoryInstance() { if (sVideosRepository == null) { sVideosRepository = new VideosRepository(); } return sVideosRepository; } /** * View Model talks to repository through this method to fetch the live data. * * @param category category * @return The list of categories which is wrapped in a live data. */ public LiveData<List<VideoEntity>> getVideosInSameCategoryLiveData(String category) { // always try to retrive from local cache firstly if (mVideoEntitiesCache.containsKey(category)) { return mVideoEntitiesCache.get(category); } LiveData<List<VideoEntity>> videoEntities = mVideoDao.loadVideoInSameCateogry(category); mVideoEntitiesCache.put(category, videoEntities); return videoEntities; } public LiveData<List<CategoryEntity>> getAllCategories() { if (mCategories == null) { mCategories = mCategoryDao.loadAllCategories(); } return mCategories; } public LiveData<List<VideoEntity>> getSearchResult(String query) { return mVideoDao.searchVideos(query); } public LiveData<VideoEntity> getVideoById(Long id) { return mVideoDao.loadVideoById(id); } /** * Helper function to access the database and update the video information in the database. * * @param video video entity * @param category which fields to update * @param value updated value */ @WorkerThread public synchronized void updateDatabase(VideoEntity video, String category, String value) { try { mDb.beginTransaction(); switch (category) { case VIDEO: video.setVideoLocalStorageUrl(value); break; case BACKGROUND: video.setVideoBgImageLocalStorageUrl(value); break; case CARD: video.setVideoCardImageLocalStorageUrl(value); break; case STATUS: video.setStatus(value); break; case RENTED: video.setRented(true); break; } mDb.videoDao().updateVideo(video); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } @Inject public VideosRepository() { createAndPopulateDatabase(); mVideoDao = mDb.videoDao(); mCategoryDao = mDb.categoryDao(); mVideoEntitiesCache = new HashMap<>(); } private void createAndPopulateDatabase() { mDb = Room.databaseBuilder(SampleApplication.getInstance(), AppDatabase.class, AppDatabase.DATABASE_NAME).build(); // insert contents into database try { String url = "https://storage.googleapis.com/android-tv/"; initializeDb(mDb, url); } catch (IOException e) { e.printStackTrace(); } } private void initializeDb(AppDatabase db, String url) throws IOException { // json data String json; if (AppConfiguration.IS_DEBUGGING_VERSION) { // when use debugging version, we won't fetch data from network but using local // json file (only contain 4 video entities in 2 categories.) json = Utils.inputStreamToString(SampleApplication .getInstance() .getApplicationContext() .getResources() .openRawResource(R.raw.live_movie_debug)); Gson gson = new Gson(); VideosWithGoogleTag videosWithGoogleTag = gson.fromJson(json, VideosWithGoogleTag.class); populateDatabase(videosWithGoogleTag,db); } else { buildDatabase(db, url); } } /** * Takes the contents of a JSON object and populates the database * * @param db Room database. */ private static void buildDatabase(final AppDatabase db, String url) throws IOException { Retrofit retrofit = new Retrofit .Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .build(); VideoDownloadingService service = retrofit.create(VideoDownloadingService.class); Call<VideosWithGoogleTag> videosWithGoogleTagCall = service.getVideosList(); videosWithGoogleTagCall.enqueue(new Callback<VideosWithGoogleTag>() { @Override public void onResponse(Call<VideosWithGoogleTag> call, Response<VideosWithGoogleTag> response) { VideosWithGoogleTag videosWithGoogleTag = response.body(); if (videosWithGoogleTag == null) { Log.d(TAG, "onResponse: result is null"); return; } populateDatabase(videosWithGoogleTag, db); } @Override public void onFailure(Call<VideosWithGoogleTag> call, Throwable t) { Log.d(TAG, "Fail to download the content"); } }); } private static void populateDatabase(VideosWithGoogleTag videosWithGoogleTag, final AppDatabase db) { for (final VideosWithGoogleTag.VideosGroupByCategory videosGroupByCategory : videosWithGoogleTag.getAllResources()) { // create category table final CategoryEntity categoryEntity = new CategoryEntity(); categoryEntity.setCategoryName(videosGroupByCategory.getCategory()); // create video table with customization postProcessing(videosGroupByCategory); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { db.beginTransaction(); db.categoryDao().insertCategory(categoryEntity); db.videoDao().insertAllVideos(videosGroupByCategory.getVideos()); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return null; } }.execute(); } } /** * Helper function to make some customization on raw data */ private static void postProcessing(VideosWithGoogleTag.VideosGroupByCategory videosGroupByCategory) { for (VideoEntity each : videosGroupByCategory.getVideos()) { each.setCategory(videosGroupByCategory.getCategory()); each.setVideoLocalStorageUrl(""); each.setVideoBgImageLocalStorageUrl(""); each.setVideoCardImageLocalStorageUrl(""); each.setVideoUrl(each.getVideoUrls().get(0)); each.setRented(false); each.setStatus(""); each.setTrailerVideoUrl("https://storage.googleapis.com/android-tv/Sample%20videos/Google%2B/Google%2B_%20Say%20more%20with%20Hangouts.mp4"); } } }
{ "content_hash": "570f5bfc7401bb8e45560f0cfeb2f080", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 153, "avg_line_length": 37.01145038167939, "alnum_prop": 0.6443229864906672, "repo_name": "googlearchive/leanback-showcase", "id": "00a1b59b60cb224cbc493561ec55f093c225ff90", "size": "10316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/android/support/v17/leanback/supportleanbackshowcase/app/room/db/repo/VideosRepository.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "564504" }, { "name": "Python", "bytes": "59726" } ], "symlink_target": "" }
<html> <head> <title>Craig Chung's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Craig Chung's panel show appearances</h1> <p>Craig Chung has appeared in <span class="total">4</span> episodes between 2018-2018. Note that these appearances may be for more than one person if multiple people have the same name.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances male" title="4"></div><span class="year">2018</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2018-06-05</strong> / <a href="../shows/the-drum.html">The Drum</a></li> <li><strong>2018-04-27</strong> / <a href="../shows/the-drum.html">The Drum</a></li> <li><strong>2018-03-12</strong> / <a href="../shows/the-drum.html">The Drum</a></li> <li><strong>2018-02-09</strong> / <a href="../shows/the-drum.html">The Drum</a></li> </ol> </div> </body> </html>
{ "content_hash": "39a44423e3fbc24cdd11dcd1abce5301", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 191, "avg_line_length": 37.666666666666664, "alnum_prop": 0.6548672566371682, "repo_name": "slowe/panelshows", "id": "d4db6b37ba753c6fe31a20aef2d0a6384c913aaa", "size": "1243", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "people/9gtpyxai.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8431" }, { "name": "HTML", "bytes": "25483901" }, { "name": "JavaScript", "bytes": "95028" }, { "name": "Perl", "bytes": "19899" } ], "symlink_target": "" }
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'landing', templateUrl: './landing.html' }) export class LandingComponent implements OnInit { public isMobile: boolean; public ngOnInit(): void { this.isMobile = window.isMobile(); } }
{ "content_hash": "6b8e0563b3cba250b621738c4dec0d12", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 50, "avg_line_length": 19.714285714285715, "alnum_prop": 0.6884057971014492, "repo_name": "VS-work/vs-website", "id": "63ad8ced1790d3868ea50cb38c7cc513b9f1c6be", "size": "276", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/components/landing/landing.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56227" }, { "name": "HTML", "bytes": "109665" }, { "name": "JavaScript", "bytes": "49460" }, { "name": "TypeScript", "bytes": "107081" } ], "symlink_target": "" }
package com.mocircle.flow.handler.node; import com.mocircle.flow.BuildConfig; import com.mocircle.flow.model.Token; import com.mocircle.flow.model.action.SimpleActionNode; import com.mocircle.flow.model.control.Fork; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 16) public class ForkHandlerTest { Fork f; SimpleActionNode in; SimpleActionNode out1; SimpleActionNode out2; SimpleActionNode out3; @Before public void setup() { f = new Fork(); in = new SimpleActionNode(Token.TYPE_NORMAL); out1 = new SimpleActionNode(Token.TYPE_NORMAL); out2 = new SimpleActionNode(Token.TYPE_NORMAL); out3 = new SimpleActionNode(Token.TYPE_NORMAL); } @Test public void testIsSupported() { ForkHandler handler = new ForkHandler(); Assert.assertTrue(handler.isSupported(f)); Assert.assertFalse(handler.isSupported(in)); } @Test public void testHandleNode() { ForkHandler handler = new ForkHandler(); in.addOutgoingNode(f); f.addOutgoingNode(out1); f.addOutgoingNode(out2); f.addOutgoingNode(out3); NodeHandleResult result = handler.handleNode(f); Assert.assertEquals(3, result.getNextNodes().size()); } }
{ "content_hash": "850e44eaa58ef280c27711d1567189b5", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 61, "avg_line_length": 27.672727272727272, "alnum_prop": 0.7030223390275953, "repo_name": "mocircle/circleflow-android", "id": "8d66fb4228b4940b4bab5cce215cb27e95d2afb3", "size": "2121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "circleflow/src/test/java/com/mocircle/flow/handler/node/ForkHandlerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "296129" } ], "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_45) on Thu Mar 26 16:48:37 UTC 2015 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class com.hazelcast.util.StringUtil (Hazelcast Root 3.4.2 API) </TITLE> <META NAME="date" CONTENT="2015-03-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hazelcast.util.StringUtil (Hazelcast Root 3.4.2 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/hazelcast/util/StringUtil.html" title="class in com.hazelcast.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?com/hazelcast/util//class-useStringUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="StringUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.hazelcast.util.StringUtil</B></H2> </CENTER> No usage of com.hazelcast.util.StringUtil <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/hazelcast/util/StringUtil.html" title="class in com.hazelcast.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?com/hazelcast/util//class-useStringUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="StringUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2015 <a href="http://www.hazelcast.com/">Hazelcast, Inc.</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "99617e29889af4c19aca971ff07aba28", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 201, "avg_line_length": 41.26896551724138, "alnum_prop": 0.6191510695187166, "repo_name": "akiskip/KoDeMat-Collaboration-Platform-Application", "id": "14638bb60b1cafec2f4e9d9ca11639a27e34caa5", "size": "5984", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "KoDeMat_TouchScreen/lib/hazelcast-3.4.2/hazelcast-3.4.2/docs/javadoc/com/hazelcast/util/class-use/StringUtil.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1255" }, { "name": "CSS", "bytes": "12362" }, { "name": "GLSL", "bytes": "105719" }, { "name": "HTML", "bytes": "17271482" }, { "name": "Java", "bytes": "1388877" }, { "name": "JavaScript", "bytes": "110983" }, { "name": "Shell", "bytes": "1365" } ], "symlink_target": "" }
/* Simple pthreads mutex and condition-variable wrappers Ben Barsdell (2015) BSD 3-Clause license Note: Unlike the C++11 std::mutex, the pthreads-based mutex here supports inter-process sharing. Note: According to the docs, setting a mutex as recursive can lead to problems with condition variables. Example ------- Mutex mutex(Mutex::PROCESS_SHARED); ConditionVariable cv(ConditionVariable::PROCESS_SHARED); void foo() { UniqueLock<Mutex> lock(mutex); if( !cv.wait_for(lock, timeout_secs, [](){ return x == y; }) ) { // Timed out } // ... } */ #pragma once #include <cerrno> #include <cstring> #include <limits> #include <pthread.h> template<typename MutexType> class LockGuard { public: typedef MutexType mutex_type; explicit LockGuard(mutex_type& m) : _mutex(m) { _mutex.lock(); } ~LockGuard() { _mutex.unlock(); } private: // Prevent copying or assignment void operator=(const LockGuard&); LockGuard(const LockGuard&); mutex_type& _mutex; }; template<typename MutexType> class UniqueLock { public: typedef MutexType mutex_type; explicit UniqueLock(mutex_type& m, bool locked=true) : _mutex(m), _locked(locked) { if( locked ) { _mutex.lock(); } } ~UniqueLock() { this->unlock(); } void unlock() { if( !_locked ) { return; } _mutex.unlock(); _locked = false; } void lock() { if( _locked ) { return; } _mutex.lock(); _locked = true; } mutex_type const& mutex() const { return _mutex; } mutex_type& mutex() { return _mutex; } bool owns_lock() const { return _locked; } operator bool() { return this->owns_lock(); } private: // Not copy-assignable UniqueLock& operator=(const UniqueLock& ); UniqueLock(const UniqueLock& ); mutex_type& _mutex; bool _locked; }; namespace pthread { class Mutex { pthread_mutex_t _mutex; // Not copy-assignable Mutex(const Mutex& ); Mutex& operator=(const Mutex& ); static void check_error(int ret) { if( ret ) { throw Mutex::Error(std::strerror(ret)); } } class Attrs { pthread_mutexattr_t _attr; Attrs(Attrs const& ); Attrs& operator=(Attrs const& ); public: Attrs() { check_error( pthread_mutexattr_init(&_attr) ); } ~Attrs() { pthread_mutexattr_destroy(&_attr); } pthread_mutexattr_t* handle() { return &_attr; } }; public: struct Error : public std::runtime_error { Error(const std::string& what_arg) : std::runtime_error(what_arg) {} }; enum { RECURSIVE = 1<<0, PROCESS_SHARED = 1<<1 }; Mutex(unsigned flags=0) { Mutex::Attrs attrs; if( flags & Mutex::RECURSIVE ) { check_error( pthread_mutexattr_settype(attrs.handle(), PTHREAD_MUTEX_RECURSIVE) ); } if( flags & Mutex::PROCESS_SHARED ) { check_error( pthread_mutexattr_setpshared(attrs.handle(), PTHREAD_PROCESS_SHARED) ); } check_error( pthread_mutex_init(&_mutex, attrs.handle()) ); } ~Mutex() { pthread_mutex_destroy(&_mutex); } void lock() { check_error( pthread_mutex_lock(&_mutex) ); } bool trylock() { int ret = pthread_mutex_trylock(&_mutex); if( ret == EBUSY ) { return false; } else { check_error(ret); return true; } } void unlock() { check_error( pthread_mutex_unlock(&_mutex) ); } operator const pthread_mutex_t&() const { return _mutex; } operator pthread_mutex_t&() { return _mutex; } }; class ConditionVariable { pthread_cond_t _cond; // Not copy-assignable ConditionVariable(ConditionVariable const& ); ConditionVariable& operator=(ConditionVariable const& ); static void check_error(int ret) { if( ret) { throw ConditionVariable::Error(strerror(ret)); } } class Attrs { pthread_condattr_t _attr; Attrs(Attrs const& ); Attrs& operator=(Attrs const& ); public: Attrs() { check_error( pthread_condattr_init(&_attr) ); } ~Attrs() { pthread_condattr_destroy(&_attr); } pthread_condattr_t* handle() { return &_attr; } }; public: struct Error : public std::runtime_error { Error(const std::string& what_arg) : std::runtime_error(what_arg) {} }; enum { PROCESS_SHARED = 1<<1 }; ConditionVariable(unsigned flags=0) { ConditionVariable::Attrs attrs; if( flags & ConditionVariable::PROCESS_SHARED ) { check_error( pthread_condattr_setpshared(attrs.handle(), PTHREAD_PROCESS_SHARED) ); } check_error( pthread_cond_init(&_cond, attrs.handle()) ); } ~ConditionVariable() { pthread_cond_destroy(&_cond); } void wait(UniqueLock<Mutex>& lock) { check_error( pthread_cond_wait(&_cond, &(pthread_mutex_t&)lock.mutex()) ); } template<typename Predicate> void wait(UniqueLock<Mutex>& lock, Predicate pred) { while( !pred() ) { this->wait(lock); } } bool wait_until(UniqueLock<Mutex>& lock, timespec const& abstime) { int ret = pthread_cond_timedwait(&_cond, &(pthread_mutex_t&)lock.mutex(), &abstime); if( ret == ETIMEDOUT ) { return false; } else { check_error(ret); return true; } } template<typename Predicate> bool wait_until(UniqueLock<Mutex>& lock, timespec const& abstime, Predicate pred) { while( !pred() ) { if( !this->wait_until(lock, abstime) ) { return pred(); } } return true; } template<typename Predicate> bool wait_for(UniqueLock<Mutex>& lock, double timeout_secs, Predicate pred) { struct timespec abstime = {0}; check_error( clock_gettime(CLOCK_REALTIME, &abstime) ); //time_t secs = (time_t)(std::min(timeout_secs, double(INT_MAX))+0.5); time_t secs = (time_t)(std::min(timeout_secs, double(std::numeric_limits<time_t>::max()))+0.5); abstime.tv_sec += secs; abstime.tv_nsec += (long)((timeout_secs - secs)*1e9 + 0.5); return this->wait_until(lock, abstime, pred); } void notify_one() { check_error( pthread_cond_signal(&_cond) ); } void notify_all() { check_error( pthread_cond_broadcast(&_cond) ); } }; } // namespace pthread
{ "content_hash": "0d8c33f2ea9c7cc597c4a0981bb64ea3", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 84, "avg_line_length": 28.923809523809524, "alnum_prop": 0.6264405663483701, "repo_name": "benbarsdell/bifrost", "id": "6f2635730af3d4af4e7d049401e98a1d84ab798f", "size": "6074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Mutex.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "655" }, { "name": "C++", "bytes": "397502" }, { "name": "Makefile", "bytes": "3062" }, { "name": "Python", "bytes": "2746" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\XMPXmpMM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class ManagedFromDocumentID extends AbstractTag { protected $Id = 'ManagedFromDocumentID'; protected $Name = 'ManagedFromDocumentID'; protected $FullName = 'XMP::xmpMM'; protected $GroupName = 'XMP-xmpMM'; protected $g0 = 'XMP'; protected $g1 = 'XMP-xmpMM'; protected $g2 = 'Other'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Managed From Document ID'; }
{ "content_hash": "b039d3a73ed68cd0f038edb1fb951826", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 56, "avg_line_length": 17.13888888888889, "alnum_prop": 0.6823338735818476, "repo_name": "bburnichon/PHPExiftool", "id": "e611c7fe502ab16b8cfcf25f0ccdc19e9ba2852d", "size": "841", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/XMPXmpMM/ManagedFromDocumentID.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
/** * (created at 2011-1-19) */ package org.opencloudb.paser.ast.expression.function.string; import org.opencloudb.paser.ast.expression.Expression; import org.opencloudb.paser.ast.expression.TernaryOperatorExpression; import org.opencloudb.paser.visitor.SQLASTVisitor; /** * <code>higherPreExpr 'NOT'? 'LIKE' higherPreExpr ('ESCAPE' higherPreExpr)?</code> * * @author mycat */ public class LikeExpression extends TernaryOperatorExpression { private final boolean not; /** * @param escape null is no ESCAPE */ public LikeExpression(boolean not, Expression comparee, Expression pattern, Expression escape) { super(comparee, pattern, escape); this.not = not; } public boolean isNot() { return not; } @Override public int getPrecedence() { return PRECEDENCE_COMPARISION; } @Override public void accept(SQLASTVisitor visitor) { visitor.visit(this); } }
{ "content_hash": "a2f16691f80f52ec4e32dfb13ff656e7", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 100, "avg_line_length": 24.95, "alnum_prop": 0.6583166332665331, "repo_name": "xingh/opencloudb", "id": "32e8c5cc6e6535f16ace03d527acf3948ed7c895", "size": "1622", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/java/org/opencloudb/paser/ast/expression/function/string/LikeExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2897952" }, { "name": "Shell", "bytes": "10250" } ], "symlink_target": "" }
/* Created by yegor on 7/6/16. */ package ws.epigraph.java import java.io.{File, IOException, PrintWriter, StringWriter} import java.nio.file.{FileAlreadyExistsException, Files, Path} import java.util import java.util.Collections import java.util.concurrent._ import org.slf4s.LoggerFactory import ws.epigraph.compiler._ import ws.epigraph.java.service._ import ws.epigraph.lang.Qn import ws.epigraph.schema.ResourcesSchema import scala.annotation.tailrec import scala.collection.JavaConversions._ import scala.collection.{JavaConversions, immutable, mutable} class EpigraphJavaGenerator private( val cctx: CContext, val javaOutputRoot: Path, val resourcesOutputRoot: Path, val settings: Settings ) { /** * Checks if java and resources output roots are nested in each other, * and returns true if the directories are the same. */ @throws[IllegalArgumentException] private def validateOutputRoots(): Boolean = { val javaPath = javaOutputRoot.toAbsolutePath val resourcesPath = resourcesOutputRoot.toAbsolutePath val samePaths = javaPath == resourcesPath if (!samePaths) { if (javaPath.startsWith(resourcesPath) || resourcesPath.startsWith(javaPath)) { throw new IllegalArgumentException("One of Java or resources output paths may not be nested under the other") } } samePaths } private val singleOutput = validateOutputRoots() private val log = LoggerFactory.apply(this.getClass) private val ctx: GenContext = new GenContext(settings) // there seems to be a hard to find race in projections codegen, manifesting in // sometimes broken builtin-services-service code. Temporarily disabling parallel codegen to help find it private val parallel: Boolean = false // ! ctx.settings.debug def this(ctx: CContext, javaOutputRoot: File, resourcesOutputRoot: File, settings: Settings) { this(ctx, javaOutputRoot.toPath, resourcesOutputRoot.toPath, settings) } @throws[IOException] def generate() { def tmpSibling(path: Path): Path = JavaGenUtils.rmrf( path.resolveSibling(path.getFileName.toString + "~tmp"), path.getParent ) val tmpJavaRoot: Path = tmpSibling(javaOutputRoot) val tmpResourcesRoot: Path = if (singleOutput) tmpJavaRoot else tmpSibling(resourcesOutputRoot) // TODO only generate request projection classes if there are any resources defined ? val startTime: Long = System.currentTimeMillis val generators: mutable.Queue[JavaGen] = mutable.Queue() for (schemaFile <- cctx.schemaFiles.values) { for (typeDef <- JavaConversions.asJavaIterable(schemaFile.typeDefs)) { try { typeDef.kind match { case CTypeKind.ENTITY => val varTypeDef: CEntityTypeDef = typeDef.asInstanceOf[CEntityTypeDef] generators += new EntityTypeGen(varTypeDef, ctx) case CTypeKind.RECORD => val recordTypeDef: CRecordTypeDef = typeDef.asInstanceOf[CRecordTypeDef] generators += new RecordGen(recordTypeDef, ctx) case CTypeKind.MAP => val mapTypeDef: CMapTypeDef = typeDef.asInstanceOf[CMapTypeDef] generators += new NamedMapGen(mapTypeDef, ctx) case CTypeKind.LIST => val listTypeDef: CListTypeDef = typeDef.asInstanceOf[CListTypeDef] generators += new NamedListGen(listTypeDef, ctx) case CTypeKind.ENUM | CTypeKind.STRING | CTypeKind.INTEGER | CTypeKind.LONG | CTypeKind.DOUBLE | CTypeKind.BOOLEAN => generators += new PrimitiveGen(typeDef.asInstanceOf[CPrimitiveTypeDef], ctx) case _ => throw new UnsupportedOperationException(typeDef.kind.toString) } } catch { case _: CompilerException => // keep going collecting errors } } } for (alt <- cctx.anonListTypes.values) { try { generators += new AnonListGen(alt, ctx) } catch { case _: CompilerException => } } for (amt <- cctx.anonMapTypes.values) { try { generators += new AnonMapGen(amt, ctx) } catch { case _: CompilerException => } } runGeneratorsAndHandleErrors(queue(generators), _.writeUnder(tmpJavaRoot, tmpResourcesRoot)) generators.clear() // final Set<CDataType> anonMapValueTypes = new HashSet<>(); // for (CAnonMapType amt : ctx.anonMapTypes().values()) { // anonMapValueTypes.add(amt.valueDataType()); // } // for (CDataType valueType : anonMapValueTypes) { // new AnonBaseMapGen(valueType, ctx).writeUnder(tmpJavaRoot, tmpResourcesRoot); // } if (cctx.schemaFiles.nonEmpty) generators += new IndexGen(ctx) // generate server/client stubs val serverSettings = ctx.settings.serverSettings() val clientSettings = ctx.settings.clientSettings() if (serverSettings.generate() || clientSettings.generate()) { val serverServicesOpt = Option(serverSettings.services()) val serverTransformersOpt = Option(serverSettings.transformers()) val clientServicesOpt = Option(clientSettings.services()) for (entry <- cctx.resourcesSchemas.entrySet) { val rs: ResourcesSchema = entry.getValue val namespace: Qn = rs.namespace for (resourceDeclaration <- rs.resources.values) { // resource declarations (mostly op projections) are used by both server and client generators += new ResourceDeclarationGen(resourceDeclaration, namespace, ctx) val resourceName: String = namespace.append(resourceDeclaration.fieldName).toString // server stub // change them to be patters/regex? if (serverSettings.generate()) { if (serverServicesOpt.isEmpty || serverServicesOpt.exists(services => services.contains(resourceName))) { generators += new AbstractResourceFactoryGen(resourceDeclaration, namespace, ctx) } } // client if (clientSettings.generate()) { if (clientServicesOpt.isEmpty || clientServicesOpt.exists(services => services.contains(resourceName))) { generators += new ResourceClientGen(resourceDeclaration, namespace, ctx) } } } for (transformerDeclaration <- rs.transformers.values) { generators += new TransformerDeclarationGen(transformerDeclaration, namespace, ctx) val transformerName = namespace.append(transformerDeclaration.name()).toString if (serverSettings.generate()) { if (serverTransformersOpt.isEmpty || serverTransformersOpt.exists( transformers => transformers.contains( transformerName ) )) { generators += new AbstractTransformerGen(transformerDeclaration, namespace, ctx) } } } } } runGeneratorsAndHandleErrors(queue(generators), _.writeUnder(tmpJavaRoot, tmpResourcesRoot)) val endTime: Long = System.currentTimeMillis log.info(s"Epigraph Java code generation took ${ endTime - startTime }ms") if (Files.exists(tmpJavaRoot)) { // move new java root to the final location JavaGenUtils.move(tmpJavaRoot, javaOutputRoot, javaOutputRoot.getParent) } if (!singleOutput && Files.exists(tmpResourcesRoot)) { // move new resources root to the final location JavaGenUtils.move(tmpResourcesRoot, resourcesOutputRoot, resourcesOutputRoot.getParent) } } @tailrec private def runGeneratorsAndHandleErrors( generators: immutable.Queue[JavaGen], runner: JavaGen => Unit): Unit = { val doDebugTraces = ctx.settings.debug() val generatorsCopy = generators // mutable state, should be thread-safe val postponedGenerators = new java.util.concurrent.ConcurrentLinkedQueue[JavaGen]() val genParents = new java.util.concurrent.ConcurrentHashMap[JavaGen, JavaGen]() // will synchronize on this one if (parallel) { // run asynchronously val executor = Executors.newWorkStealingPool() val phaser = new Phaser(1) // active jobs counter + 1 def submit(generator: JavaGen): Unit = { val runStrategy = generator.shouldRunStrategy if (runStrategy.checkAndMark) { phaser.register() executor.submit( new Runnable { override def run(): Unit = { try { runGenerator(generator)(submit) } catch { case e: Exception => exceptionHandler(generator, runStrategy, e) } finally { phaser.arriveAndDeregister() } } } ) } } generators.foreach { submit } // generators.clear() phaser.arriveAndAwaitAdvance() executor.shutdown() if (!executor.awaitTermination(10, TimeUnit.MINUTES)) throw new RuntimeException("Code generation timeout") } else { // run sequentially var _generators = generators while (_generators.nonEmpty) { val (generator, newGenerators) = _generators.dequeue _generators = newGenerators val runStrategy = generator.shouldRunStrategy if (runStrategy.checkAndMark) { try { runGenerator(generator) { ch => _generators :+= ch } } catch { case e: Exception => exceptionHandler(generator, runStrategy, e) } } } } // child -> submit subgens (child.name, child asm) // child -> fail, run parent first, postpone child // parent -> submit subgens (child!) // parent -> run // child -> submit subgens again(!!) --> clash // child -> run def runGenerator(generator: JavaGen)(scheduleGeneratorRun: JavaGen => Unit): Unit = { addDebugInfo(generator) // children may be scheduled only after this generator was successfully executed // otherwise, if it fails, some of the children may re-schedule it in the *current* run again, // leading to a loop //generator.children.foreach(scheduleGeneratorRun) try { runner.apply(generator) generator.children.foreach(scheduleGeneratorRun) } catch { case tle: TryLaterException => // val description = generator.description val description = describeGenerator(generator, showGensProducingSameFile = false) log.debug(s"Postponing '$description' because: ${ tle.getMessage }") generator.shouldRunStrategy.unmark() postponedGenerators.add(generator) // run generator on next iteration if (tle.extraGeneratorsToRun.nonEmpty) { // these are the generators that have to be finished before `generator` is tried again // won't postpone them till next run but will include in the current one log.debug(s"Also including ${ tle.extraGeneratorsToRun.size } generators that have to run first:") tle.extraGeneratorsToRun.foreach(g => log.debug(g.description)) tle.extraGeneratorsToRun.foreach(scheduleGeneratorRun) } } } def exceptionHandler(generator: JavaGen, runStrategy: ShouldRunStrategy, ex: Exception) = { def msg = if (doDebugTraces) { val sw = new StringWriter sw.append(ex.toString).append("\n") sw.append(describeGenerator(generator, showGensProducingSameFile = true)) if (!ex.isInstanceOf[FileAlreadyExistsException]) { // not interested in these traces sw.append("\n") ex.printStackTrace(new PrintWriter(sw)) } sw.toString } else ex.toString log.debug("Unhandled exception", ex) cctx.errors.add(CMessage.error(null, CMessagePosition.NA, msg)) } //<editor-fold desc="Debugging stuff"> def addDebugInfo(gen: JavaGen): Unit = { log.debug("Running: " + gen.description) if (doDebugTraces) { val children = gen.children children.foreach { c => try { genParents.put(c, gen) } catch { case _: Exception => // ignore exceptions here } } } } def describeGenerator(g: JavaGen, showGensProducingSameFile: Boolean): String = { val sw = new StringWriter val visited = Collections.newSetFromMap(new util.IdentityHashMap[JavaGen, java.lang.Boolean]()) var sp = "" var gen = g while (gen != null && !visited.contains(gen)) { sw.append(sp) sw.append(gen.hashCode().toString).append(" ") sw.append(gen.description.replace("\n", "\n" + sp)) sw.append("\n") sp = sp + " " visited.add(gen) gen = genParents.getOrElse(gen, null) } if (showGensProducingSameFile) { val samePathGens = genParents.keys.filter(_.relativeFilePath == g.relativeFilePath) sw.append("Producing: " + g.relativeFilePath) if (samePathGens.nonEmpty) { sw.append("\n also produced by: \n") samePathGens.foreach(t => sw.append(describeGenerator(t, showGensProducingSameFile = false))) } } sw.toString } //</editor-fold> // run postponed generators, if any // some of the postponed generators may have been executed by concurrent threads, so check again here val postponedNotRun = postponedGenerators.toSeq.filter(gp => gp.shouldRunStrategy.check) postponedGenerators.clear() val postponedGeneratorsSize = postponedNotRun.size if (postponedGeneratorsSize > 0) { //noinspection ComparingUnrelatedTypes (should actually be OK?) if (generatorsCopy == postponedNotRun) { // couldn't make any progress, abort val msg = new StringWriter() msg.append("The following generators couldn't finish:\n") postponedNotRun.foreach( sg => msg.append(describeGenerator(sg, showGensProducingSameFile = true)).append("\n") ) cctx.errors.add(CMessage.error(null, CMessagePosition.NA, msg.toString)) handleErrors() } else { log.debug(s"Retrying $postponedGeneratorsSize generators") val postponedQueue = queue(postponedNotRun) // don't schedule children to run again on retries (have already been scheduled during this run) runGeneratorsAndHandleErrors(postponedQueue, runner) } } else { handleErrors() } } private def queue[T](i: Iterable[T]): immutable.Queue[T] = { val q = immutable.Queue[T]() q ++ i } private def handleErrors() { if (!cctx.errors.isEmpty) { EpigraphCompiler.renderErrors(cctx) throw new Exception("Build failed") // todo better integration with mvn/gradle/... } } }
{ "content_hash": "bb18a541630c0d8670ec1f99685c2101", "timestamp": "", "source": "github", "line_count": 416, "max_line_length": 117, "avg_line_length": 35.69711538461539, "alnum_prop": 0.6511784511784512, "repo_name": "SumoLogic/epigraph", "id": "e549a5d0621d747d3cc6add408d87af4d996e273", "size": "15443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/codegen/src/main/scala/ws/epigraph/java/EpigraphJavaGenerator.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "37668" }, { "name": "HTML", "bytes": "1261" }, { "name": "Java", "bytes": "3698452" }, { "name": "Lex", "bytes": "7018" }, { "name": "Scala", "bytes": "817541" }, { "name": "Shell", "bytes": "4933" } ], "symlink_target": "" }
package org.graphwalker.modelchecker; import com.google.common.base.CharMatcher; import org.graphwalker.core.model.Edge; import java.util.ArrayList; import java.util.List; /** * Created by krikar on 2015-11-08. */ public class EdgeChecker { private EdgeChecker() { } /** * Checks the edge for problems or any possible errors. * Any findings will be added to a list of strings. * <p/> * TODO: Implement a rule framework so that organisations and projects can create their own rule set (think model based code convention) * * @return A list of issues found in the edge */ static public List<String> hasIssues(Edge.RuntimeEdge edge) { List<String> issues = new ArrayList<>(ElementChecker.hasIssues(edge)); if (edge.getTargetVertex() == null) { issues.add("Edge must have a target vertex."); } if (edge.hasName() && CharMatcher.whitespace().matchesAnyOf(edge.getName())) { issues.add("Name of edge cannot have any white spaces."); } if (edge.getWeight() < 0 || edge.getWeight() > 1) { issues.add("The weight must be a value between 0 and 1."); } return issues; } }
{ "content_hash": "d6016f0487c79091b2c3777cc7d19d9e", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 138, "avg_line_length": 27.452380952380953, "alnum_prop": 0.6773633998265395, "repo_name": "GraphWalker/graphwalker-project", "id": "9420fab4addb3c98db2db3c989293427397973d0", "size": "1153", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "graphwalker-model-checker/src/main/java/org/graphwalker/modelchecker/EdgeChecker.java", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "8311" }, { "name": "CSS", "bytes": "1884" }, { "name": "HTML", "bytes": "348" }, { "name": "Java", "bytes": "1121867" }, { "name": "JavaScript", "bytes": "46375" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.4.1: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.4.1 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</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><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.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)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_extension_configuration.html">ExtensionConfiguration</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::ExtensionConfiguration Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1_extension_configuration.html">v8::ExtensionConfiguration</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ExtensionConfiguration</b>(int name_count, const char *names[]) (defined in <a class="el" href="classv8_1_1_extension_configuration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1_extension_configuration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ImplementationUtilities</b> (defined in <a class="el" href="classv8_1_1_extension_configuration.html">v8::ExtensionConfiguration</a>)</td><td class="entry"><a class="el" href="classv8_1_1_extension_configuration.html">v8::ExtensionConfiguration</a></td><td class="entry"><span class="mlabel">friend</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:46:56 for V8 API Reference Guide for node.js v0.4.1 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "f52f83f15cd37598c303aba57c8bc8be", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 409, "avg_line_length": 48.907407407407405, "alnum_prop": 0.6597879591063991, "repo_name": "v8-dox/v8-dox.github.io", "id": "20ec90165d785631e46636f35b378e9b19a1db86", "size": "5282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "a5e67ad/html/classv8_1_1_extension_configuration-members.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace lux { namespace { struct Level_list { std::vector<std::string> levels; }; sf2_structDef(Level_list, levels ) } sf2_structDef(Level_info, id, name, author, description, pack, environment_id, environment_brightness, environment_light_color, environment_light_direction, ambient_brightness, background_tint, music_id ) sf2_structDef(Level_pack_entry, aid, position ) sf2_structDef(Level_pack, name, description, level_ids, icon_texture_id, map_texture_id ) namespace { auto level_aid(const std::string& id) { return asset::AID{"level"_strid, id+".map"}; } void add_to_list(Engine& engine, const std::string& id) { auto level_list = engine.assets().load_maybe<Level_list>("cfg:my_levels"_aid).process(Level_list{}, [](auto p){return *p;}); if(std::find(level_list.levels.begin(), level_list.levels.end(), id) == level_list.levels.end()) { level_list.levels.push_back(id); engine.assets().save<Level_list>("cfg:my_levels"_aid, level_list); } } constexpr auto epsilon = 0.00001f; template<class T> bool is_vec_same(const T& lhs, const T& rhs) { return glm::all(glm::lessThan(glm::abs(lhs-rhs), T(epsilon))); } } bool Level_info::operator==(const Level_info& rhs)const noexcept { return id==rhs.id && name==rhs.name && author==rhs.author && description==rhs.description && pack==rhs.pack && environment_id==rhs.environment_id && std::abs(environment_brightness-rhs.environment_brightness)<epsilon && is_vec_same(environment_light_color, rhs.environment_light_color) && is_vec_same(environment_light_direction, rhs.environment_light_direction) && std::abs(ambient_brightness-rhs.ambient_brightness)<epsilon && is_vec_same(background_tint, rhs.background_tint) && music_id==rhs.music_id; } auto list_local_levels(Engine& engine) -> std::vector<Level_info_ptr> { auto level_list = engine.assets().load<Level_list>("cfg:levels"_aid); auto my_level_list = engine.assets().load_maybe<Level_list>("cfg:my_levels"_aid).process(Level_list{}, [](auto p){return *p;}); auto ret = std::vector<Level_info_ptr>(); ret.reserve(level_list->levels.size() + my_level_list.levels.size()); for(auto& lid : level_list->levels) { ret.emplace_back(engine.assets().load<Level_info>(level_aid(lid))); } for(auto& lid : my_level_list.levels) { ret.emplace_back(engine.assets().load<Level_info>(level_aid(lid))); } return ret; } auto get_level(Engine& engine, const std::string& id) -> Level_info_ptr { return engine.assets().load<Level_info>(level_aid(id)); } auto load_level(Engine& engine, ecs::Entity_manager& ecs, const std::string& id) -> util::maybe<Level_info> { auto data = engine.assets().load_raw(level_aid(id)); if(data.is_nothing()) { return util::nothing(); } auto& stream = data.get_or_throw(); Level_info level_data; sf2::deserialize_json(stream, [&](auto& msg, uint32_t row, uint32_t column) { ERROR("Error parsing LevelData from "<<id<<" at "<<row<<":"<<column<<": "<<msg); }, level_data); ecs.read(stream, true); return level_data; } void save_level(Engine& engine, ecs::Entity_manager& ecs, const Level_info& level) { auto stream = engine.assets().save_raw(level_aid(level.id)); sf2::serialize_json(stream, level); stream<<std::endl; // line-break and flush ecs.write(stream, +[](ecs::Component_type comp) { return comp==sys::physics::Transform_comp::type() || comp==ecs::blueprint_comp_id || comp==sys::graphic::Terrain_data_comp::type(); }); stream.close(); add_to_list(engine, level.id); } auto Level_pack::find_level(std::string id)const -> util::maybe<int> { auto r = std::find_if(level_ids.begin(), level_ids.end(), [id](auto& l) { return l.aid ==id; }); return r!=level_ids.end() ? util::just(static_cast<int>(std::distance(level_ids.begin(),r))) : util::nothing(); } auto list_level_packs(Engine& engine) -> std::vector<Level_pack_ptr> { auto aids = engine.assets().list("level_pack"_strid); auto packs = std::vector<Level_pack_ptr>{}; packs.reserve(aids.size()); for(auto& aid : aids) { packs.emplace_back(get_level_pack(engine, aid.name())); } return packs; } auto get_level_pack(Engine& engine, const std::string& id) -> Level_pack_ptr { return engine.assets().load<Level_pack>(asset::AID{"level_pack"_strid, id}); } auto get_next_level(Engine& engine, const std::string& level_id) -> util::maybe<std::string> { auto level = get_level(engine, level_id); if(!level || level->pack.empty()) return util::nothing(); auto pack = get_level_pack(engine, level->pack); if(!pack) return util::nothing(); auto level_idx = pack->find_level(level_id); if(level_idx.is_nothing()) return util::nothing(); auto next_idx = static_cast<std::size_t>(level_idx.get_or_throw()+1); if(next_idx >= pack->level_ids.size()) return util::nothing(); return pack->level_ids.at(next_idx).aid; } namespace { struct Savegame { std::unordered_set<std::string> unlocked_levels; }; sf2_structDef(Savegame, unlocked_levels ) auto load_savegame(Engine& engine) -> const Savegame& { static auto savegame = engine.assets().load_maybe<Savegame>(asset::AID{"cfg"_strid, "savegame"}); if(savegame.is_nothing()) { auto new_savegame = Savegame{}; engine.assets().save(asset::AID{"cfg"_strid, "savegame"}, new_savegame); savegame = engine.assets().load_maybe<Savegame>(asset::AID{"cfg"_strid, "savegame"}); } return *savegame.get_or_throw(); } } void unlock_level(Engine& engine, const std::string& id) { auto savegame_copy = load_savegame(engine); savegame_copy.unlocked_levels.emplace(id); engine.assets().save(asset::AID{"cfg"_strid, "savegame"}, savegame_copy); } void unlock_next_levels(Engine& engine, const std::string& id) { get_next_level(engine, id).process([&](auto& next) { auto savegame_copy = load_savegame(engine); savegame_copy.unlocked_levels.emplace(next); engine.assets().save(asset::AID{"cfg"_strid, "savegame"}, savegame_copy); }); } auto is_level_locked(Engine& engine, const std::string& id) -> bool { const auto& unlocked_levels = load_savegame(engine).unlocked_levels; return unlocked_levels.find(id)==unlocked_levels.end(); } auto list_remote_levels(Engine&, int32_t count, int32_t offset) -> std::vector<Level_info> { // TODO return {}; } auto download_level(Engine&, const std::string& id) -> std::future<void> { // TODO std::promise<void> dummy; auto future = dummy.get_future(); dummy.set_value(); return future; } void upload_level(Engine&, const std::string& id) { // TODO } }
{ "content_hash": "7b03378c115099beee776dcbf7e5875b", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 129, "avg_line_length": 29.448275862068964, "alnum_prop": 0.6497365339578455, "repo_name": "lowkey42/teamproject", "id": "8504709e6caaff905e8c5c92ec662b784fb6387a", "size": "7074", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/game/level.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "759915" }, { "name": "CMake", "bytes": "102816" }, { "name": "GLSL", "bytes": "28632" } ], "symlink_target": "" }
<?php namespace Chamilo\Application\Weblcms\Tool\Implementation\Teams\Exception; use Chamilo\Application\Weblcms\Tool\Implementation\Teams\Manager; use Chamilo\Libraries\Architecture\Exceptions\UserException; use Chamilo\Libraries\Translation\Translation; /*** * @package Chamilo\Application\Weblcms\Tool\Implementation\Teams\Exception * @author Sven Vanpoucke - Hogeschool Gent */ class TooManyUsersException extends UserException { /** * TooManyUsersException constructor. */ public function __construct() { parent::__construct( Translation::getInstance()->getTranslator()->trans("TooManyUsersException", [], Manager::class) ); } }
{ "content_hash": "6a86daf7415a0b8d80be778c2c2aaf1f", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 107, "avg_line_length": 28.875, "alnum_prop": 0.733044733044733, "repo_name": "cosnics/cosnics", "id": "4e93747a63c573e93bf3a8d14129515855e622ff", "size": "693", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Chamilo/Application/Weblcms/Tool/Implementation/Teams/Exception/TooManyUsersException.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "262730" }, { "name": "C", "bytes": "12354" }, { "name": "CSS", "bytes": "1334431" }, { "name": "CoffeeScript", "bytes": "41023" }, { "name": "Gherkin", "bytes": "24033" }, { "name": "HTML", "bytes": "1016812" }, { "name": "Hack", "bytes": "424" }, { "name": "JavaScript", "bytes": "10768095" }, { "name": "Less", "bytes": "331253" }, { "name": "Makefile", "bytes": "3221" }, { "name": "PHP", "bytes": "23623996" }, { "name": "Python", "bytes": "2408" }, { "name": "Ruby", "bytes": "618" }, { "name": "SCSS", "bytes": "163532" }, { "name": "Shell", "bytes": "7965" }, { "name": "Smarty", "bytes": "15750" }, { "name": "Twig", "bytes": "388197" }, { "name": "TypeScript", "bytes": "123212" }, { "name": "Vue", "bytes": "454138" }, { "name": "XSLT", "bytes": "43009" } ], "symlink_target": "" }
package com.aries.library.fast.demo.base; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import com.aries.library.fast.demo.touch.ItemTouchHelperAdapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import java.util.Collections; import java.util.List; /** * @Author: AriesHoo on 2018/8/10 10:04 * @E-Mail: AriesHoo@126.com * Function: 实现拖拽排序功能 * Description: */ public abstract class BaseItemTouchQuickAdapter<T, K extends BaseViewHolder> extends BaseQuickAdapter<T, K> implements ItemTouchHelperAdapter { public BaseItemTouchQuickAdapter(@LayoutRes int layoutResId, @Nullable List<T> data) { super(layoutResId, data); // this.mData = data == null ? new ArrayList<>() : data; // if (layoutResId != 0) { // this.mLayoutResId = layoutResId; // } } public BaseItemTouchQuickAdapter(@Nullable List<T> data) { this(0, data); } public BaseItemTouchQuickAdapter(@LayoutRes int layoutResId) { this(layoutResId, null); } @Override public void onItemMove(int fromPosition, int toPosition) { if (fromPosition < 0 || toPosition < 0 || toPosition >= getData().size()) { return; } Collections.swap(getData(), fromPosition, toPosition); notifyItemMoved(fromPosition, toPosition); } @Override public void onItemSwiped(int position) { } }
{ "content_hash": "f3cc6fdf3b45b9f0e85734db2fbea680", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 143, "avg_line_length": 29.74, "alnum_prop": 0.6879623402824478, "repo_name": "AriesHoo/FastLib", "id": "eaa899286e4a27e0dd1bcde22b202b689753700e", "size": "1503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/aries/library/fast/demo/base/BaseItemTouchQuickAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "644681" } ], "symlink_target": "" }
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc2667.TestRobot.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc2667.TestRobot.Robot; /** * */ public class RaiseElevator extends Command { public RaiseElevator() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.elevator); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=INITIALIZE Robot.elevator.enable(); Robot.elevator.setSetpoint(1.5); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=INITIALIZE } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=ISFINISHED return Robot.elevator.onTarget(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=ISFINISHED } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
{ "content_hash": "304cc69d289e7a24aad0b86701aa9a91", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 79, "avg_line_length": 31.74137931034483, "alnum_prop": 0.7159152634437805, "repo_name": "Team2667/Team2667-2015", "id": "df1dfd1e30b730cd77d44d97e0d62ba706ca2269", "size": "1841", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/usfirst/frc2667/TestRobot/commands/RaiseElevator.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "43210" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0c17ba102cff72c81d3daf37566b6863", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f68db2170e2f6ad40ae42dc49eed3667d0990089", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Aconitum/Aconitum lasiocarpum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict'; const connection = require('mongoose').connection; const state = require('mongoose/lib/connectionstate'); const onOpen = (fn) => { if(connection.readyState === state.connected) return fn(); else { return new Promise((resolve, reject) => { connection.once('open', () => fn().then(resolve, reject)); }); } }; module.exports = { drop() { return () => { onOpen(() => connection.dropDatabase()); }; }, dropCollection(name) { return () => { onOpen(() => { const collection = connection.collections[name]; return collection ? collection.drop() : Promise.resolve(); }); }; } };
{ "content_hash": "2aa2bd99880546fe232089e61758df48", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 66, "avg_line_length": 22.896551724137932, "alnum_prop": 0.5783132530120482, "repo_name": "TheLunchBunch/lunch", "id": "03c7d32cda09859369983b4179c60c6f8500e060", "size": "664", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "test/db.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2816" }, { "name": "HTML", "bytes": "7246" }, { "name": "JavaScript", "bytes": "37635" } ], "symlink_target": "" }
package limits import ( "errors" "fmt" "github.com/m3db/m3/src/x/instrument" ) type limitOpts struct { iOpts instrument.Options docsLimitOpts LookbackLimitOptions bytesReadLimitOpts LookbackLimitOptions diskSeriesReadLimitOpts LookbackLimitOptions diskAggregateDocsLimitOpts LookbackLimitOptions sourceLoggerBuilder SourceLoggerBuilder } // NewOptions creates limit options with default values. func NewOptions() Options { return &limitOpts{ sourceLoggerBuilder: &sourceLoggerBuilder{}, } } // Validate validates the options. func (o *limitOpts) Validate() error { if o.iOpts == nil { return errors.New("limit options invalid: no instrument options") } if err := o.docsLimitOpts.validate(); err != nil { return fmt.Errorf("doc limit options invalid: %w", err) } if err := o.bytesReadLimitOpts.validate(); err != nil { return fmt.Errorf("bytes limit options invalid: %w", err) } return nil } // SetInstrumentOptions sets the instrument options. func (o *limitOpts) SetInstrumentOptions(value instrument.Options) Options { opts := *o opts.iOpts = value return &opts } // InstrumentOptions returns the instrument options. func (o *limitOpts) InstrumentOptions() instrument.Options { return o.iOpts } // SetDocsLimitOpts sets the doc limit options. func (o *limitOpts) SetDocsLimitOpts(value LookbackLimitOptions) Options { opts := *o opts.docsLimitOpts = value return &opts } // DocsLimitOpts returns the doc limit options. func (o *limitOpts) DocsLimitOpts() LookbackLimitOptions { return o.docsLimitOpts } // SetBytesReadLimitOpts sets the byte read limit options. func (o *limitOpts) SetBytesReadLimitOpts(value LookbackLimitOptions) Options { opts := *o opts.bytesReadLimitOpts = value return &opts } // BytesReadLimitOpts returns the byte read limit options. func (o *limitOpts) BytesReadLimitOpts() LookbackLimitOptions { return o.bytesReadLimitOpts } // SetDiskSeriesReadLimitOpts sets the disk ts read limit options. func (o *limitOpts) SetDiskSeriesReadLimitOpts(value LookbackLimitOptions) Options { opts := *o opts.diskSeriesReadLimitOpts = value return &opts } // DiskSeriesReadLimitOpts returns the disk ts read limit options. func (o *limitOpts) DiskSeriesReadLimitOpts() LookbackLimitOptions { return o.diskSeriesReadLimitOpts } // SetDiskSeriesReadLimitOpts sets the disk ts read limit options. func (o *limitOpts) SetAggregateDocsLimitOpts(value LookbackLimitOptions) Options { opts := *o opts.diskAggregateDocsLimitOpts = value return &opts } // DiskSeriesReadLimitOpts returns the disk ts read limit options. func (o *limitOpts) AggregateDocsLimitOpts() LookbackLimitOptions { return o.diskAggregateDocsLimitOpts } // SetSourceLoggerBuilder sets the source logger. func (o *limitOpts) SetSourceLoggerBuilder(value SourceLoggerBuilder) Options { opts := *o opts.sourceLoggerBuilder = value return &opts } // SourceLoggerBuilder sets the source logger. func (o *limitOpts) SourceLoggerBuilder() SourceLoggerBuilder { return o.sourceLoggerBuilder }
{ "content_hash": "0d3f51753e2558b7bc29224e0873c0a9", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 84, "avg_line_length": 27.292035398230087, "alnum_prop": 0.7668612191958496, "repo_name": "m3db/m3db", "id": "ec19b8404cf83646604f357ff6ac5953b63a5995", "size": "4206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dbnode/storage/limits/options.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2136" }, { "name": "Dockerfile", "bytes": "3601" }, { "name": "Go", "bytes": "5968763" }, { "name": "HTML", "bytes": "11315" }, { "name": "JavaScript", "bytes": "25" }, { "name": "Makefile", "bytes": "27412" }, { "name": "Shell", "bytes": "16249" }, { "name": "Thrift", "bytes": "11122" } ], "symlink_target": "" }
/** * @jsx React.DOM */ /* not used but thats how you can use touch events * */ //React.initializeTouchEvents(true); /* not used but thats how you can use animation and other transition goodies * */ var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; /** * we will use yes for true * we will use no for false * * React has some built ins that rely on state being true/false like classSet() * and these will not work with yes/no but can easily be modified / reproduced * * this single app uses the yes/no var so if you want you can switch back to true/false * * */ var yes = 'yes', no = 'no'; //var yes = true, no = false; /* bootstrap components * */ var Flash = ReactBootstrap.Alert; var Btn = ReactBootstrap.Button; var Modal = ReactBootstrap.Modal; /* create the container object * */ var snowUI = { passthrough: {}, //special for passing functions between components }; /* create flash message * */ snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash', getInitialState: function() { return { isVisible: true }; }, getDefaultProps: function() { return ({showclass:'info'}); }, render: function() { console.log(this.props); if(!this.state.isVisible) return null; var message = this.props.message ? this.props.message : this.props.children; return ( Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash}, React.DOM.p(null, message) ) ); }, dismissFlash: function() { this.setState({isVisible: false}); } }); /* my little man component * simple example * */ snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan', getDefaultProps: function() { return ({divstyle:{float:'right',}}); }, render: function() { return this.transferPropsTo( React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}}) ); } }); //loading div snowUI.loading = React.createClass({displayName: 'loading', getInitialState: function () { return ({active:false}) }, componentDidMount: function() { var _this = this if (this.isMounted()) { snowUI.passthrough.loader = {} snowUI.passthrough.loader.start = function() { console.log('start loading passthrough') this.setState({active:true}); }.bind(this) snowUI.passthrough.loader.stop = function() { console.log('stop loading passthrough') this.setState({active:false}); }.bind(this) } }, render: function() { var loadme = function() { if(this.state.active) { return (React.DOM.div({key: "load", className: "loader"}, "Loading ", React.DOM.br(null), React.DOM.div({id: "loadgif"}) )); } else { return false } }.bind(this) return ( React.DOM.div(null, ReactCSSTransitionGroup({transitionName: "loading"}, loadme() ) ) ); } }); React.renderComponent(snowUI.loading(null), document.getElementById('snowcoins-loader')); //wallet component snowUI.wallet = React.createClass({displayName: 'wallet', render: function() { //this.props.methods.loaderStop(); console.log('wallet component') return ( React.DOM.div(null) ); } }); //receive component snowUI.receive = React.createClass({displayName: 'receive', render: function() { console.log('receive component') this.props.methods.loaderStop(); return ( React.DOM.div(null) ) } }); //settings component snowUI.settings = React.createClass({displayName: 'settings', render: function() { console.log('settings') this.props.methods.loaderStop(); return ( React.DOM.div(null) ); } }); //inq component snowUI.inq = React.createClass({displayName: 'inq', render: function() { console.log('inqueue') this.props.methods.loaderStop(); return ( React.DOM.div(null) ); } }); //wallet select snowUI.walletSelect = React.createClass({displayName: 'walletSelect', componentDidMount: function() { this.updateSelect(); }, componentDidUpdate: function() { this.updateSelect(); }, componentWillUpdate: function() { $("#walletselect").selectbox("detach"); }, updateSelect: function() { var _this = this $("#walletselect").selectbox({ onChange: function (val, inst) { _this.props.route(val) }, effect: "fade" }); //console.log('wallet select updated') }, render: function() { var wallets; if(this.props.wally instanceof Array) { var wallets = this.props.wally.map(function (w) { return ( React.DOM.option({key: w.key, value: snowPath.wallet + '/' + w.key}, w.name) ); }); } if(this.props.section === snowPath.wallet) { var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet; } else { var _df = this.props.section; } //console.log(_df) return this.transferPropsTo( React.DOM.div({className: "list"}, React.DOM.div({className: "walletmsg", style: {display:'none'}}), React.DOM.select({onChange: this.props.route, id: "walletselect", value: _df}, wallets, React.DOM.optgroup(null), React.DOM.option({value: snowPath.wallet + '/new'}, snowtext.menu.plus.name), React.DOM.option({value: snowPath.wallet}, snowtext.menu.list.name), React.DOM.option({value: snowPath.receive}, snowtext.menu.receive.name), React.DOM.option({value: snowPath.settings}, snowtext.menu.settings.name), React.DOM.option({value: snowPath.inq}, snowtext.menu.inqueue.name) ) ) ); } }); var UI = React.createClass({displayName: 'UI', getInitialState: function() { /** * initialize the app * the plan is to keep only active references in root state. * we should use props for the fill outs * */ return { section: this.props.section || 'wallet', moon: this.props.moon || false, wallet: this.props.wallet || false, mywallets: [], }; }, componentDidMount: function() { //grab our initial data $.get("/api/snowcoins/local/contacts/?setnonce=true") .done(function( resp,status,xhr ) { _csrf = xhr.getResponseHeader("x-snow-token"); console.log('wally',resp.wally) this.setState({mywallets:resp.wally}); //add the loader }.bind(this)); }, componentWillReceiveProps: function(nextProps) { if(nextProps.section)this.setState({section:nextProps.section}); if(nextProps.moon)this.setState({moon:nextProps.moon}); if(nextProps.wallet)this.setState({wallet:nextProps.wallet}); //wallet list if(nextProps.mywallets)this.setState({mywallets:nextProps.mywallets}); //if(nextProps.section)this.loaderStart() return false; }, componentWillUpdate: function() { this.loaderStart() return false }, updateState: function(prop,value) { this.setState({prop:value}); return false }, loaderStart: function() { if(typeof snowUI.passthrough.loader === 'object') snowUI.passthrough.loader.start() return false }, loaderStop: function() { if(typeof snowUI.passthrough.loader === 'object') snowUI.passthrough.loader.stop() return false }, changeTheme: function() { var mbody = $('body'); if(mbody.hasClass('themeable-snowcoinslight')==true) { mbody.removeClass('themeable-snowcoinslight'); } else { mbody.addClass('themeable-snowcoinslight'); } return false }, valueRoute: function(route) { bone.router.navigate(snowPath.root + route, {trigger:true}); console.log(snowPath.root + route) return false }, hrefRoute: function(route) { route.preventDefault(); bone.router.navigate(snowPath.root + $(route.target)[0].pathname, {trigger:true}); console.log(snowPath.root + $(route.target)[0].pathname) return false }, eggy: function() { eggy(); }, render: function() { var methods = { hrefRoute: this.hrefRoute, valueRoute: this.valueRoute, updateState: this.updateState, loaderStart: this.loaderStart, loaderStop: this.loaderStop, } var comp = {} comp[snowPath.wallet]=snowUI.wallet; comp[snowPath.receive]=snowUI.receive; comp[snowPath.settings]=snowUI.settings; comp[snowPath.inq]=snowUI.inq; var mycomp = comp[this.state.section] return ( React.DOM.div(null, React.DOM.div({id: "snowpi-body"}, React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}), React.DOM.div({id: "walletbar", className: "affix"}, React.DOM.div({className: "wallet"}, React.DOM.div({className: "button-group"}, Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name), React.DOM.ul({className: "dropdown-menu", role: "menu"}, React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet + '/new'}, snowtext.menu.plus.name)), React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet}, snowtext.menu.list.name)), React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.receive}, snowtext.menu.receive.name)), React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.settings}, snowtext.menu.settings.name)), React.DOM.li({className: "divider"}), React.DOM.li({className: "nav-item-snowcat"}), React.DOM.li({className: "divider"}), React.DOM.li(null, React.DOM.div(null, React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.inq, className: "nav-item-inq"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))), React.DOM.div({className: "clearfix"}) ) ) ) ) ), snowUI.walletSelect({route: this.valueRoute, section: this.state.section, wallet: this.state.wallet, wally: this.state.mywallets}), React.DOM.div({className: "logo", onClick: this.eggy}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"})) ), React.DOM.div({className: "container-fluid"}, React.DOM.div({id: "menuspy", className: "dogemenu col-xs-1 col-md-2", 'data-spy': "affix", 'data-offset-top': "0"} ), React.DOM.div({id: "menuspyhelper", className: "dogemenu col-xs-1 col-md-2"}), React.DOM.div({className: "dogeboard col-xs-11 col-md-10"}, snowUI.AppInfo(null), React.DOM.div({className: "dogeboard-left col-xs-12 col-md-12"}, mycomp({methods: methods}) ) ) ) /* end snowpi-body */ ) ) ); } }); //app info snowUI.AppInfo = React.createClass({displayName: 'AppInfo', render: function() { return ( React.DOM.div({id: "easter-egg", style: {display:'none'}}, React.DOM.div(null, React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Get Snowcoins"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")), React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz")) ), React.DOM.h4(null, "Built With"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose")) ), React.DOM.h4(null, "Donate"), React.DOM.div({className: "row"}, React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")), React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")), React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")), React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")), React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin")) ) ), React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Digital Coin Wallets"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin ")) ), React.DOM.h4(null, "Links"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/snowcoins", target: "_blank"}, "/r/snowcoins")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/dogecoin", target: "_blank"}, "/r/dogecoin")) ) ), React.DOM.div({className: "clearfix"}) ) ) ); } });
{ "content_hash": "623461ad170628796eeff280e7643cae", "timestamp": "", "source": "github", "line_count": 449, "max_line_length": 295, "avg_line_length": 37.783964365256125, "alnum_prop": 0.6391983495431771, "repo_name": "inquisive/wallet-manager", "id": "e73e1c37d2df1545f534c37b1412eaa731157df6", "size": "16968", "binary": false, "copies": "1", "ref": "refs/heads/v1.0.1", "path": "public/js/.module-cache/bf7ca71d6fb3bcab97bab413862bccbcaef7f92c.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "8949" }, { "name": "CSS", "bytes": "315113" }, { "name": "JavaScript", "bytes": "11425194" } ], "symlink_target": "" }
from utils import load_yaml_fixture, set_recent_dates, set_archive_dates, filter_by_tag, filter_by_expr, ModelTestCase class RecentURLPatternTestCase(ModelTestCase): fixtures = ['users.yaml', 'recent.yaml'] @classmethod def setUpClass(cls): set_recent_dates('reference.yaml') def test_recent_reports_returns_page(self): self.request_status('/report/', 200) def test_recent_region_reports_returns_page(self): self.request_status('/report/?region=all', 200) def test_recent_concelho_reports_returns_page(self): self.request_status('/report/?concelho=all', 200) def test_recent_island_reports_returns_page(self): self.request_status('/report/?island=corvo', 200) class RecentTestCase(ModelTestCase): fixtures = ['users.yaml', 'recent.yaml'] @classmethod def setUpClass(cls): set_recent_dates('reference.yaml') def test_recent_returns_records(self): self.request_fetches_all('/report/', 'recent.yaml') def test_recent_region_all_return_records(self): self.request_fetches_all('/report/?region=all', 'recent.yaml') def test_recent_concelho_all_return_records(self): self.request_fetches_all('/report/?region=all', 'recent.yaml') def test_recent_species_all_return_records(self): self.request_fetches_all('/report/?region=all&species=all', 'recent.yaml') def test_recent_region_return_records(self): self.request_matches('/report/?region=lisboa&species=all', filter_by_tag(load_yaml_fixture('recent.yaml'), 'region:lisboa')) def test_recent_concelho_return_records(self): self.request_matches('/report/?concelho=loures&species=all', filter_by_tag(load_yaml_fixture('recent.yaml'), 'concelho:loures')) def test_recent_concelho_iou_species_name_return_records(self): self.request_matches('/report/?concelho=loures&species=pied flycatcher', filter_by_tag(filter_by_tag(load_yaml_fixture('recent.yaml'), 'concelho:loures'), 'pied flycatcher')) def test_recent_concelho_por_species_name_return_records(self): self.request_matches('/report/?concelho=loures&species=papa moscas', filter_by_tag(filter_by_tag(load_yaml_fixture('recent.yaml'), 'concelho:loures'), 'papa moscas')) def test_recent_concelho_latin_species_name_return_records(self): self.request_matches('/report/?concelho=loures&species=ficedula hypoleuca', filter_by_tag(filter_by_tag(load_yaml_fixture('recent.yaml'), 'concelho:loures'), 'ficedula hypoleuca')) class ArchiveURLPatternTestCase(ModelTestCase): fixtures = ['users.yaml', 'archive.yaml'] @classmethod def setUpClass(cls): set_archive_dates('reference.yaml') def test_archive_year_returns_page(self): self.request_status('/report/?region=all&start=2010', 200) def test_archive_month_returns_page(self): self.request_status('/report/?region=all&start=2010-02', 200) def test_archive_year_species_returns_page(self): self.request_status('/report/?region=all&species=all&start=2010', 200) def test_archive_month_species_returns_page(self): self.request_status('/report/?region=all&species=all&start=2010-02', 200)
{ "content_hash": "8dcbb5ad0a3147c5800c204b991953c1", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 118, "avg_line_length": 41.11904761904762, "alnum_prop": 0.6543138390272148, "repo_name": "pombredanne/reed", "id": "ba6ac7138c183f71b959aa38efed50a227c70ca3", "size": "3454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reed/tests/news.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#if !defined(CETTY_CHANNEL_ABSTRACTCHANNELSINK_H) #define CETTY_CHANNEL_ABSTRACTCHANNELSINK_H /* * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com) * Distributed under under the Apache License, version 2.0 (the "License"). */ #include "cetty/channel/ChannelSink.h" namespace cetty { namespace channel { /** * A skeletal {@link ChannelSink} implementation. * * * @author <a href="http://gleamynode.net/">Trustin Lee</a> * * @author <a href="mailto:frankee.zhou@gmail.com">Frankee Zhou</a> */ class AbstractChannelSink : public ChannelSink { public: virtual ~AbstractChannelSink() {} virtual void eventSunk(const ChannelPipeline& pipeline, const ChannelEvent& e); /** * Sends an {@link ExceptionEvent} upstream with the specified * <tt>cause</tt>. * * @param event the {@link ChannelEvent} which caused a * {@link ChannelHandler} to raise an exception * @param cause the exception raised by a {@link ChannelHandler} */ virtual void exceptionCaught(const ChannelPipeline& pipeline, const ChannelEvent& e, const ChannelPipelineException& cause); }; }} #endif //#if !defined(CETTY_CHANNEL_ABSTRACTCHANNELSINK_H)
{ "content_hash": "e31cfc4e506a238bcbdd7515e628de35", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 83, "avg_line_length": 29.045454545454547, "alnum_prop": 0.6643192488262911, "repo_name": "frankee/Cetty", "id": "6d62d725d6ff52c58f091df96d99b7202672f8b4", "size": "1901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/cetty/channel/AbstractChannelSink.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "30104" }, { "name": "C++", "bytes": "2125937" }, { "name": "CMake", "bytes": "16348" } ], "symlink_target": "" }
/* * File: PythonAPICache.cpp * Author: alain * * Created on May 28, 2017, 10:49 PM */ #include <Surelog/API/PythonAPI.h> #include <Surelog/Cache/Cache.h> #include <Surelog/Cache/PythonAPICache.h> #include <Surelog/Cache/python_api_generated.h> #include <Surelog/CommandLine/CommandLineParser.h> #include <Surelog/Common/FileSystem.h> #include <Surelog/ErrorReporting/ErrorContainer.h> #include <Surelog/Library/Library.h> #include <Surelog/SourceCompile/CompilationUnit.h> #include <Surelog/SourceCompile/CompileSourceFile.h> #include <Surelog/SourceCompile/Compiler.h> #include <Surelog/SourceCompile/ParseFile.h> #include <Surelog/SourceCompile/PreprocessFile.h> #include <Surelog/SourceCompile/PythonListen.h> #include <Surelog/SourceCompile/SymbolTable.h> #include <Surelog/Utils/StringUtils.h> #include <antlr4-runtime.h> #include <flatbuffers/util.h> #include <sys/stat.h> #include <sys/types.h> #include <cstdio> #include <ctime> #include <filesystem> namespace SURELOG { static std::string FlbSchemaVersion = "1.0"; PythonAPICache::PythonAPICache(PythonListen* listener) : m_listener(listener) {} PathId PythonAPICache::getCacheFileId_(PathId sourceFileId) const { ParseFile* parseFile = m_listener->getParseFile(); if (!sourceFileId) sourceFileId = parseFile->getFileId(LINE1); if (!sourceFileId) return BadPathId; FileSystem* const fileSystem = FileSystem::getInstance(); CommandLineParser* clp = m_listener->getCompileSourceFile()->getCommandLineParser(); SymbolTable* symbolTable = m_listener->getCompileSourceFile()->getSymbolTable(); const std::string& libName = m_listener->getCompileSourceFile()->getLibrary()->getName(); return fileSystem->getPythonCacheFile(clp->fileunit(), sourceFileId, libName, symbolTable); } bool PythonAPICache::restore_(PathId cacheFileId, const std::vector<char>& content) { if (!cacheFileId || content.empty()) return false; const PYTHONAPICACHE::PythonAPICache* ppcache = PYTHONAPICACHE::GetPythonAPICache(content.data()); SymbolTable canonicalSymbols; restoreSymbols(ppcache->m_symbols(), &canonicalSymbols); restoreErrors(ppcache->m_errors(), &canonicalSymbols, m_listener->getCompileSourceFile()->getErrorContainer(), m_listener->getCompileSourceFile()->getSymbolTable()); return true; } bool PythonAPICache::checkCacheIsValid_( PathId cacheFileId, const std::vector<char>& content) const { if (!cacheFileId || content.empty()) return false; if (!PYTHONAPICACHE::PythonAPICacheBufferHasIdentifier(content.data())) { return false; } FileSystem* const fileSystem = FileSystem::getInstance(); SymbolTable* symbolTable = m_listener->getCompileSourceFile()->getSymbolTable(); const PYTHONAPICACHE::PythonAPICache* ppcache = PYTHONAPICACHE::GetPythonAPICache(content.data()); auto header = ppcache->m_header(); const PathId scriptFileId = fileSystem->toPathId( fileSystem->remap(ppcache->m_python_script_file()->string_view()), symbolTable); std::filesystem::file_time_type ct = fileSystem->modtime(cacheFileId); std::filesystem::file_time_type ft = fileSystem->modtime(scriptFileId); if (ft == std::filesystem::file_time_type::min()) { return false; } if (ct == std::filesystem::file_time_type::min()) { return false; } if (ct < ft) { return false; } return checkIfCacheIsValid(header, FlbSchemaVersion, cacheFileId, m_listener->getParseFile()->getFileId(LINE1)); } bool PythonAPICache::checkCacheIsValid_(PathId cacheFileId) const { std::vector<char> content; return cacheFileId && openFlatBuffers(cacheFileId, content) && checkCacheIsValid_(cacheFileId, content); } bool PythonAPICache::isValid() const { return checkCacheIsValid_(getCacheFileId_(BadPathId)); } bool PythonAPICache::restore() { bool cacheAllowed = m_listener->getCompileSourceFile() ->getCommandLineParser() ->cacheAllowed(); if (!cacheAllowed) return false; PathId cacheFileId = getCacheFileId_(BadPathId); std::vector<char> content; return cacheFileId && openFlatBuffers(cacheFileId, content) && checkCacheIsValid_(cacheFileId, content) && restore_(cacheFileId, content); } bool PythonAPICache::save() { CommandLineParser* clp = m_listener->getCompileSourceFile()->getCommandLineParser(); if (!clp->cacheAllowed()) return false; PathId cacheFileId = getCacheFileId_(BadPathId); if (!cacheFileId) return false; FileSystem* const fileSystem = FileSystem::getInstance(); ParseFile* parseFile = m_listener->getParseFile(); flatbuffers::FlatBufferBuilder builder(1024); /* Create header section */ auto header = createHeader(builder, FlbSchemaVersion); std::string pythonScriptFile = PythonAPI::getListenerScript(); auto scriptFile = builder.CreateString(pythonScriptFile); /* Cache the errors and canonical symbols */ ErrorContainer* errorContainer = m_listener->getCompileSourceFile()->getErrorContainer(); PathId subjectFileId = m_listener->getParseFile()->getFileId(LINE1); SymbolTable canonicalSymbols; auto errorCache = cacheErrors( builder, &canonicalSymbols, errorContainer, *m_listener->getCompileSourceFile()->getSymbolTable(), subjectFileId); auto symbolVec = builder.CreateVectorOfStrings(canonicalSymbols.getSymbols()); /* Create Flatbuffers */ auto ppcache = PYTHONAPICACHE::CreatePythonAPICache( builder, header, scriptFile, errorCache, symbolVec); FinishPythonAPICacheBuffer(builder, ppcache); /* Save Flatbuffer */ return saveFlatbuffers(builder, cacheFileId, m_listener->getCompileSourceFile()->getSymbolTable()); } } // namespace SURELOG
{ "content_hash": "ec97e3ee2e50939e88809db5e979d1d0", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 80, "avg_line_length": 34.48823529411764, "alnum_prop": 0.7187446699641822, "repo_name": "chipsalliance/Surelog", "id": "32158d97e1f69edca4232541a54a286cff1c505c", "size": "6430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Cache/PythonAPICache.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "155641" }, { "name": "C", "bytes": "3114" }, { "name": "C++", "bytes": "2808920" }, { "name": "CMake", "bytes": "41750" }, { "name": "Forth", "bytes": "81" }, { "name": "Makefile", "bytes": "4820" }, { "name": "Nix", "bytes": "784" }, { "name": "Python", "bytes": "110922" }, { "name": "SWIG", "bytes": "351" }, { "name": "Shell", "bytes": "1349" }, { "name": "Slash", "bytes": "37570" }, { "name": "SystemVerilog", "bytes": "872314" }, { "name": "Tcl", "bytes": "68865" }, { "name": "V", "bytes": "1092" }, { "name": "Verilog", "bytes": "495242" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FeedReader.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FeedReader.Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6b59b07a-7672-488a-b045-ef1c6418bdb7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "63584b28d3ad978ceddbe3a0b7de5277", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.02777777777778, "alnum_prop": 0.7451957295373666, "repo_name": "joseph-iussa/feed-reader", "id": "e1874b1f6c5bb8c6d8066906e3ad966ecfcd05c4", "size": "1408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FeedReader.UnitTests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "49838" } ], "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>br.com.triplify</groupId> <artifactId>br.com.triplify</artifactId> <version>0.0.1</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <properties> <spring.version>3.0.5.RELEASE</spring.version> <jdk.version>1.6</jdk.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Apache Commons Upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- Apache Commons Upload --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!-- JSON Library --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> <!-- OWL API --> <dependency> <groupId>net.sourceforge.owlapi</groupId> <artifactId>owlapi-distribution</artifactId> <version>3.4.10</version> </dependency> </dependencies> </project>
{ "content_hash": "478b346f2962f7ac6ab12e2ae1855e92", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 204, "avg_line_length": 26.89010989010989, "alnum_prop": 0.6591744993870045, "repo_name": "LucasBassetti/triplify", "id": "cb60ef2b1e9f40be07fd8be5d5e5bf173a2c7eb5", "size": "2447", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "target/m2e-wtp/web-resources/META-INF/maven/br.com.triplify/br.com.triplify/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1108308" }, { "name": "HTML", "bytes": "4766520" }, { "name": "Java", "bytes": "57103" }, { "name": "JavaScript", "bytes": "5771422" }, { "name": "PHP", "bytes": "3368" } ], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN @interface NSArray (SMFoundation) - (nullable id)firstObject; - (NSArray *)arrayWithObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate; - (NSArray *)arrayByRemovingObjectsOfClass:(Class)aClass; - (NSArray *)arrayByKeepingObjectsOfClass:(Class)aClass; - (NSArray *)arrayByRemovingObjectsFromArray:(NSArray *)otherArray; - (NSArray *)transformedArrayUsingHandler:(id (^)(id originalObject, NSUInteger index))handler; - (NSRange)fullRange; - (NSArray *)sm_map:(id(^)(id obj))block; - (void)sm_apply:(void(^)(id obj))block; @end NS_ASSUME_NONNULL_END
{ "content_hash": "2ad4a3d0ef70a4b893afe5ea2b031ee0", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 97, "avg_line_length": 33.333333333333336, "alnum_prop": 0.7516666666666667, "repo_name": "s6530085/SMFoundation", "id": "b99551ceb976e835e73c46bda01decc7fb259f1c", "size": "786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SMFoundation/NSArray+SMFoundation.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "95640" }, { "name": "Ruby", "bytes": "518" } ], "symlink_target": "" }
title: "WebElement #11: Vladimír Kriška - Testovanie web aplikácií s CasperJS" layout: event hasVideo: false facebookId: 183116585156588 --- Ku CasperJS som sa dostal keď som hľadal nástroj, ktorý by vedel simulovať browser a zároveň s týmto browserom pracovať - či už s DOMom samotným alebo JavaScriptom. Narazil som na PhantomJS. CasperJS, je jednoduchá utilitka na testovanie webov, ktorá PhantomJS využíva a reč bude práve o nej. Na prednáška sa dozviete ako CasperJS funguje, ako ho používať, na čo všetko sa vám zíde a ukážem vám pár príkladov, kedy mi CasperJS zachránil kopec času. {% include slideshare.html id="14356762" %}
{ "content_hash": "2866420c67d40e208e31ccab90ebc413", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 119, "avg_line_length": 39.9375, "alnum_prop": 0.7902973395931142, "repo_name": "newPOPE/webelement.sk", "id": "3115283e5a025cb65d759304080c96f4cd40b9fe", "size": "681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2012-09-06-webelement-11-testovanie-web-aplikacii-s-casperjs.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "227" }, { "name": "CSS", "bytes": "12685" }, { "name": "HTML", "bytes": "11291" }, { "name": "JavaScript", "bytes": "1778" }, { "name": "Makefile", "bytes": "979" }, { "name": "PHP", "bytes": "1511" }, { "name": "Shell", "bytes": "215" } ], "symlink_target": "" }
import unittest from base64 import b64decode, b64encode from collections import namedtuple from unittest import mock from google.api_core.gapic_v1.method import DEFAULT from airflow.providers.google.cloud.hooks.kms import CloudKMSHook from airflow.providers.google.common.consts import CLIENT_INFO Response = namedtuple("Response", ["plaintext", "ciphertext"]) PLAINTEXT = b"Test plaintext" PLAINTEXT_b64 = b64encode(PLAINTEXT).decode("ascii") CIPHERTEXT_b64 = b64encode(b"Test ciphertext").decode("ascii") CIPHERTEXT = b64decode(CIPHERTEXT_b64.encode("utf-8")) AUTH_DATA = b"Test authdata" TEST_PROJECT = "test-project" TEST_LOCATION = "global" TEST_KEY_RING = "test-key-ring" TEST_KEY = "test-key" TEST_KEY_ID = ( f"projects/{TEST_PROJECT}/locations/{TEST_LOCATION}/keyRings/{TEST_KEY_RING}/cryptoKeys/{TEST_KEY}" ) RESPONSE = Response(PLAINTEXT, PLAINTEXT) def mock_init( self, gcp_conn_id, delegate_to=None, impersonation_chain=None, ): pass class TestCloudKMSHook(unittest.TestCase): def setUp(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_init, ): self.kms_hook = CloudKMSHook(gcp_conn_id="test") @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook._get_credentials") @mock.patch("airflow.providers.google.cloud.hooks.kms.KeyManagementServiceClient") def test_kms_client_creation(self, mock_client, mock_get_creds): result = self.kms_hook.get_conn() mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) assert mock_client.return_value == result assert self.kms_hook._conn == result @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook.get_conn") def test_encrypt(self, mock_get_conn): mock_get_conn.return_value.encrypt.return_value = RESPONSE result = self.kms_hook.encrypt(TEST_KEY_ID, PLAINTEXT) mock_get_conn.assert_called_once_with() mock_get_conn.return_value.encrypt.assert_called_once_with( request=dict( name=TEST_KEY_ID, plaintext=PLAINTEXT, additional_authenticated_data=None, ), retry=DEFAULT, timeout=None, metadata=(), ) assert PLAINTEXT_b64 == result @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook.get_conn") def test_encrypt_with_auth_data(self, mock_get_conn): mock_get_conn.return_value.encrypt.return_value = RESPONSE result = self.kms_hook.encrypt(TEST_KEY_ID, PLAINTEXT, AUTH_DATA) mock_get_conn.assert_called_once_with() mock_get_conn.return_value.encrypt.assert_called_once_with( request=dict( name=TEST_KEY_ID, plaintext=PLAINTEXT, additional_authenticated_data=AUTH_DATA, ), retry=DEFAULT, timeout=None, metadata=(), ) assert PLAINTEXT_b64 == result @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook.get_conn") def test_decrypt(self, mock_get_conn): mock_get_conn.return_value.decrypt.return_value = RESPONSE result = self.kms_hook.decrypt(TEST_KEY_ID, CIPHERTEXT_b64) mock_get_conn.assert_called_once_with() mock_get_conn.return_value.decrypt.assert_called_once_with( request=dict( name=TEST_KEY_ID, ciphertext=CIPHERTEXT, additional_authenticated_data=None, ), retry=DEFAULT, timeout=None, metadata=(), ) assert PLAINTEXT == result @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook.get_conn") def test_decrypt_with_auth_data(self, mock_get_conn): mock_get_conn.return_value.decrypt.return_value = RESPONSE result = self.kms_hook.decrypt(TEST_KEY_ID, CIPHERTEXT_b64, AUTH_DATA) mock_get_conn.assert_called_once_with() mock_get_conn.return_value.decrypt.assert_called_once_with( request=dict( name=TEST_KEY_ID, ciphertext=CIPHERTEXT, additional_authenticated_data=AUTH_DATA, ), retry=DEFAULT, timeout=None, metadata=(), ) assert PLAINTEXT == result
{ "content_hash": "ef53a23cf2075e6562f741d786dfbd4d", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 109, "avg_line_length": 36.36585365853659, "alnum_prop": 0.6431924882629108, "repo_name": "Acehaidrey/incubator-airflow", "id": "0832a480b4656ee2ac1a924292e859aa37d85b86", "size": "5261", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "tests/providers/google/cloud/hooks/test_kms.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25785" }, { "name": "Dockerfile", "bytes": "76693" }, { "name": "HCL", "bytes": "3786" }, { "name": "HTML", "bytes": "164512" }, { "name": "JavaScript", "bytes": "236992" }, { "name": "Jinja", "bytes": "37155" }, { "name": "Jupyter Notebook", "bytes": "2929" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "21727510" }, { "name": "R", "bytes": "313" }, { "name": "Shell", "bytes": "495253" }, { "name": "TypeScript", "bytes": "326556" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Tempest: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="style.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="icon.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Tempest </div> </td> <td> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.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)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('struct_list_box_1_1_proxy_delegate.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Tempest::ListBox::ProxyDelegate Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>createView</b>(size_t position) (defined in <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>)</td><td class="entry"><a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>createView</b>(size_t position, Role) (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>delegate</b> (defined in <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>)</td><td class="entry"><a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>invalidateView</b> (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>onItemSelected</b> (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>onItemViewSelected</b> (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>operator=</b>(slot &amp;other) (defined in <a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ProxyDelegate</b>(const std::shared_ptr&lt; ListDelegate &gt; &amp;d) (defined in <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>)</td><td class="entry"><a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>R_Count</b> enum value (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>R_Default</b> enum value (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>R_ListBoxItem</b> enum value (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>R_ListBoxView</b> enum value (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>R_ListItem</b> enum value (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>removeView</b>(Widget *w, size_t position) (defined in <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>)</td><td class="entry"><a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Role</b> enum name (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>size</b>() const (defined in <a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a>)</td><td class="entry"><a class="el" href="struct_list_box_1_1_proxy_delegate.html">Tempest::ListBox::ProxyDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>slot</b>() (defined in <a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>slot</b>(const slot &amp;other) (defined in <a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>update</b>(Widget *w, size_t position) (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>updateView</b> (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~ListDelegate</b>() (defined in <a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_list_delegate.html">Tempest::ListDelegate</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~slot</b>() (defined in <a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1slot.html">Tempest::slot</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.12 </li> </ul> </div> </body> </html>
{ "content_hash": "7139e7918777f2ea6acbaf4de30fc5a7", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 420, "avg_line_length": 90.27067669172932, "alnum_prop": 0.6799100449775113, "repo_name": "enotio/Tempest", "id": "dff110328b651c13f7c84150851cdd08b961bcde", "size": "12006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/html/struct_list_box_1_1_proxy_delegate-members.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "209674" }, { "name": "C++", "bytes": "997335" }, { "name": "CSS", "bytes": "26404" }, { "name": "Java", "bytes": "10502" }, { "name": "Makefile", "bytes": "3047" }, { "name": "Objective-C", "bytes": "387" }, { "name": "Objective-C++", "bytes": "50885" }, { "name": "QML", "bytes": "1647" }, { "name": "QMake", "bytes": "11871" } ], "symlink_target": "" }